repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
texel-sensei/eversim
src/core/physics/constraints/distance_constraint.cpp
974
#include "core/physics/constraints/distance_constraint.h" #include <istream> #include "core/physics/body_template.h" using namespace std; namespace eversim { namespace core { namespace physics { constraint_factory::data_container distance_constraint_factory::parse(std::istream& data) const { data.exceptions(istream::badbit); float target_distance; data >> target_distance; if(data.fail()) { target_distance = -1; } return target_distance; } std::unique_ptr<constraint> distance_constraint_factory::build( constraint_descriptor const& desc, body const* bdy ) const { assert(desc.arity == 2); auto target = boost::any_cast<float>(desc.extra_data); auto c = make_unique<distance_constraint>(target); c->stiffness = desc.stiffness; c->particles = { { bdy, desc.particles[0] }, { bdy, desc.particles[1] } }; if(c->distance <= 0) { c->distance = length(c->particles[0]->pos - c->particles[1]->pos); } return c; } }}}
apache-2.0
aws/aws-sdk-java
aws-java-sdk-wellarchitected/src/main/java/com/amazonaws/services/wellarchitected/model/transform/LensUpgradeSummaryMarshaller.java
3630
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.wellarchitected.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.wellarchitected.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * LensUpgradeSummaryMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class LensUpgradeSummaryMarshaller { private static final MarshallingInfo<String> WORKLOADID_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("WorkloadId").build(); private static final MarshallingInfo<String> WORKLOADNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("WorkloadName").build(); private static final MarshallingInfo<String> LENSALIAS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("LensAlias").build(); private static final MarshallingInfo<String> LENSARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("LensArn").build(); private static final MarshallingInfo<String> CURRENTLENSVERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CurrentLensVersion").build(); private static final MarshallingInfo<String> LATESTLENSVERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("LatestLensVersion").build(); private static final LensUpgradeSummaryMarshaller instance = new LensUpgradeSummaryMarshaller(); public static LensUpgradeSummaryMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(LensUpgradeSummary lensUpgradeSummary, ProtocolMarshaller protocolMarshaller) { if (lensUpgradeSummary == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(lensUpgradeSummary.getWorkloadId(), WORKLOADID_BINDING); protocolMarshaller.marshall(lensUpgradeSummary.getWorkloadName(), WORKLOADNAME_BINDING); protocolMarshaller.marshall(lensUpgradeSummary.getLensAlias(), LENSALIAS_BINDING); protocolMarshaller.marshall(lensUpgradeSummary.getLensArn(), LENSARN_BINDING); protocolMarshaller.marshall(lensUpgradeSummary.getCurrentLensVersion(), CURRENTLENSVERSION_BINDING); protocolMarshaller.marshall(lensUpgradeSummary.getLatestLensVersion(), LATESTLENSVERSION_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
alibaba/nacos
example/src/main/java/com/alibaba/nacos/example/ConfigExample.java
2392
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.example; import java.util.Properties; import java.util.concurrent.Executor; import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.listener.Listener; import com.alibaba.nacos.api.exception.NacosException; /** * Config service example. * * @author Nacos */ public class ConfigExample { public static void main(String[] args) throws NacosException, InterruptedException { String serverAddr = "localhost"; String dataId = "test"; String group = "DEFAULT_GROUP"; Properties properties = new Properties(); properties.put("serverAddr", serverAddr); ConfigService configService = NacosFactory.createConfigService(properties); String content = configService.getConfig(dataId, group, 5000); System.out.println(content); configService.addListener(dataId, group, new Listener() { @Override public void receiveConfigInfo(String configInfo) { System.out.println("receive:" + configInfo); } @Override public Executor getExecutor() { return null; } }); boolean isPublishOk = configService.publishConfig(dataId, group, "content"); System.out.println(isPublishOk); Thread.sleep(3000); content = configService.getConfig(dataId, group, 5000); System.out.println(content); boolean isRemoveOk = configService.removeConfig(dataId, group); System.out.println(isRemoveOk); Thread.sleep(3000); content = configService.getConfig(dataId, group, 5000); System.out.println(content); Thread.sleep(300000); } }
apache-2.0
sridevikoushik31/openstack
nova/tests/network/test_api.py
10503
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for network API.""" import itertools import random import mox from nova import context from nova import exception from nova import network from nova.network import api from nova.network import floating_ips from nova.network import rpcapi as network_rpcapi from nova import policy from nova import test FAKE_UUID = 'a47ae74e-ab08-547f-9eee-ffd23fc46c16' class NetworkPolicyTestCase(test.TestCase): def setUp(self): super(NetworkPolicyTestCase, self).setUp() policy.reset() policy.init() self.context = context.get_admin_context() def tearDown(self): super(NetworkPolicyTestCase, self).tearDown() policy.reset() def test_check_policy(self): self.mox.StubOutWithMock(policy, 'enforce') target = { 'project_id': self.context.project_id, 'user_id': self.context.user_id, } policy.enforce(self.context, 'network:get_all', target) self.mox.ReplayAll() api.check_policy(self.context, 'get_all') class ApiTestCase(test.TestCase): def setUp(self): super(ApiTestCase, self).setUp() self.network_api = network.API() self.context = context.RequestContext('fake-user', 'fake-project') def test_allocate_for_instance_handles_macs_passed(self): # If a macs argument is supplied to the 'nova-network' API, it is just # ignored. This test checks that the call down to the rpcapi layer # doesn't pass macs down: nova-network doesn't support hypervisor # mac address limits (today anyhow). macs = set(['ab:cd:ef:01:23:34']) self.mox.StubOutWithMock( self.network_api.network_rpcapi, "allocate_for_instance") kwargs = dict(zip(['host', 'instance_id', 'project_id', 'requested_networks', 'rxtx_factor', 'vpn', 'macs'], itertools.repeat(mox.IgnoreArg()))) self.network_api.network_rpcapi.allocate_for_instance( mox.IgnoreArg(), **kwargs).AndReturn([]) self.mox.ReplayAll() instance = dict(id='id', uuid='uuid', project_id='project_id', host='host', instance_type={'rxtx_factor': 0}) self.network_api.allocate_for_instance( self.context, instance, 'vpn', 'requested_networks', macs=macs) def _do_test_associate_floating_ip(self, orig_instance_uuid): """Test post-association logic.""" new_instance = {'uuid': 'new-uuid'} def fake_associate(*args, **kwargs): return orig_instance_uuid self.stubs.Set(floating_ips.FloatingIP, 'associate_floating_ip', fake_associate) def fake_instance_get_by_uuid(context, instance_uuid): return {'uuid': instance_uuid} self.stubs.Set(self.network_api.db, 'instance_get_by_uuid', fake_instance_get_by_uuid) def fake_get_nw_info(ctxt, instance): class FakeNWInfo(object): def json(self): pass return FakeNWInfo() self.stubs.Set(self.network_api, '_get_instance_nw_info', fake_get_nw_info) if orig_instance_uuid: expected_updated_instances = [new_instance['uuid'], orig_instance_uuid] else: expected_updated_instances = [new_instance['uuid']] def fake_instance_info_cache_update(context, instance_uuid, cache): self.assertEquals(instance_uuid, expected_updated_instances.pop()) self.stubs.Set(self.network_api.db, 'instance_info_cache_update', fake_instance_info_cache_update) self.network_api.associate_floating_ip(self.context, new_instance, '172.24.4.225', '10.0.0.2') def test_associate_preassociated_floating_ip(self): self._do_test_associate_floating_ip('orig-uuid') def test_associate_unassociated_floating_ip(self): self._do_test_associate_floating_ip(None) def _stub_migrate_instance_calls(self, method, multi_host, info): fake_instance_type = {'rxtx_factor': 'fake_factor'} fake_instance = {'uuid': 'fake_uuid', 'instance_type': fake_instance_type, 'project_id': 'fake_project_id'} fake_migration = {'source_compute': 'fake_compute_source', 'dest_compute': 'fake_compute_dest'} def fake_mig_inst_method(*args, **kwargs): info['kwargs'] = kwargs def fake_is_multi_host(*args, **kwargs): return multi_host def fake_get_floaters(*args, **kwargs): return ['fake_float1', 'fake_float2'] self.stubs.Set(network_rpcapi.NetworkAPI, method, fake_mig_inst_method) self.stubs.Set(self.network_api, '_is_multi_host', fake_is_multi_host) self.stubs.Set(self.network_api, '_get_floating_ip_addresses', fake_get_floaters) expected = {'instance_uuid': 'fake_uuid', 'source_compute': 'fake_compute_source', 'dest_compute': 'fake_compute_dest', 'rxtx_factor': 'fake_factor', 'project_id': 'fake_project_id', 'floating_addresses': None} if multi_host: expected['floating_addresses'] = ['fake_float1', 'fake_float2'] return fake_instance, fake_migration, expected def test_migrate_instance_start_with_multhost(self): info = {'kwargs': {}} arg1, arg2, expected = self._stub_migrate_instance_calls( 'migrate_instance_start', True, info) expected['host'] = 'fake_compute_source' self.network_api.migrate_instance_start(self.context, arg1, arg2) self.assertEqual(info['kwargs'], expected) def test_migrate_instance_start_without_multhost(self): info = {'kwargs': {}} arg1, arg2, expected = self._stub_migrate_instance_calls( 'migrate_instance_start', False, info) self.network_api.migrate_instance_start(self.context, arg1, arg2) self.assertEqual(info['kwargs'], expected) def test_migrate_instance_finish_with_multhost(self): info = {'kwargs': {}} arg1, arg2, expected = self._stub_migrate_instance_calls( 'migrate_instance_finish', True, info) expected['host'] = 'fake_compute_dest' self.network_api.migrate_instance_finish(self.context, arg1, arg2) self.assertEqual(info['kwargs'], expected) def test_migrate_instance_finish_without_multhost(self): info = {'kwargs': {}} arg1, arg2, expected = self._stub_migrate_instance_calls( 'migrate_instance_finish', False, info) self.network_api.migrate_instance_finish(self.context, arg1, arg2) self.assertEqual(info['kwargs'], expected) def test_is_multi_host_instance_has_no_fixed_ip(self): def fake_fixed_ip_get_by_instance(ctxt, uuid): raise exception.FixedIpNotFoundForInstance(instance_uuid=uuid) self.stubs.Set(self.network_api.db, 'fixed_ip_get_by_instance', fake_fixed_ip_get_by_instance) instance = {'uuid': FAKE_UUID} self.assertFalse(self.network_api._is_multi_host(self.context, instance)) def test_is_multi_host_network_has_no_project_id(self): is_multi_host = random.choice([True, False]) network = {'project_id': None, 'multi_host': is_multi_host, } network_ref = self.network_api.db.network_create_safe( self.context.elevated(), network) def fake_fixed_ip_get_by_instance(ctxt, uuid): fixed_ip = [{'network_id': network_ref['id'], 'instance_uuid': FAKE_UUID, }] return fixed_ip self.stubs.Set(self.network_api.db, 'fixed_ip_get_by_instance', fake_fixed_ip_get_by_instance) instance = {'uuid': FAKE_UUID} result = self.network_api._is_multi_host(self.context, instance) self.assertEqual(is_multi_host, result) def test_is_multi_host_network_has_project_id(self): is_multi_host = random.choice([True, False]) network = {'project_id': self.context.project_id, 'multi_host': is_multi_host, } network_ref = self.network_api.db.network_create_safe( self.context.elevated(), network) def fake_fixed_ip_get_by_instance(ctxt, uuid): fixed_ip = [{'network_id': network_ref['id'], 'instance_uuid': FAKE_UUID, }] return fixed_ip self.stubs.Set(self.network_api.db, 'fixed_ip_get_by_instance', fake_fixed_ip_get_by_instance) instance = {'uuid': FAKE_UUID} result = self.network_api._is_multi_host(self.context, instance) self.assertEqual(is_multi_host, result) def test_get_backdoor_port(self): backdoor_port = 59697 def fake_get_backdoor_port(ctxt, host): return backdoor_port self.stubs.Set(self.network_api.network_rpcapi, 'get_backdoor_port', fake_get_backdoor_port) port = self.network_api.get_backdoor_port(self.context, 'fake_host') self.assertEqual(port, backdoor_port)
apache-2.0
ispras/NetBlox
src/ru/ispras/modis/NetBlox/parser/basicParsersAndUtils/XMLStringValuesRangeProcessor.java
1708
package ru.ispras.modis.NetBlox.parser.basicParsersAndUtils; import java.util.LinkedList; import java.util.List; import org.xml.sax.Attributes; import ru.ispras.modis.NetBlox.exceptions.ScenarioException; import ru.ispras.modis.NetBlox.parser.xmlParser.ParserContext; import ru.ispras.modis.NetBlox.parser.xmlParser.XMLElementProcessor; import ru.ispras.modis.NetBlox.scenario.RangeOfValues; /** * Parses xml string values that can contain a range of string values. * * @author ilya */ public class XMLStringValuesRangeProcessor extends XMLRangedStringValueProcessor { private List<String> values = new LinkedList<String>(); @Override public void createElement(XMLElementProcessor aparent, String tagName, Attributes attributes, ParserContext acontext) { values = new LinkedList<String>(); String valuesRepresentation = attributes.getValue(ATTRIBUTE_EXPLICIT_OR_RANGE); if (valuesRepresentation != null && !valuesRepresentation.equalsIgnoreCase(ATTRIBUTE_PRESENTATION_VALUES)) { StringBuilder messageBuilder = new StringBuilder("String values must be specified explicitly ("). append(ATTRIBUTE_EXPLICIT_OR_RANGE).append("='").append(ATTRIBUTE_PRESENTATION_VALUES).append("'). Check tag: "). append(tagName); throw new ScenarioException(messageBuilder.toString()); } super.createElement(aparent, tagName, attributes, acontext); } @Override protected int extractValuesFromRange(String[] range, String stepString) { throw new UnsupportedOperationException(); } @Override protected void addValue(String value) { values.add(value); } public RangeOfValues<String> getValues() { return new RangeOfValues<String>(variationId, variationTag, values); } }
apache-2.0
yingzhuo/captcha4j
src/main/java/ref/com/jhlabs/image/WaterFilter.java
4684
/* Copyright 2006 Jerry Huxtable Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ref.com.jhlabs.image; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; /** * A filter which produces a water ripple distortion. */ @SuppressWarnings("all") public class WaterFilter extends TransformFilter { private float wavelength = 16; private float amplitude = 10; private float phase = 0; private float centreX = 0.5f; private float centreY = 0.5f; private float radius = 50; private float radius2 = 0; private float icentreX; private float icentreY; public WaterFilter() { setEdgeAction( CLAMP ); } /** * Set the wavelength of the ripples. * @param wavelength the wavelength * @see #getWavelength */ public void setWavelength(float wavelength) { this.wavelength = wavelength; } /** * Get the wavelength of the ripples. * @return the wavelength * @see #setWavelength */ public float getWavelength() { return wavelength; } /** * Set the amplitude of the ripples. * @param amplitude the amplitude * @see #getAmplitude */ public void setAmplitude(float amplitude) { this.amplitude = amplitude; } /** * Get the amplitude of the ripples. * @return the amplitude * @see #setAmplitude */ public float getAmplitude() { return amplitude; } /** * Set the phase of the ripples. * @param phase the phase * @see #getPhase */ public void setPhase(float phase) { this.phase = phase; } /** * Get the phase of the ripples. * @return the phase * @see #setPhase */ public float getPhase() { return phase; } /** * Set the centre of the effect in the X direction as a proportion of the image size. * @param centreX the center * @see #getCentreX */ public void setCentreX( float centreX ) { this.centreX = centreX; } /** * Get the centre of the effect in the X direction as a proportion of the image size. * @return the center * @see #setCentreX */ public float getCentreX() { return centreX; } /** * Set the centre of the effect in the Y direction as a proportion of the image size. * @param centreY the center * @see #getCentreY */ public void setCentreY( float centreY ) { this.centreY = centreY; } /** * Get the centre of the effect in the Y direction as a proportion of the image size. * @return the center * @see #setCentreY */ public float getCentreY() { return centreY; } /** * Set the centre of the effect as a proportion of the image size. * @param centre the center * @see #getCentre */ public void setCentre( Point2D centre ) { this.centreX = (float)centre.getX(); this.centreY = (float)centre.getY(); } /** * Get the centre of the effect as a proportion of the image size. * @return the center * @see #setCentre */ public Point2D getCentre() { return new Point2D.Float( centreX, centreY ); } /** * Set the radius of the effect. * @param radius the radius * @min-value 0 * @see #getRadius */ public void setRadius(float radius) { this.radius = radius; } /** * Get the radius of the effect. * @return the radius * @see #setRadius */ public float getRadius() { return radius; } private boolean inside(int v, int a, int b) { return a <= v && v <= b; } public BufferedImage filter( BufferedImage src, BufferedImage dst ) { icentreX = src.getWidth() * centreX; icentreY = src.getHeight() * centreY; if ( radius == 0 ) radius = Math.min(icentreX, icentreY); radius2 = radius*radius; return super.filter( src, dst ); } protected void transformInverse(int x, int y, float[] out) { float dx = x-icentreX; float dy = y-icentreY; float distance2 = dx*dx + dy*dy; if (distance2 > radius2) { out[0] = x; out[1] = y; } else { float distance = (float)Math.sqrt(distance2); float amount = amplitude * (float)Math.sin(distance / wavelength * ImageMath.TWO_PI - phase); amount *= (radius-distance)/radius; if ( distance != 0 ) amount *= wavelength/distance; out[0] = x + dx*amount; out[1] = y + dy*amount; } } public String toString() { return "Distort/Water Ripples..."; } }
apache-2.0
zackp30/crateincinerator
ruby/unicorn.rb
19
worker_processes 5
apache-2.0
aws/aws-sdk-java
aws-java-sdk-iotfleethub/src/main/java/com/amazonaws/services/iotfleethub/model/transform/ListTagsForResourceRequestMarshaller.java
2068
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.iotfleethub.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.iotfleethub.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * ListTagsForResourceRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class ListTagsForResourceRequestMarshaller { private static final MarshallingInfo<String> RESOURCEARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH) .marshallLocationName("resourceArn").build(); private static final ListTagsForResourceRequestMarshaller instance = new ListTagsForResourceRequestMarshaller(); public static ListTagsForResourceRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(ListTagsForResourceRequest listTagsForResourceRequest, ProtocolMarshaller protocolMarshaller) { if (listTagsForResourceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listTagsForResourceRequest.getResourceArn(), RESOURCEARN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
abutun/kabman
KabMan Application/Kabman/Import/GridCellValueErrorStates.cs
169
 namespace KabMan { public enum GridCellValueErrorStates { None, Error, Warning, Null, Empty, Invalid } }
apache-2.0
JuergenWeichand/downloadclient
src/main/java/de/bayern/gdi/services/CatalogService.java
17911
/* * DownloadClient Geodateninfrastruktur Bayern * * (c) 2016 GSt. GDI-BY (gdi.bayern.de) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.bayern.gdi.services; import de.bayern.gdi.utils.Misc; import de.bayern.gdi.utils.NamespaceContextMap; import de.bayern.gdi.utils.XML; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.namespace.NamespaceContext; import javax.xml.xpath.XPathConstants; import org.apache.commons.io.IOUtils; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * @author Jochen Saalfeld ([email protected]) */ public class CatalogService { private static final String CSW_NAMESPACE = "http://www.opengis.net/cat/csw/2.0.2"; private static final String CSW_SCHEMA = "http://schemas.opengis.net/csw/2.0.2/csw.xsd"; private static final String GMD_NAMESPACE = "http://www.isotc211.org/2005/gmd"; private static final String GMD_SCHEMA = "http://www.isotc211.org/2005/gmd/gmd.xsd"; private static final String OWS_NAMESPACE = "http://www.opengis.net/ows"; private static final String SRV_NAMESPACE = "http://www.isotc211.org/2005/srv"; private static final String GCO_NAMESPACE = "http://www.isotc211.org/2005/gco"; private static final String CSW_QUERY_FILEPATH = "csw_searchQuery.xml"; private static final Logger log = Logger.getLogger(CatalogService.class.getName()); private URL catalogURL; private String userName; private static final int MIN_SEARCHLENGTH = 2; private String password; private String providerName; private NamespaceContext context; private URL getRecordsURL; /** * Constructor. * * @param url String URL * @param userName Username * @param password Password * @throws URISyntaxException if URL is wrong * @throws IOException if something in IO is wrong */ public CatalogService(String url, String userName, String password) throws URISyntaxException, IOException { this(new URL(url), userName, password); } /** * Constructor. * * @param url Stirng URL * @throws URISyntaxException if URL is wrong * @throws IOException if something in IO is wrong */ public CatalogService(String url) throws URISyntaxException, IOException { this(url, null, null); } /** * Constructor. * * @param url URL * @throws URISyntaxException if URL is wrong * @throws IOException if something in IO is wrong */ public CatalogService(URL url) throws URISyntaxException, IOException { this(url, null, null); } /** * Constructor. * * @param url URL * @param userName Username * @param password Password * @throws URISyntaxException if URL is wrong * @throws IOException if something in IO is wrong */ public CatalogService(URL url, String userName, String password) throws URISyntaxException, IOException { this.catalogURL = url; this.userName = userName; this.password = password; this.context = new NamespaceContextMap( "csw", CSW_NAMESPACE, "gmd", GMD_NAMESPACE, "ows", OWS_NAMESPACE, "srv", SRV_NAMESPACE, "gco", GCO_NAMESPACE); Document xml = XML.getDocument(this.catalogURL, this.userName, this.password); if (xml != null) { String getProviderExpr = "//ows:ServiceIdentification/ows:Title"; Node providerNameNode = (Node) XML.xpath(xml, getProviderExpr, XPathConstants.NODE, context); this.providerName = providerNameNode.getTextContent(); String getRecordsURLExpr = "//ows:OperationsMetadata" + "/ows:Operation[@name='GetRecords']" + "/ows:DCP" + "/ows:HTTP" + "/ows:Post" + "/@*[name()='xlink:href']"; String getRecordsURLStr = (String) XML.xpath(xml, getRecordsURLExpr, XPathConstants.STRING, context); this.getRecordsURL = null; this.getRecordsURL = new URL(getRecordsURLStr); } } /** * gets the Name of the service Provider. * * @return Name of the service Provider */ public String getProviderName() { return this.providerName; } /** * retrieves a Map of ServiceNames and URLs for a Filter-Word. * * @param filter the Word to filter to * @return Map of Service Names and URLs * @throws URISyntaxException if URL is wrong * @throws IOException if something in IO is wrong */ public List<Service> getServicesByFilter(String filter) throws URISyntaxException, IOException { List<Service> services = new ArrayList<Service>(); if (filter.length() > MIN_SEARCHLENGTH && this.getRecordsURL != null) { String search = loadXMLFilter(filter); Document xml = XML.getDocument(this.getRecordsURL, this.userName, this.password, search, true); Node exceptionNode = (Node) XML.xpath(xml, "//ows:ExceptionReport", XPathConstants.NODE, this.context); if (exceptionNode != null) { String exceptionCode = (String) XML.xpath(xml, "//ows:ExceptionReport/ows:Exception/@exceptionCode", XPathConstants.STRING, this.context); String exceptionlocator = (String) XML.xpath(xml, "//ows:ExceptionReport/ows:Exception/@locator", XPathConstants.STRING, this.context); String exceptiontext = (String) XML.xpath(xml, "//ows:ExceptionReport/ows:Exception/ows:ExceptionText", XPathConstants.STRING, this.context); String excpetion = "An Excpetion was thrown by the CSW: \n"; excpetion += "\texceptionCode: " + exceptionCode + "\n"; excpetion += "\tlocator: " + exceptionlocator + "\n"; excpetion += "\texceptiontext: " + exceptiontext + "\n"; log.log(Level.SEVERE, excpetion, xml); return null; } String nodeListOfServicesExpr = "//csw:SearchResults//gmd:MD_Metadata"; NodeList servicesNL = (NodeList) XML.xpath(xml, nodeListOfServicesExpr, XPathConstants.NODESET, this.context); services = parseServices(servicesNL); } return services; } private String makeCapabiltiesURL(String url, String type) { if (url.endsWith("?") && type.toUpperCase().contains("WFS")) { return url + "service=wfs" + "&acceptversions=" + getVersionOfType(type) + "&request=GetCapabilities"; } if (!url.toUpperCase().contains("GETCAPABILITIES") && type .toUpperCase().contains("WFS")) { return url + "?service=wfs" + "&acceptversions=" + getVersionOfType(type) + "&request=GetCapabilities"; } return url; } private String getVersionOfType(String type) { String versionNumber = type.substring(type.lastIndexOf(" ") + 1); if ("2.0".equals(versionNumber)) { versionNumber = "2.0.0"; } else if ("1.0".equals(versionNumber)) { versionNumber = "1.0.0"; } else if ("1.1".equals(versionNumber)) { versionNumber = "1.1.0"; } return versionNumber; } /** * parses the services. * @param servicesNL node list of service entries * @return list of services * @throws MalformedURLException if url is wrong */ public List<Service> parseServices(NodeList servicesNL) throws MalformedURLException { List<Service> services = new ArrayList<Service>(); for (int i = 0; i < servicesNL.getLength(); i++) { Node serviceN = servicesNL.item(i); String nameExpr = "gmd:identificationInfo" + "/srv:SV_ServiceIdentification" + "/gmd:citation" + "/gmd:CI_Citation" + "/gmd:title" + "/gco:CharacterString"; String serviceName = (String) XML.xpath(serviceN, nameExpr, XPathConstants.STRING, context); String restrictionExpr = "gmd:identificationInfo" + "/srv:SV_ServiceIdentification" + "/gmd:resourceConstraints" + "/gmd:MD_SecurityConstraints" + "/gmd:classification" + "/gmd:MD_ClassificationCode"; String restriction = (String) XML.xpath(serviceN, restrictionExpr, XPathConstants.STRING, context); boolean restricted = false; if ("restricted".equals(restriction)) { restricted = true; } String typeExpr = "gmd:identificationInfo" + "/srv:SV_ServiceIdentification" + "/srv:serviceType" + "/gco:LocalName"; String serviceType = (String) XML.xpath(serviceN, typeExpr, XPathConstants.STRING, context); String serviceTypeVersionExpr = "gmd:identificationInfo" + "/srv:SV_ServiceIdentification" + "/srv:serviceTypeVersion" + "/gco:CharacterString"; String serviceTypeVersion = (String) XML.xpath(serviceN, serviceTypeVersionExpr, XPathConstants.STRING, context); String serviceURL = getServiceURL(serviceN); if (serviceTypeVersion.equals("")) { serviceTypeVersion = "ATOM"; } if (!serviceName.equals("") && serviceURL != null) { serviceURL = makeCapabiltiesURL(serviceURL, serviceTypeVersion); Service service = new Service(new URL(serviceURL), serviceName, restricted, Service.guessServiceType(serviceTypeVersion)); services.add(service); } } return services; } private String getServiceURL(Node serviceNode) { String onLineExpr = "gmd:distributionInfo" + "/gmd:MD_Distribution" + "/gmd:transferOptions" + "/gmd:MD_DigitalTransferOptions" + "/gmd:onLine"; NodeList onlineNL = (NodeList) XML.xpath(serviceNode, onLineExpr, XPathConstants.NODESET, context); for (int j = 0; j < onlineNL.getLength(); j++) { Node onlineN = onlineNL.item(j); String urlExpr = "gmd:CI_OnlineResource" + "/gmd:linkage" + "/gmd:URL"; String onLineserviceURL = (String) XML.xpath(onlineN, urlExpr, XPathConstants.STRING, context); String applicationprofileExpr = "gmd:CI_OnlineResource" + "/gmd:applicationProfile" + "/gco:CharacterString"; String applicationProfile = (String) XML.xpath(onlineN, applicationprofileExpr, XPathConstants.STRING, context); applicationProfile = applicationProfile.toLowerCase(); if (applicationProfile.equals("wfs-url") || applicationProfile.equals("feed-url")) { return onLineserviceURL; } else if (applicationProfile.equals("dienste-url") || applicationProfile.equals("download")) { return onLineserviceURL; } } String operationMetaDataExpr = "gmd:identificationInfo" + "/srv:SV_ServiceIdentification" + "/srv:containsOperations"; NodeList operationsMetadataNL = (NodeList) XML.xpath(serviceNode, operationMetaDataExpr, XPathConstants.NODESET, context); Node firstNode = null; for (int j = 0; j < operationsMetadataNL.getLength(); j++) { Node operationMetadataNode = operationsMetadataNL.item(j); if (j == 0) { firstNode = operationMetadataNode; } String operationsNameExpr = "srv:SV_OperationMetadata" + "/srv:operationName" + "/gco:CharacterString"; String applicationProfile = (String) XML.xpath( operationMetadataNode, operationsNameExpr, XPathConstants.STRING, context); if (applicationProfile.toLowerCase(). equals("getcapabilities")) { String operationsURLExpr = "srv:SV_OperationMetadata" + "/srv:connectPoint" + "/gmd:CI_OnlineResource" + "/gmd:linkage" + "/gmd:URL"; String operationsURL = (String) XML.xpath( operationMetadataNode, operationsURLExpr, XPathConstants.STRING, context); if (!operationsURL.isEmpty()) { return operationsURL; } } } if (firstNode != null) { String operationsURLExpr = "srv:SV_OperationMetadata" + "/srv:connectPoint" + "/gmd:CI_OnlineResource" + "/gmd:linkage" + "/gmd:URL"; String operationsURL = (String) XML.xpath( firstNode, operationsURLExpr, XPathConstants.STRING, context); return operationsURL; } return null; } /** * http://www.weichand.de/2012/03/24/ * grundlagen-catalogue-service-web-csw-2-0-2/ . */ private URL setURLRequestAndSearch(String search) { URL newURL = null; String constraintAnyText = "csw:AnyText Like '%" + search + "%'"; try { constraintAnyText = URLEncoder.encode(constraintAnyText, "UTF-8"); newURL = new URL(this.catalogURL.toString().replace( "GetCapabilities", "GetRecords" + "&version=2.0.2" + "&namespace=xmlns" + "(csw=" + CSW_NAMESPACE + ")," + "xmlns(gmd=" + GMD_NAMESPACE + ")" + "&resultType=results" + "&outputFormat=application/xml" + "&outputSchema=" + GMD_NAMESPACE + "&startPosition=1" + "&maxRecords=20" + "&typeNames=csw:Record" + "&elementSetName=full" + "&constraintLanguage=CQL_TEXT" + "&constraint_language_version=1.1.0" + "&constraint=" + constraintAnyText)); } catch (MalformedURLException | UnsupportedEncodingException e) { log.log(Level.SEVERE, e.getMessage(), e); } return newURL; } private String loadXMLFilter(String search) { StringWriter writer = new StringWriter(); try { InputStream stream = Misc.getResource(CSW_QUERY_FILEPATH); IOUtils.copy(stream, writer, "UTF-8"); } catch (IOException e) { log.log(Level.SEVERE, e.getMessage(), e); } String xmlStr = writer.toString(); return xmlStr.replace("{SUCHBEGRIFF}", search); } /** * returns the catalog url. * @return the url of the catalog */ public URL getUrl() { return this.catalogURL; } }
apache-2.0
hortonworks/cloudbreak
template-manager-core/src/main/java/com/sequenceiq/cloudbreak/template/filesystem/gcs/GcsFileSystemConfigurationsView.java
1137
package com.sequenceiq.cloudbreak.template.filesystem.gcs; import java.util.Collection; import com.sequenceiq.cloudbreak.template.filesystem.BaseFileSystemConfigurationsView; import com.sequenceiq.cloudbreak.template.filesystem.StorageLocationView; import com.sequenceiq.common.model.FileSystemType; import com.sequenceiq.common.api.filesystem.GcsFileSystem; public class GcsFileSystemConfigurationsView extends BaseFileSystemConfigurationsView { private String serviceAccountEmail; public GcsFileSystemConfigurationsView(GcsFileSystem gcsFileSystem, Collection<StorageLocationView> locations, boolean defaultFs) { super(FileSystemType.GCS.name(), gcsFileSystem.getStorageContainer(), defaultFs, locations, null); serviceAccountEmail = gcsFileSystem.getServiceAccountEmail(); } public String getServiceAccountEmail() { return serviceAccountEmail; } public void setServiceAccountEmail(String serviceAccountEmail) { this.serviceAccountEmail = serviceAccountEmail; } @Override public String getProtocol() { return FileSystemType.GCS.getProtocol(); } }
apache-2.0
litiebiao2012/pacific
pacific-common/src/main/java/com/pacific/common/web/CsrfInterceptor.java
1862
package com.pacific.common.web; import com.pacific.common.web.xuser.XUserSession; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; /** * Created by panwang.chengpw on 1/22/15. */ public class CsrfInterceptor extends HandlerInterceptorAdapter { private Logger logger = LoggerFactory.getLogger(CsrfInterceptor.class); private static String CSRF_TOKEN = "csrfToken"; private boolean debugMode = true; private List<String> excludePath; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (logger.isDebugEnabled()) { logger.debug(""); } if (isCheckCsrfToken(request)) { boolean isPass = checkCsrfToken(request); return isPass || debugMode; } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } private boolean isCheckCsrfToken(HttpServletRequest request) { if (StringUtils.equalsIgnoreCase(request.getMethod(), "POST") || StringUtils.endsWith(request.getRequestURI(), ".json")) { return true; } return false; } private boolean checkCsrfToken(HttpServletRequest request) { return StringUtils.equals(request.getParameter(CSRF_TOKEN), XUserSession.getCurrent().getCsrfToken()); } public void setDebugMode(boolean debugMode) { this.debugMode = debugMode; } }
apache-2.0
rwinch/spring-security-oauth
spring-security-oauth2/src/main/java/org/springframework/security/oauth2/common/exceptions/OAuth2Exception.java
5574
package org.springframework.security.oauth2.common.exceptions; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.codehaus.jackson.map.annotate.JsonDeserialize; import org.codehaus.jackson.map.annotate.JsonSerialize; /** * Base exception for OAuth 2 exceptions. * * @author Ryan Heaton * @author Rob Winch * @author Dave Syer */ @JsonSerialize(using = OAuth2ExceptionSerializer.class) @JsonDeserialize(using = OAuth2ExceptionDeserializer.class) public class OAuth2Exception extends RuntimeException { public static final String ERROR = "error"; public static final String DESCRIPTION = "error_description"; public static final String URI = "error_uri"; public static final String INVALID_REQUEST = "invalid_request"; public static final String INVALID_CLIENT = "invalid_client"; public static final String INVALID_GRANT = "invalid_grant"; public static final String UNAUTHORIZED_CLIENT = "unauthorized_client"; public static final String UNSUPPORTED_GRANT_TYPE = "unsupported_grant_type"; public static final String INVALID_SCOPE = "invalid_scope"; public static final String INVALID_TOKEN = "invalid_token"; public static final String REDIRECT_URI_MISMATCH ="redirect_uri_mismatch"; public static final String UNSUPPORTED_RESPONSE_TYPE ="unsupported_response_type"; public static final String ACCESS_DENIED = "access_denied"; private Map<String, String> additionalInformation = null; public OAuth2Exception(String msg, Throwable t) { super(msg, t); } public OAuth2Exception(String msg) { super(msg); } /** * The OAuth2 error code. * * @return The OAuth2 error code. */ public String getOAuth2ErrorCode() { return "invalid_request"; } /** * The HTTP error code associated with this error. * * @return The HTTP error code associated with this error. */ public int getHttpErrorCode() { return 400; } /** * Get any additional information associated with this error. * * @return Additional information, or null if none. */ public Map<String, String> getAdditionalInformation() { return this.additionalInformation; } /** * Add some additional information with this OAuth error. * * @param key The key. * @param value The value. */ public void addAdditionalInformation(String key, String value) { if (this.additionalInformation == null) { this.additionalInformation = new TreeMap<String, String>(); } this.additionalInformation.put(key, value); } /** * Creates the appropriate subclass of OAuth2Exception given the errorCode. * @param errorCode * @param errorMessage * @return */ public static OAuth2Exception create(String errorCode, String errorMessage) { if (errorMessage == null) { errorMessage = errorCode == null ? "OAuth Error" : errorCode; } if (INVALID_CLIENT.equals(errorCode)) { return new InvalidClientException(errorMessage); } else if (UNAUTHORIZED_CLIENT.equals(errorCode)) { return new UnauthorizedClientException(errorMessage); } else if (INVALID_GRANT.equals(errorCode)) { return new InvalidGrantException(errorMessage); } else if (INVALID_SCOPE.equals(errorCode)) { return new InvalidScopeException(errorMessage); } else if (INVALID_TOKEN.equals(errorCode)) { return new InvalidTokenException(errorMessage); } else if (INVALID_REQUEST.equals(errorCode)) { return new InvalidRequestException(errorMessage); } else if (REDIRECT_URI_MISMATCH.equals(errorCode)) { return new RedirectMismatchException(errorMessage); } else if (UNSUPPORTED_GRANT_TYPE.equals(errorCode)) { return new UnsupportedGrantTypeException(errorMessage); } else if (UNSUPPORTED_RESPONSE_TYPE.equals(errorCode)) { return new UnsupportedResponseTypeException(errorMessage); } else if (ACCESS_DENIED.equals(errorCode)) { return new UserDeniedAuthorizationException(errorMessage); } else { return new OAuth2Exception(errorMessage); } } /** * Creates an {@link OAuth2Exception} from a Map<String,String>. * * @param errorParams * @return */ public static OAuth2Exception valueOf(Map<String, String> errorParams) { String errorCode = errorParams.get(ERROR); String errorMessage = errorParams.containsKey(DESCRIPTION) ? errorParams.get(DESCRIPTION) : null; OAuth2Exception ex = create(errorCode, errorMessage); Set<Map.Entry<String, String>> entries = errorParams.entrySet(); for (Map.Entry<String, String> entry : entries) { String key = entry.getKey(); if (!ERROR.equals(key) && !DESCRIPTION.equals(key)) { ex.addAdditionalInformation(key, entry.getValue()); } } return ex; } @Override public String toString() { return getSummary(); } /** * @return a comma-delimited list of details (key=value pairs) */ public String getSummary() { StringBuilder builder = new StringBuilder(); String delim = ""; String error = this.getOAuth2ErrorCode(); if (error != null) { builder.append(delim).append("error=\"").append(error).append("\""); delim = ", "; } String errorMessage = this.getMessage(); if (errorMessage != null) { builder.append(delim).append("error_description=\"").append(errorMessage).append("\""); delim = ", "; } Map<String, String> additionalParams = this.getAdditionalInformation(); if (additionalParams != null) { for (Map.Entry<String, String> param : additionalParams.entrySet()) { builder.append(delim).append(param.getKey()).append("=\"").append(param.getValue()).append("\""); delim = ", "; } } return builder.toString(); } }
apache-2.0
trungnv84/do-an
administrator/components/com_do_an_tot_nghiep/controllers/danh_sach_giao_vien.php
1435
<?php /** * @version 1.0.0 * @package com_do_an_tot_nghiep * @copyright Copyright (C) 2014. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * @author NVHoang <[email protected]> - http://hoangtrung.org */ // No direct access. defined('_JEXEC') or die; jimport('joomla.application.component.controlleradmin'); /** * Danh_sach_giao_vien list controller class. */ class Do_an_tot_nghiepControllerDanh_sach_giao_vien extends JControllerAdmin { /** * Proxy for getModel. * @since 1.6 */ public function getModel($name = 'giao_vien', $prefix = 'Do_an_tot_nghiepModel') { $model = parent::getModel($name, $prefix, array('ignore_request' => true)); return $model; } /** * Method to save the submitted ordering values for records via AJAX. * * @return void * * @since 3.0 */ public function saveOrderAjax() { // Get the input $input = JFactory::getApplication()->input; $pks = $input->post->get('cid', array(), 'array'); $order = $input->post->get('order', array(), 'array'); // Sanitize the input JArrayHelper::toInteger($pks); JArrayHelper::toInteger($order); // Get the model $model = $this->getModel(); // Save the ordering $return = $model->saveorder($pks, $order); if ($return) { echo "1"; } // Close the application JFactory::getApplication()->close(); } }
apache-2.0
Somoaudience/Prebid.js
test/spec/modules/madvertiseBidAdapter_spec.js
6253
import {expect} from 'chai'; import {config} from 'src/config'; import * as utils from 'src/utils'; import {spec} from 'modules/madvertiseBidAdapter'; describe('madvertise adapater', () => { describe('Test validate req', () => { it('should accept minimum valid bid', () => { let bid = { bidder: 'madvertise', sizes: [[728, 90]], params: { s: 'test' } }; const isValid = spec.isBidRequestValid(bid); expect(isValid).to.equal(true); }); it('should reject no sizes', () => { let bid = { bidder: 'madvertise', params: { s: 'test' } }; const isValid = spec.isBidRequestValid(bid); expect(isValid).to.equal(false); }); it('should reject empty sizes', () => { let bid = { bidder: 'madvertise', sizes: [], params: { s: 'test' } }; const isValid = spec.isBidRequestValid(bid); expect(isValid).to.equal(false); }); it('should reject wrong format sizes', () => { let bid = { bidder: 'madvertise', sizes: [['728x90']], params: { s: 'test' } }; const isValid = spec.isBidRequestValid(bid); expect(isValid).to.equal(false); }); it('should reject no params', () => { let bid = { bidder: 'madvertise', sizes: [[728, 90]] }; const isValid = spec.isBidRequestValid(bid); expect(isValid).to.equal(false); }); it('should reject missing s', () => { let bid = { bidder: 'madvertise', params: {} }; const isValid = spec.isBidRequestValid(bid); expect(isValid).to.equal(false); }); }); describe('Test build request', () => { beforeEach(function () { let mockConfig = { consentManagement: { cmpApi: 'IAB', timeout: 1111, allowAuctionWithoutConsent: 'cancel' } }; sinon.stub(config, 'getConfig').callsFake((key) => { return utils.deepAccess(mockConfig, key); }); }); afterEach(function () { config.getConfig.restore(); }); let bid = [{ bidder: 'madvertise', sizes: [[728, 90], [300, 100]], bidId: '51ef8751f9aead', adUnitCode: 'div-gpt-ad-1460505748561-0', transactionId: 'd7b773de-ceaa-484d-89ca-d9f51b8d61ec', auctionId: '18fd8b8b0bd757', bidderRequestId: '418b37f85e772c', params: { s: 'test', } }]; it('minimum request with gdpr consent', () => { let bidderRequest = { gdprConsent: { consentString: 'BOJ/P2HOJ/P2HABABMAAAAAZ+A==', vendorData: {}, gdprApplies: true } }; const req = spec.buildRequests(bid, bidderRequest); expect(req).to.exist.and.to.be.a('array'); expect(req[0]).to.have.property('method'); expect(req[0].method).to.equal('GET'); expect(req[0]).to.have.property('url'); expect(req[0].url).to.contain('//mobile.mng-ads.com/?rt=bid_request&v=1.0'); expect(req[0].url).to.contain(`&s=test`); expect(req[0].url).to.contain(`&sizes[0]=728x90`); expect(req[0].url).to.contain(`&gdpr=1`); expect(req[0].url).to.contain(`&consent[0][format]=IAB`); expect(req[0].url).to.contain(`&consent[0][value]=BOJ/P2HOJ/P2HABABMAAAAAZ+A==`) }); it('minimum request without gdpr consent', () => { let bidderRequest = {}; const req = spec.buildRequests(bid, bidderRequest); expect(req).to.exist.and.to.be.a('array'); expect(req[0]).to.have.property('method'); expect(req[0].method).to.equal('GET'); expect(req[0]).to.have.property('url'); expect(req[0].url).to.contain('//mobile.mng-ads.com/?rt=bid_request&v=1.0'); expect(req[0].url).to.contain(`&s=test`); expect(req[0].url).to.contain(`&sizes[0]=728x90`); expect(req[0].url).not.to.contain(`&gdpr=1`); expect(req[0].url).not.to.contain(`&consent[0][format]=`); expect(req[0].url).not.to.contain(`&consent[0][value]=`) }); }); describe('Test interpret response', () => { it('General banner response', () => { let bid = { bidder: 'madvertise', sizes: [[728, 90]], bidId: '51ef8751f9aead', adUnitCode: 'div-gpt-ad-1460505748561-0', transactionId: 'd7b773de-ceaa-484d-89ca-d9f51b8d61ec', auctionId: '18fd8b8b0bd757', bidderRequestId: '418b37f85e772c', params: { s: 'test', connection_type: 'WIFI', age: 25, } }; let resp = spec.interpretResponse({body: { requestId: 'REQUEST_ID', cpm: 1, ad: '<html><h3>I am an ad</h3></html>', Width: 320, height: 50, creativeId: 'CREATIVE_ID', dealId: 'DEAL_ID', ttl: 180, currency: 'EUR', netRevenue: true }}, {bidId: bid.bidId}); expect(resp).to.exist.and.to.be.a('array'); expect(resp[0]).to.have.property('requestId', bid.bidId); expect(resp[0]).to.have.property('cpm', 1); expect(resp[0]).to.have.property('width', 320); expect(resp[0]).to.have.property('height', 50); expect(resp[0]).to.have.property('ad', '<html><h3>I am an ad</h3></html>'); expect(resp[0]).to.have.property('ttl', 180); expect(resp[0]).to.have.property('creativeId', 'CREATIVE_ID'); expect(resp[0]).to.have.property('netRevenue', true); expect(resp[0]).to.have.property('currency', 'EUR'); expect(resp[0]).to.have.property('dealId', 'DEAL_ID'); }); it('No response', () => { let bid = { bidder: 'madvertise', sizes: [[728, 90]], bidId: '51ef8751f9aead', adUnitCode: 'div-gpt-ad-1460505748561-0', transactionId: 'd7b773de-ceaa-484d-89ca-d9f51b8d61ec', auctionId: '18fd8b8b0bd757', bidderRequestId: '418b37f85e772c', params: { s: 'test', connection_type: 'WIFI', age: 25, } }; let resp = spec.interpretResponse({body: null}, {bidId: bid.bidId}); expect(resp).to.exist.and.to.be.a('array').that.is.empty; }); }); });
apache-2.0
alexsnaps/ehcache3
clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/xml/ClusteringCacheManagerServiceConfigurationParser.java
22089
/* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ehcache.clustered.client.internal.config.xml; import org.ehcache.clustered.client.config.ClusteringServiceConfiguration; import org.ehcache.clustered.client.config.Timeouts; import org.ehcache.clustered.client.config.builders.TimeoutsBuilder; import org.ehcache.clustered.client.internal.ConnectionSource; import org.ehcache.clustered.client.service.ClusteringService; import org.ehcache.clustered.common.ServerSideConfiguration; import org.ehcache.config.units.MemoryUnit; import org.ehcache.spi.service.ServiceCreationConfiguration; import org.ehcache.xml.BaseConfigParser; import org.ehcache.xml.CacheManagerServiceConfigurationParser; import org.ehcache.xml.exceptions.XmlConfigurationException; import org.ehcache.xml.model.TimeType; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.io.IOException; import java.math.BigInteger; import java.net.InetSocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import static org.ehcache.clustered.client.internal.config.xml.ClusteredCacheConstants.NAMESPACE; import static org.ehcache.clustered.client.internal.config.xml.ClusteredCacheConstants.XML_SCHEMA; import static org.ehcache.clustered.client.internal.config.xml.ClusteredCacheConstants.TC_CLUSTERED_NAMESPACE_PREFIX; import static org.ehcache.xml.XmlModel.convertToJavaTimeUnit; /** * Provides parsing support for the {@code <service>} elements representing a {@link ClusteringService ClusteringService}. * * @see ClusteredCacheConstants#XSD */ public class ClusteringCacheManagerServiceConfigurationParser extends BaseConfigParser<ClusteringServiceConfiguration> implements CacheManagerServiceConfigurationParser<ClusteringService> { public static final String CLUSTER_ELEMENT_NAME = "cluster"; public static final String CONNECTION_ELEMENT_NAME = "connection"; public static final String CLUSTER_CONNECTION_ELEMENT_NAME = "cluster-connection"; public static final String CLUSTER_TIER_MANAGER_ATTRIBUTE_NAME = "cluster-tier-manager"; public static final String SERVER_ELEMENT_NAME = "server"; public static final String HOST_ATTRIBUTE_NAME = "host"; public static final String PORT_ATTRIBUTE_NAME = "port"; public static final String READ_TIMEOUT_ELEMENT_NAME = "read-timeout"; public static final String WRITE_TIMEOUT_ELEMENT_NAME = "write-timeout"; public static final String CONNECTION_TIMEOUT_ELEMENT_NAME = "connection-timeout"; public static final String URL_ATTRIBUTE_NAME = "url"; public static final String DEFAULT_RESOURCE_ELEMENT_NAME = "default-resource"; public static final String SHARED_POOL_ELEMENT_NAME = "shared-pool"; public static final String SERVER_SIDE_CONFIG = "server-side-config"; public static final String AUTO_CREATE_ATTRIBUTE_NAME = "auto-create"; public static final String UNIT_ATTRIBUTE_NAME = "unit"; public static final String NAME_ATTRIBUTE_NAME = "name"; public static final String FROM_ATTRIBUTE_NAME = "from"; public static final String DEFAULT_UNIT_ATTRIBUTE_VALUE = "seconds"; public ClusteringCacheManagerServiceConfigurationParser() { super(ClusteringServiceConfiguration.class); } @Override public Source getXmlSchema() throws IOException { return new StreamSource(XML_SCHEMA.openStream()); } @Override public URI getNamespace() { return NAMESPACE; } /** * Complete interpretation of the top-level elements defined in <code>{@value ClusteredCacheConstants#XSD}</code>. * This method is called only for those elements from the namespace set by {@link ClusteredCacheConstants#NAMESPACE}. * <p> * This method presumes the element presented is valid according to the XSD. * * @param fragment the XML fragment to process * @return a {@link org.ehcache.clustered.client.config.ClusteringServiceConfiguration ClusteringServiceConfiguration} */ @Override public ServiceCreationConfiguration<ClusteringService> parseServiceCreationConfiguration(final Element fragment) { if ("cluster".equals(fragment.getLocalName())) { ClusteringCacheManagerServiceConfigurationParser.ServerSideConfig serverConfig = null; URI connectionUri = null; List<InetSocketAddress> serverAddresses = new ArrayList<>(); String clusterTierManager = null; Duration getTimeout = null, putTimeout = null, connectionTimeout = null; final NodeList childNodes = fragment.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { final Node item = childNodes.item(i); if (Node.ELEMENT_NODE == item.getNodeType()) { switch (item.getLocalName()) { case "connection": /* * <connection> is a required element in the XSD */ final Attr urlAttribute = ((Element)item).getAttributeNode("url"); final String urlValue = urlAttribute.getValue(); try { connectionUri = new URI(urlValue); } catch (URISyntaxException e) { throw new XmlConfigurationException( String.format("Value of %s attribute on XML configuration element <%s> in <%s> is not a valid URI - '%s'", urlAttribute.getName(), item.getNodeName(), fragment.getTagName(), connectionUri), e); } break; case "cluster-connection": clusterTierManager = ((Element)item).getAttribute("cluster-tier-manager"); final NodeList serverNodes = item.getChildNodes(); for (int j = 0; j < serverNodes.getLength(); j++) { final Node serverNode = serverNodes.item(j); final String host = ((Element)serverNode).getAttributeNode("host").getValue(); final Attr port = ((Element)serverNode).getAttributeNode("port"); InetSocketAddress address; if (port == null) { address = InetSocketAddress.createUnresolved(host, 0); } else { String portString = port.getValue(); address = InetSocketAddress.createUnresolved(host, Integer.parseInt(portString)); } serverAddresses.add(address); } break; case "read-timeout": /* * <read-timeout> is an optional element */ getTimeout = processTimeout(fragment, item); break; case "write-timeout": /* * <write-timeout> is an optional element */ putTimeout = processTimeout(fragment, item); break; case "connection-timeout": /* * <connection-timeout> is an optional element */ connectionTimeout = processTimeout(fragment, item); break; case "server-side-config": /* * <server-side-config> is an optional element */ serverConfig = processServerSideConfig(item); break; default: throw new XmlConfigurationException( String.format("Unknown XML configuration element <%s> in <%s>", item.getNodeName(), fragment.getTagName())); } } } try { Timeouts timeouts = getTimeouts(getTimeout, putTimeout, connectionTimeout); if (serverConfig == null) { if (connectionUri != null) { return new ClusteringServiceConfiguration(connectionUri, timeouts); } else { return new ClusteringServiceConfiguration(serverAddresses, clusterTierManager, timeouts); } } ServerSideConfiguration serverSideConfiguration; if (serverConfig.defaultServerResource == null) { serverSideConfiguration = new ServerSideConfiguration(serverConfig.pools); } else { serverSideConfiguration = new ServerSideConfiguration(serverConfig.defaultServerResource, serverConfig.pools); } if (connectionUri != null) { return new ClusteringServiceConfiguration(connectionUri, timeouts, serverConfig.autoCreate, serverSideConfiguration); } else { return new ClusteringServiceConfiguration(serverAddresses, clusterTierManager, timeouts, serverConfig.autoCreate, serverSideConfiguration); } } catch (IllegalArgumentException e) { throw new XmlConfigurationException(e); } } throw new XmlConfigurationException(String.format("XML configuration element <%s> in <%s> is not supported", fragment.getTagName(), (fragment.getParentNode() == null ? "null" : fragment.getParentNode().getLocalName()))); } @Override public Class<ClusteringService> getServiceType() { return ClusteringService.class; } /** * Translates a {@link ServiceCreationConfiguration} to an xml element * * @param serviceCreationConfiguration */ @Override public Element unparseServiceCreationConfiguration(final ServiceCreationConfiguration<ClusteringService> serviceCreationConfiguration) { Element rootElement = unparseConfig(serviceCreationConfiguration); return rootElement; } private Element createRootUrlElement(Document doc, ClusteringServiceConfiguration clusteringServiceConfiguration) { Element rootElement = doc.createElementNS(getNamespace().toString(), TC_CLUSTERED_NAMESPACE_PREFIX + CLUSTER_ELEMENT_NAME); Element urlElement = createUrlElement(doc, clusteringServiceConfiguration); rootElement.appendChild(urlElement); return rootElement; } protected Element createUrlElement(Document doc, ClusteringServiceConfiguration clusteringServiceConfiguration) { Element urlElement = doc.createElement(TC_CLUSTERED_NAMESPACE_PREFIX + CONNECTION_ELEMENT_NAME); urlElement.setAttribute(URL_ATTRIBUTE_NAME, clusteringServiceConfiguration.getClusterUri().toString()); return urlElement; } private Element createServerElement(Document doc, ClusteringServiceConfiguration clusteringServiceConfiguration) { if (!(clusteringServiceConfiguration.getConnectionSource() instanceof ConnectionSource.ServerList)) { throw new IllegalArgumentException("When connection URL is null, source of connection MUST be of type ConnectionSource.ServerList.class"); } ConnectionSource.ServerList servers = (ConnectionSource.ServerList)clusteringServiceConfiguration.getConnectionSource(); Element rootElement = doc.createElementNS(getNamespace().toString(), TC_CLUSTERED_NAMESPACE_PREFIX + CLUSTER_ELEMENT_NAME); Element connElement = createConnectionElementWrapper(doc, clusteringServiceConfiguration); servers.getServers().forEach(server -> { Element serverElement = doc.createElement(TC_CLUSTERED_NAMESPACE_PREFIX + SERVER_ELEMENT_NAME); serverElement.setAttribute(HOST_ATTRIBUTE_NAME, server.getHostName()); /* If port is greater than 0, set the attribute. Otherwise, do not set. Default value will be taken. */ if (server.getPort() > 0) { serverElement.setAttribute(PORT_ATTRIBUTE_NAME, Integer.toString(server.getPort())); } connElement.appendChild(serverElement); }); rootElement.appendChild(connElement); return rootElement; } protected Element createConnectionElementWrapper(Document doc, ClusteringServiceConfiguration clusteringServiceConfiguration) { Element connElement = doc.createElement(TC_CLUSTERED_NAMESPACE_PREFIX + CLUSTER_CONNECTION_ELEMENT_NAME); connElement.setAttribute(CLUSTER_TIER_MANAGER_ATTRIBUTE_NAME, clusteringServiceConfiguration.getConnectionSource() .getClusterTierManager()); return connElement; } @Override protected Element createRootElement(Document doc, ClusteringServiceConfiguration clusteringServiceConfiguration) { Element rootElement; if (clusteringServiceConfiguration.getConnectionSource() instanceof ConnectionSource.ClusterUri) { rootElement = createRootUrlElement(doc, clusteringServiceConfiguration); } else { rootElement = createServerElement(doc, clusteringServiceConfiguration); } processTimeUnits(doc, rootElement, clusteringServiceConfiguration); Element serverSideConfigurationElem = processServerSideElements(doc, clusteringServiceConfiguration); rootElement.appendChild(serverSideConfigurationElem); return rootElement; } private void processTimeUnits(Document doc, Element parent, ClusteringServiceConfiguration clusteringServiceConfiguration) { if (clusteringServiceConfiguration.getTimeouts() != null) { Timeouts timeouts = clusteringServiceConfiguration.getTimeouts(); Element readTimeoutElem = createTimeoutElement(doc, READ_TIMEOUT_ELEMENT_NAME, timeouts.getReadOperationTimeout()); Element writeTimeoutElem = createTimeoutElement(doc, WRITE_TIMEOUT_ELEMENT_NAME, timeouts.getWriteOperationTimeout()); Element connectionTimeoutElem = createTimeoutElement(doc, CONNECTION_TIMEOUT_ELEMENT_NAME, timeouts.getConnectionTimeout()); /* Important: do not change the order of following three elements if corresponding change is not done in xsd */ parent.appendChild(readTimeoutElem); parent.appendChild(writeTimeoutElem); parent.appendChild(connectionTimeoutElem); } } private Element createTimeoutElement(Document doc, String timeoutName, Duration timeout) { Element retElement = null; if (READ_TIMEOUT_ELEMENT_NAME.equals(timeoutName)) { retElement = doc.createElement(TC_CLUSTERED_NAMESPACE_PREFIX + READ_TIMEOUT_ELEMENT_NAME); } else if (WRITE_TIMEOUT_ELEMENT_NAME.equals(timeoutName)) { retElement = doc.createElement(TC_CLUSTERED_NAMESPACE_PREFIX + WRITE_TIMEOUT_ELEMENT_NAME); } else { retElement = doc.createElement(TC_CLUSTERED_NAMESPACE_PREFIX + CONNECTION_TIMEOUT_ELEMENT_NAME); } retElement.setAttribute(UNIT_ATTRIBUTE_NAME, DEFAULT_UNIT_ATTRIBUTE_VALUE); retElement.setTextContent(Long.toString(timeout.getSeconds())); return retElement; } protected Element processServerSideElements(Document doc, ClusteringServiceConfiguration clusteringServiceConfiguration) { Element serverSideConfigurationElem = createServerSideConfigurationElement(doc, clusteringServiceConfiguration); if (clusteringServiceConfiguration.getServerConfiguration() != null) { ServerSideConfiguration serverSideConfiguration = clusteringServiceConfiguration.getServerConfiguration(); String defaultServerResource = serverSideConfiguration.getDefaultServerResource(); if (!(defaultServerResource == null || defaultServerResource.trim().length() == 0)) { Element defaultResourceElement = createDefaultServerResourceElement(doc, defaultServerResource); serverSideConfigurationElem.appendChild(defaultResourceElement); } Map<String, ServerSideConfiguration.Pool> resourcePools = serverSideConfiguration.getResourcePools(); if (resourcePools != null) { resourcePools.forEach( (key, value) -> { Element poolElement = createSharedPoolElement(doc, key, value); serverSideConfigurationElem.appendChild(poolElement); } ); } } return serverSideConfigurationElem; } private Element createServerSideConfigurationElement(Document doc, ClusteringServiceConfiguration clusteringServiceConfiguration) { Element serverSideConfigurationElem = doc.createElement(TC_CLUSTERED_NAMESPACE_PREFIX + SERVER_SIDE_CONFIG); serverSideConfigurationElem.setAttribute(AUTO_CREATE_ATTRIBUTE_NAME, Boolean.toString(clusteringServiceConfiguration .isAutoCreate())); return serverSideConfigurationElem; } private Element createSharedPoolElement(Document doc, String poolName, ServerSideConfiguration.Pool pool) { Element poolElement = doc.createElement(TC_CLUSTERED_NAMESPACE_PREFIX + SHARED_POOL_ELEMENT_NAME); poolElement.setAttribute(NAME_ATTRIBUTE_NAME, poolName); String from = pool.getServerResource(); if (from != null) { if (from.trim().length() == 0) { throw new XmlConfigurationException("Resource pool name can not be empty."); } poolElement.setAttribute(FROM_ATTRIBUTE_NAME, from); } long memoryInBytes = MemoryUnit.B.convert(pool.getSize(), MemoryUnit.B); poolElement.setAttribute(UNIT_ATTRIBUTE_NAME, MemoryUnit.B.toString()); poolElement.setTextContent(Long.toString(memoryInBytes)); return poolElement; } private Element createDefaultServerResourceElement(Document doc, String defaultServerResource) { Element defaultResourceElement = doc.createElement(TC_CLUSTERED_NAMESPACE_PREFIX + DEFAULT_RESOURCE_ELEMENT_NAME); defaultResourceElement.setAttribute(FROM_ATTRIBUTE_NAME, defaultServerResource); return defaultResourceElement; } private ClusteringCacheManagerServiceConfigurationParser.ServerSideConfig processServerSideConfig(Node serverSideConfigElement) { ClusteringCacheManagerServiceConfigurationParser.ServerSideConfig serverSideConfig = new ClusteringCacheManagerServiceConfigurationParser.ServerSideConfig(); serverSideConfig.autoCreate = Boolean.parseBoolean(((Element)serverSideConfigElement).getAttribute("auto-create")); final NodeList serverSideNodes = serverSideConfigElement.getChildNodes(); for (int i = 0; i < serverSideNodes.getLength(); i++) { final Node item = serverSideNodes.item(i); if (Node.ELEMENT_NODE == item.getNodeType()) { String nodeLocalName = item.getLocalName(); if ("default-resource".equals(nodeLocalName)) { serverSideConfig.defaultServerResource = ((Element)item).getAttribute("from"); } else if ("shared-pool".equals(nodeLocalName)) { Element sharedPoolElement = (Element)item; String poolName = sharedPoolElement.getAttribute("name"); // required Attr fromAttr = sharedPoolElement.getAttributeNode("from"); // optional String fromResource = (fromAttr == null ? null : fromAttr.getValue()); Attr unitAttr = sharedPoolElement.getAttributeNode("unit"); // optional - default 'B' String unit = (unitAttr == null ? "B" : unitAttr.getValue()); MemoryUnit memoryUnit = MemoryUnit.valueOf(unit.toUpperCase(Locale.ENGLISH)); String quantityValue = sharedPoolElement.getFirstChild().getNodeValue(); long quantity; try { quantity = Long.parseLong(quantityValue); } catch (NumberFormatException e) { throw new XmlConfigurationException("Magnitude of value specified for <shared-pool name=\"" + poolName + "\"> is too large"); } ServerSideConfiguration.Pool poolDefinition; if (fromResource == null) { poolDefinition = new ServerSideConfiguration.Pool(memoryUnit.toBytes(quantity)); } else { poolDefinition = new ServerSideConfiguration.Pool(memoryUnit.toBytes(quantity), fromResource); } if (serverSideConfig.pools.put(poolName, poolDefinition) != null) { throw new XmlConfigurationException("Duplicate definition for <shared-pool name=\"" + poolName + "\">"); } } } } return serverSideConfig; } private Duration processTimeout(Element parentElement, Node timeoutNode) { try { // <xxx-timeout> are direct subtype of ehcache:time-type; use JAXB to interpret it JAXBContext context = JAXBContext.newInstance(TimeType.class.getPackage().getName()); Unmarshaller unmarshaller = context.createUnmarshaller(); JAXBElement<TimeType> jaxbElement = unmarshaller.unmarshal(timeoutNode, TimeType.class); TimeType timeType = jaxbElement.getValue(); BigInteger amount = timeType.getValue(); if (amount.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) { throw new XmlConfigurationException( String.format("Value of XML configuration element <%s> in <%s> exceeds allowed value - %s", timeoutNode.getNodeName(), parentElement.getTagName(), amount)); } return Duration.of(amount.longValue(), convertToJavaTimeUnit(timeType.getUnit())); } catch (JAXBException e) { throw new XmlConfigurationException(e); } } private Timeouts getTimeouts(Duration getTimeout, Duration putTimeout, Duration connectionTimeout) { TimeoutsBuilder builder = TimeoutsBuilder.timeouts(); if (getTimeout != null) { builder.read(getTimeout); } if (putTimeout != null) { builder.write(putTimeout); } if (connectionTimeout != null) { builder.connection(connectionTimeout); } return builder.build(); } private static final class ServerSideConfig { private boolean autoCreate = false; private String defaultServerResource = null; private final Map<String, ServerSideConfiguration.Pool> pools = new HashMap<>(); } }
apache-2.0
MobileManAG/Project-H-Backend
src/main/java/com/mobileman/projecth/domain/util/questionary/MorbusBechterewQuestionaryUtil.java
2019
/******************************************************************************* * Copyright 2015 MobileMan GmbH * www.mobileman.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ /** * Project: projecth * * @author mobileman * @date 3.1.2011 * @version 1.0 * * (c) 2010 MobileMan GmbH */ package com.mobileman.projecth.domain.util.questionary; import java.util.Arrays; import java.util.List; /** * @author mobileman * */ public final class MorbusBechterewQuestionaryUtil { private MorbusBechterewQuestionaryUtil(){} /** * Question "Wie ausgeprägt war Ihre Morgensteifigkeit nach dem aufwachen?" * @return id */ public static Long getMorgensteifigkeitQuestionId() { return 2004L; } /** * Question * "Wie ausgeprägt war Ihre Morgensteifigkeit nach dem aufwachen?" * "Wenn ja, wie lange dauerte diese Morgensteifigkeit im Allgemeinen?" * @return id */ public static Long getMorgensteifigkeitLangeQuestionId() { return 2005L; } /** * "Wie würden Sie Ihre allgemeine Müdigkeit und Erschöpfung beschreiben?" * "Wie stark waren ihre Schmerzen in Nacken, Rücken oder Hüfte?" * "Wie stark waren Ihre Schmerzen oder Schwellungen an anderen Gelenken?" * "Wie unangenehm waren für Sie berührungs- oder druckempfindliche Körperstellen?" * @return ids */ public static List<Long> getValue2QuestionsId() { return Arrays.asList(2000L, 2001L, 2002L, 2003L); } }
apache-2.0
kebernet/erigo
client-framework/src/test/java/net/kebernet/configuration/client/impl/MulticastDNSDevicesTest.java
2766
/* * Copyright (c) 2017 Robert Cooper * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.kebernet.configuration.client.impl; import com.google.common.util.concurrent.SettableFuture; import net.kebernet.configuration.client.model.Device; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Created by rcooper on 7/6/17. */ public class MulticastDNSDevicesTest { private static int port = MockServer.randomPort(); private static MockServer mockServer; @BeforeClass public static void setup() throws Exception { mockServer = new MockServer(port); } @AfterClass public static void tearDown() throws Exception { mockServer.stop(); } @Test public void testDiscovery() throws Exception { SettableFuture<Device> deviceFuture = SettableFuture.create(); MulticastDNSDevices devices = new MulticastDNSDevices(new HttpClient(null, null)); //Listen for initial discovery devices.listenForDevices(result -> { result.stream().filter(d-> d.getName().startsWith("Unit Test Device") ).findFirst().ifPresent(deviceFuture::set); return true; }); devices.startListening(); Device device = deviceFuture.get(2, TimeUnit.MINUTES); assertTrue(device != null); assertTrue(device.getAddress().startsWith("http://")); //Check the stored list. SettableFuture<Device> deviceFuture2 = SettableFuture.create(); devices.listKnownDevices(result -> { result.stream().filter(d-> d.getName().startsWith("Unit Test Device") ).findFirst().ifPresent(deviceFuture2::set); return false; }); device = deviceFuture.get(1, TimeUnit.MINUTES); assertTrue(device != null); assertTrue(device.getAddress().startsWith("http://")); assertEquals("http://www.kebernet.net/_/rsrc/1264535093579/Home/therespie.jpg", device.getThumbnailUrl()); devices.stopListening(); } }
apache-2.0
XLabs/xlabs.github.io
html/class_x_labs_1_1_forms_1_1_validation_1_1_property_setter.js
859
var class_x_labs_1_1_forms_1_1_validation_1_1_property_setter = [ [ "InvalidValueProperty", "class_x_labs_1_1_forms_1_1_validation_1_1_property_setter.html#ad5b507b1b8b569f3d7eeb24a1288f758", null ], [ "PropertyProperty", "class_x_labs_1_1_forms_1_1_validation_1_1_property_setter.html#a6325f26c5daa2fc8373095edf1777731", null ], [ "ValidValueProperty", "class_x_labs_1_1_forms_1_1_validation_1_1_property_setter.html#ab8a5e0f53c43dd5fdef1f274602871df", null ], [ "InvalidValue", "class_x_labs_1_1_forms_1_1_validation_1_1_property_setter.html#a68a0e10c81f4254b6f54ee612281fe7b", null ], [ "Property", "class_x_labs_1_1_forms_1_1_validation_1_1_property_setter.html#a684b6bb59d8b7133f817207fa8b65c6e", null ], [ "ValidValue", "class_x_labs_1_1_forms_1_1_validation_1_1_property_setter.html#a0b5ec908d452da300f85cd93f45ba682", null ] ];
apache-2.0
S-Callier/serialization
src/main/java/sebastien/callier/serialization/codec/extendable/object/field/FieldCodec.java
1434
/* * Copyright 2017 Sebastien Callier * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sebastien.callier.serialization.codec.extendable.object.field; import sebastien.callier.serialization.deserializer.InputStreamWrapper; import sebastien.callier.serialization.serializer.OutputStreamWrapper; import java.io.IOException; /** * @author Sebastien Callier * @since 2017 */ public interface FieldCodec { /** * @param wrapper the output to write * @param instance the object containing this field * @throws IOException */ void write( OutputStreamWrapper wrapper, Object instance) throws IOException; /** * @param wrapper the input to read from * @param instance the instance where to set the field value * @throws IOException */ void read( InputStreamWrapper wrapper, Object instance) throws IOException; }
apache-2.0
cloudfoundry/cf-java-client
cloudfoundry-client/src/main/java/org/cloudfoundry/client/v2/domains/Domains.java
3147
/* * Copyright 2013-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cloudfoundry.client.v2.domains; import reactor.core.publisher.Mono; /** * Main entry point to the Cloud Foundry Domains Client API */ public interface Domains { /** * Makes the deprecated <a href="https://apidocs.cloudfoundry.org/latest-release/domains_%28deprecated%29/create_a_domain_owned_by_the_given_organization_%28deprecated%29.html">Create a Domain * owned by the given Organization</a> request and the deprecated <a href="https://apidocs.cloudfoundry.org/latest-release/domains_%28deprecated%29/create_a_shared_domain_%28deprecated%29.html"> * Create a Shared Domain</a> request * * @param request the Create a Domain request * @return the response from the Create a Domain request */ @Deprecated Mono<CreateDomainResponse> create(CreateDomainRequest request); /** * Makes the deprecated <a href="https://apidocs.cloudfoundry.org/latest-release/domains_%28deprecated%29/delete_a_particular_domain_%28deprecated%29.html">Delete a Particular Domain</a> request * * @param request the Delete a Particular Domain request * @return the response from the Delete a Particular Domain request */ @Deprecated Mono<DeleteDomainResponse> delete(DeleteDomainRequest request); /** * Makes the deprecated <a href="https://apidocs.cloudfoundry.org/latest-release/domains_(deprecated)/retrieve_a_particular_domain_(deprecated).html">Get Domain</a> request * * @param request The Get Domain request * @return the response from the Get Domain request */ @Deprecated Mono<GetDomainResponse> get(GetDomainRequest request); /** * Makes the deprecated <a href="https://apidocs.cloudfoundry.org/latest-release/domains_%28deprecated%29/list_all_domains_%28deprecated%29.html">List all Domains</a> request * * @param request the List all Domains request * @return the response from the List all Domains request */ @Deprecated Mono<ListDomainsResponse> list(ListDomainsRequest request); /** * Makes the deprecated <a href="https://apidocs.cloudfoundry.org/latest-release/domains_%28deprecated%29/list_all_spaces_for_the_domain_%28deprecated%29.html">List all Spaces for the Domain</a> * request * * @param request the List all Spaces for the Domain request * @return the response from the List all Spaces for the Domain request */ @Deprecated Mono<ListDomainSpacesResponse> listSpaces(ListDomainSpacesRequest request); }
apache-2.0
iQuick/NewsMe
videoplaysdk/src/main/java/com/sina/sinavideo/sdk/utils/VDResolutionManager.java
6103
package com.sina.sinavideo.sdk.utils; import java.util.List; import com.sina.sinavideo.sdk.data.VDResolutionData; import com.sina.sinavideo.sdk.data.VDResolutionData.VDResolution; import android.annotation.SuppressLint; import android.content.Context; /** * 清晰度部分逻辑太复杂,单独做了一个类出来处理<br /> * <br /> * 清晰度方案1:用户方式<br /> * 1、查找sp里面,如果有上次用户点击的清晰度,那么就按照用户选择的来<br/> * 2、如果没有找到,那么就从默认最低的清晰度开始搞<br/> * 3、在解析情绪度回来的时候,检查当前所有的清晰度,如果命中,那么就直接选出,如果没有命中,那么就往下寻找一个最接近当前清晰度的来播放<br/> * 4、如果是在3G环境中,那么123都无效,按照最小的来<br /> * <br /> * 清晰度方案2:暴力方式<br /> * 直接选择最低一档的清晰度,不再记录用户行为<br /> * * @author sunxiao * */ public class VDResolutionManager { public final static int RESOLUTION_SOLUTION_OBTAIN_USER = 0; public final static int RESOLUTION_SOLUTION_NONE = 1; private String mResolutionTag = VDResolutionData.TYPE_DEFINITION_SD; private VDResolutionData mResolutionData = null; @SuppressLint("unused") private Context mContext = null; private int mResolutionSolutionType = RESOLUTION_SOLUTION_OBTAIN_USER; private static class VDResolutionManagerINSTANCE { private static VDResolutionManager instance = new VDResolutionManager(); } public static VDResolutionManager getInstance(Context context) { VDResolutionManager instance = VDResolutionManagerINSTANCE.instance; instance.mContext = context.getApplicationContext(); instance.initResolutionTag(context); return instance; } /** * 初始化代码,用于外部调用来设置当前的清晰度获取方式 * * @param solutionType */ public void init(int solutionType) { setSolution(solutionType); } /** * 改变当前默认的清晰度逻辑,默认为用户方式 * * @param solutionType */ private void setSolution(int solutionType) { if (solutionType < 0) { return; } boolean isOnlyMobileNet = VDUtility.isOnlyMobileType(mContext); if (isOnlyMobileNet) { // 在只有移动环境时候,只用标清方式 mResolutionTag = VDResolutionData.TYPE_DEFINITION_SD; return; } mResolutionSolutionType = solutionType; initResolutionTag(mContext); } /** * 初始化清晰度tag,按照已经设定的解决方案来处理 */ private void initResolutionTag(Context context) { if (mResolutionSolutionType == RESOLUTION_SOLUTION_OBTAIN_USER) { String savedResolutionTag = VDSharedPreferencesUtil .getCurResolution(context); if (savedResolutionTag != null) { mResolutionTag = savedResolutionTag; } } else if (mResolutionSolutionType == RESOLUTION_SOLUTION_NONE) { mResolutionTag = VDResolutionData.TYPE_DEFINITION_SD; } } /** * 对输入的数据进行过滤以及重新排序 * * @param resolutionData */ private VDResolutionData resortResolutionData( VDResolutionData resolutionData) { VDResolutionData newResolutionData = new VDResolutionData(); List<String> tagList = VDResolutionData.getDefDescTagList(); for (String value : tagList) { VDResolution resolution = resolutionData .getResolutionWithTag(value); if (resolution != null) { newResolutionData.addResolution(resolution); } } return newResolutionData; } /** * 校对当前的清晰度tag,如果resolutionData中没有当前的tag,那么找一个最接近的来 * * NOTE 这个要求resolutionData按照从小到大分辨率的顺序来 */ private String nearResolutionTag(VDResolutionData resolutionData, String currTag) { if (resolutionData == null || resolutionData.getResolutionSize() == 0) { return currTag; } // step1:如果只有一个清晰度,那么直接返回 if (resolutionData.getResolutionSize() == 1) { return resolutionData.getResolutionList().get(0).getTag(); } // step2:如果有多个,那么按照倒排序方式进行resolutionData的遍历,然后得到与当前currTag最接近的值 String tag = currTag; List<String> tagList = VDResolutionData.getDefDescTagList(); int currTagIndex = tagList.indexOf(currTag); List<String> currTagList = resolutionData.getTagList(); int num = currTagList.size() - 1; int base = 100; for (int i = num; i >= 0; i--) { int absCurrSplit = Math.abs(i - currTagIndex); if (absCurrSplit <= base) { base = absCurrSplit; tag = currTagList.get(i); } } return tag; } public boolean isParsed() { return (mResolutionData != null && mResolutionData.getResolutionSize() > 0) ? true : false; } /** * 得到当前的清晰度数据 * * @return */ public VDResolutionData getResolutionData() { return mResolutionData; } /** * 得到当前的清晰度 * * @return */ public VDResolution getCurrResolution() { return mResolutionData.getResolutionWithTag(mResolutionTag); } /** * 得到当前的清晰度tag * * @return */ public String getCurrResolutionTag() { return mResolutionTag; } /** * 解析完毕后,设置清晰度列表 * * @param resolutionData */ public void setResolutionData(VDResolutionData resolutionData) { if (resolutionData == null) { return; } resolutionData = resortResolutionData(resolutionData); mResolutionData = resolutionData; mResolutionTag = nearResolutionTag(resolutionData, mResolutionTag); } /** * 清晰度改变,设置一个新的可选择tag * * @param resolutionTag */ public void setResolutionTag(String resolutionTag) { if (resolutionTag == null) { return; } if (mResolutionData.isContainTag(resolutionTag)) { mResolutionTag = resolutionTag; VDSharedPreferencesUtil.setResolution(mContext, resolutionTag); } } /** * 因为是个单例,所以用来清理资源 */ public void release() { mResolutionData = null; mResolutionTag = null; mContext = null; } }
apache-2.0
anpho/one
3.0/one3/platforms/blackberry10/www/plugins/com.blackberry.invoke.card/www/client.js
7339
cordova.define("com.blackberry.invoke.card.client", function(require, exports, module) { /* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var _self = {}, _ID = "com.blackberry.invoke.card", exec = cordova.require("cordova/exec"), _btoa = require('./btoa'), _noop = function () {}; function cb(done, cancel, invoke) { return function (data) { var type = data.type, result = data.result; switch (type) { case "done": if (done && typeof(done) === "function") { done(result); } break; case "cancel": if (cancel && typeof(cancel) === "function") { cancel(result); } break; case "invoke": if (invoke && typeof(invoke) === "function") { invoke(result); } break; } }; } function defineReadOnlyField(obj, field, value) { Object.defineProperty(obj, field, { "value": value, "writable": false }); } _self.invokeMediaPlayer = function (options, done, cancel, invokeCallback) { var callback = cb(done, cancel, invokeCallback); exec(callback, _noop, _ID, "invokeMediaPlayer", {options: options || {}}); }; _self.invokeCamera = function (mode, done, cancel, invokeCallback) { var callback = cb(done, cancel, invokeCallback); exec(callback, _noop, _ID, "invokeCamera", {mode: mode || ""}); }; _self.invokeFilePicker = function (options, done, cancel, invokeCallback) { /* * options = { * mode: Picker or Saver or PickerMultiple or SaverMultiple, //one of them * type:["Picture","Document","Music","Video","Other"], // , separated types but we pass array * defaultType: "Picture"|"Document"|"Music"|"Video"|"Other" * title: "some string", * defaultSaveFileNames: ["fileName1","fileName2"], // , separated but we pass array * directory:["/path/folder1","/path/folder2"], //, separated but we pass array * filter:[".jpg",".bmp"], // , separated but we pass array * viewMode:ListView or GridView or Default, // one of them * sortBy:Default or Name or Date or Suffix or Size, //one of them * sortOrder:Default or Ascending or Descending // one of them * imageCrop: true|false, * allowOverwrite: true|false * } */ var callback = cb(done, cancel, invokeCallback); exec(callback, _noop, _ID, "invokeFilePicker", {options: options || ""}); }; _self.invokeIcsViewer = function (options, done, cancel, invokeCallback) { /* * options = { * uri: path to the ICS file on device * accountId: id of the calendar account to open the file in (optional) * } */ var callback = cb(done, cancel, invokeCallback); exec(callback, _noop, _ID, "invokeIcsViewer", {options: options || ""}); }; _self.invokeCalendarPicker = function (options, done, cancel, invokeCallback) { /* * options = { * filepath: path to file where .vcs will be saved * } */ var callback = cb(done, cancel, invokeCallback); exec(callback, _noop, _ID, "invokeCalendarPicker", {options: options || ""}); }; _self.invokeCalendarComposer = function (options, done, cancel, invokeCallback) { /* options = { * accountId : account ID //used with syncId or folderId to identify a specific account * syncId : sync ID * folderId : folder ID * subject : event subject * body : event body * startTime : event start time e.g: Wed Jun 13 09:39:56 2012 * duration : event duration * participants : array of pariticipant email addresses * } */ var callback = cb(done, cancel, invokeCallback); exec(callback, _noop, _ID, "invokeCalendarComposer", {options: options || ""}); }; _self.invokeEmailComposer = function (options, done, cancel, invokeCallback) { /* options = { * from : accountId this message should be sent from * subject : message subject * body : plaintext message body * calendarevent : calendar event ID * to : array of recipient emails * cc : array of emails * attachment : array of attachment filepaths * } */ var callback = cb(done, cancel, invokeCallback); exec(callback, _noop, _ID, "invokeEmailComposer", {options: options || ""}); }; _self.invokeTargetPicker = function (request, title, onSuccess, onError) { var callback = function (data) { if (data.status === "success") { if (onSuccess && typeof(onSuccess) === "function") { onSuccess(data.result); } } else if (data.status === "error") { if (onError && typeof(onError) === "function") { onError(data.result); } } }; try { if (request.hasOwnProperty('data')) { request.data = _btoa(request.data); } exec(callback, _noop, _ID, "invokeTargetPicker", { request: request, title: title }); } catch (e) { onError(e); } }; //CAMERA PROPERTIES defineReadOnlyField(_self, "CAMERA_MODE_PHOTO", 'photo'); defineReadOnlyField(_self, "CAMERA_MODE_VIDEO", 'video'); defineReadOnlyField(_self, "CAMERA_MODE_FULL", 'full'); //FILE PICKER PROPERTIES defineReadOnlyField(_self, "FILEPICKER_MODE_PICKER", 'Picker'); defineReadOnlyField(_self, "FILEPICKER_MODE_SAVER", 'Saver'); defineReadOnlyField(_self, "FILEPICKER_MODE_PICKER_MULTIPLE", 'PickerMultiple'); defineReadOnlyField(_self, "FILEPICKER_MODE_SAVER_MULTIPLE", 'SaverMultiple'); defineReadOnlyField(_self, "FILEPICKER_VIEWER_MODE_LIST", 'ListView'); defineReadOnlyField(_self, "FILEPICKER_VIEWER_MODE_GRID", 'GridView'); defineReadOnlyField(_self, "FILEPICKER_VIEWER_MODE_DEFAULT", 'Default'); defineReadOnlyField(_self, "FILEPICKER_SORT_BY_NAME", 'Name'); defineReadOnlyField(_self, "FILEPICKER_SORT_BY_DATE", 'Date'); defineReadOnlyField(_self, "FILEPICKER_SORT_BY_SUFFIX", 'Suffix'); defineReadOnlyField(_self, "FILEPICKER_SORT_BY_SIZE", 'Size'); defineReadOnlyField(_self, "FILEPICKER_SORT_ORDER_ASCENDING", 'Ascending'); defineReadOnlyField(_self, "FILEPICKER_SORT_ORDER_DESCENDING", 'Descending'); defineReadOnlyField(_self, "FILEPICKER_TYPE_PICTURE", 'picture'); defineReadOnlyField(_self, "FILEPICKER_TYPE_DOCUMENT", 'document'); defineReadOnlyField(_self, "FILEPICKER_TYPE_MUSIC", 'music'); defineReadOnlyField(_self, "FILEPICKER_TYPE_VIDEO", 'video'); defineReadOnlyField(_self, "FILEPICKER_TYPE_OTHER", 'other'); module.exports = _self; });
apache-2.0
Deepaksoftvision/GPC_POC
src/test/java/pageObjects/modules/GMailPageObjects.java
818
/** * */ package pageObjects.modules; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import pageObjects.initializePageObjects.PageFactoryInitializer; import ru.yandex.qatools.allure.annotations.Step; import utils.RandomGenerator; /** * @author Gladson Antony * @date Sep 17, 2016 * */ public class GMailPageObjects extends PageFactoryInitializer { @FindBy(xpath="//input[@id='Email']") private WebElement emailIDTextBox; @FindBy(xpath="//input[@id='next']") private WebElement nextButton; @Step("To Enter Email ID and Click Next Button") public void enterEmailID() { utils.FluentWaiting.waitUntillElementToBeClickable(30, 500, emailIDTextBox); emailIDTextBox.sendKeys(RandomGenerator.GenerateRandomEMAILIDs("google.com")); nextButton.click(); } }
apache-2.0
LQJJ/demo
126-go-common-master/app/interface/main/ugcpay-rank/internal/server/http/elec.go
2048
package http import ( "net/http" api "go-common/app/interface/main/ugcpay-rank/api/http" "go-common/app/interface/main/ugcpay-rank/internal/conf" bm "go-common/library/net/http/blademaster" "github.com/json-iterator/go" ) const ( _contentTypeJSON = "application/json; charset=utf-8" ) func elecMonthUP(ctx *bm.Context) { var ( err error arg = &api.ArgRankElecMonthUP{} resp *api.RespRankElecMonthUP bytes []byte ) if err = ctx.Bind(arg); err != nil { return } if arg.RankSize <= 0 || arg.RankSize > conf.Conf.Biz.ElecUPRankSize { arg.RankSize = conf.Conf.Biz.ElecUPRankSize } if resp, err = svc.RankElecMonthUP(ctx, arg.UPMID, arg.RankSize); err != nil { ctx.JSON(nil, err) return } if bytes, err = jsoniter.ConfigFastest.Marshal(resp); err != nil { ctx.JSON(nil, err) return } ctx.Bytes(http.StatusOK, _contentTypeJSON, bytes) } func elecMonth(ctx *bm.Context) { var ( err error arg = &api.ArgRankElecMonth{} resp *api.RespRankElecMonth bytes []byte ) if err = ctx.Bind(arg); err != nil { return } if arg.RankSize <= 0 || arg.RankSize > conf.Conf.Biz.ElecAVRankSize { arg.RankSize = conf.Conf.Biz.ElecAVRankSize } if resp, err = svc.RankElecMonth(ctx, arg.UPMID, arg.AVID, arg.RankSize); err != nil { ctx.JSON(nil, err) return } if bytes, err = jsoniter.ConfigFastest.Marshal(resp); err != nil { ctx.JSON(nil, err) return } ctx.Bytes(http.StatusOK, _contentTypeJSON, bytes) } func elecAllAV(ctx *bm.Context) { var ( err error arg = &api.ArgRankElecMonth{} resp *api.RespRankElecAllAV bytes []byte ) if err = ctx.Bind(arg); err != nil { return } if arg.RankSize <= 0 || arg.RankSize > conf.Conf.Biz.ElecAVRankSize { arg.RankSize = conf.Conf.Biz.ElecAVRankSize } if resp, err = svc.RankElecAllAV(ctx, arg.UPMID, arg.AVID, arg.RankSize); err != nil { ctx.JSON(nil, err) return } if bytes, err = jsoniter.ConfigFastest.Marshal(resp); err != nil { ctx.JSON(nil, err) return } ctx.Bytes(http.StatusOK, _contentTypeJSON, bytes) }
apache-2.0
alexbonavila/LaravelMarketInformation
app/Http/Transformers/Transformer.php
425
<?php namespace App\Http\Transformers; /** * Class Transformer * @package App\Http\Transformers */ abstract class Transformer { /** * @param array $items * @return array */ public function transformCollection(array $items) { return array_map([$this, 'transform'], $items); } /** * @param $item * @return mixed */ abstract public function transform($item); }
apache-2.0
spark3dp/webapp-samples
plugins/login/login.js
884
/** * Run when DOM is ready. * The spark object already exists in this point */ jQuery(function ($) { //First let's see if we have a valid access token if (ADSKSpark.Client.isAccessTokenValid()) { $('#auth-iframe-wrapper').hide(); $('.logged-out-container').hide(); $('.logged-in-container').show(); } else { // Set up the iframe for the login screen //and it's appropriate source $('.logged-out-container').show(); $('.logged-in-container').hide(); var div = $('<div id="auth-iframe-wrapper"><iframe style="width: 100%;border: 0;height: 541px;"></iframe></div>'); var loginContainer = $(".login-container"); if(loginContainer.length>0){ loginContainer.append(div); } else { $("body").append(div); } $('#auth-iframe-wrapper iframe').attr('src', ADSKSpark.Client.getLoginRedirectUrl(true,false)); $('.logged-in-container').hide(); } });
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-codedeploy/src/main/java/com/amazonaws/services/codedeploy/model/MultipleIamArnsProvidedException.java
1300
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.codedeploy.model; import javax.annotation.Generated; /** * <p> * Both an IAM user ARN and an IAM session ARN were included in the request. Use only one ARN type. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class MultipleIamArnsProvidedException extends com.amazonaws.services.codedeploy.model.AmazonCodeDeployException { private static final long serialVersionUID = 1L; /** * Constructs a new MultipleIamArnsProvidedException with the specified error message. * * @param message * Describes the error encountered. */ public MultipleIamArnsProvidedException(String message) { super(message); } }
apache-2.0
AlexanderZf44/APermyakov
chapter_005/src/main/java/ru/apermyakov/testtask/Parser.java
1620
package ru.apermyakov.testtask; /** * Class for parsing string to order. * * @author apermyakov * @version 1.0 * @since 13.11.2017 */ public class Parser { /** * Method for parsing string to string array. * * @param text insert test * @return string array */ private String[] parse(String text) { String[] parsingText = new String[5]; int parsingIndex = 0; int startIndex = -1; boolean startRecord = false; for (int index = 0; index < text.length(); index++) { if (text.charAt(index) == '\"') { if (startRecord) { parsingText[parsingIndex++] = text.substring(startIndex, index); startRecord = false; } else { startRecord = true; } startIndex = index + 1; } } return parsingText; } /** * Method for parsing add orders string. * * @param text insert string * @return add order */ public Order parseAddOrder(String text) { String[] addOrder = this.parse(text); return new Order(addOrder[0], addOrder[1], Double.valueOf(addOrder[2]), Integer.valueOf(addOrder[3]), Integer.valueOf(addOrder[4])); } /** * Method for parsing delete order string. * * @param text insert text * @return delete order */ public Order parseDeleteOrder(String text) { String[] deleteOrder = this.parse(text); return new Order(deleteOrder[0], "", 0D, 0, Integer.valueOf(deleteOrder[1])); } }
apache-2.0
uusa35/tickets
app/Http/Requests/CreateTicket.php
1496
<?php namespace App\Http\Requests; use App\Http\Requests\Request; use App\Ticket; use Illuminate\Support\Facades\Auth; use Intervention\Image\Facades\Image; class CreateTicket extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { if (Auth::user()) { return true; } return false; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'title' => 'required|min:2|max:255', 'body' => 'required|min:2|max:255', 'img_url' => 'image|mimes:jpeg,bmp,png' ]; } public function persist() { $fileName = $this->saveImage('img_url'); $this->request->add(['img_url' => $fileName]); $ticket = Ticket::create($this->request->all()); return $ticket; } public function saveImage($imageInputName) { if ($this->hasFile($imageInputName)) { $fileName = $this->file($imageInputName)->getClientOriginalName(); $fileName = rand(0, 10000) . '' . e($fileName); $path = public_path('uploads/' . $fileName); $realPath = $this->file($imageInputName)->getRealPath(); Image::make($realPath)->resize(200, 200)->save($path); return $fileName; } return false; } }
apache-2.0
liuyunlong1229/source-code
springboot-integration/src/main/java/org/springboot/integration/filter/TokenSource.java
299
package org.springboot.integration.filter; /** * Created by Administrator on 2017/7/16. */ /** * REQUEST 表示从参数列表,HttpServletRequest中构造token * FILED 表示从参数列表中构造token,此时必须指定参数名称 */ public enum TokenSource { REQUEST,FILED }
apache-2.0
Esri/arcgis-samples-winphone
src/ArcGISWindowsPhoneSDK/Samples/Address/LocationToAddress.xaml.cs
2309
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Input; using System.Windows.Media; using ESRI.ArcGIS.Client; using ESRI.ArcGIS.Client.Symbols; using ESRI.ArcGIS.Client.Tasks; using Microsoft.Phone.Controls; namespace ArcGISWindowsPhoneSDK.Samples { public partial class LocationToAddress : PhoneApplicationPage { private ESRI.ArcGIS.Client.Geometry.MapPoint _mapClick; public LocationToAddress() { InitializeComponent(); } private void MyMap_MapGesture(object sender, Map.MapGestureEventArgs e) { if (e.Gesture == GestureType.Tap && MyMap.Extent != null) { Locator locatorTask = new Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"); locatorTask.LocationToAddressCompleted += LocatorTask_LocationToAddressCompleted; locatorTask.Failed += LocatorTask_Failed; // Tolerance (distance) specified in meters double tolerance = 30; locatorTask.LocationToAddressAsync(e.MapPoint, tolerance); Graphic graphic = new Graphic() { Symbol = DefaultMarkerSymbol, Geometry = e.MapPoint }; GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer; graphicsLayer.Graphics.Clear(); graphicsLayer.Graphics.Add(graphic); } } private void LocatorTask_LocationToAddressCompleted(object sender, AddressEventArgs args) { Address address = args.Address; Dictionary<string, object> attributes = address.Attributes; string locAddress = string.Format("{0}\n{1}, {2} {3}",attributes["Address"],attributes["City"], attributes["Region"], attributes["Postal"]); AddressText.Text = locAddress; AddressBorder.Visibility = Visibility.Visible; } private void LocatorTask_Failed(object sender, TaskFailedEventArgs e) { AddressBorder.Visibility = Visibility.Collapsed; MessageBox.Show("Locator service failed: " + e.Error); } } }
apache-2.0
HPI-Hackathon/automatch
api/models/User.js
2968
/** * User.js * * @description :: TODO: You might write a short summary of how this model works and what it represents here. * @docs :: http://sailsjs.org/#!documentation/models */ var request = require('request'); var bcrypt = require('bcrypt'); module.exports = { attributes: { name: 'STRING', email: { type: 'STRING', unique: true }, password: 'STRING', identifier: 'STRING', liked: 'ARRAY', hated: 'ARRAY', favorites: 'ARRAY', /** * Matches the given password hash against the saved one * * @param string password Password hash to compare against * @param function cb Callback given an error and if it matched */ authenticate: function authenticate(password, cb) { bcrypt.compare(password, this.password, function(err, match) { if (err) return cb(err); cb(null, match); }); } }, /** * Generate a password hash given a plaintext password * @param string password The plain text password * @param function cb The callback to call given error and a hash */ genPassword: function getPassword(password, cb) { bcrypt.genSalt(10, function(err, salt) { if (err) return cb(err); bcrypt.hash(password, salt, function(err, hash) { if (err) return cb(err); cb(null, hash); }); }); }, beforeUpdate: function beforeUpdate(attrs, next) { if (!attrs.password) return next(); this.genPassword(attrs.password, function(err, hash) { if (err) return next(err); attrs.password = hash; next(); }); }, beforeCreate: function beforeCreate(attrs, next) { if (!attrs.password) return next(); this.genPassword(attrs.password, function(err, hash) { if (err) return next(err); attrs.password = hash; next(); }); }, /** * Loads an object mapping category names as returned by the mobile * API to names as used by the mobile API * * @param function cb The callback to call once finished */ loadCategoryMap: function loadCategoryMap(cb) { var self = this; request('http://m.mobile.de/svc/r/Car', { headers: { 'Accept-Language': 'en-US,en' } }, function(err, res, body) { if (err) return cb(err); // we want a potential exception to be fatal var data = JSON.parse(body); self.categoryMap = data.categories; cb(); }); }, /** * Translates a given category name to the category as used by the * API. @see loadCategoryMap * * @param String category The category to be translated * @return String The translated category name */ translateCategory: function translateCategory(category) { var map = this.categoryMap; for (var i = 0; i < map.length; i++) { if (map[i].n == category) { return map[i].i; } } }, };
apache-2.0
strapdata/elassandra5-rc
core/src/main/java/org/elasticsearch/index/mapper/LegacyLongFieldMapper.java
13361
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.mapper; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.index.FieldInfo; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.Terms; import org.apache.lucene.search.LegacyNumericRangeQuery; import org.apache.lucene.search.Query; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefBuilder; import org.apache.lucene.util.LegacyNumericUtils; import org.elasticsearch.Version; import org.elasticsearch.action.fieldstats.FieldStats; import org.elasticsearch.common.Explicit; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.fielddata.IndexFieldData; import org.elasticsearch.index.fielddata.IndexNumericFieldData.NumericType; import org.elasticsearch.index.fielddata.plain.DocValuesIndexFieldData; import org.elasticsearch.index.query.QueryShardContext; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Map; import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeLongValue; import static org.elasticsearch.index.mapper.TypeParsers.parseNumberField; /** * */ public class LegacyLongFieldMapper extends LegacyNumberFieldMapper { public static final String CONTENT_TYPE = "long"; public static class Defaults extends LegacyNumberFieldMapper.Defaults { public static final MappedFieldType FIELD_TYPE = new LongFieldType(); static { FIELD_TYPE.freeze(); } } public static class Builder extends LegacyNumberFieldMapper.Builder<Builder, LegacyLongFieldMapper> { public Builder(String name) { super(name, Defaults.FIELD_TYPE, Defaults.PRECISION_STEP_64_BIT); builder = this; } public Builder nullValue(long nullValue) { this.fieldType.setNullValue(nullValue); return this; } @Override public LegacyLongFieldMapper build(BuilderContext context) { if (context.indexCreatedVersion().onOrAfter(Version.V_5_0_0_alpha2)) { throw new IllegalStateException("Cannot use legacy numeric types after 5.0"); } setupFieldType(context); return new LegacyLongFieldMapper(name, fieldType, defaultFieldType, ignoreMalformed(context), coerce(context), includeInAll, context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo); } @Override protected int maxPrecisionStep() { return 64; } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { LegacyLongFieldMapper.Builder builder = new LegacyLongFieldMapper.Builder(name); parseNumberField(builder, name, node, parserContext); for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, Object> entry = iterator.next(); String propName = entry.getKey(); Object propNode = entry.getValue(); if (propName.equals("null_value")) { if (propNode == null) { throw new MapperParsingException("Property [null_value] cannot be null."); } builder.nullValue(nodeLongValue(propNode)); iterator.remove(); } } return builder; } } public static class LongFieldType extends NumberFieldType { public LongFieldType() { super(LegacyNumericType.LONG); } protected LongFieldType(LongFieldType ref) { super(ref); } @Override public NumberFieldType clone() { return new LongFieldType(this); } @Override public String typeName() { return CONTENT_TYPE; } @Override public Long nullValue() { return (Long)super.nullValue(); } @Override public BytesRef indexedValueForSearch(Object value) { BytesRefBuilder bytesRef = new BytesRefBuilder(); LegacyNumericUtils.longToPrefixCoded(parseLongValue(value), 0, bytesRef); // 0 because of exact match return bytesRef.get(); } @Override public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, QueryShardContext context) { return LegacyNumericRangeQuery.newLongRange(name(), numericPrecisionStep(), lowerTerm == null ? null : parseLongValue(lowerTerm), upperTerm == null ? null : parseLongValue(upperTerm), includeLower, includeUpper); } @Override public FieldStats stats(IndexReader reader) throws IOException { int maxDoc = reader.maxDoc(); FieldInfo fi = org.apache.lucene.index.MultiFields.getMergedFieldInfos(reader).fieldInfo(name()); if (fi == null) { return null; } Terms terms = org.apache.lucene.index.MultiFields.getTerms(reader, name()); if (terms == null) { return new FieldStats.Long(maxDoc, 0, -1, -1, isSearchable(), isAggregatable()); } long minValue = LegacyNumericUtils.getMinLong(terms); long maxValue = LegacyNumericUtils.getMaxLong(terms); return new FieldStats.Long( maxDoc, terms.getDocCount(), terms.getSumDocFreq(), terms.getSumTotalTermFreq(), isSearchable(), isAggregatable(), minValue, maxValue); } @Override public IndexFieldData.Builder fielddataBuilder() { failIfNoDocValues(); return new DocValuesIndexFieldData.Builder().numericType(NumericType.LONG); } } protected LegacyLongFieldMapper(String simpleName, MappedFieldType fieldType, MappedFieldType defaultFieldType, Explicit<Boolean> ignoreMalformed, Explicit<Boolean> coerce, Boolean includeInAll, Settings indexSettings, MultiFields multiFields, CopyTo copyTo) { super(simpleName, fieldType, defaultFieldType, ignoreMalformed, coerce, includeInAll, indexSettings, multiFields, copyTo); } @Override public LongFieldType fieldType() { return (LongFieldType) super.fieldType(); } @Override protected boolean customBoost() { return true; } @Override protected void innerParseCreateField(ParseContext context, List<IndexableField> fields) throws IOException { long value; float boost = fieldType().boost(); if (context.externalValueSet()) { Object externalValue = context.externalValue(); if (externalValue == null) { if (fieldType().nullValue() == null) { return; } value = fieldType().nullValue(); } else if (externalValue instanceof String) { String sExternalValue = (String) externalValue; if (sExternalValue.length() == 0) { if (fieldType().nullValue() == null) { return; } value = fieldType().nullValue(); } else { value = Long.parseLong(sExternalValue); } } else { value = ((Number) externalValue).longValue(); } if (context.includeInAll(includeInAll, this)) { context.allEntries().addText(fieldType().name(), Long.toString(value), boost); } } else { XContentParser parser = context.parser(); if (parser.currentToken() == XContentParser.Token.VALUE_NULL || (parser.currentToken() == XContentParser.Token.VALUE_STRING && parser.textLength() == 0)) { if (fieldType().nullValue() == null) { return; } value = fieldType().nullValue(); if (fieldType().nullValueAsString() != null && (context.includeInAll(includeInAll, this))) { context.allEntries().addText(fieldType().name(), fieldType().nullValueAsString(), boost); } } else if (parser.currentToken() == XContentParser.Token.START_OBJECT && Version.indexCreated(context.indexSettings()).before(Version.V_5_0_0_alpha1)) { XContentParser.Token token; String currentFieldName = null; Long objValue = fieldType().nullValue(); while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else { if ("value".equals(currentFieldName) || "_value".equals(currentFieldName)) { if (parser.currentToken() != XContentParser.Token.VALUE_NULL) { objValue = parser.longValue(coerce.value()); } } else if ("boost".equals(currentFieldName) || "_boost".equals(currentFieldName)) { boost = parser.floatValue(); } else { throw new IllegalArgumentException("unknown property [" + currentFieldName + "]"); } } } if (objValue == null) { // no value return; } value = objValue; } else { value = parser.longValue(coerce.value()); if (context.includeInAll(includeInAll, this)) { context.allEntries().addText(fieldType().name(), parser.text(), boost); } } } if (fieldType().indexOptions() != IndexOptions.NONE || fieldType().stored()) { CustomLongNumericField field = new CustomLongNumericField(value, fieldType()); if (boost != 1f && Version.indexCreated(context.indexSettings()).before(Version.V_5_0_0_alpha1)) { field.setBoost(boost); } fields.add(field); } if (fieldType().hasDocValues()) { addDocValue(context, fields, value); } } @Override protected String contentType() { return CONTENT_TYPE; } @Override protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException { super.doXContentBody(builder, includeDefaults, params); if (includeDefaults || fieldType().numericPrecisionStep() != Defaults.PRECISION_STEP_64_BIT) { builder.field("precision_step", fieldType().numericPrecisionStep()); } if (includeDefaults || fieldType().nullValue() != null) { builder.field("null_value", fieldType().nullValue()); } if (includeInAll != null) { builder.field("include_in_all", includeInAll); } else if (includeDefaults) { builder.field("include_in_all", false); } } public static class CustomLongNumericField extends CustomNumericField { private final long number; public CustomLongNumericField(long number, MappedFieldType fieldType) { super(number, fieldType); this.number = number; } @Override public TokenStream tokenStream(Analyzer analyzer, TokenStream previous) { if (fieldType().indexOptions() != IndexOptions.NONE) { return getCachedStream().setLongValue(number); } return null; } @Override public String numericAsString() { return Long.toString(number); } } @Override public String cqlType() { return "bigint"; } }
apache-2.0
sabob/jock
rivets-examples/src/js/lib/spar/ractive/create.js
626
define(function (require) { var $ = require("jquery"); function create(options) { var that = {}; var ractiveFn = options.ractiveFn; var ractive = new ractiveFn({ el: options.target, oncomplete: function () { console.log("oncomplete"); this.transitionsEnabled = true; }, onrender: function () { console.log("onrender"); }, onteardown: function () { console.log("onteardown"); } }); return ractive; } return create; });
apache-2.0
amplab/succinct
core/src/main/java/edu/berkeley/cs/succinct/util/SuccinctConfiguration.java
1108
package edu.berkeley.cs.succinct.util; public class SuccinctConfiguration { private int saSamplingRate; private int isaSamplingRate; private int npaSamplingRate; public SuccinctConfiguration(int saSamplingRate, int isaSamplingRate, int npaSamplingRate) { this.saSamplingRate = saSamplingRate; this.isaSamplingRate = isaSamplingRate; this.npaSamplingRate = npaSamplingRate; } public SuccinctConfiguration() { this(SuccinctConstants.DEFAULT_SA_SAMPLING_RATE, SuccinctConstants.DEFAULT_ISA_SAMPLING_RATE, SuccinctConstants.DEFAULT_NPA_SAMPLING_RATE); } public int getSaSamplingRate() { return saSamplingRate; } public void setSaSamplingRate(int saSamplingRate) { this.saSamplingRate = saSamplingRate; } public int getIsaSamplingRate() { return isaSamplingRate; } public void setIsaSamplingRate(int isaSamplingRate) { this.isaSamplingRate = isaSamplingRate; } public int getNpaSamplingRate() { return npaSamplingRate; } public void setNpaSamplingRate(int npaSamplingRate) { this.npaSamplingRate = npaSamplingRate; } }
apache-2.0
jarvan4dev/nodejs-crawler
service/async-test.js
595
/** * Created by jarvan4dev on 2017/2/28. */ var async = require('async'); var arr = [{name:'Jack', delay: 20000}, {name:'Mike', delay: 10000}, {name:'Freewind', delay: 30000}]; /** * 所有操作并发执行,且全部未出错,最终得到的err为undefined。注意最终callback只有一个参数err。 */ // 1.1 async.each(arr, function(item, callback) { console.log('1.1 enter: ' + item.name); setTimeout(function(){ console.log('1.1 handle: ' + item.name); callback(); }, item.delay); }, function(err) { console.log('1.1 err: ' + err); });
apache-2.0
mikkokar/styx
components/proxy/src/main/java/com/hotels/styx/routing/interceptors/RewriteInterceptor.java
2832
/* Copyright (C) 2013-2019 Expedia Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.hotels.styx.routing.interceptors; import com.google.common.collect.ImmutableList; import com.hotels.styx.api.Eventual; import com.hotels.styx.api.HttpInterceptor; import com.hotels.styx.api.LiveHttpRequest; import com.hotels.styx.api.LiveHttpResponse; import com.hotels.styx.api.extension.service.RewriteConfig; import com.hotels.styx.api.extension.service.RewriteRule; import com.hotels.styx.client.RewriteRuleset; import com.hotels.styx.config.schema.Schema; import com.hotels.styx.infrastructure.configuration.yaml.JsonNodeConfig; import com.hotels.styx.routing.config.HttpInterceptorFactory; import com.hotels.styx.routing.config.StyxObjectDefinition; import static com.hotels.styx.config.schema.SchemaDsl.field; import static com.hotels.styx.config.schema.SchemaDsl.list; import static com.hotels.styx.config.schema.SchemaDsl.object; import static com.hotels.styx.config.schema.SchemaDsl.string; /** * A built-in interceptor for URL rewrite. */ public class RewriteInterceptor implements HttpInterceptor { public static final Schema.FieldType SCHEMA = list( object( field("urlPattern", string()), field("replacement", string()) )); private final RewriteRuleset rewriteRuleset; private RewriteInterceptor(RewriteRuleset rewriteRuleset) { this.rewriteRuleset = rewriteRuleset; } @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { return chain.proceed(this.rewriteRuleset.rewrite(request)); } /** * A factory for built-in interceptors. */ public static class Factory implements HttpInterceptorFactory { @Override public HttpInterceptor build(StyxObjectDefinition configBlock) { ImmutableList.Builder<RewriteRule> rules = ImmutableList.builder(); configBlock.config().iterator().forEachRemaining( node -> { RewriteConfig rewriteConfig = new JsonNodeConfig(node).as(RewriteConfig.class); rules.add(rewriteConfig); } ); return new RewriteInterceptor(new RewriteRuleset(rules.build())); } } }
apache-2.0
mindie/Cindy
src/main/java/co/mindie/cindy/hibernate/criterions/FulltextSearch.java
2589
///////////////////////////////////////////////// // Project : WSFramework // Package : co.mindie.wsframework.criterions // FulltextSearch.java // // Author : Simon CORSIN <[email protected]> // File created on Mar 26, 2014 at 5:57:57 PM //////// package co.mindie.cindy.hibernate.criterions; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.criterion.CriteriaQuery; import org.hibernate.criterion.Criterion; import org.hibernate.engine.spi.TypedValue; public class FulltextSearch implements Criterion { //////////////////////// // VARIABLES //////////////// private static final long serialVersionUID = -7841457214173304285L; private String propertyName; private String searchText; private FulltextSearchMode searchMode; //////////////////////// // CONSTRUCTORS //////////////// public FulltextSearch(String propertyName, String searchText) { this(propertyName, searchText, FulltextSearchMode.NATURAL_LANGUAGE); } public FulltextSearch(String propertyName, String searchText, FulltextSearchMode searchMode) { if (propertyName == null) { throw new IllegalArgumentException("column"); } if (searchText == null) { throw new IllegalArgumentException("searchText"); } if (searchMode == null) { throw new IllegalArgumentException("searchMode"); } this.propertyName = propertyName; this.searchText = searchText; this.searchMode = searchMode; } //////////////////////// // METHODS //////////////// @Override public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { String[] columns = criteriaQuery.findColumns(propertyName, criteria); if (columns.length != 1) { throw new HibernateException("FulltextSearch may only be used with single-column properties"); } String searchModeStr = null; switch (this.searchMode) { case BOOLEAN: searchModeStr = "BOOLEAN"; break; case NATURAL_LANGUAGE: searchModeStr = "NATURAL_LANGUAGE"; break; default: throw new HibernateException("Null SearchMode set"); } String columnsStr = columns[0]; for (int i = 1; i < columns.length; i++) { columnsStr += ", " + columns[i]; } return "match (" + columnsStr + ") against (? IN " + searchModeStr + " MODE)"; } @Override public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { return new TypedValue[]{ criteriaQuery.getTypedValue(criteria, propertyName, this.searchText) }; } //////////////////////// // GETTERS/SETTERS //////////////// }
apache-2.0
JetstormEnterprise/pkmn
PknTry/src/Jetstorm/Enterprise/Entities/Pokemon/Drowzee.java
960
package Jetstorm.Enterprise.Entities.Pokemon; public class Drowzee extends Pokemon { public Drowzee(int startingLevel) { species = "DROWZEE"; nickname = "DROWZEE"; typeOne = 13; // psychic typeTwo = 18; // none pkmNumber = 96; abilityOne = 1; // insomnia or forewarn hiddenAbility = 1; // inner focus friendship = 70; bodyStyle = 12; // 12? human like pokemonColor = 3; // yellow eggGroup = 8; // human-like secondEggGroup = 18; // none height = 1.0; // meters standard weight = 32.4; // kg standard hatchTime = 5355; // Lowest levelStyle = "Medium Fast"; baseExpYield = 102; EVYield[0] = 0; EVYield[1] = 0; EVYield[2] = 0; EVYield[3] = 0; EVYield[4] = 1; EVYield[5] = 0; genderRatio = 0.5; catchRate = 190; baseHealth = 60; baseAttack = 48; baseDefense = 45; baseSpAttack = 43; baseSpDefense = 90; baseSpeed = 42; super.init(startingLevel); } }
apache-2.0
tlong2/amphtml
extensions/amp-analytics/0.1/vendors.js
13472
/** * Copyright 2015 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { IFRAME_TRANSPORTS, IFRAME_TRANSPORTS_CANARY, } from './iframe-transport-vendors'; import {getMode} from '../../../src/mode'; import {hasOwn} from '../../../src/utils/object'; import { includeJsonLiteral, jsonConfiguration, jsonLiteral, } from '../../../src/json'; import {isCanary} from '../../../src/experiments'; import {ACQUIALIFT_CONFIG} from './vendors/acquialift'; import {ADOBEANALYTICS_CONFIG} from './vendors/adobeanalytics'; import {ADOBEANALYTICS_NATIVECONFIG_CONFIG} from './vendors/adobeanalytics_nativeConfig'; import {AFSANALYTICS_CONFIG} from './vendors/afsanalytics'; import {ALEXAMETRICS_CONFIG} from './vendors/alexametrics'; import {AMPLITUDE_CONFIG} from './vendors/amplitude'; import {ATINTERNET_CONFIG} from './vendors/atinternet'; import {BAIDUANALYTICS_CONFIG} from './vendors/baiduanalytics'; import {BG_CONFIG} from './vendors/bg'; import {BURT_CONFIG} from './vendors/burt'; import {BYSIDE_CONFIG} from './vendors/byside'; import {CHARTBEAT_CONFIG} from './vendors/chartbeat'; import {CLICKY_CONFIG} from './vendors/clicky'; import {COLANALYTICS_CONFIG} from './vendors/colanalytics'; import {COMSCORE_CONFIG} from './vendors/comscore'; import {CXENSE_CONFIG} from './vendors/cxense'; import {DEEPBI_CONFIG} from './vendors/deepbi'; import {DYNATRACE_CONFIG} from './vendors/dynatrace'; import {EPICA_CONFIG} from './vendors/epica'; import {EULERIANANALYTICS_CONFIG} from './vendors/euleriananalytics'; import {FACEBOOKPIXEL_CONFIG} from './vendors/facebookpixel'; import {GEMIUS_CONFIG} from './vendors/gemius'; import {GOOGLEADWORDS_CONFIG} from './vendors/googleadwords'; import {GOOGLEANALYTICS_CONFIG} from './vendors/googleanalytics'; import {GTAG_CONFIG} from './vendors/gtag'; import {IBEATANALYTICS_CONFIG} from './vendors/ibeatanalytics'; import {INFONLINE_CONFIG} from './vendors/infonline'; import {IPLABEL_CONFIG} from './vendors/iplabel'; import {KEEN_CONFIG} from './vendors/keen'; import {KENSHOO_CONFIG} from './vendors/kenshoo'; import {KRUX_CONFIG} from './vendors/krux'; import {LINKPULSE_CONFIG} from './vendors/linkpulse'; import {LOTAME_CONFIG} from './vendors/lotame'; import {MARINSOFTWARE_CONFIG} from './vendors/marinsoftware'; import {MEDIAMETRIE_CONFIG} from './vendors/mediametrie'; import {MEDIARITHMICS_CONFIG} from './vendors/mediarithmics'; import {MEDIATOR_CONFIG} from './vendors/mediator'; import {MEMO_CONFIG} from './vendors/memo'; import {METRIKA_CONFIG} from './vendors/metrika'; import {MOAT_CONFIG} from './vendors/moat'; import {MOBIFY_CONFIG} from './vendors/mobify'; import {MPARTICLE_CONFIG} from './vendors/mparticle'; import {MPULSE_CONFIG} from './vendors/mpulse'; import {NAVEGG_CONFIG} from './vendors/navegg'; import {NEWRELIC_CONFIG} from './vendors/newrelic'; import {NIELSEN_CONFIG} from './vendors/nielsen'; import {NIELSEN_MARKETING_CLOUD_CONFIG} from './vendors/nielsen-marketing-cloud'; import {OEWADIRECT_CONFIG} from './vendors/oewadirect'; import {OEWA_CONFIG} from './vendors/oewa'; import {ORACLEINFINITYANALYTICS_CONFIG} from './vendors/oracleInfinityAnalytics'; import {PARSELY_CONFIG} from './vendors/parsely'; import {PERMUTIVE_CONFIG} from './vendors/permutive'; import {PIANO_CONFIG} from './vendors/piano'; import {PINPOLL_CONFIG} from './vendors/pinpoll'; import {PISTATS_CONFIG} from './vendors/piStats'; import {PRESSBOARD_CONFIG} from './vendors/pressboard'; import {QUANTCAST_CONFIG} from './vendors/quantcast'; import {RAKAM_CONFIG} from './vendors/rakam'; import {REPPUBLIKA_CONFIG} from './vendors/reppublika'; import {RETARGETLY_CONFIG} from './vendors/retargetly'; import {SEGMENT_CONFIG} from './vendors/segment'; import {SHINYSTAT_CONFIG} from './vendors/shinystat'; import {SIMPLEREACH_CONFIG} from './vendors/simplereach'; import {SNOWPLOW_CONFIG} from './vendors/snowplow'; import {SNOWPLOW_V2_CONFIG} from './vendors/snowplow_v2'; import {TEAANALYTICS_CONFIG} from './vendors/teaanalytics'; import {TEALIUMCOLLECT_CONFIG} from './vendors/tealiumcollect'; import {TOP100_CONFIG} from './vendors/top100'; import {TOPMAILRU_CONFIG} from './vendors/topmailru'; import {TREASUREDATA_CONFIG} from './vendors/treasuredata'; import {UMENGANALYTICS_CONFIG} from './vendors/umenganalytics'; import {UPSCORE_CONFIG} from './vendors/upscore'; import {VPONANALYTICS_CONFIG} from './vendors/vponanalytics'; import {WEBENGAGE_CONFIG} from './vendors/webengage'; import {WEBTREKK_CONFIG} from './vendors/webtrekk'; import {WEBTREKK_V2_CONFIG} from './vendors/webtrekk_v2'; import {_FAKE_} from './vendors/_fake_.js'; const DEFAULT_CONFIG = jsonLiteral({ 'transport': {'beacon': true, 'xhrpost': true, 'image': true}, 'vars': { 'accessReaderId': 'ACCESS_READER_ID', 'ampdocHost': 'AMPDOC_HOST', 'ampdocHostname': 'AMPDOC_HOSTNAME', 'ampdocUrl': 'AMPDOC_URL', 'ampGeo': 'AMP_GEO', 'ampState': 'AMP_STATE', 'ampVersion': 'AMP_VERSION', 'ancestorOrigin': 'ANCESTOR_ORIGIN', 'authdata': 'AUTHDATA', 'availableScreenHeight': 'AVAILABLE_SCREEN_HEIGHT', 'availableScreenWidth': 'AVAILABLE_SCREEN_WIDTH', 'backgroundState': 'BACKGROUND_STATE', 'browserLanguage': 'BROWSER_LANGUAGE', 'canonicalHost': 'CANONICAL_HOST', 'canonicalHostname': 'CANONICAL_HOSTNAME', 'canonicalPath': 'CANONICAL_PATH', 'canonicalUrl': 'CANONICAL_URL', 'clientId': 'CLIENT_ID', 'consentState': 'CONSENT_STATE', 'contentLoadTime': 'CONTENT_LOAD_TIME', 'cookie': 'COOKIE', 'counter': 'COUNTER', 'documentCharset': 'DOCUMENT_CHARSET', 'documentReferrer': 'DOCUMENT_REFERRER', 'domainLookupTime': 'DOMAIN_LOOKUP_TIME', 'domInteractiveTime': 'DOM_INTERACTIVE_TIME', 'externalReferrer': 'EXTERNAL_REFERRER', 'firstContentfulPaint': 'FIRST_CONTENTFUL_PAINT', 'firstViewportReady': 'FIRST_VIEWPORT_READY', 'fragmentParam': 'FRAGMENT_PARAM', 'makeBodyVisible': 'MAKE_BODY_VISIBLE', 'htmlAttr': 'HTML_ATTR', 'incrementalEngagedTime': 'INCREMENTAL_ENGAGED_TIME', 'navRedirectCount': 'NAV_REDIRECT_COUNT', 'navTiming': 'NAV_TIMING', 'navType': 'NAV_TYPE', 'pageDownloadTime': 'PAGE_DOWNLOAD_TIME', 'pageLoadTime': 'PAGE_LOAD_TIME', 'pageViewId': 'PAGE_VIEW_ID', 'queryParam': 'QUERY_PARAM', 'random': 'RANDOM', 'redirectTime': 'REDIRECT_TIME', 'resourceTiming': 'RESOURCE_TIMING', 'screenColorDepth': 'SCREEN_COLOR_DEPTH', 'screenHeight': 'SCREEN_HEIGHT', 'screenWidth': 'SCREEN_WIDTH', 'scrollHeight': 'SCROLL_HEIGHT', 'scrollLeft': 'SCROLL_LEFT', 'scrollTop': 'SCROLL_TOP', 'scrollWidth': 'SCROLL_WIDTH', 'serverResponseTime': 'SERVER_RESPONSE_TIME', 'sourceUrl': 'SOURCE_URL', 'sourceHost': 'SOURCE_HOST', 'sourceHostname': 'SOURCE_HOSTNAME', 'sourcePath': 'SOURCE_PATH', 'tcpConnectTime': 'TCP_CONNECT_TIME', 'timestamp': 'TIMESTAMP', 'timezone': 'TIMEZONE', 'timezoneCode': 'TIMEZONE_CODE', 'title': 'TITLE', 'totalEngagedTime': 'TOTAL_ENGAGED_TIME', 'userAgent': 'USER_AGENT', 'viewer': 'VIEWER', 'viewportHeight': 'VIEWPORT_HEIGHT', 'viewportWidth': 'VIEWPORT_WIDTH', }, }); /** * @const {!JsonObject} */ export const ANALYTICS_CONFIG = ANALYTICS_VENDOR_SPLIT ? jsonConfiguration({'default': includeJsonLiteral(DEFAULT_CONFIG)}) : jsonConfiguration({ // Default parent configuration applied to all amp-analytics tags. 'default': includeJsonLiteral(DEFAULT_CONFIG), 'acquialift': includeJsonLiteral(ACQUIALIFT_CONFIG), 'adobeanalytics': includeJsonLiteral(ADOBEANALYTICS_CONFIG), 'adobeanalytics_nativeConfig': includeJsonLiteral( ADOBEANALYTICS_NATIVECONFIG_CONFIG ), 'afsanalytics': includeJsonLiteral(AFSANALYTICS_CONFIG), 'alexametrics': includeJsonLiteral(ALEXAMETRICS_CONFIG), 'amplitude': includeJsonLiteral(AMPLITUDE_CONFIG), 'atinternet': includeJsonLiteral(ATINTERNET_CONFIG), 'baiduanalytics': includeJsonLiteral(BAIDUANALYTICS_CONFIG), 'bg': includeJsonLiteral(BG_CONFIG), 'burt': includeJsonLiteral(BURT_CONFIG), 'byside': includeJsonLiteral(BYSIDE_CONFIG), 'chartbeat': includeJsonLiteral(CHARTBEAT_CONFIG), 'clicky': includeJsonLiteral(CLICKY_CONFIG), 'colanalytics': includeJsonLiteral(COLANALYTICS_CONFIG), 'comscore': includeJsonLiteral(COMSCORE_CONFIG), 'cxense': includeJsonLiteral(CXENSE_CONFIG), 'deepbi': includeJsonLiteral(DEEPBI_CONFIG), 'dynatrace': includeJsonLiteral(DYNATRACE_CONFIG), 'epica': includeJsonLiteral(EPICA_CONFIG), 'euleriananalytics': includeJsonLiteral(EULERIANANALYTICS_CONFIG), 'facebookpixel': includeJsonLiteral(FACEBOOKPIXEL_CONFIG), 'gemius': includeJsonLiteral(GEMIUS_CONFIG), 'googleadwords': includeJsonLiteral(GOOGLEADWORDS_CONFIG), 'googleanalytics': includeJsonLiteral(GOOGLEANALYTICS_CONFIG), 'gtag': includeJsonLiteral(GTAG_CONFIG), 'ibeatanalytics': includeJsonLiteral(IBEATANALYTICS_CONFIG), 'infonline': includeJsonLiteral(INFONLINE_CONFIG), 'iplabel': includeJsonLiteral(IPLABEL_CONFIG), 'keen': includeJsonLiteral(KEEN_CONFIG), 'kenshoo': includeJsonLiteral(KENSHOO_CONFIG), 'krux': includeJsonLiteral(KRUX_CONFIG), 'linkpulse': includeJsonLiteral(LINKPULSE_CONFIG), 'lotame': includeJsonLiteral(LOTAME_CONFIG), 'marinsoftware': includeJsonLiteral(MARINSOFTWARE_CONFIG), 'mediametrie': includeJsonLiteral(MEDIAMETRIE_CONFIG), 'mediarithmics': includeJsonLiteral(MEDIARITHMICS_CONFIG), 'mediator': includeJsonLiteral(MEDIATOR_CONFIG), 'memo': includeJsonLiteral(MEMO_CONFIG), 'metrika': includeJsonLiteral(METRIKA_CONFIG), 'moat': includeJsonLiteral(MOAT_CONFIG), 'mobify': includeJsonLiteral(MOBIFY_CONFIG), 'mparticle': includeJsonLiteral(MPARTICLE_CONFIG), 'mpulse': includeJsonLiteral(MPULSE_CONFIG), 'navegg': includeJsonLiteral(NAVEGG_CONFIG), 'newrelic': includeJsonLiteral(NEWRELIC_CONFIG), 'nielsen': includeJsonLiteral(NIELSEN_CONFIG), 'nielsen-marketing-cloud': includeJsonLiteral( NIELSEN_MARKETING_CLOUD_CONFIG ), 'oewa': includeJsonLiteral(OEWA_CONFIG), 'oewadirect': includeJsonLiteral(OEWADIRECT_CONFIG), 'oracleInfinityAnalytics': includeJsonLiteral( ORACLEINFINITYANALYTICS_CONFIG ), 'parsely': includeJsonLiteral(PARSELY_CONFIG), 'piStats': includeJsonLiteral(PISTATS_CONFIG), 'permutive': includeJsonLiteral(PERMUTIVE_CONFIG), 'piano': includeJsonLiteral(PIANO_CONFIG), 'pinpoll': includeJsonLiteral(PINPOLL_CONFIG), 'pressboard': includeJsonLiteral(PRESSBOARD_CONFIG), 'quantcast': includeJsonLiteral(QUANTCAST_CONFIG), 'retargetly': includeJsonLiteral(RETARGETLY_CONFIG), 'rakam': includeJsonLiteral(RAKAM_CONFIG), 'reppublika': includeJsonLiteral(REPPUBLIKA_CONFIG), 'segment': includeJsonLiteral(SEGMENT_CONFIG), 'shinystat': includeJsonLiteral(SHINYSTAT_CONFIG), 'simplereach': includeJsonLiteral(SIMPLEREACH_CONFIG), 'snowplow': includeJsonLiteral(SNOWPLOW_CONFIG), 'snowplow_v2': includeJsonLiteral(SNOWPLOW_V2_CONFIG), 'teaanalytics': includeJsonLiteral(TEAANALYTICS_CONFIG), 'tealiumcollect': includeJsonLiteral(TEALIUMCOLLECT_CONFIG), 'top100': includeJsonLiteral(TOP100_CONFIG), 'topmailru': includeJsonLiteral(TOPMAILRU_CONFIG), 'treasuredata': includeJsonLiteral(TREASUREDATA_CONFIG), 'umenganalytics': includeJsonLiteral(UMENGANALYTICS_CONFIG), 'upscore': includeJsonLiteral(UPSCORE_CONFIG), 'vponanalytics': includeJsonLiteral(VPONANALYTICS_CONFIG), 'webengage': includeJsonLiteral(WEBENGAGE_CONFIG), 'webtrekk': includeJsonLiteral(WEBTREKK_CONFIG), 'webtrekk_v2': includeJsonLiteral(WEBTREKK_V2_CONFIG), }); if (!ANALYTICS_VENDOR_SPLIT) { if (getMode().test || getMode().localDev) { ANALYTICS_CONFIG['_fake_'] = _FAKE_; } ANALYTICS_CONFIG['infonline']['triggers']['pageview']['iframePing'] = true; ANALYTICS_CONFIG['adobeanalytics_nativeConfig']['triggers']['pageLoad'][ 'iframePing' ] = true; ANALYTICS_CONFIG['oewa']['triggers']['pageview']['iframePing'] = true; mergeIframeTransportConfig( ANALYTICS_CONFIG, isCanary(self) ? IFRAME_TRANSPORTS_CANARY : IFRAME_TRANSPORTS ); } /** * Merges iframe transport config. * * @param {!JsonObject} config * @param {!JsonObject} iframeTransportConfig */ function mergeIframeTransportConfig(config, iframeTransportConfig) { for (const vendor in iframeTransportConfig) { if (hasOwn(iframeTransportConfig, vendor)) { const url = iframeTransportConfig[vendor]; config[vendor]['transport'] = { ...config[vendor]['transport'], 'iframe': url, }; } } }
apache-2.0
markymarkmk2/VSMServer
src/de/dimm/vsm/preview/RecursiveRenderJob.java
7645
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.dimm.vsm.preview; import de.dimm.vsm.Exceptions.PathResolveException; import de.dimm.vsm.GeneralPreferences; import de.dimm.vsm.Main; import de.dimm.vsm.auth.User; import de.dimm.vsm.fsengine.StorageNodeHandler; import de.dimm.vsm.fsengine.StoragePoolHandler; import de.dimm.vsm.fsengine.VSMInputStream; import de.dimm.vsm.hash.StringUtils; import de.dimm.vsm.jobs.InteractionEntry; import de.dimm.vsm.jobs.JobInterface; import de.dimm.vsm.log.Log; import static de.dimm.vsm.preview.PreviewReader.getPreviewRoot; import de.dimm.vsm.preview.imagemagick.PreviewRenderer; import de.dimm.vsm.preview.imagemagick.RenderFactory; import de.dimm.vsm.records.AbstractStorageNode; import de.dimm.vsm.records.FileSystemElemNode; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Properties; import org.im4java.core.CommandException; /** * * @author Administrator */ public class RecursiveRenderJob implements IRenderJob, JobInterface{ StoragePoolHandler sp_handler; FileSystemElemNode rootNode; Properties props; String actStatus; long filesDone = 0; long filesRendered = 0; boolean abort; public RecursiveRenderJob( StoragePoolHandler sp_handler, FileSystemElemNode node, Properties props ) { this.sp_handler = sp_handler; this.rootNode = node; this.props = props; } @Override public void setAbort( boolean abort ) { this.abort = abort; state = JOBSTATE.ABORTING; } @Override public boolean isAbort() { return abort; } @Override public void render() { state = JOBSTATE.RUNNING; try { render(rootNode); state = isAbort() ? JOBSTATE.ABORTED : JOBSTATE.FINISHED_OK_REMOVE; } catch (IOException exception) { state = JOBSTATE.ABORTED; actStatus = "Abbruch in recursive render:" + exception.getMessage(); Log.err(actStatus, exception); } } public void render(FileSystemElemNode node) throws IOException { if (node.isDirectory()) { renderDir(node); } else { renderFile(node); } } void renderDir(FileSystemElemNode node ) throws IOException { List<FileSystemElemNode> children = node.getChildren(sp_handler.getEm()); for (FileSystemElemNode child : children) { if (isAbort()) { break; } render(child); } } private boolean isPropTrue( String key ) { if (props == null) return false; String val = props.getProperty(key, IPreviewData.FALSE ); return val.equals( IPreviewData.TRUE); } void renderFile(FileSystemElemNode node) throws IOException { String suffix = PreviewRenderer.getSuffix(node.getName()); IRenderer renderer = RenderFactory.getRenderer(suffix); filesDone++; File imageFile = getOutFile(node); // Delete Only if (isPropTrue(IPreviewData.DELETE)) { if (imageFile.exists()) { imageFile.delete(); } return; } if (imageFile.exists()) { return; } actStatus = "Rendere " + node.getName() + "..."; try (InputStream fis = new VSMInputStream(sp_handler, node)) { renderer.render(suffix, fis, imageFile); filesRendered++; } catch (SQLException exception) { actStatus = Main.Txt("DB-Fehler beim Generieren der Preview von Datei ") + node.getName() + " " + exception.getMessage(); Log.err(actStatus, exception); throw new IOException(actStatus); } catch (IOException exception) { actStatus = Main.Txt("IO-Fehler beim Generieren der Preview von Datei ") + node.getName() + " " + exception.getMessage(); Log.err(actStatus, exception); throw new IOException(actStatus); } catch (CommandException exception) { actStatus = sp_handler.buildCheckOpenNodeErrText(node); if (StringUtils.isEmpty(actStatus)) { actStatus = node.getName() + " " + exception.getMessage(); } Log.warn(actStatus); } catch (Exception exception) { actStatus = Main.Txt("Fehler beim Generieren der Preview von Datei ") + node.getName() + " " + exception.getMessage(); Log.err(actStatus, exception); throw new IOException(actStatus); } } private File getOutFile( FileSystemElemNode node ) throws IOException { StringBuilder sb = new StringBuilder(); String previewRoot = getPreviewRoot(sp_handler); if (previewRoot == null) { AbstractStorageNode snode = sp_handler.get_primary_dedup_node_for_write(); if (snode != null) { previewRoot = snode.getMountPoint(); } } File outFile = null; try { if (previewRoot != null) { StorageNodeHandler.build_preview_path(node, node.getAttributes(), sb); outFile = new File (previewRoot, sb.toString()); } else { // Kein persistenter PreviewRoot? // Dann kann auch nichts dauerhaft gespeichert werden throw new IOException("Kein PreviewRoot eingerichtet"); } if (!outFile.getParentFile().exists()) { outFile.getParentFile().mkdirs(); } } catch (PathResolveException exc ) { actStatus = "Fehler beim Erzeugen des Previewpfades"; throw new IOException(actStatus , exc); } return outFile; } JOBSTATE state; Date startTime = new Date(); @Override public JOBSTATE getJobState() { return state; } @Override public void setJobState( JOBSTATE jOBSTATE ) { state = jOBSTATE; } @Override public InteractionEntry getInteractionEntry() { return null; } @Override public String getStatusStr() { return actStatus; } @Override public String getStatisticStr() { return "Files done: " + filesDone + " files rendered: " + filesRendered; } @Override public Date getStartTime() { return startTime; } @Override public Object getResultData() { return null; } @Override public String getProcessPercent() { return ""; } @Override public String getProcessPercentDimension() { return ""; } @Override public void abortJob() { setAbort(true); } @Override public void run() { render(); } @Override public User getUser() { return null; } @Override public void close() { } }
apache-2.0
NessComputing/components-ness-sequencer
src/main/java/com/nesscomputing/sequencer/ImmutableSequencerImpl.java
3981
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.sequencer; import java.io.ObjectStreamException; import java.io.Serializable; import javax.annotation.Nonnull; import javax.annotation.concurrent.Immutable; import com.fasterxml.jackson.annotation.JsonCreator; import com.google.common.collect.Iterables; import gnu.trove.map.TObjectIntMap; import gnu.trove.map.hash.TObjectIntHashMap; /** * A Sequencer that is initialized upon construction and may never * change afterward. */ @Immutable class ImmutableSequencerImpl<K> extends ImmutableSequencer<K> { private static final long serialVersionUID = 1L; private static final float LOAD_FACTOR = 0.5f; private final TObjectIntMap<K> forward; private final K[] reverse; @SuppressWarnings("unchecked") ImmutableSequencerImpl() { forward = new TObjectIntHashMap<>(0, LOAD_FACTOR, -1); reverse = (K[]) new Object[0]; } @SuppressWarnings("unchecked") @JsonCreator ImmutableSequencerImpl(Iterable<K> elements) { final int size = Iterables.size(elements); forward = new TObjectIntHashMap<>(size, LOAD_FACTOR, -1); reverse = (K[]) new Object[size]; int v = 0; for (K k : elements) { forward.put(k, v); reverse[v] = k; v++; } } @SuppressWarnings("unchecked") ImmutableSequencerImpl(Sequencer<K> sequencer) { final int size = sequencer.size(); forward = new TObjectIntHashMap<>(size, LOAD_FACTOR, -1); reverse = (K[]) new Object[size]; for (int v = 0; v < size; v++) { final K k = sequencer.unsequence(v); forward.put(k, v); reverse[v] = k; } } @Nonnull public static <K> ImmutableSequencerImpl<K> copyOf(@Nonnull Sequencer<K> seq) { if (seq instanceof ImmutableSequencerImpl) { return (ImmutableSequencerImpl<K>) seq; } return new ImmutableSequencerImpl<>(seq); } @Override protected int depth() { return 1; } @Override public boolean containsKey(Object key) { return forward.containsKey(key); } @Override public int sequenceIfExists(K key) { assert forward.getNoEntryValue() == -1 : "noEntryValue must be == -1"; return forward.get(key); } @Override public void sequenceExisting(Iterable<K> keys, TObjectIntMap<K> result) { assert forward.getNoEntryValue() == -1 : "noEntryValue must be == -1"; for (K key : keys) { int val = forward.get(key); if (val != forward.getNoEntryValue()) { result.put(key, val); } } } @Override public K unsequence(int index) { return reverse[index]; } @Override public int size() { return forward.size(); } private Object writeReplace() throws ObjectStreamException { return new SerProxy<>(reverse); } private static class SerProxy<K> implements Serializable { private static final long serialVersionUID = 1L; private final K[] arr; SerProxy(K[] arr) { this.arr = arr; } private Object readResolve() throws ObjectStreamException { return ImmutableSequencer.of(arr); } } }
apache-2.0
Fabric3/spring-samples
apps/bigbank/bigbank-loan/src/main/java/org/fabric3/samples/bigbank/services/risk/RiskRequest.java
1520
/* * See the NOTICE file distributed with this work for information * regarding copyright ownership. This file is licensed * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.fabric3.samples.bigbank.services.risk; import java.io.Serializable; /** * @version $Revision$ $Date$ */ public class RiskRequest implements Serializable { private static final long serialVersionUID = -5185791927524383209L; private long id; private int creditScore; private double downPayment; private double amount; public RiskRequest(long id, int creditScore, double amount, double downPayment) { this.id = id; this.creditScore = creditScore; this.amount = amount; this.downPayment = downPayment; } public long getId() { return id; } public int getCreditScore() { return creditScore; } public double getAmount() { return amount; } public double getDownPayment() { return downPayment; } }
apache-2.0
StellarCN/py-stellar-base
stellar_sdk/call_builder/base/base_transactions_call_builder.py
3729
from typing import Union from ...call_builder.base.base_call_builder import BaseCallBuilder from ...type_checked import type_checked __all__ = ["BaseTransactionsCallBuilder"] @type_checked class BaseTransactionsCallBuilder(BaseCallBuilder): """Creates a new :class:`TransactionsCallBuilder` pointed to server defined by horizon_url. See `List All Transactions <https://developers.stellar.org/api/resources/transactions/list/>`__ for more information. :param horizon_url: Horizon server URL. """ def __init__(self, horizon_url: str) -> None: super().__init__(horizon_url) self.endpoint: str = "transactions" def transaction(self, transaction_hash: str): """The transaction details endpoint provides information on a single transaction. The transaction hash provided in the hash argument specifies which transaction to load. See `Retrieve a Transaction <https://developers.stellar.org/api/resources/transactions/single/>`__ for more information. :param transaction_hash: transaction hash :return: current TransactionsCallBuilder instance """ self.endpoint = f"transactions/{transaction_hash}" return self def for_account(self, account_id: str): """This endpoint represents all transactions that affected a given account. See `Retrieve an Account's Transactions <https://developers.stellar.org/api/resources/accounts/transactions/>`__ for more information. :param account_id: account id :return: current TransactionsCallBuilder instance """ self.endpoint = f"accounts/{account_id}/transactions" return self def for_ledger(self, sequence: Union[str, int]): """This endpoint represents all transactions in a given ledger. See `Retrieve a Ledger's Transactions <https://developers.stellar.org/api/resources/ledgers/transactions/>`__ for more information. :param sequence: ledger sequence :return: current TransactionsCallBuilder instance """ self.endpoint = f"ledgers/{sequence}/transactions" return self def for_claimable_balance(self, claimable_balance_id: str): """This endpoint represents all transactions referencing a given claimable balance and can be used in streaming mode. See `Claimable Balances - Retrieve related Transactions <https://developers.stellar.org/api/resources/claimablebalances/transactions/>`__ :param claimable_balance_id: This claimable balance’s id encoded in a hex string representation. :return: current TransactionsCallBuilder instance """ self.endpoint = f"claimable_balances/{claimable_balance_id}/transactions" return self def for_liquidity_pool(self, liquidity_pool_id: str): """This endpoint represents all transactions referencing a given liquidity pool. See `Liquidity Pools - Retrieve related Transactions <https://developers.stellar.org/api/resources/liquiditypools/transactions/>`__ :param liquidity_pool_id: The ID of the liquidity pool in hex string. :return: this TransactionsCallBuilder instance """ self.endpoint = f"liquidity_pools/{liquidity_pool_id}/transactions" return self def include_failed(self, include_failed: bool): """Adds a parameter defining whether to include failed transactions. By default only transactions of successful transactions are returned. :param include_failed: Set to `True` to include failed transactions. :return: current TransactionsCallBuilder instance """ self._add_query_param("include_failed", include_failed) return self
apache-2.0
firebase/snippets-web
auth-next/manage.js
4347
// [SNIPPET_REGISTRY disabled] // [SNIPPETS_SEPARATION enabled] function getUserProfile() { // [START auth_get_user_profile] const { getAuth } = require("firebase/auth"); const auth = getAuth(); const user = auth.currentUser; if (user !== null) { // The user object has basic properties such as display name, email, etc. const displayName = user.displayName; const email = user.email; const photoURL = user.photoURL; const emailVerified = user.emailVerified; // The user's ID, unique to the Firebase project. Do NOT use // this value to authenticate with your backend server, if // you have one. Use User.getToken() instead. const uid = user.uid; } // [END auth_get_user_profile] } function getUserProfileProvider() { // [START auth_get_user_profile_provider] const { getAuth } = require("firebase/auth"); const auth = getAuth(); const user = auth.currentUser; if (user !== null) { user.providerData.forEach((profile) => { console.log("Sign-in provider: " + profile.providerId); console.log(" Provider-specific UID: " + profile.uid); console.log(" Name: " + profile.displayName); console.log(" Email: " + profile.email); console.log(" Photo URL: " + profile.photoURL); }); } // [END auth_get_user_profile_provider] } function updateUserProfile() { // [START auth_update_user_profile] const { getAuth, updateProfile } = require("firebase/auth"); const auth = getAuth(); updateProfile(auth.currentUser, { displayName: "Jane Q. User", photoURL: "https://example.com/jane-q-user/profile.jpg" }).then(() => { // Profile updated! // ... }).catch((error) => { // An error occurred // ... }); // [END auth_update_user_profile] } function updateUserEmail() { // [START auth_update_user_email] const { getAuth, updateEmail } = require("firebase/auth"); const auth = getAuth(); updateEmail(auth.currentUser, "[email protected]").then(() => { // Email updated! // ... }).catch((error) => { // An error occurred // ... }); // [END auth_update_user_email] } function sendEmailVerification() { // [START send_email_verification] const { getAuth, sendEmailVerification } = require("firebase/auth"); const auth = getAuth(); const user = auth.currentUser; sendEmailVerification(user).then(() => { // Email sent. }).catch((error) => { // An error ocurred // ... }); // [END send_email_verification] } function updatePassword() { function getASecureRandomPassword() { return "correcthorsebatterystaple"; } // [START auth_update_password] const { getAuth, updatePassword } = require("firebase/auth"); const auth = getAuth(); const user = auth.currentUser; const newPassword = getASecureRandomPassword(); updatePassword(user, newPassword).then(() => { // Update successful. }).catch((error) => { // An error ocurred // ... }); // [END auth_update_password] } function sendPasswordReset() { // [START auth_send_password_reset] const { getAuth, sendPasswordResetEmail } = require("firebase/auth"); const auth = getAuth(); const emailAddress = "[email protected]"; sendPasswordResetEmail(auth, emailAddress).then(() => { // Email sent. }).catch((error) => { // An error ocurred // ... }); // [END auth_send_password_reset] } function deleteUser() { // [START auth_delete_user] const { getAuth, deleteUser } = require("firebase/auth"); const auth = getAuth(); const user = auth.currentUser; deleteUser(user).then(() => { // User deleted. }).catch((error) => { // An error ocurred // ... }); // [END auth_delete_user] } function reauthenticateWithCredential() { /** * @returns {object} */ function promptForCredentials() { return {}; } // [START auth_reauth_with_credential] const { getAuth, reauthenticateWithCredential } = require("firebase/auth"); const auth = getAuth(); const user = auth.currentUser; // TODO(you): prompt the user to re-provide their sign-in credentials const credential = promptForCredentials(); reauthenticateWithCredential(user, credential).then(() => { // User re-authenticated. }).catch((error) => { // An error ocurred // ... }); // [END auth_reauth_with_credential] }
apache-2.0
ThiagoGarciaAlves/intellij-community
platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsTreeView.java
32766
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.options.newEditor; import com.intellij.icons.AllIcons; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.ide.projectView.PresentationData; import com.intellij.ide.util.treeView.NodeDescriptor; import com.intellij.openapi.Disposable; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.options.*; import com.intellij.openapi.options.ex.ConfigurableWrapper; import com.intellij.openapi.options.ex.SortedConfigurableGroup; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.registry.Registry; import com.intellij.ui.*; import com.intellij.ui.components.GradientViewport; import com.intellij.ui.treeStructure.*; import com.intellij.ui.treeStructure.filtered.FilteringTreeBuilder; import com.intellij.ui.treeStructure.filtered.FilteringTreeStructure; import com.intellij.util.ui.GraphicsUtil; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import com.intellij.util.ui.tree.WideSelectionTreeUI; import com.intellij.util.ui.update.MergingUpdateQueue; import com.intellij.util.ui.update.Update; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.accessibility.Accessible; import javax.accessibility.AccessibleContext; import javax.accessibility.AccessibleRole; import javax.swing.*; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.plaf.TreeUI; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import java.awt.*; import java.awt.datatransfer.Transferable; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.IdentityHashMap; import java.util.List; /** * @author Sergey.Malenkov */ public class SettingsTreeView extends JComponent implements Accessible, Disposable, OptionsEditorColleague { private static final int ICON_GAP = 5; private static final String NODE_ICON = "settings.tree.view.icon"; private static final Color WRONG_CONTENT = JBColor.RED; private static final Color MODIFIED_CONTENT = JBColor.BLUE; public static final Color FOREGROUND = new JBColor(Gray.x1A, Gray.xBB); final SimpleTree myTree; final FilteringTreeBuilder myBuilder; private final SettingsFilter myFilter; private final MyRoot myRoot; private final JScrollPane myScroller; private final IdentityHashMap<Configurable, MyNode> myConfigurableToNodeMap = new IdentityHashMap<>(); private final IdentityHashMap<UnnamedConfigurable, ConfigurableWrapper> myConfigurableToWrapperMap = new IdentityHashMap<>(); private final MergingUpdateQueue myQueue = new MergingUpdateQueue("SettingsTreeView", 150, false, this, this, this) .setRestartTimerOnAdd(true); private Configurable myQueuedConfigurable; private boolean myPaintInternalInfo; public SettingsTreeView(SettingsFilter filter, ConfigurableGroup[] groups) { myFilter = filter; myRoot = new MyRoot(groups); myTree = new MyTree(); myTree.putClientProperty(WideSelectionTreeUI.TREE_TABLE_TREE_KEY, Boolean.TRUE); myTree.setBackground(UIUtil.SIDE_PANEL_BACKGROUND); myTree.getInputMap().clear(); TreeUtil.installActions(myTree); myTree.setOpaque(true); myTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); myTree.setCellRenderer(new MyRenderer()); myTree.setRootVisible(false); myTree.setShowsRootHandles(false); myTree.setExpandableItemsEnabled(false); RelativeFont.BOLD.install(myTree); setComponentPopupMenuTo(myTree); myTree.setTransferHandler(new TransferHandler() { @Nullable @Override protected Transferable createTransferable(JComponent c) { return SettingsTreeView.createTransferable(myTree.getSelectionPath()); } @Override public int getSourceActions(JComponent c) { return COPY; } }); myScroller = ScrollPaneFactory.createScrollPane(null, true); myScroller.setViewport(new GradientViewport(myTree, JBUI.insetsTop(5), true) { private JLabel myHeader; @Override protected Component getHeader() { if (0 == myTree.getY()) { return null; // separator is not needed without scrolling } if (myHeader == null) { myHeader = new JLabel(); myHeader.setForeground(FOREGROUND); myHeader.setIconTextGap(ICON_GAP); myHeader.setBorder(BorderFactory.createEmptyBorder(1, 10 + getLeftMargin(0), 0, 0)); } myHeader.setFont(myTree.getFont()); myHeader.setIcon(myTree.getEmptyHandle()); int height = myHeader.getPreferredSize().height; String group = findGroupNameAt(0, height + 3); if (group == null || !group.equals(findGroupNameAt(0, 0))) { return null; // do not show separator over another group } myHeader.setText(group); return myHeader; } }); if (!Registry.is("ide.scroll.background.auto")) { myScroller.setBackground(UIUtil.SIDE_PANEL_BACKGROUND); myScroller.getViewport().setBackground(UIUtil.SIDE_PANEL_BACKGROUND); myScroller.getVerticalScrollBar().setBackground(UIUtil.SIDE_PANEL_BACKGROUND); } add(myScroller); myTree.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { myBuilder.revalidateTree(); } @Override public void componentMoved(ComponentEvent e) { myBuilder.revalidateTree(); } @Override public void componentShown(ComponentEvent e) { myBuilder.revalidateTree(); } }); myTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent event) { MyNode node = extractNode(event.getNewLeadSelectionPath()); select(node == null ? null : node.myConfigurable); } }); if (Registry.is("show.configurables.ids.in.settings")) { new HeldDownKeyListener() { @Override protected void heldKeyTriggered(JComponent component, boolean pressed) { myPaintInternalInfo = pressed; SettingsTreeView.this.setMinimumSize(null); // an easy way to repaint the tree ((Tree)component).setCellRenderer(new MyRenderer()); } }.installOn(myTree); } myBuilder = new MyBuilder(new SimpleTreeStructure.Impl(myRoot)); myBuilder.setFilteringMerge(300, null); Disposer.register(this, myBuilder); } private static void setComponentPopupMenuTo(JTree tree) { tree.setComponentPopupMenu(new JPopupMenu() { private Transferable transferable; @Override public void show(Component invoker, int x, int y) { if (invoker != tree) return; TreePath path = tree.getClosestPathForLocation(x, y); transferable = createTransferable(path); if (transferable == null) return; Rectangle bounds = tree.getPathBounds(path); if (bounds == null || bounds.y > y) return; bounds.y += bounds.height; if (bounds.y < y) return; super.show(invoker, x, bounds.y); } { add(new CopyAction(() -> transferable)); } }); } private static Transferable createTransferable(TreePath path) { MyNode node = path == null ? null : extractNode(path); return node == null ? null : CopyAction.createTransferable(getPathNames(node)); } @NotNull Collection<String> getPathNames(Configurable configurable) { return getPathNames(findNode(configurable)); } private static Collection<String> getPathNames(MyNode node) { ArrayDeque<String> path = new ArrayDeque<>(); while (node != null) { path.push(node.myDisplayName); SimpleNode parent = node.getParent(); node = parent instanceof MyNode ? (MyNode)parent : null; } return path; } static Configurable getConfigurable(SimpleNode node) { return node instanceof MyNode ? ((MyNode)node).myConfigurable : null; } @Nullable MyNode findNode(Configurable configurable) { ConfigurableWrapper wrapper = myConfigurableToWrapperMap.get(configurable); return myConfigurableToNodeMap.get(wrapper != null ? wrapper : configurable); } @Nullable SearchableConfigurable findConfigurableById(@NotNull String id) { for (Configurable configurable : myConfigurableToNodeMap.keySet()) { if (configurable instanceof SearchableConfigurable) { SearchableConfigurable searchable = (SearchableConfigurable)configurable; if (id.equals(searchable.getId())) { return searchable; } } } return null; } @Nullable <T extends UnnamedConfigurable> T findConfigurable(@NotNull Class<T> type) { for (UnnamedConfigurable configurable : myConfigurableToNodeMap.keySet()) { if (configurable instanceof ConfigurableWrapper) { ConfigurableWrapper wrapper = (ConfigurableWrapper)configurable; configurable = wrapper.getConfigurable(); myConfigurableToWrapperMap.put(configurable, wrapper); } if (type.isInstance(configurable)) { return type.cast(configurable); } } return null; } @Nullable Project findConfigurableProject(@Nullable Configurable configurable) { MyNode node = findNode(configurable); return node == null ? null : findConfigurableProject(node, true); } @Nullable private static Project findConfigurableProject(@NotNull MyNode node, boolean checkProjectLevel) { Configurable configurable = node.myConfigurable; Project project = node.getProject(); if (checkProjectLevel) { Configurable.VariableProjectAppLevel wrapped = ConfigurableWrapper.cast(Configurable.VariableProjectAppLevel.class, configurable); if (wrapped != null) return wrapped.isProjectLevel() ? project : null; } if (configurable instanceof ConfigurableWrapper) return project; if (configurable instanceof SortedConfigurableGroup) return project; SimpleNode parent = node.getParent(); return parent instanceof MyNode ? findConfigurableProject((MyNode)parent, checkProjectLevel) : null; } @Nullable private static Project prepareProject(CachingSimpleNode parent, Configurable configurable) { if (configurable instanceof ConfigurableWrapper) { ConfigurableWrapper wrapper = (ConfigurableWrapper)configurable; return wrapper.getExtensionPoint().getProject(); } if (configurable instanceof SortedConfigurableGroup) { SortedConfigurableGroup group = (SortedConfigurableGroup)configurable; Configurable[] configurables = group.getConfigurables(); if (configurables != null && configurables.length != 0) { Project project = prepareProject(parent, configurables[0]); if (project != null) { for (int i = 1; i < configurables.length; i++) { if (project != prepareProject(parent, configurables[i])) { return null; } } } return project; } } return parent == null ? null : parent.getProject(); } private static int getLeftMargin(int level) { return 3 + level * (11 + ICON_GAP); } @Nullable private String findGroupNameAt(int x, int y) { TreePath path = myTree.getClosestPathForLocation(x - myTree.getX(), y - myTree.getY()); while (path != null) { MyNode node = extractNode(path); if (node == null) { return null; } if (myRoot == node.getParent()) { return node.myDisplayName; } path = path.getParentPath(); } return null; } @Nullable private static MyNode extractNode(@Nullable Object object) { if (object instanceof TreePath) { TreePath path = (TreePath)object; object = path.getLastPathComponent(); } if (object instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)object; object = node.getUserObject(); } if (object instanceof FilteringTreeStructure.FilteringNode) { FilteringTreeStructure.FilteringNode node = (FilteringTreeStructure.FilteringNode)object; object = node.getDelegate(); } return object instanceof MyNode ? (MyNode)object : null; } @Override public void doLayout() { myScroller.setBounds(0, 0, getWidth(), getHeight()); } void selectFirst() { for (ConfigurableGroup eachGroup : myRoot.myGroups) { Configurable[] kids = eachGroup.getConfigurables(); if (kids.length > 0) { select(kids[0]); return; } } } ActionCallback select(@Nullable final Configurable configurable) { if (myBuilder.isSelectionBeingAdjusted()) { return ActionCallback.REJECTED; } final ActionCallback callback = new ActionCallback(); myQueuedConfigurable = configurable; myQueue.queue(new Update(this) { public void run() { if (configurable == myQueuedConfigurable) { if (configurable == null) { fireSelected(null, callback); } else { myBuilder.getReady(this).doWhenDone(() -> { if (configurable != myQueuedConfigurable) return; MyNode editorNode = findNode(configurable); FilteringTreeStructure.FilteringNode editorUiNode = myBuilder.getVisibleNodeFor(editorNode); if (editorUiNode == null) return; if (!myBuilder.getSelectedElements().contains(editorUiNode)) { myBuilder.select(editorUiNode, () -> fireSelected(configurable, callback)); } else { myBuilder.scrollSelectionToVisible(() -> fireSelected(configurable, callback), false); } }); } } } @Override public void setRejected() { super.setRejected(); callback.setRejected(); } }); return callback; } private void fireSelected(Configurable configurable, ActionCallback callback) { ConfigurableWrapper wrapper = myConfigurableToWrapperMap.get(configurable); myFilter.myContext.fireSelected(wrapper != null ? wrapper : configurable, this).doWhenProcessed(callback.createSetDoneRunnable()); } @Override public void dispose() { myQueuedConfigurable = null; } @Override public ActionCallback onSelected(@Nullable Configurable configurable, Configurable oldConfigurable) { return select(configurable); } @Override public ActionCallback onModifiedAdded(Configurable configurable) { myTree.repaint(); return ActionCallback.DONE; } @Override public ActionCallback onModifiedRemoved(Configurable configurable) { myTree.repaint(); return ActionCallback.DONE; } @Override public ActionCallback onErrorsChanged() { return ActionCallback.DONE; } private final class MyRoot extends CachingSimpleNode { private final ConfigurableGroup[] myGroups; private MyRoot(ConfigurableGroup[] groups) { super(null); myGroups = groups; } @Override protected SimpleNode[] buildChildren() { if (myGroups == null || myGroups.length == 0) { return NO_CHILDREN; } ArrayList<MyNode> list = new ArrayList<>(); for (ConfigurableGroup group : myGroups) { for (Configurable configurable : group.getConfigurables()) { list.add(new MyNode(this, configurable, 0)); } } return list.toArray(new SimpleNode[list.size()]); } } private final class MyNode extends CachingSimpleNode { private final Configurable.Composite myComposite; private final Configurable myConfigurable; private final String myDisplayName; private final int myLevel; private MyNode(CachingSimpleNode parent, Configurable configurable, int level) { super(prepareProject(parent, configurable), parent); myComposite = configurable instanceof Configurable.Composite ? (Configurable.Composite)configurable : null; myConfigurable = configurable; String name = configurable.getDisplayName(); myDisplayName = name != null ? name.replace("\n", " ") : "{ " + configurable.getClass().getSimpleName() + " }"; myLevel = level; } @Override protected SimpleNode[] buildChildren() { if (myConfigurable != null) { myConfigurableToNodeMap.put(myConfigurable, this); } if (myComposite == null) { return NO_CHILDREN; } Configurable[] configurables = myComposite.getConfigurables(); if (configurables == null || configurables.length == 0) { return NO_CHILDREN; } SimpleNode[] result = new SimpleNode[configurables.length]; for (int i = 0; i < configurables.length; i++) { result[i] = new MyNode(this, configurables[i], myLevel + 1); if (myConfigurable != null) { myFilter.myContext.registerKid(myConfigurable, configurables[i]); } } return result; } protected void update(PresentationData presentation) { super.update(presentation); presentation.addText(myDisplayName, getPlainAttributes()); } @Override public boolean isAlwaysLeaf() { return myComposite == null; } } private final class MyRenderer extends CellRendererPanel implements TreeCellRenderer { final SimpleColoredComponent myTextLabel = new SimpleColoredComponent(); final JLabel myNodeIcon = new JLabel(); final JLabel myProjectIcon = new JLabel(); MyRenderer() { setLayout(new BorderLayout(ICON_GAP, 0)); myNodeIcon.setName(NODE_ICON); myTextLabel.setOpaque(false); add(BorderLayout.CENTER, myTextLabel); add(BorderLayout.WEST, myNodeIcon); add(BorderLayout.EAST, myProjectIcon); setBorder(BorderFactory.createEmptyBorder(1, 10, 3, 10)); } @Override public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new MyAccessibleContext(); } return accessibleContext; } // TODO: consider making MyRenderer a subclass of SimpleColoredComponent. // This should eliminate the need to add this accessibility stuff. private class MyAccessibleContext extends JPanel.AccessibleJPanel { @Override public String getAccessibleName() { return myTextLabel.getCharSequence(true).toString(); } } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean focused) { myTextLabel.clear(); setPreferredSize(null); MyNode node = extractNode(value); boolean isGroup = node != null && myRoot == node.getParent(); String name = node != null ? node.myDisplayName : String.valueOf(value); myTextLabel.append(name, isGroup ? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES); myTextLabel.setFont(isGroup ? myTree.getFont() : UIUtil.getLabelFont()); // update font color for modified configurables myTextLabel.setForeground(selected ? UIUtil.getTreeSelectionForeground() : FOREGROUND); if (!selected && node != null) { Configurable configurable = node.myConfigurable; if (configurable != null) { if (myFilter.myContext.getErrors().containsKey(configurable)) { myTextLabel.setForeground(WRONG_CONTENT); } else if (myFilter.myContext.getModified().contains(configurable)) { myTextLabel.setForeground(MODIFIED_CONTENT); } } } // configure project icon Project project = null; if (node != null) { project = findConfigurableProject(node, false); } Configurable configurable = null; if(node != null) configurable = node.myConfigurable; setProjectIcon(myProjectIcon, configurable, project, selected); // configure node icon Icon nodeIcon = null; if (value instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)value; if (0 == treeNode.getChildCount()) { nodeIcon = myTree.getEmptyHandle(); } else { nodeIcon = myTree.isExpanded(new TreePath(treeNode.getPath())) ? myTree.getExpandedHandle() : myTree.getCollapsedHandle(); } } myNodeIcon.setIcon(nodeIcon); if (node != null && myPaintInternalInfo) { String id = node.myConfigurable instanceof ConfigurableWrapper ? ((ConfigurableWrapper)node.myConfigurable).getId() : node.myConfigurable instanceof SearchableConfigurable ? ((SearchableConfigurable)node.myConfigurable).getId() : node.myConfigurable.getClass().getSimpleName(); PluginDescriptor plugin = node.myConfigurable instanceof ConfigurableWrapper ? ((ConfigurableWrapper)node.myConfigurable).getExtensionPoint().getPluginDescriptor() : null; String pluginId = plugin == null ? null : plugin.getPluginId().getIdString(); String pluginName = pluginId == null || PluginManagerCore.CORE_PLUGIN_ID.equals(pluginId) ? null : plugin instanceof IdeaPluginDescriptor ? ((IdeaPluginDescriptor)plugin).getName() : pluginId; myTextLabel.append(" ", SimpleTextAttributes.REGULAR_ATTRIBUTES, false); myTextLabel.append(pluginName == null ? id : id + " (" + pluginName + ")", SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES, false); } // calculate minimum size if (node != null && tree.isVisible()) { int width = getLeftMargin(node.myLevel) + getPreferredSize().width; Insets insets = tree.getInsets(); if (insets != null) { width += insets.left + insets.right; } JScrollBar bar = myScroller.getVerticalScrollBar(); if (bar != null && bar.isVisible()) { width += bar.getWidth(); } width = Math.min(width, 300); // maximal width for minimum size JComponent view = SettingsTreeView.this; Dimension size = view.getMinimumSize(); if (size.width < width) { size.width = width; view.setMinimumSize(size); view.revalidate(); view.repaint(); } } return this; } } protected void setProjectIcon(JLabel projectIcon, Configurable configurable, @Nullable Project project, boolean selected) { if (project != null) { projectIcon.setIcon(selected ? AllIcons.General.ProjectConfigurableSelected : AllIcons.General.ProjectConfigurable); projectIcon.setToolTipText(OptionsBundle.message(project.isDefault() ? "configurable.default.project.tooltip" : "configurable.current.project.tooltip")); projectIcon.setVisible(true); } else { projectIcon.setVisible(false); } } private final class MyTree extends SimpleTree { @Override public String getToolTipText(MouseEvent event) { if (event != null) { Component component = getDeepestRendererComponentAt(event.getX(), event.getY()); if (component instanceof JLabel) { JLabel label = (JLabel)component; if (label.getIcon() != null) { String text = label.getToolTipText(); if (text != null) { return text; } } } } return super.getToolTipText(event); } @Override protected boolean paintNodes() { return false; } @Override protected boolean highlightSingleNode() { return false; } @Override public void setUI(TreeUI ui) { super.setUI(ui instanceof MyTreeUi ? ui : new MyTreeUi()); } @Override protected boolean isCustomUI() { return true; } @Override protected void configureUiHelper(TreeUIHelper helper) { } @Override public boolean getScrollableTracksViewportWidth() { return true; } @Override public void processKeyEvent(KeyEvent e) { TreePath path = myTree.getSelectionPath(); if (path != null) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { if (isExpanded(path)) { collapsePath(path); return; } } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { if (isCollapsed(path)) { expandPath(path); return; } } } super.processKeyEvent(e); } @Override protected void processMouseEvent(MouseEvent event) { MyTreeUi ui = (MyTreeUi)myTree.getUI(); if (!ui.processMouseEvent(event)) { super.processMouseEvent(event); } } } private static final class MyTreeUi extends WideSelectionTreeUI { boolean processMouseEvent(MouseEvent event) { if (super.tree instanceof SimpleTree) { SimpleTree tree = (SimpleTree)super.tree; boolean toggleNow = MouseEvent.MOUSE_RELEASED == event.getID() && UIUtil.isActionClick(event, MouseEvent.MOUSE_RELEASED) && !isToggleEvent(event); if (toggleNow || MouseEvent.MOUSE_PRESSED == event.getID()) { Component component = tree.getDeepestRendererComponentAt(event.getX(), event.getY()); if (component != null && NODE_ICON.equals(component.getName())) { if (toggleNow) { toggleExpandState(tree.getPathForLocation(event.getX(), event.getY())); } event.consume(); return true; } } } return false; } @Override protected boolean shouldPaintExpandControl(TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) { return false; } @Override protected void paintHorizontalPartOfLeg(Graphics g, Rectangle clipBounds, Insets insets, Rectangle bounds, TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) { } @Override protected void paintVerticalPartOfLeg(Graphics g, Rectangle clipBounds, Insets insets, TreePath path) { } @Override public void paint(Graphics g, JComponent c) { GraphicsUtil.setupAntialiasing(g); super.paint(g, c); } @Override protected void paintRow(Graphics g, Rectangle clipBounds, Insets insets, Rectangle bounds, TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) { if (tree != null) { bounds.width = tree.getWidth(); Container parent = tree.getParent(); if (parent instanceof JViewport) { JViewport viewport = (JViewport)parent; bounds.width = viewport.getWidth() - viewport.getViewPosition().x - insets.right / 2; } bounds.width -= bounds.x; } super.paintRow(g, clipBounds, insets, bounds, path, row, isExpanded, hasBeenExpanded, isLeaf); } @Override protected int getRowX(int row, int depth) { return getLeftMargin(depth - 1); } } private final class MyBuilder extends FilteringTreeBuilder { List<Object> myToExpandOnResetFilter; boolean myRefilteringNow; boolean myWasHoldingFilter; public MyBuilder(SimpleTreeStructure structure) { super(myTree, myFilter, structure, null); myTree.addTreeExpansionListener(new TreeExpansionListener() { public void treeExpanded(TreeExpansionEvent event) { invalidateExpansions(); } public void treeCollapsed(TreeExpansionEvent event) { invalidateExpansions(); } }); } private void invalidateExpansions() { if (!myRefilteringNow) { myToExpandOnResetFilter = null; } } @Override protected boolean isSelectable(Object object) { return object instanceof MyNode; } @Override public boolean isAutoExpandNode(NodeDescriptor nodeDescriptor) { return myFilter.myContext.isHoldingFilter(); } @Override public boolean isToEnsureSelectionOnFocusGained() { return false; } @Override protected ActionCallback refilterNow(Object preferredSelection, boolean adjustSelection) { final List<Object> toRestore = new ArrayList<>(); if (myFilter.myContext.isHoldingFilter() && !myWasHoldingFilter && myToExpandOnResetFilter == null) { myToExpandOnResetFilter = myBuilder.getUi().getExpandedElements(); } else if (!myFilter.myContext.isHoldingFilter() && myWasHoldingFilter && myToExpandOnResetFilter != null) { toRestore.addAll(myToExpandOnResetFilter); myToExpandOnResetFilter = null; } myWasHoldingFilter = myFilter.myContext.isHoldingFilter(); ActionCallback result = super.refilterNow(preferredSelection, adjustSelection); myRefilteringNow = true; return result.doWhenDone(() -> { myRefilteringNow = false; if (!myFilter.myContext.isHoldingFilter() && getSelectedElements().isEmpty()) { restoreExpandedState(toRestore); } }); } private void restoreExpandedState(List<Object> toRestore) { TreePath[] selected = myTree.getSelectionPaths(); if (selected == null) { selected = new TreePath[0]; } List<TreePath> toCollapse = new ArrayList<>(); for (int eachRow = 0; eachRow < myTree.getRowCount(); eachRow++) { if (!myTree.isExpanded(eachRow)) continue; TreePath eachVisiblePath = myTree.getPathForRow(eachRow); if (eachVisiblePath == null) continue; Object eachElement = myBuilder.getElementFor(eachVisiblePath.getLastPathComponent()); if (toRestore.contains(eachElement)) continue; for (TreePath eachSelected : selected) { if (!eachVisiblePath.isDescendant(eachSelected)) { toCollapse.add(eachVisiblePath); } } } for (TreePath each : toCollapse) { myTree.collapsePath(each); } } } @Override public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new AccessibleSettingsTreeView(); } return accessibleContext; } protected class AccessibleSettingsTreeView extends AccessibleJComponent { @Override public AccessibleRole getAccessibleRole() { return AccessibleRole.PANEL; } } }
apache-2.0
stdlib-js/stdlib
lib/node_modules/@stdlib/streams/node/from-constant/test/test.object_mode.js
3866
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var tape = require( 'tape' ); var inspectStream = require( '@stdlib/streams/node/inspect-sink' ); var ConstantStream = require( './../lib/main.js' ); var objectMode = require( './../lib/object_mode.js' ); // TESTS // tape( 'main export is a function', function test( t ) { t.ok( true, __filename ); t.equal( typeof objectMode, 'function', 'main export is a function' ); t.end(); }); tape( 'the function throws an error if provided an options argument which is not an object', function test( t ) { var values; var i; values = [ '5', 5, NaN, true, false, void 0, null, [], function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { objectMode( 'beep', value ); }; } }); tape( 'the function throws an error if provided an invalid `iter` option', function test( t ) { var values; var i; values = [ 'abc', -5, 3.14, null, true, false, void 0, NaN, [], {}, function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { objectMode( 'beep', { 'iter': value }); }; } }); tape( 'if provided an invalid readable stream option, the function throws an error', function test( t ) { var values; var i; values = [ '5', -5, NaN, true, false, null, void 0, {}, [], function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { objectMode( 'beep', { 'highWaterMark': value }); }; } }); tape( 'the function returns a stream instance', function test( t ) { var s = objectMode( 'beep' ); t.equal( s instanceof ConstantStream, true, 'returns a stream instance' ); t.end(); }); tape( 'the function returns a stream instance (options)', function test( t ) { var s = objectMode( 'beep', {} ); t.equal( s instanceof ConstantStream, true, 'returns a stream instance' ); t.end(); }); tape( 'the function returns a stream which always streams the same value', function test( t ) { var iStream; var value; var opts; var s; value = [ 1, 2, 3, 4 ]; opts = { 'iter': 10 }; s = objectMode( value, opts ); s.on( 'end', onEnd ); opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect ); s.pipe( iStream ); function inspect( v ) { t.equal( v, value, 'returns expected value' ); } function onEnd() { t.end(); } }); tape( 'the function does not support overriding the `objectMode` option', function test( t ) { var iStream; var opts; var s; opts = { 'objectMode': false, 'iter': 10 }; s = objectMode( 'beep', opts ); s.on( 'end', onEnd ); opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect ); s.pipe( iStream ); function inspect( v ) { t.equal( v, 'beep', 'returns expected value' ); } function onEnd() { t.end(); } });
apache-2.0
CarstenHollmann/iceland
core/src/main/java/org/n52/iceland/i18n/I18NDAORepository.java
2591
/* * Copyright 2015-2018 52°North Initiative for Geospatial Open Source * Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.n52.iceland.i18n; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Optional; import javax.inject.Inject; import org.n52.iceland.i18n.metadata.AbstractI18NMetadata; import org.n52.janmayen.Producer; import org.n52.janmayen.component.AbstractComponentRepository; import org.n52.janmayen.lifecycle.Constructable; import com.google.common.collect.Maps; /** * I18N DAO repository * * @author <a href="mailto:[email protected]">Carsten Hollmann</a> * @since 1.0.0 */ public class I18NDAORepository extends AbstractComponentRepository<I18NDAOKey, I18NDAO<?>, I18NDAOFactory> implements Constructable { private final Map<I18NDAOKey, Producer<I18NDAO<?>>> daos = Maps.newHashMap(); @Inject private Optional<Collection<I18NDAO<?>>> components = Optional.of(Collections.emptyList()); @Inject private Optional<Collection<I18NDAOFactory>> componentFactories = Optional.of(Collections.emptyList()); @Override public void init() { this.daos.clear(); this.daos.putAll(getUniqueProviders(this.components, this.componentFactories)); } /** * Get the available DAO * * @param <T> the meta data type * @param c the meta data class * * @return the loaded DAO */ @SuppressWarnings("unchecked") public <T extends AbstractI18NMetadata> I18NDAO<T> getDAO(Class<T> c) { Producer<I18NDAO<?>> producer = daos.get(new I18NDAOKey(c)); // TODO check for subtypes I18NDAO<?> dao = producer == null ? null : producer.get(); return (I18NDAO<T>) dao; } public boolean isSupported() { if (!daos.isEmpty()) { for (Producer<I18NDAO<?>> dao : daos.values()) { if (dao.get() != null && dao.get().isSupported()) { return true; } } } return false; } }
apache-2.0
jasper07/md-template
test/unit/util/groupers.js
2899
/*global QUnit, jQuery *///declare unusual global vars for JSLint/SAPUI5 validation sap.ui.require( [ 'sap/ui/demo/mdtemplate/util/groupers', 'sap/ui/model/resource/ResourceModel', 'sap/ui/thirdparty/sinon', 'sap/ui/thirdparty/sinon-qunit' ], function (Groupers, ResourceModel) { "use strict"; var $ = jQuery; QUnit.module("Grouping functions", { setup: function () { this._oResourceModel = new ResourceModel({ bundleUrl : [$.sap.getModulePath("sap.ui.demo.mdtemplate"), "i18n/messageBundle.properties"].join("/") }); }, teardown: function () { this._oResourceModel.destroy(); } }); function createContextObject(vValue) { return { getProperty: function () { return vValue; } }; } QUnit.test("Should Group the Rating", function () { // Arrange var iRating2 = 2, oContextObject2 = createContextObject(iRating2), iRating5 = 5, oContextObject5 = createContextObject(iRating5), oGetModelStub = this.stub(), oControlStub = { getModel: oGetModelStub }, oGrouperReturn; // System under test oGetModelStub.withArgs("i18n").returns(this._oResourceModel); // Assert oGrouperReturn = $.proxy(Groupers.Group1, oControlStub)(oContextObject2); strictEqual(oGrouperReturn.key, iRating2,"The key was as expected for rating 2"); strictEqual(oGrouperReturn.text, this._oResourceModel.getResourceBundle().getText("masterGroup1Header", [iRating2]),"The group header is correct for rating 2"); oGrouperReturn = $.proxy(Groupers.Group1, oControlStub)(oContextObject5); strictEqual(oGrouperReturn.key, iRating5,"The key was as expected for rating 5"); strictEqual(oGrouperReturn.text, this._oResourceModel.getResourceBundle().getText("masterGroup1Header", [iRating5]),"The group header is correct for rating 5"); }); QUnit.test("Should group the price", function () { // Arrange var oContextObjectLower = createContextObject(17.2), oContextObjectHigher = createContextObject(55.5), oGetModelStub = this.stub(), oControlStub = { getModel: oGetModelStub }, oGrouperReturn; // System under test oGetModelStub.withArgs("i18n").returns(this._oResourceModel); // Assert oGrouperReturn = $.proxy(Groupers.Group2, oControlStub)(oContextObjectLower); strictEqual(oGrouperReturn.key,"LE20", "The key is as expected for a low value"); strictEqual(oGrouperReturn.text,this._oResourceModel.getResourceBundle().getText("masterGroup2Header1"), "The group header is as expected for a low value"); oGrouperReturn = $.proxy(Groupers.Group2, oControlStub)(oContextObjectHigher); strictEqual(oGrouperReturn.key,"GT20", "The key is as expected for a high value"); strictEqual(oGrouperReturn.text,this._oResourceModel.getResourceBundle().getText("masterGroup2Header2"), "The group header is as expected for a high value"); }); });
apache-2.0
kaushikgopal/CountdownApp
CountdownAppModule/src/main/java/com/cmuse13/countdownapp/countdownmodule/activities/MainActivity.java
4064
package com.cmuse13.countdownapp.countdownmodule.activities; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.cmuse13.countdownapp.countdownmodule.R; import com.cmuse13.countdownapp.countdownmodule.fragments.BaseFragment; import com.cmuse13.countdownapp.countdownmodule.fragments.SettingsDialogFragment; import com.cmuse13.countdownapp.countdownmodule.utils.CountdownHelper; import org.joda.time.DateTime; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_activity_actions, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: openSettingsDialog(); return true; default: return super.onOptionsItemSelected(item); } } private void openSettingsDialog() { SettingsDialogFragment fragment = new SettingsDialogFragment(); fragment.show(getFragmentManager(), "settingsDialogFragment"); } public static class MainFragment extends BaseFragment { private TextView mDaysToGo; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_main, container, true); } @Override public void onResume() { super.onResume(); startCountdown(); } private void startCountdown() { mDaysToGo = (TextView) getView().findViewById(R.id.days_to_go); final DateTime today = new DateTime(); final int quarterEndMonth = (((((today.getMonthOfYear() - 1)) / 3 + 1) * 3) + 1) % 12; final DateTime quarterEnd = new DateTime(2014, quarterEndMonth, 1, 0, 0); final Handler mHandler = new Handler(); final int periodLength = 90; new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() { // do something mHandler.post(new Runnable() { @Override public void run() { int daysRemaining = CountdownHelper.getDaysToGo(today, quarterEnd); mDaysToGo.setText(String.valueOf(daysRemaining)); changeBackgroundColor(daysRemaining, periodLength); } }); } }, 0, 1000); } private void changeBackgroundColor(int daysRemaining, int periodLength) { CountdownHelper.COLOR color = CountdownHelper.getColorForDaysToGo(daysRemaining, periodLength); int finalColor = 0; switch (color) { case GREEN: finalColor = getResources().getColor(R.color.green); break; case YELLOW: finalColor = getResources().getColor(R.color.yellow); break; case RED: finalColor = getResources().getColor(R.color.red); break; } getView().setBackgroundColor(finalColor); } } }
apache-2.0
jonny-novikov/google-gdata
src/unittests/core/GDataLoggingRequestFactoryTest.cs
3598
using NUnit.Framework; namespace Google.GData.Client.UnitTests.Core { /// <summary> ///This is a test class for GDataLoggingRequestFactoryTest and is intended ///to contain all GDataLoggingRequestFactoryTest Unit Tests ///</summary> [TestFixture] [Category("CoreClient")] public class GDataLoggingRequestFactoryTest { /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get; set; } /// <summary> ///A test for CombinedLogFileName ///</summary> [Test] public void CombinedLogFileNameTest() { string service = "TestValue"; // TODO: Initialize to an appropriate value string applicationName = "TestValue"; // TODO: Initialize to an appropriate value GDataLoggingRequestFactory target = new GDataLoggingRequestFactory(service, applicationName); // TODO: Initialize to an appropriate value string expected = "TestValue"; string actual; target.CombinedLogFileName = expected; actual = target.CombinedLogFileName; Assert.AreEqual(expected, actual); } /// <summary> ///A test for RequestFileName ///</summary> [Test] public void RequestFileNameTest() { string service = "TestValue"; // TODO: Initialize to an appropriate value string applicationName = "TestValue"; // TODO: Initialize to an appropriate value GDataLoggingRequestFactory target = new GDataLoggingRequestFactory(service, applicationName); // TODO: Initialize to an appropriate value string expected = "TestValue"; string actual; target.RequestFileName = expected; actual = target.RequestFileName; Assert.AreEqual(expected, actual); } /// <summary> ///A test for ResponseFileName ///</summary> [Test] public void ResponseFileNameTest() { string service = "TestValue"; // TODO: Initialize to an appropriate value string applicationName = "TestValue"; // TODO: Initialize to an appropriate value GDataLoggingRequestFactory target = new GDataLoggingRequestFactory(service, applicationName); // TODO: Initialize to an appropriate value string expected = "TestValue"; string actual; target.ResponseFileName = expected; actual = target.ResponseFileName; Assert.AreEqual(expected, actual); } //You can use the following additional attributes as you write your tests: // // //Use ClassInitialize to run code before running the first test in the class //[ClassInitialize()] //public static void MyClassInitialize(TestContext testContext) //{ //} // //Use ClassCleanup to run code after all tests in a class have run //[ClassCleanup()] //public static void MyClassCleanup() //{ //} // //Use TestInitialize to run code before running each test //[TestInitialize()] //public void MyTestInitialize() //{ //} // //Use TestCleanup to run code after each test has run //[TestCleanup()] //public void MyTestCleanup() //{ //} // } }
apache-2.0
eberhardmayer/taskana
rest/src/main/java/org/taskana/rest/security/RoleGranterFromMap.java
582
package org.taskana.rest.security; import java.security.Principal; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.springframework.security.authentication.jaas.AuthorityGranter; public class RoleGranterFromMap implements AuthorityGranter { private static Map<String, String> USER_ROLES = new HashMap<String, String>(); static { USER_ROLES.put("test", "ROLE_ADMINISTRATOR"); // USER_ROLES.put("test", "TRUE"); } public Set<String> grant(Principal principal) { return Collections.singleton("DUMMY"); } }
apache-2.0
iLib-js/iLib
tools/cldr/gencurrencies.js
7258
/* * gencurrencies.js - ilib tool to generate the json data about currency * the CLDR data files * * Copyright © 2016, 2018-2020, JEDLSoft * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ /* * This code is intended to be run under node.js */ var fs = require('fs'); var util = require('util'); var common = require('./common.js'); var coelesce = common.coelesce; var mkdirs = common.makeDirs; var path = require("path"); function usage() { console.log("Usage: gencurrency [-h] [iLib locale Dir] [toDir]\n" + "Generate the currency.jf files for each country.\n\n" + "-h or --help\n" + " this help\n" + "iLibDataDir\n" + " Current ilib locale directory in order to refer the current currency info.\n" + "toDir\n" + " directory to output the currency.jf json files. Default: current dir."); process.exit(1); } function getUsingCurrency(object) { var i, curObj, cur, ret = []; for (i = 0; i < object.length; i++) { for (curObj in object[i]) { if(object[i][curObj]._to === undefined && object[i][curObj]._from !== undefined && object[i][curObj]._tender === undefined) { ret.push(curObj); } } } return ret; } function getDecimals(currency, fractions) { var cur; for(cur in fractions) { if(cur === currency) { return Number(fractions[cur]._digits); } } /* * in CLDR, default _digits value is 2 * "DEFAULT": { * "_rounding": "0", * "_digits": "2" * } */ return 2; } function getNameAndSign(currency, cldrData, ilibData) { var cur, arr = []; for(cur in cldrData) { if(cur === currency) { if(cldrData[cur]['symbol-alt-narrow'] !== undefined) { arr['sign'] = cldrData[cur]['symbol-alt-narrow']; } else if(cldrData[cur]['symbol-alt-variant'] !== undefined && cldrData[cur]['symbol-alt-narrow'] === undefined) { arr['sign'] = cldrData[cur]['symbol-alt-variant']; } else if(cldrData[cur]['symbol-alt-variant'] === undefined && cldrData[cur]['symbol-alt-narrow'] === undefined && ilibData && ilibData[cur] && ilibData[cur]['sign'] !== undefined) { arr['sign'] = ilibData[cur]['sign']; } else { arr['sign'] = cldrData[cur]['symbol']; } if(arr['sign'] === undefined) { arr['sign'] = currency; } arr['name'] = cldrData[cur].displayName; return arr; } } return undefined; } var currencyDataFileName; var toDir = "./tmp"; process.argv.forEach(function (val, index, array) { if (val === "-h" || val === "--help") { usage(); } }); if (process.argv.length < 2) { console.error('Error: not enough arguments'); usage(); } if (process.argv.length > 2) { ilibDir = process.argv[2]; } if (process.argv.length > 3) { toDir = process.argv[3]; } console.log("gencurrency - generate currency information files.\n" + "Copyright © 2016, 2018-2020, JEDLSoft"); console.log("output dir: " + toDir); var ilibDataFileName = path.join(ilibDir, "currency.json"); if (!fs.existsSync(toDir)) { common.makeDirs(toDir); } var ilibData = {}; if (fs.existsSync(ilibDataFileName)) { var ilibDataString = fs.readFileSync(ilibDataFileName, "utf-8"); ilibData = JSON.parse(ilibDataString); } var supplementalData = require("cldr-core/supplemental/currencyData.json"); var mainData = require("cldr-numbers-full/main/en/currencies.json"); var currencyData = supplementalData.supplemental.currencyData; var currencyDispData = mainData.main['en'].numbers.currencies; var currencyObj = {}; // for saving currency.jf in each directory var currencyInfoObj = {}; // currency information object for currency.json var filename, nameAndSign = [], cur = []; var rootCurrency = {"currency": "USD"} fs.writeFileSync(path.join(toDir, "currency.jf"), JSON.stringify(rootCurrency, true, 4), "utf-8"); var zxxPath = path.join(toDir, "zxx"); if (!fs.existsSync(zxxPath)) { mkdirs(zxxPath); } fs.writeFileSync(path.join(zxxPath, "currency.jf"), JSON.stringify(rootCurrency, true, 4), "utf-8"); for (var region in currencyData.region) { if (region && currencyData.region[region]) { filename = path.join(toDir, 'und', region); if (!fs.existsSync(filename)) { mkdirs(filename); } cur = getUsingCurrency(currencyData.region[region]); if(cur.length === 0) { continue; } for (var i = 0; i < cur.length; i++) { nameAndSign = getNameAndSign(cur[i], currencyDispData, ilibData); currencyObj.currency = cur[i]; currencyInfoObj[cur[i]] = {}; console.log(region + '/' + cur[i]); currencyInfoObj[cur[i]].name = nameAndSign['name']; currencyInfoObj[cur[i]].decimals = getDecimals(cur[i], currencyData.fractions); currencyInfoObj[cur[i]].sign = nameAndSign['sign']; fn = path.join(filename, "currency.jf"); fs.writeFileSync(fn, JSON.stringify(currencyObj, true, 4), "utf-8"); } } } var keys = Object.keys(currencyInfoObj); var fnJson = path.join(toDir, "currency.json"); var sortedInfoObj = {}; var key; var primaryCur = []; keys.sort(); //for currency that has large circulation for(var i = keys.length-1; i >= 0; i--) { if(keys[i] === "USD") { primaryCur.push(keys[i]); keys.splice(i, 1); } if(keys[i] === "CHF") { primaryCur.push(keys[i]); keys.splice(i, 1); } if(keys[i] === "RON") { primaryCur.push(keys[i]); keys.splice(i, 1); } if(keys[i] === "RUB") { primaryCur.push(keys[i]); keys.splice(i, 1); } if(keys[i] === "SEK") { primaryCur.push(keys[i]); keys.splice(i, 1); } if(keys[i] === "GBP") { primaryCur.push(keys[i]); keys.splice(i, 1); } if(keys[i] === "PKR") { primaryCur.push(keys[i]); keys.splice(i, 1); } if(keys[i] === "KES") { primaryCur.push(keys[i]); keys.splice(i, 1); } if(keys[i] === "KRW") { primaryCur.push(keys[i]); keys.splice(i, 1); } } for(var i = primaryCur.length-1; i >= 0; i--) { keys.unshift(primaryCur[i]); } for(var i = 0; i < keys.length; i++) { key = keys[i]; sortedInfoObj[key] = {}; sortedInfoObj[key].name = currencyInfoObj[key].name sortedInfoObj[key].decimals = currencyInfoObj[key].decimals sortedInfoObj[key].sign = currencyInfoObj[key].sign } fs.writeFileSync(fnJson, JSON.stringify(sortedInfoObj, true, 4), "utf-8");
apache-2.0
lcmanager/gdb
gdb-web-control/src/main/resources/public/js/bootstrap-dialog.js
46537
/* global define */ /* ================================================ * Make use of Bootstrap's modal more monkey-friendly. * * For Bootstrap 3. * * [email protected] * * https://github.com/nakupanda/bootstrap3-dialog * * Licensed under The MIT License. * ================================================ */ (function (root, factory) { "use strict"; // CommonJS module is defined if (typeof module !== 'undefined' && module.exports) { var isNode = (typeof process !== "undefined"); var isElectron = isNode && ('electron' in process.versions); if (isElectron) { root.BootstrapDialog = factory(root.jQuery); } else { module.exports = factory(require('jquery'), require('bootstrap')); } } // AMD module is defined else if (typeof define === "function" && define.amd) { define("bootstrap-dialog", ["jquery", "bootstrap"], function ($) { return factory($); }); } else { // planted over the root! root.BootstrapDialog = factory(root.jQuery); } }(this, function ($) { "use strict"; /* ================================================ * Definition of BootstrapDialogModal. * Extend Bootstrap Modal and override some functions. * BootstrapDialogModal === Modified Modal. * ================================================ */ var Modal = $.fn.modal.Constructor; var BootstrapDialogModal = function (element, options) { Modal.call(this, element, options); }; BootstrapDialogModal.getModalVersion = function () { var version = null; if (typeof $.fn.modal.Constructor.VERSION === 'undefined') { version = 'v3.1'; } else if (/3\.2\.\d+/.test($.fn.modal.Constructor.VERSION)) { version = 'v3.2'; } else if (/3\.3\.[1,2]/.test($.fn.modal.Constructor.VERSION)) { version = 'v3.3'; // v3.3.1, v3.3.2 } else { version = 'v3.3.4'; } return version; }; BootstrapDialogModal.ORIGINAL_BODY_PADDING = parseInt(($('body').css('padding-right') || 0), 10); BootstrapDialogModal.METHODS_TO_OVERRIDE = {}; BootstrapDialogModal.METHODS_TO_OVERRIDE['v3.1'] = {}; BootstrapDialogModal.METHODS_TO_OVERRIDE['v3.2'] = { hide: function (e) { if (e) { e.preventDefault(); } e = $.Event('hide.bs.modal'); this.$element.trigger(e); if (!this.isShown || e.isDefaultPrevented()) { return; } this.isShown = false; // Remove css class 'modal-open' when the last opened dialog is closing. var openedDialogs = this.getGlobalOpenedDialogs(); if (openedDialogs.length === 0) { this.$body.removeClass('modal-open'); } this.resetScrollbar(); this.escape(); $(document).off('focusin.bs.modal'); this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.bs.modal'); $.support.transition && this.$element.hasClass('fade') ? this.$element .one('bsTransitionEnd', $.proxy(this.hideModal, this)) .emulateTransitionEnd(300) : this.hideModal(); } }; BootstrapDialogModal.METHODS_TO_OVERRIDE['v3.3'] = { /** * Overrided. * * @returns {undefined} */ setScrollbar: function () { var bodyPad = BootstrapDialogModal.ORIGINAL_BODY_PADDING; if (this.bodyIsOverflowing) { this.$body.css('padding-right', bodyPad + this.scrollbarWidth); } }, /** * Overrided. * * @returns {undefined} */ resetScrollbar: function () { var openedDialogs = this.getGlobalOpenedDialogs(); if (openedDialogs.length === 0) { this.$body.css('padding-right', BootstrapDialogModal.ORIGINAL_BODY_PADDING); } }, /** * Overrided. * * @returns {undefined} */ hideModal: function () { this.$element.hide(); this.backdrop($.proxy(function () { var openedDialogs = this.getGlobalOpenedDialogs(); if (openedDialogs.length === 0) { this.$body.removeClass('modal-open'); } this.resetAdjustments(); this.resetScrollbar(); this.$element.trigger('hidden.bs.modal'); }, this)); } }; BootstrapDialogModal.METHODS_TO_OVERRIDE['v3.3.4'] = $.extend({}, BootstrapDialogModal.METHODS_TO_OVERRIDE['v3.3']); BootstrapDialogModal.prototype = { constructor: BootstrapDialogModal, /** * New function, to get the dialogs that opened by BootstrapDialog. * * @returns {undefined} */ getGlobalOpenedDialogs: function () { var openedDialogs = []; $.each(BootstrapDialog.dialogs, function (id, dialogInstance) { if (dialogInstance.isRealized() && dialogInstance.isOpened()) { openedDialogs.push(dialogInstance); } }); return openedDialogs; } }; // Add compatible methods. BootstrapDialogModal.prototype = $.extend(BootstrapDialogModal.prototype, Modal.prototype, BootstrapDialogModal.METHODS_TO_OVERRIDE[BootstrapDialogModal.getModalVersion()]); /* ================================================ * Definition of BootstrapDialog. * ================================================ */ var BootstrapDialog = function (options) { this.defaultOptions = $.extend(true, { id: BootstrapDialog.newGuid(), buttons: [], data: {}, onshow: null, onshown: null, onhide: null, onhidden: null }, BootstrapDialog.defaultOptions); this.indexedButtons = {}; this.registeredButtonHotkeys = {}; this.draggableData = { isMouseDown: false, mouseOffset: {} }; this.realized = false; this.opened = false; this.initOptions(options); this.holdThisInstance(); }; BootstrapDialog.BootstrapDialogModal = BootstrapDialogModal; /** * Some constants. */ BootstrapDialog.NAMESPACE = 'bootstrap-dialog'; BootstrapDialog.TYPE_DEFAULT = 'type-default'; BootstrapDialog.TYPE_INFO = 'type-info'; BootstrapDialog.TYPE_PRIMARY = 'type-primary'; BootstrapDialog.TYPE_SUCCESS = 'type-success'; BootstrapDialog.TYPE_WARNING = 'type-warning'; BootstrapDialog.TYPE_DANGER = 'type-danger'; BootstrapDialog.DEFAULT_TEXTS = {}; BootstrapDialog.DEFAULT_TEXTS[BootstrapDialog.TYPE_DEFAULT] = 'Information'; BootstrapDialog.DEFAULT_TEXTS[BootstrapDialog.TYPE_INFO] = 'Information'; BootstrapDialog.DEFAULT_TEXTS[BootstrapDialog.TYPE_PRIMARY] = 'Information'; BootstrapDialog.DEFAULT_TEXTS[BootstrapDialog.TYPE_SUCCESS] = 'Success'; BootstrapDialog.DEFAULT_TEXTS[BootstrapDialog.TYPE_WARNING] = 'Warning'; BootstrapDialog.DEFAULT_TEXTS[BootstrapDialog.TYPE_DANGER] = 'Danger'; BootstrapDialog.DEFAULT_TEXTS['OK'] = 'OK'; BootstrapDialog.DEFAULT_TEXTS['CANCEL'] = 'Cancel'; BootstrapDialog.DEFAULT_TEXTS['CONFIRM'] = 'Confirmation'; BootstrapDialog.SIZE_NORMAL = 'size-normal'; BootstrapDialog.SIZE_SMALL = 'size-small'; BootstrapDialog.SIZE_WIDE = 'size-wide'; // size-wide is equal to modal-lg BootstrapDialog.SIZE_LARGE = 'size-large'; BootstrapDialog.BUTTON_SIZES = {}; BootstrapDialog.BUTTON_SIZES[BootstrapDialog.SIZE_NORMAL] = ''; BootstrapDialog.BUTTON_SIZES[BootstrapDialog.SIZE_SMALL] = ''; BootstrapDialog.BUTTON_SIZES[BootstrapDialog.SIZE_WIDE] = ''; BootstrapDialog.BUTTON_SIZES[BootstrapDialog.SIZE_LARGE] = 'btn-lg'; BootstrapDialog.ICON_SPINNER = 'glyphicon glyphicon-asterisk'; /** * Default options. */ BootstrapDialog.defaultOptions = { type: BootstrapDialog.TYPE_PRIMARY, size: BootstrapDialog.SIZE_NORMAL, cssClass: '', title: null, message: null, nl2br: true, closable: true, closeByBackdrop: true, closeByKeyboard: true, spinicon: BootstrapDialog.ICON_SPINNER, autodestroy: true, draggable: false, animate: true, description: '', tabindex: -1 }; /** * Config default options. */ BootstrapDialog.configDefaultOptions = function (options) { BootstrapDialog.defaultOptions = $.extend(true, BootstrapDialog.defaultOptions, options); }; /** * Open / Close all created dialogs all at once. */ BootstrapDialog.dialogs = {}; BootstrapDialog.openAll = function () { $.each(BootstrapDialog.dialogs, function (id, dialogInstance) { dialogInstance.open(); }); }; BootstrapDialog.closeAll = function () { $.each(BootstrapDialog.dialogs, function (id, dialogInstance) { dialogInstance.close(); }); }; /** * Get dialog instance by given id. * * @returns dialog instance */ BootstrapDialog.getDialog = function (id) { var dialog = null; if (typeof BootstrapDialog.dialogs[id] !== 'undefined') { dialog = BootstrapDialog.dialogs[id]; } return dialog; }; /** * Set a dialog. * * @returns the dialog that has just been set. */ BootstrapDialog.setDialog = function (dialog) { BootstrapDialog.dialogs[dialog.getId()] = dialog; return dialog; }; /** * Alias of BootstrapDialog.setDialog(dialog) * * @param {type} dialog * @returns {unresolved} */ BootstrapDialog.addDialog = function (dialog) { return BootstrapDialog.setDialog(dialog); }; /** * Move focus to next visible dialog. */ BootstrapDialog.moveFocus = function () { var lastDialogInstance = null; $.each(BootstrapDialog.dialogs, function (id, dialogInstance) { if (dialogInstance.isRealized() && dialogInstance.isOpened()) { lastDialogInstance = dialogInstance; } }); if (lastDialogInstance !== null) { lastDialogInstance.getModal().focus(); } }; BootstrapDialog.METHODS_TO_OVERRIDE = {}; BootstrapDialog.METHODS_TO_OVERRIDE['v3.1'] = { handleModalBackdropEvent: function () { this.getModal().on('click', {dialog: this}, function (event) { event.target === this && event.data.dialog.isClosable() && event.data.dialog.canCloseByBackdrop() && event.data.dialog.close(); }); return this; }, /** * To make multiple opened dialogs look better. * * Will be removed in later version, after Bootstrap Modal >= 3.3.0, updating z-index is unnecessary. */ updateZIndex: function () { if (this.isOpened()) { var zIndexBackdrop = 1050; var zIndexModal = 1060; var dialogCount = 0; $.each(BootstrapDialog.dialogs, function (dialogId, dialogInstance) { if (dialogInstance.isRealized() && dialogInstance.isOpened()) { dialogCount++; } }); var $modal = this.getModal(); var $backdrop = $modal.data('bs.modal').$backdrop; $modal.css('z-index', zIndexModal + (dialogCount - 1) * 20); $backdrop.css('z-index', zIndexBackdrop + (dialogCount - 1) * 20); } return this; }, open: function () { !this.isRealized() && this.realize(); this.getModal().modal('show'); this.updateZIndex(); return this; } }; BootstrapDialog.METHODS_TO_OVERRIDE['v3.2'] = { handleModalBackdropEvent: BootstrapDialog.METHODS_TO_OVERRIDE['v3.1']['handleModalBackdropEvent'], updateZIndex: BootstrapDialog.METHODS_TO_OVERRIDE['v3.1']['updateZIndex'], open: BootstrapDialog.METHODS_TO_OVERRIDE['v3.1']['open'] }; BootstrapDialog.METHODS_TO_OVERRIDE['v3.3'] = {}; BootstrapDialog.METHODS_TO_OVERRIDE['v3.3.4'] = $.extend({}, BootstrapDialog.METHODS_TO_OVERRIDE['v3.1']); BootstrapDialog.prototype = { constructor: BootstrapDialog, initOptions: function (options) { this.options = $.extend(true, this.defaultOptions, options); return this; }, holdThisInstance: function () { BootstrapDialog.addDialog(this); return this; }, initModalStuff: function () { this.setModal(this.createModal()) .setModalDialog(this.createModalDialog()) .setModalContent(this.createModalContent()) .setModalHeader(this.createModalHeader()) .setModalBody(this.createModalBody()) .setModalFooter(this.createModalFooter()); this.getModal().append(this.getModalDialog()); this.getModalDialog().append(this.getModalContent()); this.getModalContent() .append(this.getModalHeader()) .append(this.getModalBody()) .append(this.getModalFooter()); return this; }, createModal: function () { var $modal = $('<div class="modal" role="dialog" aria-hidden="true"></div>'); $modal.prop('id', this.getId()); $modal.attr('aria-labelledby', this.getId() + '_title'); return $modal; }, getModal: function () { return this.$modal; }, setModal: function ($modal) { this.$modal = $modal; return this; }, createModalDialog: function () { return $('<div class="modal-dialog"></div>'); }, getModalDialog: function () { return this.$modalDialog; }, setModalDialog: function ($modalDialog) { this.$modalDialog = $modalDialog; return this; }, createModalContent: function () { return $('<div class="modal-content"></div>'); }, getModalContent: function () { return this.$modalContent; }, setModalContent: function ($modalContent) { this.$modalContent = $modalContent; return this; }, createModalHeader: function () { return $('<div class="modal-header"></div>'); }, getModalHeader: function () { return this.$modalHeader; }, setModalHeader: function ($modalHeader) { this.$modalHeader = $modalHeader; return this; }, createModalBody: function () { return $('<div class="modal-body"></div>'); }, getModalBody: function () { return this.$modalBody; }, setModalBody: function ($modalBody) { this.$modalBody = $modalBody; return this; }, createModalFooter: function () { return $('<div class="modal-footer"></div>'); }, getModalFooter: function () { return this.$modalFooter; }, setModalFooter: function ($modalFooter) { this.$modalFooter = $modalFooter; return this; }, createDynamicContent: function (rawContent) { var content = null; if (typeof rawContent === 'function') { content = rawContent.call(rawContent, this); } else { content = rawContent; } if (typeof content === 'string') { content = this.formatStringContent(content); } return content; }, formatStringContent: function (content) { if (this.options.nl2br) { return content.replace(/\r\n/g, '<br />').replace(/[\r\n]/g, '<br />'); } return content; }, setData: function (key, value) { this.options.data[key] = value; return this; }, getData: function (key) { return this.options.data[key]; }, setId: function (id) { this.options.id = id; return this; }, getId: function () { return this.options.id; }, getType: function () { return this.options.type; }, setType: function (type) { this.options.type = type; this.updateType(); return this; }, updateType: function () { if (this.isRealized()) { var types = [BootstrapDialog.TYPE_DEFAULT, BootstrapDialog.TYPE_INFO, BootstrapDialog.TYPE_PRIMARY, BootstrapDialog.TYPE_SUCCESS, BootstrapDialog.TYPE_WARNING, BootstrapDialog.TYPE_DANGER]; this.getModal().removeClass(types.join(' ')).addClass(this.getType()); } return this; }, getSize: function () { return this.options.size; }, setSize: function (size) { this.options.size = size; this.updateSize(); return this; }, updateSize: function () { if (this.isRealized()) { var dialog = this; // Dialog size this.getModal().removeClass(BootstrapDialog.SIZE_NORMAL) .removeClass(BootstrapDialog.SIZE_SMALL) .removeClass(BootstrapDialog.SIZE_WIDE) .removeClass(BootstrapDialog.SIZE_LARGE); this.getModal().addClass(this.getSize()); // Smaller dialog. this.getModalDialog().removeClass('modal-sm'); if (this.getSize() === BootstrapDialog.SIZE_SMALL) { this.getModalDialog().addClass('modal-sm'); } // Wider dialog. this.getModalDialog().removeClass('modal-lg'); if (this.getSize() === BootstrapDialog.SIZE_WIDE) { this.getModalDialog().addClass('modal-lg'); } // Button size $.each(this.options.buttons, function (index, button) { var $button = dialog.getButton(button.id); var buttonSizes = ['btn-lg', 'btn-sm', 'btn-xs']; var sizeClassSpecified = false; if (typeof button['cssClass'] === 'string') { var btnClasses = button['cssClass'].split(' '); $.each(btnClasses, function (index, btnClass) { if ($.inArray(btnClass, buttonSizes) !== -1) { sizeClassSpecified = true; } }); } if (!sizeClassSpecified) { $button.removeClass(buttonSizes.join(' ')); $button.addClass(dialog.getButtonSize()); } }); } return this; }, getCssClass: function () { return this.options.cssClass; }, setCssClass: function (cssClass) { this.options.cssClass = cssClass; return this; }, getTitle: function () { return this.options.title; }, setTitle: function (title) { this.options.title = title; this.updateTitle(); return this; }, updateTitle: function () { if (this.isRealized()) { var title = this.getTitle() !== null ? this.createDynamicContent(this.getTitle()) : this.getDefaultText(); this.getModalHeader().find('.' + this.getNamespace('title')).html('').append(title).prop('id', this.getId() + '_title'); } return this; }, getMessage: function () { return this.options.message; }, setMessage: function (message) { this.options.message = message; this.updateMessage(); return this; }, updateMessage: function () { if (this.isRealized()) { var message = this.createDynamicContent(this.getMessage()); this.getModalBody().find('.' + this.getNamespace('message')).html('').append(message); } return this; }, isClosable: function () { return this.options.closable; }, setClosable: function (closable) { this.options.closable = closable; this.updateClosable(); return this; }, setCloseByBackdrop: function (closeByBackdrop) { this.options.closeByBackdrop = closeByBackdrop; return this; }, canCloseByBackdrop: function () { return this.options.closeByBackdrop; }, setCloseByKeyboard: function (closeByKeyboard) { this.options.closeByKeyboard = closeByKeyboard; return this; }, canCloseByKeyboard: function () { return this.options.closeByKeyboard; }, isAnimate: function () { return this.options.animate; }, setAnimate: function (animate) { this.options.animate = animate; return this; }, updateAnimate: function () { if (this.isRealized()) { this.getModal().toggleClass('fade', this.isAnimate()); } return this; }, getSpinicon: function () { return this.options.spinicon; }, setSpinicon: function (spinicon) { this.options.spinicon = spinicon; return this; }, addButton: function (button) { this.options.buttons.push(button); return this; }, addButtons: function (buttons) { var that = this; $.each(buttons, function (index, button) { that.addButton(button); }); return this; }, getButtons: function () { return this.options.buttons; }, setButtons: function (buttons) { this.options.buttons = buttons; this.updateButtons(); return this; }, /** * If there is id provided for a button option, it will be in dialog.indexedButtons list. * * In that case you can use dialog.getButton(id) to find the button. * * @param {type} id * @returns {undefined} */ getButton: function (id) { if (typeof this.indexedButtons[id] !== 'undefined') { return this.indexedButtons[id]; } return null; }, getButtonSize: function () { if (typeof BootstrapDialog.BUTTON_SIZES[this.getSize()] !== 'undefined') { return BootstrapDialog.BUTTON_SIZES[this.getSize()]; } return ''; }, updateButtons: function () { if (this.isRealized()) { if (this.getButtons().length === 0) { this.getModalFooter().hide(); } else { this.getModalFooter().show().find('.' + this.getNamespace('footer')).html('').append(this.createFooterButtons()); } } return this; }, isAutodestroy: function () { return this.options.autodestroy; }, setAutodestroy: function (autodestroy) { this.options.autodestroy = autodestroy; }, getDescription: function () { return this.options.description; }, setDescription: function (description) { this.options.description = description; return this; }, setTabindex: function (tabindex) { this.options.tabindex = tabindex; return this; }, getTabindex: function () { return this.options.tabindex; }, updateTabindex: function () { if (this.isRealized()) { this.getModal().attr('tabindex', this.getTabindex()); } return this; }, getDefaultText: function () { return BootstrapDialog.DEFAULT_TEXTS[this.getType()]; }, getNamespace: function (name) { return BootstrapDialog.NAMESPACE + '-' + name; }, createHeaderContent: function () { var $container = $('<div></div>'); $container.addClass(this.getNamespace('header')); // title $container.append(this.createTitleContent()); // Close button $container.prepend(this.createCloseButton()); return $container; }, createTitleContent: function () { var $title = $('<div></div>'); $title.addClass(this.getNamespace('title')); return $title; }, createCloseButton: function () { var $container = $('<div></div>'); $container.addClass(this.getNamespace('close-button')); var $icon = $('<button class="close">&times;</button>'); $container.append($icon); $container.on('click', {dialog: this}, function (event) { event.data.dialog.close(); }); return $container; }, createBodyContent: function () { var $container = $('<div></div>'); $container.addClass(this.getNamespace('body')); // Message $container.append(this.createMessageContent()); return $container; }, createMessageContent: function () { var $message = $('<div></div>'); $message.addClass(this.getNamespace('message')); return $message; }, createFooterContent: function () { var $container = $('<div></div>'); $container.addClass(this.getNamespace('footer')); return $container; }, createFooterButtons: function () { var that = this; var $container = $('<div></div>'); $container.addClass(this.getNamespace('footer-buttons')); this.indexedButtons = {}; $.each(this.options.buttons, function (index, button) { if (!button.id) { button.id = BootstrapDialog.newGuid(); } var $button = that.createButton(button); that.indexedButtons[button.id] = $button; $container.append($button); }); return $container; }, createButton: function (button) { var $button = $('<button class="btn"></button>'); $button.prop('id', button.id); $button.data('button', button); // Icon if (typeof button.icon !== 'undefined' && $.trim(button.icon) !== '') { $button.append(this.createButtonIcon(button.icon)); } // Label if (typeof button.label !== 'undefined') { $button.append(button.label); } // Css class if (typeof button.cssClass !== 'undefined' && $.trim(button.cssClass) !== '') { $button.addClass(button.cssClass); } else { $button.addClass('btn-default'); } // Hotkey if (typeof button.hotkey !== 'undefined') { this.registeredButtonHotkeys[button.hotkey] = $button; } // Button on click $button.on('click', {dialog: this, $button: $button, button: button}, function (event) { var dialog = event.data.dialog; var $button = event.data.$button; var button = $button.data('button'); if (button.autospin) { $button.toggleSpin(true); } if (typeof button.action === 'function') { return button.action.call($button, dialog, event); } }); // Dynamically add extra functions to $button this.enhanceButton($button); //Initialize enabled or not if (typeof button.enabled !== 'undefined') { $button.toggleEnable(button.enabled); } return $button; }, /** * Dynamically add extra functions to $button * * Using '$this' to reference 'this' is just for better readability. * * @param {type} $button * @returns {_L13.BootstrapDialog.prototype} */ enhanceButton: function ($button) { $button.dialog = this; // Enable / Disable $button.toggleEnable = function (enable) { var $this = this; if (typeof enable !== 'undefined') { $this.prop("disabled", !enable).toggleClass('disabled', !enable); } else { $this.prop("disabled", !$this.prop("disabled")); } return $this; }; $button.enable = function () { var $this = this; $this.toggleEnable(true); return $this; }; $button.disable = function () { var $this = this; $this.toggleEnable(false); return $this; }; // Icon spinning, helpful for indicating ajax loading status. $button.toggleSpin = function (spin) { var $this = this; var dialog = $this.dialog; var $icon = $this.find('.' + dialog.getNamespace('button-icon')); if (typeof spin === 'undefined') { spin = !($button.find('.icon-spin').length > 0); } if (spin) { $icon.hide(); $button.prepend(dialog.createButtonIcon(dialog.getSpinicon()).addClass('icon-spin')); } else { $icon.show(); $button.find('.icon-spin').remove(); } return $this; }; $button.spin = function () { var $this = this; $this.toggleSpin(true); return $this; }; $button.stopSpin = function () { var $this = this; $this.toggleSpin(false); return $this; }; return this; }, createButtonIcon: function (icon) { var $icon = $('<span></span>'); $icon.addClass(this.getNamespace('button-icon')).addClass(icon); return $icon; }, /** * Invoke this only after the dialog is realized. * * @param {type} enable * @returns {undefined} */ enableButtons: function (enable) { $.each(this.indexedButtons, function (id, $button) { $button.toggleEnable(enable); }); return this; }, /** * Invoke this only after the dialog is realized. * * @returns {undefined} */ updateClosable: function () { if (this.isRealized()) { // Close button this.getModalHeader().find('.' + this.getNamespace('close-button')).toggle(this.isClosable()); } return this; }, /** * Set handler for modal event 'show.bs.modal'. * This is a setter! */ onShow: function (onshow) { this.options.onshow = onshow; return this; }, /** * Set handler for modal event 'shown.bs.modal'. * This is a setter! */ onShown: function (onshown) { this.options.onshown = onshown; return this; }, /** * Set handler for modal event 'hide.bs.modal'. * This is a setter! */ onHide: function (onhide) { this.options.onhide = onhide; return this; }, /** * Set handler for modal event 'hidden.bs.modal'. * This is a setter! */ onHidden: function (onhidden) { this.options.onhidden = onhidden; return this; }, isRealized: function () { return this.realized; }, setRealized: function (realized) { this.realized = realized; return this; }, isOpened: function () { return this.opened; }, setOpened: function (opened) { this.opened = opened; return this; }, handleModalEvents: function () { this.getModal().on('show.bs.modal', {dialog: this}, function (event) { var dialog = event.data.dialog; dialog.setOpened(true); if (dialog.isModalEvent(event) && typeof dialog.options.onshow === 'function') { var openIt = dialog.options.onshow(dialog); if (openIt === false) { dialog.setOpened(false); } return openIt; } }); this.getModal().on('shown.bs.modal', {dialog: this}, function (event) { var dialog = event.data.dialog; dialog.isModalEvent(event) && typeof dialog.options.onshown === 'function' && dialog.options.onshown(dialog); }); this.getModal().on('hide.bs.modal', {dialog: this}, function (event) { var dialog = event.data.dialog; dialog.setOpened(false); if (dialog.isModalEvent(event) && typeof dialog.options.onhide === 'function') { var hideIt = dialog.options.onhide(dialog); if (hideIt === false) { dialog.setOpened(true); } return hideIt; } }); this.getModal().on('hidden.bs.modal', {dialog: this}, function (event) { var dialog = event.data.dialog; dialog.isModalEvent(event) && typeof dialog.options.onhidden === 'function' && dialog.options.onhidden(dialog); if (dialog.isAutodestroy()) { dialog.setRealized(false); delete BootstrapDialog.dialogs[dialog.getId()]; $(this).remove(); } BootstrapDialog.moveFocus(); }); // Backdrop, I did't find a way to change bs3 backdrop option after the dialog is popped up, so here's a new wheel. this.handleModalBackdropEvent(); // ESC key support this.getModal().on('keyup', {dialog: this}, function (event) { event.which === 27 && event.data.dialog.isClosable() && event.data.dialog.canCloseByKeyboard() && event.data.dialog.close(); }); // Button hotkey this.getModal().on('keyup', {dialog: this}, function (event) { var dialog = event.data.dialog; if (typeof dialog.registeredButtonHotkeys[event.which] !== 'undefined') { var $button = $(dialog.registeredButtonHotkeys[event.which]); !$button.prop('disabled') && $button.focus().trigger('click'); } }); return this; }, handleModalBackdropEvent: function () { this.getModal().on('click', {dialog: this}, function (event) { $(event.target).hasClass('modal-backdrop') && event.data.dialog.isClosable() && event.data.dialog.canCloseByBackdrop() && event.data.dialog.close(); }); return this; }, isModalEvent: function (event) { return typeof event.namespace !== 'undefined' && event.namespace === 'bs.modal'; }, makeModalDraggable: function () { if (this.options.draggable) { this.getModalHeader().addClass(this.getNamespace('draggable')).on('mousedown', {dialog: this}, function (event) { var dialog = event.data.dialog; dialog.draggableData.isMouseDown = true; var dialogOffset = dialog.getModalDialog().offset(); dialog.draggableData.mouseOffset = { top: event.clientY - dialogOffset.top, left: event.clientX - dialogOffset.left }; }); this.getModal().on('mouseup mouseleave', {dialog: this}, function (event) { event.data.dialog.draggableData.isMouseDown = false; }); $('body').on('mousemove', {dialog: this}, function (event) { var dialog = event.data.dialog; if (!dialog.draggableData.isMouseDown) { return; } dialog.getModalDialog().offset({ top: event.clientY - dialog.draggableData.mouseOffset.top, left: event.clientX - dialog.draggableData.mouseOffset.left }); }); } return this; }, realize: function () { this.initModalStuff(); this.getModal().addClass(BootstrapDialog.NAMESPACE) .addClass(this.getCssClass()); this.updateSize(); if (this.getDescription()) { this.getModal().attr('aria-describedby', this.getDescription()); } this.getModalFooter().append(this.createFooterContent()); this.getModalHeader().append(this.createHeaderContent()); this.getModalBody().append(this.createBodyContent()); this.getModal().data('bs.modal', new BootstrapDialogModal(this.getModal(), { backdrop: 'static', keyboard: false, show: false })); this.makeModalDraggable(); this.handleModalEvents(); this.setRealized(true); this.updateButtons(); this.updateType(); this.updateTitle(); this.updateMessage(); this.updateClosable(); this.updateAnimate(); this.updateSize(); this.updateTabindex(); return this; }, open: function () { !this.isRealized() && this.realize(); this.getModal().modal('show'); return this; }, close: function () { !this.isRealized() && this.realize(); this.getModal().modal('hide'); return this; } }; // Add compatible methods. BootstrapDialog.prototype = $.extend(BootstrapDialog.prototype, BootstrapDialog.METHODS_TO_OVERRIDE[BootstrapDialogModal.getModalVersion()]); /** * RFC4122 version 4 compliant unique id creator. * * Added by https://github.com/tufanbarisyildirim/ * * @returns {String} */ BootstrapDialog.newGuid = function () { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); }; /* ================================================ * For lazy people * ================================================ */ /** * Shortcut function: show * * @param {type} options * @returns the created dialog instance */ BootstrapDialog.show = function (options) { return new BootstrapDialog(options).open(); }; /** * Alert window * * @returns the created dialog instance */ BootstrapDialog.alert = function () { var alertOptions = {}; var defaultAlertOptions = { type: BootstrapDialog.TYPE_PRIMARY, title: null, message: null, closable: false, draggable: false, buttonLabel: BootstrapDialog.DEFAULT_TEXTS.OK, callback: null }; if (typeof arguments[0] === 'object' && arguments[0].constructor === {}.constructor) { alertOptions = $.extend(true, defaultAlertOptions, arguments[0]); } else { alertOptions = $.extend(true, defaultAlertOptions, { message: arguments[0], callback: typeof arguments[1] !== 'undefined' ? arguments[1] : null }); } var dialog = new BootstrapDialog(alertOptions); dialog.setData('callback', alertOptions.callback); dialog.addButton({ label: alertOptions.buttonLabel, action: function (dialog) { if (typeof dialog.getData('callback') === 'function' && dialog.getData('callback').call(this, true) === false) { return false; } dialog.setData('btnClicked', true); return dialog.close(); } }); if (typeof dialog.options.onhide === 'function') { dialog.onHide(function (dialog) { var hideIt = true; if (!dialog.getData('btnClicked') && dialog.isClosable() && typeof dialog.getData('callback') === 'function') { hideIt = dialog.getData('callback')(false); } if (hideIt === false) { return false; } hideIt = this.onhide(dialog); return hideIt; }.bind({ onhide: dialog.options.onhide })); } else { dialog.onHide(function (dialog) { var hideIt = true; if (!dialog.getData('btnClicked') && dialog.isClosable() && typeof dialog.getData('callback') === 'function') { hideIt = dialog.getData('callback')(false); } return hideIt; }); } return dialog.open(); }; /** * Confirm window * * @returns the created dialog instance */ BootstrapDialog.confirm = function () { var confirmOptions = {}; var defaultConfirmOptions = { type: BootstrapDialog.TYPE_PRIMARY, title: null, message: null, closable: false, draggable: false, btnCancelLabel: BootstrapDialog.DEFAULT_TEXTS.CANCEL, btnCancelClass: null, btnOKLabel: BootstrapDialog.DEFAULT_TEXTS.OK, btnOKClass: null, callback: null }; if (typeof arguments[0] === 'object' && arguments[0].constructor === {}.constructor) { confirmOptions = $.extend(true, defaultConfirmOptions, arguments[0]); } else { confirmOptions = $.extend(true, defaultConfirmOptions, { message: arguments[0], callback: typeof arguments[1] !== 'undefined' ? arguments[1] : null }); } if (confirmOptions.btnOKClass === null) { confirmOptions.btnOKClass = ['btn', confirmOptions.type.split('-')[1]].join('-'); } var dialog = new BootstrapDialog(confirmOptions); dialog.setData('callback', confirmOptions.callback); dialog.addButton({ label: confirmOptions.btnCancelLabel, cssClass: confirmOptions.btnCancelClass, action: function (dialog) { if (typeof dialog.getData('callback') === 'function' && dialog.getData('callback').call(this, false) === false) { return false; } return dialog.close(); } }); dialog.addButton({ label: confirmOptions.btnOKLabel, cssClass: confirmOptions.btnOKClass, action: function (dialog) { if (typeof dialog.getData('callback') === 'function' && dialog.getData('callback').call(this, true) === false) { return false; } return dialog.close(); } }); return dialog.open(); }; /** * Warning window * * @param {type} message * @returns the created dialog instance */ BootstrapDialog.warning = function (message, callback) { return new BootstrapDialog({ type: BootstrapDialog.TYPE_WARNING, message: message }).open(); }; /** * Danger window * * @param {type} message * @returns the created dialog instance */ BootstrapDialog.danger = function (message, callback) { return new BootstrapDialog({ type: BootstrapDialog.TYPE_DANGER, message: message }).open(); }; /** * Success window * * @param {type} message * @returns the created dialog instance */ BootstrapDialog.success = function (message, callback) { return new BootstrapDialog({ type: BootstrapDialog.TYPE_SUCCESS, message: message }).open(); }; return BootstrapDialog; }));
apache-2.0
daxslab/daxSmail
src/com/daxslab/mail/activity/EmailAddressList.java
1692
package com.daxslab.mail.activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import com.daxslab.mail.R; import com.daxslab.mail.helper.ContactItem; public class EmailAddressList extends K9ListActivity implements OnItemClickListener { public static final String EXTRA_CONTACT_ITEM = "contact"; public static final String EXTRA_EMAIL_ADDRESS = "emailAddress"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.email_address_list); Intent i = getIntent(); ContactItem contact = (ContactItem) i.getSerializableExtra(EXTRA_CONTACT_ITEM); if (contact == null) { finish(); return; } ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.email_address_list_item, contact.emailAddresses); ListView listView = getListView(); listView.setOnItemClickListener(this); listView.setAdapter(adapter); setTitle(contact.displayName); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String item = (String)parent.getItemAtPosition(position); Toast.makeText(EmailAddressList.this, item, Toast.LENGTH_LONG).show(); Intent intent = new Intent(); intent.putExtra(EXTRA_EMAIL_ADDRESS, item); setResult(RESULT_OK, intent); finish(); } }
apache-2.0
Qinger315/Word
app/src/main/java/com/qing/android/word/Decoration/IndexBar/Helper/IndexBarDataHelperImpl.java
5285
package com.qing.android.word.Decoration.IndexBar.Helper; /** * Created by qing on 2017/6/7. */ import com.github.promeg.pinyinhelper.Pinyin; import com.qing.android.word.Decoration.IndexBar.Bean.BaseIndexPinyinBean; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * 介绍:IndexBar 的 数据相关帮助类 实现 * * 1 将汉语转成拼音(利用tinyPinyin) * 2 填充indexTag (取拼音首字母) * 3 排序源数据源 * 4 根据排序后的源数据源->indexBar的数据源 * 作者:zhangxutong * 邮箱:[email protected] * 主页:http://blog.csdn.net/zxt0601 * 时间: 2016/11/28. */ public class IndexBarDataHelperImpl implements IIndexBarDataHelper { /** * 如果需要, * 字符->拼音, * * @param datas */ @Override public IIndexBarDataHelper convert(List<? extends BaseIndexPinyinBean> datas) { if (null == datas || datas.isEmpty()) { return this; } int size = datas.size(); for (int i = 0; i < size; i++) { BaseIndexPinyinBean indexPinyinBean = datas.get(i); StringBuilder pySb = new StringBuilder(); //add by zhangxutong 2016 11 10 如果不是top 才转拼音,否则不用转了 if (indexPinyinBean.isNeedToPinyin()) { String target = indexPinyinBean.getTarget();//取出需要被拼音化的字段 //遍历target的每个char得到它的全拼音 for (int i1 = 0; i1 < target.length(); i1++) { //利用TinyPinyin将char转成拼音 //查看源码,方法内 如果char为汉字,则返回大写拼音 //如果c不是汉字,则返回String.valueOf(c) pySb.append(Pinyin.toPinyin(target.charAt(i1)).toUpperCase()); } indexPinyinBean.setBaseIndexPinyin(pySb.toString());//设置城市名全拼音 } else { //pySb.append(indexPinyinBean.getBaseIndexPinyin()); } } return this; } /** * 如果需要取出,则 * 取出首字母->tag,或者特殊字母 "#". * 否则,用户已经实现设置好 * * @param datas */ @Override public IIndexBarDataHelper fillInexTag(List<? extends BaseIndexPinyinBean> datas) { if (null == datas || datas.isEmpty()) { return this; } int size = datas.size(); for (int i = 0; i < size; i++) { BaseIndexPinyinBean indexPinyinBean = datas.get(i); if (indexPinyinBean.isNeedToPinyin()) { //以下代码设置城市拼音首字母 String tagString = indexPinyinBean.getBaseIndexPinyin().toString().substring(0, 1); if (tagString.matches("[A-Z]")) {//如果是A-Z字母开头 indexPinyinBean.setBaseIndexTag(tagString); } else {//特殊字母这里统一用#处理 indexPinyinBean.setBaseIndexTag("#"); } } } return this; } @Override public IIndexBarDataHelper sortSourceDatas(List<? extends BaseIndexPinyinBean> datas) { if (null == datas || datas.isEmpty()) { return this; } convert(datas); fillInexTag(datas); //对数据源进行排序 Collections.sort(datas, new Comparator<BaseIndexPinyinBean>() { @Override public int compare(BaseIndexPinyinBean lhs, BaseIndexPinyinBean rhs) { if (!lhs.isNeedToPinyin()) { return 0; } else if (!rhs.isNeedToPinyin()) { return 0; } else if (lhs.getBaseIndexTag().equals("#")) { return 1; } else if (rhs.getBaseIndexTag().equals("#")) { return -1; } else { return lhs.getBaseIndexPinyin().compareTo(rhs.getBaseIndexPinyin()); } } }); return this; } @Override public IIndexBarDataHelper getSortedIndexDatas(List<? extends BaseIndexPinyinBean> sourceDatas, List<String> indexDatas) { if (null == sourceDatas || sourceDatas.isEmpty()) { return this; } //按数据源来 此时sourceDatas 已经有序 int size = sourceDatas.size(); String baseIndexTag; for (int i = 0; i < size; i++) { baseIndexTag = sourceDatas.get(i).getBaseIndexTag(); if (!indexDatas.contains(baseIndexTag)) {//则判断是否已经将这个索引添加进去,若没有则添加 indexDatas.add(baseIndexTag); } } return this; } }
apache-2.0
bojanv55/AxonFramework
spring/src/test/java/org/axonframework/spring/commandhandling/distributed/jgroups/JGroupsConnectorFactoryBeanTest.java
7854
/* * Copyright (c) 2010-2016. Axon Framework * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.axonframework.spring.commandhandling.distributed.jgroups; import org.axonframework.commandhandling.CommandBus; import org.axonframework.commandhandling.CommandMessage; import org.axonframework.commandhandling.SimpleCommandBus; import org.axonframework.commandhandling.distributed.RoutingStrategy; import org.axonframework.jgroups.commandhandling.JChannelFactory; import org.axonframework.jgroups.commandhandling.JGroupsConnector; import org.axonframework.jgroups.commandhandling.JGroupsXmlConfigurationChannelFactory; import org.axonframework.serialization.Serializer; import org.axonframework.serialization.xml.XStreamSerializer; import org.jgroups.JChannel; import org.jgroups.util.Util; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.context.ApplicationContext; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Matchers.isNull; import static org.mockito.Matchers.same; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Allard Buijze */ @RunWith(PowerMockRunner.class) @PrepareForTest({JGroupsConnectorFactoryBean.class, JChannel.class, JGroupsConnector.class, JGroupsXmlConfigurationChannelFactory.class, Util.class}) public class JGroupsConnectorFactoryBeanTest { private JGroupsConnectorFactoryBean testSubject; private ApplicationContext mockApplicationContext; private JChannel mockChannel; private JGroupsConnector mockConnector; @Before public void setUp() throws Exception { PowerMockito.mockStatic(Util.class); mockApplicationContext = mock(ApplicationContext.class); mockChannel = mock(JChannel.class); mockConnector = mock(JGroupsConnector.class); when(mockApplicationContext.getBean(Serializer.class)).thenReturn(new XStreamSerializer()); PowerMockito.whenNew(JChannel.class).withParameterTypes(String.class).withArguments(isA(String.class)) .thenReturn(mockChannel); PowerMockito.whenNew(JGroupsConnector.class) .withArguments( isA(CommandBus.class), isA(JChannel.class), isA(String.class), isA(Serializer.class), isA(RoutingStrategy.class)) .thenReturn(mockConnector); testSubject = new JGroupsConnectorFactoryBean(); testSubject.setBeanName("beanName"); testSubject.setApplicationContext(mockApplicationContext); } @Test public void testCreateWithDefaultValues() throws Exception { testSubject.afterPropertiesSet(); testSubject.start(); testSubject.getObject(); PowerMockito.verifyNew(JChannel.class).withArguments("tcp_mcast.xml"); PowerMockito.verifyNew(JGroupsConnector.class).withArguments( isA(SimpleCommandBus.class), eq(mockChannel), eq("beanName"), isA(Serializer.class), isA(RoutingStrategy.class)); verify(mockConnector).connect(); verify(mockChannel, never()).close(); PowerMockito.verifyStatic(never()); Util.registerChannel(any(JChannel.class), anyString()); testSubject.stop(() -> { }); verify(mockChannel).close(); } @Test public void testCreateWithSpecifiedValues() throws Exception { testSubject.setClusterName("ClusterName"); testSubject.setConfiguration("custom.xml"); XStreamSerializer serializer = new XStreamSerializer(); testSubject.setSerializer(serializer); SimpleCommandBus localSegment = new SimpleCommandBus(); testSubject.setLocalSegment(localSegment); RoutingStrategy routingStrategy = CommandMessage::getCommandName; testSubject.setRoutingStrategy(routingStrategy); testSubject.setChannelName("localname"); testSubject.afterPropertiesSet(); testSubject.start(); testSubject.getObject(); PowerMockito.verifyNew(JChannel.class).withArguments("custom.xml"); PowerMockito.verifyNew(JGroupsConnector.class).withArguments( same(localSegment), eq(mockChannel), eq("ClusterName"), same(serializer), same(routingStrategy)); verify(mockApplicationContext, never()).getBean(Serializer.class); verify(mockChannel).setName("localname"); verify(mockConnector).connect(); verify(mockChannel, never()).close(); testSubject.stop(new Runnable() { @Override public void run() { } }); verify(mockChannel).close(); } @Test public void testCreateWithCustomChannel() throws Exception { JChannelFactory mockFactory = mock(JChannelFactory.class); when(mockFactory.createChannel()).thenReturn(mockChannel); testSubject.setChannelFactory(mockFactory); testSubject.afterPropertiesSet(); testSubject.start(); testSubject.getObject(); verify(mockFactory).createChannel(); PowerMockito.verifyNew(JGroupsConnector.class).withArguments( isA(SimpleCommandBus.class), eq(mockChannel), eq("beanName"), isA(Serializer.class), isA(RoutingStrategy.class)); verify(mockConnector).connect(); verify(mockChannel, never()).close(); testSubject.stop(new Runnable() { @Override public void run() { } }); verify(mockChannel).close(); } @Test public void testRegisterMBean() throws Exception { testSubject.setRegisterMBean(true); testSubject.afterPropertiesSet(); testSubject.start(); testSubject.getObject(); PowerMockito.verifyStatic(times(1)); Util.registerChannel(eq(mockChannel), isNull(String.class)); PowerMockito.verifyNew(JGroupsConnector.class).withArguments( isA(SimpleCommandBus.class), eq(mockChannel), eq("beanName"), isA(Serializer.class), isA(RoutingStrategy.class)); verify(mockConnector).connect(); verify(mockChannel, never()).close(); testSubject.stop(() -> { }); verify(mockChannel).close(); } @Test public void testSimpleProperties() { assertEquals(Integer.MAX_VALUE, testSubject.getPhase()); testSubject.setPhase(100); assertEquals(100, testSubject.getPhase()); assertTrue(testSubject.isAutoStartup()); } }
apache-2.0
drogba1192/pk_2016
src/main/java/dao/jdbc/package-info.java
107
/** * A csomag tartalmazza az adatbázis reprezentációhoz szükséges osztályt. */ package dao.jdbc;
apache-2.0
meggermo/jackrabbit-oak
oak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/tool/DebugSegments.java
7126
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.segment.tool; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static org.apache.jackrabbit.oak.segment.RecordId.fromString; import static org.apache.jackrabbit.oak.segment.tool.Utils.openReadOnlyFileStore; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.jackrabbit.oak.commons.PathUtils; import org.apache.jackrabbit.oak.commons.json.JsopBuilder; import org.apache.jackrabbit.oak.json.JsopDiff; import org.apache.jackrabbit.oak.segment.RecordId; import org.apache.jackrabbit.oak.segment.SegmentId; import org.apache.jackrabbit.oak.segment.SegmentNodeState; import org.apache.jackrabbit.oak.segment.file.ReadOnlyFileStore; import org.apache.jackrabbit.oak.spi.state.NodeState; /** * Print debugging information about segments, node records and node record * ranges. */ public class DebugSegments implements Runnable { private static final Pattern SEGMENT_REGEX = Pattern.compile("([0-9a-f-]+)|(([0-9a-f-]+:[0-9a-f]+)(-([0-9a-f-]+:[0-9a-f]+))?)?(/.*)?"); /** * Create a builder for the {@link DebugSegments} command. * * @return an instance of {@link Builder}. */ public static Builder builder() { return new Builder(); } /** * Collect options for the {@link DebugSegments} command. */ public static class Builder { private File path; private List<String> segments = new ArrayList<>(); private Builder() { // Prevent external instantiation. } /** * The path to an existing segment store. This parameter is required. * * @param path the path to an existing segment store. * @return this builder. */ public Builder withPath(File path) { this.path = checkNotNull(path); return this; } /** * Add a segment, node record or node record range. It is mandatory to * add at least one of a segment, node record or node record range. * <p> * A segment is specified by its ID, which is specified as a sequence of * hexadecimal digits and dashes. In example, {@code * 333dc24d-438f-4cca-8b21-3ebf67c05856}. * <p> * A node record is specified by its identifier, with an optional path. * In example, {@code 333dc24d-438f-4cca-8b21-3ebf67c05856:12345/path/to/child}. * If a path is not specified, it is take to be {@code /}. The command * will print information about the node provided by record ID and about * every child identified by the path. * <p> * A node range record is specified by two node identifiers separated by * a dash. In example, {@code 333dc24d-438f-4cca-8b21-3ebf67c05856:12345-46116fda-7a72-4dbc-af88-a09322a7753a:67890}. * The command will perform a diff between the two records and print the * result in the JSOP format. * * @param segment The specification for a segment, a node record or a * node record range. * @return this builder. */ public Builder withSegment(String segment) { this.segments.add(checkNotNull(segment)); return this; } /** * Create an executable version of the {@link DebugSegments} command. * * @return an instance of {@link Runnable}. */ public Runnable build() { checkNotNull(path); checkArgument(segments.size() > 0); return new DebugSegments(this); } } private final File path; private final List<String> segments; private DebugSegments(Builder builder) { this.path = builder.path; this.segments = new ArrayList<>(builder.segments); } @Override public void run() { try (ReadOnlyFileStore store = openReadOnlyFileStore(path)) { debugSegments(store); } catch (Exception e) { e.printStackTrace(); } } private void debugSegments(ReadOnlyFileStore store) { for (String segment : segments) { debugSegment(store, segment); } } private void debugSegment(ReadOnlyFileStore store, String segment) { Matcher matcher = SEGMENT_REGEX.matcher(segment); if (!matcher.matches()) { System.err.println("Unknown argument: " + segment); return; } if (matcher.group(1) != null) { UUID uuid = UUID.fromString(matcher.group(1)); SegmentId id = store.newSegmentId(uuid.getMostSignificantBits(), uuid.getLeastSignificantBits()); System.out.println(id.getSegment()); return; } RecordId id1 = store.getRevisions().getHead(); RecordId id2 = null; if (matcher.group(2) != null) { id1 = fromString(store, matcher.group(3)); if (matcher.group(4) != null) { id2 = fromString(store, matcher.group(5)); } } String path = "/"; if (matcher.group(6) != null) { path = matcher.group(6); } if (id2 == null) { NodeState node = store.getReader().readNode(id1); System.out.println("/ (" + id1 + ") -> " + node); for (String name : PathUtils.elements(path)) { node = node.getChildNode(name); RecordId nid = null; if (node instanceof SegmentNodeState) { nid = ((SegmentNodeState) node).getRecordId(); } System.out.println(" " + name + " (" + nid + ") -> " + node); } return; } NodeState node1 = store.getReader().readNode(id1); NodeState node2 = store.getReader().readNode(id2); for (String name : PathUtils.elements(path)) { node1 = node1.getChildNode(name); node2 = node2.getChildNode(name); } System.out.println(JsopBuilder.prettyPrint(JsopDiff.diffToJsop(node1, node2))); } }
apache-2.0
documents4j/documents4j
documents4j-transformer-msoffice/documents4j-transformer-msoffice-powerpoint/src/main/java/com/documents4j/conversion/msoffice/MicrosoftPowerpointScript.java
2288
package com.documents4j.conversion.msoffice; import com.documents4j.throwables.FileSystemInteractionException; import com.google.common.base.MoreObjects; import com.google.common.io.Files; import com.google.common.io.Resources; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.Random; /** * VBS Scripts for communicating with MS Excel. */ enum MicrosoftPowerpointScript implements MicrosoftOfficeScript { CONVERSION("/powerpoint_convert.vbs"), STARTUP("/powerpoint_start.vbs"), SHUTDOWN("/powerpoint_shutdown.vbs"), ASSERTION("/powerpoint_assert.vbs"); private static final Logger LOGGER = LoggerFactory.getLogger(MicrosoftPowerpointBridge.class); private static final Random RANDOM = new Random(); private final String path; private MicrosoftPowerpointScript(String path) { this.path = path; } public String getName() { return path.substring(1); } public String getRandomizedName() { String name = getName(); int extensionIndex = name.lastIndexOf('.'); if (extensionIndex < 0) { return String.format("%s%d", name, RANDOM.nextInt()); } else { return String.format("%s%d.%s", name.substring(0, extensionIndex), Math.abs(RANDOM.nextInt()), name.substring(extensionIndex + 1)); } } @Override public File materializeIn(File folder) { File script = new File(folder, getRandomizedName()); try { if (!script.createNewFile()) { throw new IOException(String.format("Could not create file %s", script)); } Resources.asByteSource(Resources.getResource(getClass(), path)).copyTo(Files.asByteSink(script)); } catch (IOException e) { String message = String.format("Could not copy script resource '%s' to local file system at '%s'", path, folder); LOGGER.error(message, e); throw new FileSystemInteractionException(message, e); } return script; } @Override public String toString() { return MoreObjects.toStringHelper(MicrosoftPowerpointScript.class) .add("resource", path) .toString(); } }
apache-2.0
b002368/chef-repo
chef-config/spec/unit/workstation_config_loader_spec.rb
12310
# # Author:: Daniel DeLeo (<[email protected]>) # Copyright:: Copyright 2014-2016, Chef Software, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "spec_helper" require "tempfile" require "chef-config/exceptions" require "chef-config/windows" require "chef-config/workstation_config_loader" RSpec.describe ChefConfig::WorkstationConfigLoader do let(:explicit_config_location) { nil } let(:env) { {} } let(:config_loader) do described_class.new(explicit_config_location).tap do |c| allow(c).to receive(:env).and_return(env) end end before do # We set this to nil so that a dev workstation will # not interfere with the tests. ChefConfig::Config[:config_d_dir] = nil end # Test methods that do I/O or reference external state which are stubbed out # elsewhere. describe "external dependencies" do let(:config_loader) { described_class.new(nil) } it "delegates to ENV for env" do expect(config_loader.env).to equal(ENV) end it "tests a path's existence" do expect(config_loader.path_exists?("/nope/nope/nope/nope/frab/jab/nab")).to be(false) expect(config_loader.path_exists?(__FILE__)).to be(true) end end describe "locating the config file" do context "without an explicit config" do before do allow(config_loader).to receive(:path_exists?).with(an_instance_of(String)).and_return(false) end it "has no config if HOME is not set" do expect(config_loader.config_location).to be(nil) expect(config_loader.no_config_found?).to be(true) end context "when HOME is set and contains a knife.rb" do let(:home) { "/Users/example.user" } before do allow(ChefConfig::PathHelper).to receive(:home).with(".chef").and_yield(File.join(home, ".chef")) allow(config_loader).to receive(:path_exists?).with("#{home}/.chef/knife.rb").and_return(true) end it "uses the config in HOME/.chef/knife.rb" do expect(config_loader.config_location).to eq("#{home}/.chef/knife.rb") end context "and has a config.rb" do before do allow(config_loader).to receive(:path_exists?).with("#{home}/.chef/config.rb").and_return(true) end it "uses the config in HOME/.chef/config.rb" do expect(config_loader.config_location).to eq("#{home}/.chef/config.rb") end context "and/or a parent dir contains a .chef dir" do let(:env_pwd) { "/path/to/cwd" } before do if ChefConfig.windows? env["CD"] = env_pwd else env["PWD"] = env_pwd end allow(config_loader).to receive(:path_exists?).with("#{env_pwd}/.chef/knife.rb").and_return(true) allow(File).to receive(:exist?).with("#{env_pwd}/.chef").and_return(true) allow(File).to receive(:directory?).with("#{env_pwd}/.chef").and_return(true) end it "prefers the config from parent_dir/.chef" do expect(config_loader.config_location).to eq("#{env_pwd}/.chef/knife.rb") end context "and the parent dir's .chef dir has a config.rb" do before do allow(config_loader).to receive(:path_exists?).with("#{env_pwd}/.chef/config.rb").and_return(true) end it "prefers the config from parent_dir/.chef" do expect(config_loader.config_location).to eq("#{env_pwd}/.chef/config.rb") end context "and/or the current working directory contains a .chef dir" do let(:cwd) { Dir.pwd } before do allow(config_loader).to receive(:path_exists?).with("#{cwd}/knife.rb").and_return(true) end it "prefers a knife.rb located in the cwd" do expect(config_loader.config_location).to eq("#{cwd}/knife.rb") end context "and the CWD's .chef dir has a config.rb" do before do allow(config_loader).to receive(:path_exists?).with("#{cwd}/config.rb").and_return(true) end it "prefers a config located in the cwd" do expect(config_loader.config_location).to eq("#{cwd}/config.rb") end context "and/or KNIFE_HOME is set" do let(:knife_home) { "/path/to/knife/home" } before do env["KNIFE_HOME"] = knife_home allow(config_loader).to receive(:path_exists?).with("#{knife_home}/knife.rb").and_return(true) end it "prefers a knife located in KNIFE_HOME" do expect(config_loader.config_location).to eq("/path/to/knife/home/knife.rb") end context "and KNIFE_HOME contains a config.rb" do before do env["KNIFE_HOME"] = knife_home allow(config_loader).to receive(:path_exists?).with("#{knife_home}/config.rb").and_return(true) end it "prefers a config.rb located in KNIFE_HOME" do expect(config_loader.config_location).to eq("/path/to/knife/home/config.rb") end end end end end end end end end context "when the current working dir is inside a symlinked directory" do before do # pwd according to your shell is /home/someuser/prod/chef-repo, but # chef-repo is a symlink to /home/someuser/codes/chef-repo env["CD"] = "/home/someuser/prod/chef-repo" # windows env["PWD"] = "/home/someuser/prod/chef-repo" # unix allow(Dir).to receive(:pwd).and_return("/home/someuser/codes/chef-repo") end it "loads the config from the non-dereferenced directory path" do expect(File).to receive(:exist?).with("/home/someuser/prod/chef-repo/.chef").and_return(false) expect(File).to receive(:exist?).with("/home/someuser/prod/.chef").and_return(true) expect(File).to receive(:directory?).with("/home/someuser/prod/.chef").and_return(true) expect(config_loader).to receive(:path_exists?).with("/home/someuser/prod/.chef/knife.rb").and_return(true) expect(config_loader.config_location).to eq("/home/someuser/prod/.chef/knife.rb") end end end context "when given an explicit config to load" do let(:explicit_config_location) { "/path/to/explicit/config.rb" } it "prefers the explicit config" do expect(config_loader.config_location).to eq(explicit_config_location) end end end describe "loading the config file" do context "when no explicit config is specifed and no implicit config is found" do before do allow(config_loader).to receive(:path_exists?).with(an_instance_of(String)).and_return(false) end it "skips loading" do expect(config_loader.config_location).to be(nil) expect(config_loader).not_to receive(:apply_config) config_loader.load end end context "when an explicit config is given but it doesn't exist" do let(:explicit_config_location) { "/nope/nope/nope/frab/jab/nab" } it "raises a configuration error" do expect { config_loader.load }.to raise_error(ChefConfig::ConfigurationError) end end context "when the config file exists" do let(:config_content) { "" } # We need to keep a reference to the tempfile because while #close does # not unlink the file, the object being GC'd will. let(:tempfile) do Tempfile.new("Chef-WorkstationConfigLoader-rspec-test").tap do |t| t.print(config_content) t.close end end let(:explicit_config_location) do tempfile.path end after { File.unlink(explicit_config_location) if File.exist?(explicit_config_location) } context "and is valid" do let(:config_content) { "config_file_evaluated(true)" } it "loads the config" do expect(config_loader).to receive(:apply_config).and_call_original config_loader.load expect(ChefConfig::Config.config_file_evaluated).to be(true) end it "sets ChefConfig::Config.config_file" do config_loader.load expect(ChefConfig::Config.config_file).to eq(explicit_config_location) end end context "and has a syntax error" do let(:config_content) { "{{{{{:{{" } it "raises a ConfigurationError" do expect { config_loader.load }.to raise_error(ChefConfig::ConfigurationError) end end context "and raises a ruby exception during evaluation" do let(:config_content) { ":foo\n:bar\nraise 'oops'\n:baz\n" } it "raises a ConfigurationError" do expect { config_loader.load }.to raise_error(ChefConfig::ConfigurationError) end end end end describe "when loading config.d" do context "when the conf.d directory exists" do let(:config_content) { "" } let(:tempdir) { Dir.mktmpdir("chef-workstation-test") } let!(:confd_file) do Tempfile.new(["Chef-WorkstationConfigLoader-rspec-test", ".rb"], tempdir).tap do |t| t.print(config_content) t.close end end before do ChefConfig::Config[:config_d_dir] = tempdir allow(config_loader).to receive(:path_exists?).with( an_instance_of(String)).and_return(false) end after do FileUtils.remove_entry_secure tempdir end context "and is valid" do let(:config_content) { "config_d_file_evaluated(true)" } it "loads the config" do expect(config_loader).to receive(:apply_config).and_call_original config_loader.load expect(ChefConfig::Config.config_d_file_evaluated).to be(true) end end context "and has a syntax error" do let(:config_content) { "{{{{{:{{" } it "raises a ConfigurationError" do expect { config_loader.load }.to raise_error(ChefConfig::ConfigurationError) end end context "has a non rb file" do let(:sytax_error_content) { "{{{{{:{{" } let(:config_content) { "config_d_file_evaluated(true)" } let!(:not_confd_file) do Tempfile.new(["Chef-WorkstationConfigLoader-rspec-test", ".foorb"], tempdir).tap do |t| t.print(sytax_error_content) t.close end end it "does not load the non rb file" do expect { config_loader.load }.not_to raise_error expect(ChefConfig::Config.config_d_file_evaluated).to be(true) end end end context "when the conf.d directory does not exist" do before do ChefConfig::Config[:config_d_dir] = "/nope/nope/nope/nope/notdoingit" end it "does not load anything" do expect(config_loader).not_to receive(:apply_config) end end end end
apache-2.0
kjvarga/google-api-ads-ruby
dfp_api/examples/v201611/company_service/create_companies.rb
2334
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright:: Copyright 2011, Google Inc. All Rights Reserved. # # License:: Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # This example creates new companies. To determine which companies exist, run # get_all_companies.rb. require 'dfp_api' API_VERSION = :v201611 # Number of companies to create. ITEM_COUNT = 5 def create_companies() # Get DfpApi instance and load configuration from ~/dfp_api.yml. dfp = DfpApi::Api.new # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in # the configuration file or provide your own logger: # dfp.logger = Logger.new('dfp_xml.log') # Get the CompanyService. company_service = dfp.service(:CompanyService, API_VERSION) # Create an array to store local company objects. companies = (1..ITEM_COUNT).map do |index| {:name => "Advertiser #%d-%d" % [Time.new.to_f * 1000, index], :type => 'ADVERTISER'} end # Create the companies on the server. return_companies = company_service.create_companies(companies) if return_companies return_companies.each do |company| puts "Company with ID: %d, name: %s and type: %s was created." % [company[:id], company[:name], company[:type]] end else raise 'No companies were created.' end end if __FILE__ == $0 begin create_companies() # HTTP errors. rescue AdsCommon::Errors::HttpError => e puts "HTTP Error: %s" % e # API errors. rescue DfpApi::Errors::ApiException => e puts "Message: %s" % e.message puts 'Errors:' e.errors.each_with_index do |error, index| puts "\tError [%d]:" % (index + 1) error.each do |field, value| puts "\t\t%s: %s" % [field, value] end end end end
apache-2.0
vdmeer/skb-java-interfaces
src/main/java/de/vandermeer/skb/interfaces/transformers/textformat/TextAlignment.java
2034
/* Copyright 2017 Sven van der Meer <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.vandermeer.skb.interfaces.transformers.textformat; /** * Options for text alignment. * * @author Sven van der Meer &lt;[email protected]&gt; * @version v0.0.2 build 170502 (02-May-17) for Java 1.8 * @since v0.0.1 */ public enum TextAlignment { /** Option for a justified alignment. */ JUSTIFIED (Text_To_FormattedText.ALIGN_JUSTIFIED), /** Option for a justified alignment, last line right aligned. */ JUSTIFIED_RIGHT (Text_To_FormattedText.ALIGN_JUSTIFIED_RIGHT), /** Option for a justified alignment, last line left left aligned. */ JUSTIFIED_LEFT (Text_To_FormattedText.ALIGN_JUSTIFIED_LEFT), /** Option for paragraph alignment left. */ LEFT (Text_To_FormattedText.ALIGN_LEFT), /** Option for paragraph alignment center. */ CENTER (Text_To_FormattedText.ALIGN_CENTER), /** Option for paragraph alignment right. */ RIGHT (Text_To_FormattedText.ALIGN_RIGHT), ; /** A mapping to the alignment options in {@link Text_To_FormattedText}. */ protected int mapping; /** * Creates a new alignment. * @param mapping mapping to transformer options */ TextAlignment(int mapping){ this.mapping = mapping; } /** * Returns a mapping to the alignment options defined in {@link Text_To_FormattedText}. * @return mapping */ public int getMapping(){ return this.mapping; } }
apache-2.0
CMPUT301W14T08/GeoChan
GeoChan/src/ca/ualberta/cmput301w14t08/geochan/runnables/GetImageRunnable.java
3176
/* * Copyright 2014 Artem Chikin * Copyright 2014 Artem Herasymchuk * Copyright 2014 Tom Krywitsky * Copyright 2014 Henry Pabst * Copyright 2014 Bradley Simons * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ca.ualberta.cmput301w14t08.geochan.runnables; import io.searchbox.client.JestResult; import io.searchbox.core.Get; import java.lang.reflect.Type; import android.graphics.Bitmap; import ca.ualberta.cmput301w14t08.geochan.helpers.ElasticSearchClient; import ca.ualberta.cmput301w14t08.geochan.helpers.GsonHelper; import ca.ualberta.cmput301w14t08.geochan.models.ElasticSearchResponse; import ca.ualberta.cmput301w14t08.geochan.tasks.GetImageTask; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; /** * Runnable for retrieving a bitmap object in a separate thread of execution from * ElasticSearch. * * @author Artem Chikin * */ public class GetImageRunnable implements Runnable { private GetImageTask task; private String type = ElasticSearchClient.TYPE_IMAGE; public static final int STATE_GET_IMAGE_FAILED = -1; public static final int STATE_GET_IMAGE_RUNNING = 0; public static final int STATE_GET_IMAGE_COMPLETE = 1; public GetImageRunnable(GetImageTask task) { this.task = task; } /** * Forms a query and sends a get request to ES, * then processes retrieved data as a bitmap and * sends it to the task's cache. */ @Override public void run() { task.setGetImageThread(Thread.currentThread()); android.os.Process .setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); task.handleGetImageState(STATE_GET_IMAGE_RUNNING); JestResult result = null; try { if (Thread.interrupted()) { throw new InterruptedException(); } Get get = new Get.Builder(ElasticSearchClient.URL_INDEX, task.getId()).type(type).build(); result = ElasticSearchClient.getInstance().getClient().execute(get); Type type = new TypeToken<ElasticSearchResponse<Bitmap>>() { }.getType(); Gson gson = GsonHelper.getOnlineGson(); ElasticSearchResponse<Bitmap> esResponse = gson.fromJson( result.getJsonString(), type); if (Thread.interrupted()) { throw new InterruptedException(); } task.setImageCache(esResponse.getSource()); task.handleGetImageState(STATE_GET_IMAGE_COMPLETE); } catch (Exception e) { e.printStackTrace(); } finally { if (result == null || !result.isSucceeded()) { task.handleGetImageState(STATE_GET_IMAGE_FAILED); } // task.setGetImageThread(null); Thread.interrupted(); } } }
apache-2.0
cictourgune/MDP-Airbnb
httpcomponents-core-4.4/httpcore-nio/src/main/java/org/apache/http/nio/pool/AbstractNIOConnPool.java
27010
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.pool; import java.io.IOException; import java.net.SocketAddress; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.http.annotation.ThreadSafe; import org.apache.http.concurrent.BasicFuture; import org.apache.http.concurrent.FutureCallback; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOReactorStatus; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionRequest; import org.apache.http.nio.reactor.SessionRequestCallback; import org.apache.http.pool.ConnPool; import org.apache.http.pool.ConnPoolControl; import org.apache.http.pool.PoolEntry; import org.apache.http.pool.PoolEntryCallback; import org.apache.http.pool.PoolStats; import org.apache.http.util.Args; import org.apache.http.util.Asserts; /** * Abstract non-blocking connection pool. * * @param <T> route * @param <C> connection object * @param <E> pool entry * * @since 4.2 */ @ThreadSafe public abstract class AbstractNIOConnPool<T, C, E extends PoolEntry<T, C>> implements ConnPool<T, E>, ConnPoolControl<T> { private final ConnectingIOReactor ioreactor; private final NIOConnFactory<T, C> connFactory; private final SocketAddressResolver<T> addressResolver; private final SessionRequestCallback sessionRequestCallback; private final Map<T, RouteSpecificPool<T, C, E>> routeToPool; private final LinkedList<LeaseRequest<T, C, E>> leasingRequests; private final Set<SessionRequest> pending; private final Set<E> leased; private final LinkedList<E> available; private final ConcurrentLinkedQueue<LeaseRequest<T, C, E>> completedRequests; private final Map<T, Integer> maxPerRoute; private final Lock lock; private final AtomicBoolean isShutDown; private volatile int defaultMaxPerRoute; private volatile int maxTotal; /** * @deprecated use {@link AbstractNIOConnPool#AbstractNIOConnPool(ConnectingIOReactor, * NIOConnFactory, SocketAddressResolver, int, int)} */ @Deprecated public AbstractNIOConnPool( final ConnectingIOReactor ioreactor, final NIOConnFactory<T, C> connFactory, final int defaultMaxPerRoute, final int maxTotal) { super(); Args.notNull(ioreactor, "I/O reactor"); Args.notNull(connFactory, "Connection factory"); Args.positive(defaultMaxPerRoute, "Max per route value"); Args.positive(maxTotal, "Max total value"); this.ioreactor = ioreactor; this.connFactory = connFactory; this.addressResolver = new SocketAddressResolver<T>() { @Override public SocketAddress resolveLocalAddress(final T route) throws IOException { return AbstractNIOConnPool.this.resolveLocalAddress(route); } @Override public SocketAddress resolveRemoteAddress(final T route) throws IOException { return AbstractNIOConnPool.this.resolveRemoteAddress(route); } }; this.sessionRequestCallback = new InternalSessionRequestCallback(); this.routeToPool = new HashMap<T, RouteSpecificPool<T, C, E>>(); this.leasingRequests = new LinkedList<LeaseRequest<T, C, E>>(); this.pending = new HashSet<SessionRequest>(); this.leased = new HashSet<E>(); this.available = new LinkedList<E>(); this.maxPerRoute = new HashMap<T, Integer>(); this.completedRequests = new ConcurrentLinkedQueue<LeaseRequest<T, C, E>>(); this.lock = new ReentrantLock(); this.isShutDown = new AtomicBoolean(false); this.defaultMaxPerRoute = defaultMaxPerRoute; this.maxTotal = maxTotal; } /** * @since 4.3 */ public AbstractNIOConnPool( final ConnectingIOReactor ioreactor, final NIOConnFactory<T, C> connFactory, final SocketAddressResolver<T> addressResolver, final int defaultMaxPerRoute, final int maxTotal) { super(); Args.notNull(ioreactor, "I/O reactor"); Args.notNull(connFactory, "Connection factory"); Args.notNull(addressResolver, "Address resolver"); Args.positive(defaultMaxPerRoute, "Max per route value"); Args.positive(maxTotal, "Max total value"); this.ioreactor = ioreactor; this.connFactory = connFactory; this.addressResolver = addressResolver; this.sessionRequestCallback = new InternalSessionRequestCallback(); this.routeToPool = new HashMap<T, RouteSpecificPool<T, C, E>>(); this.leasingRequests = new LinkedList<LeaseRequest<T, C, E>>(); this.pending = new HashSet<SessionRequest>(); this.leased = new HashSet<E>(); this.available = new LinkedList<E>(); this.completedRequests = new ConcurrentLinkedQueue<LeaseRequest<T, C, E>>(); this.maxPerRoute = new HashMap<T, Integer>(); this.lock = new ReentrantLock(); this.isShutDown = new AtomicBoolean(false); this.defaultMaxPerRoute = defaultMaxPerRoute; this.maxTotal = maxTotal; } /** * @deprecated (4.3) use {@link SocketAddressResolver} */ @Deprecated protected SocketAddress resolveRemoteAddress(final T route) { return null; } /** * @deprecated (4.3) use {@link SocketAddressResolver} */ @Deprecated protected SocketAddress resolveLocalAddress(final T route) { return null; } protected abstract E createEntry(T route, C conn); /** * @since 4.3 */ protected void onLease(final E entry) { } /** * @since 4.3 */ protected void onRelease(final E entry) { } /** * @since 4.4 */ protected void onReuse(final E entry) { } public boolean isShutdown() { return this.isShutDown.get(); } public void shutdown(final long waitMs) throws IOException { if (this.isShutDown.compareAndSet(false, true)) { fireCallbacks(); this.lock.lock(); try { for (final SessionRequest sessionRequest: this.pending) { sessionRequest.cancel(); } for (final E entry: this.available) { entry.close(); } for (final E entry: this.leased) { entry.close(); } for (final RouteSpecificPool<T, C, E> pool: this.routeToPool.values()) { pool.shutdown(); } this.routeToPool.clear(); this.leased.clear(); this.pending.clear(); this.available.clear(); this.leasingRequests.clear(); this.ioreactor.shutdown(waitMs); } finally { this.lock.unlock(); } } } private RouteSpecificPool<T, C, E> getPool(final T route) { RouteSpecificPool<T, C, E> pool = this.routeToPool.get(route); if (pool == null) { pool = new RouteSpecificPool<T, C, E>(route) { @Override protected E createEntry(final T route, final C conn) { return AbstractNIOConnPool.this.createEntry(route, conn); } }; this.routeToPool.put(route, pool); } return pool; } public Future<E> lease( final T route, final Object state, final long connectTimeout, final TimeUnit tunit, final FutureCallback<E> callback) { return this.lease(route, state, connectTimeout, connectTimeout, tunit, callback); } /** * @since 4.3 */ public Future<E> lease( final T route, final Object state, final long connectTimeout, final long leaseTimeout, final TimeUnit tunit, final FutureCallback<E> callback) { Args.notNull(route, "Route"); Args.notNull(tunit, "Time unit"); Asserts.check(!this.isShutDown.get(), "Connection pool shut down"); final BasicFuture<E> future = new BasicFuture<E>(callback); this.lock.lock(); try { final long timeout = connectTimeout > 0 ? tunit.toMillis(connectTimeout) : 0; final LeaseRequest<T, C, E> request = new LeaseRequest<T, C, E>(route, state, timeout, leaseTimeout, future); final boolean completed = processPendingRequest(request); if (!request.isDone() && !completed) { this.leasingRequests.add(request); } if (request.isDone()) { this.completedRequests.add(request); } } finally { this.lock.unlock(); } fireCallbacks(); return future; } @Override public Future<E> lease(final T route, final Object state, final FutureCallback<E> callback) { return lease(route, state, -1, TimeUnit.MICROSECONDS, callback); } public Future<E> lease(final T route, final Object state) { return lease(route, state, -1, TimeUnit.MICROSECONDS, null); } @Override public void release(final E entry, final boolean reusable) { if (entry == null) { return; } if (this.isShutDown.get()) { return; } this.lock.lock(); try { if (this.leased.remove(entry)) { final RouteSpecificPool<T, C, E> pool = getPool(entry.getRoute()); pool.free(entry, reusable); if (reusable) { this.available.addFirst(entry); onRelease(entry); } else { entry.close(); } processNextPendingRequest(); } } finally { this.lock.unlock(); } fireCallbacks(); } private void processPendingRequests() { final ListIterator<LeaseRequest<T, C, E>> it = this.leasingRequests.listIterator(); while (it.hasNext()) { final LeaseRequest<T, C, E> request = it.next(); final boolean completed = processPendingRequest(request); if (request.isDone() || completed) { it.remove(); } if (request.isDone()) { this.completedRequests.add(request); } } } private void processNextPendingRequest() { final ListIterator<LeaseRequest<T, C, E>> it = this.leasingRequests.listIterator(); while (it.hasNext()) { final LeaseRequest<T, C, E> request = it.next(); final boolean completed = processPendingRequest(request); if (request.isDone() || completed) { it.remove(); } if (request.isDone()) { this.completedRequests.add(request); } if (completed) { return; } } } private boolean processPendingRequest(final LeaseRequest<T, C, E> request) { final T route = request.getRoute(); final Object state = request.getState(); final long deadline = request.getDeadline(); final long now = System.currentTimeMillis(); if (now > deadline) { request.failed(new TimeoutException()); return false; } final RouteSpecificPool<T, C, E> pool = getPool(route); E entry; for (;;) { entry = pool.getFree(state); if (entry == null) { break; } if (entry.isClosed() || entry.isExpired(System.currentTimeMillis())) { entry.close(); this.available.remove(entry); pool.free(entry, false); } else { break; } } if (entry != null) { this.available.remove(entry); this.leased.add(entry); request.completed(entry); onReuse(entry); onLease(entry); return true; } // New connection is needed final int maxPerRoute = getMax(route); // Shrink the pool prior to allocating a new connection final int excess = Math.max(0, pool.getAllocatedCount() + 1 - maxPerRoute); if (excess > 0) { for (int i = 0; i < excess; i++) { final E lastUsed = pool.getLastUsed(); if (lastUsed == null) { break; } lastUsed.close(); this.available.remove(lastUsed); pool.remove(lastUsed); } } if (pool.getAllocatedCount() < maxPerRoute) { final int totalUsed = this.pending.size() + this.leased.size(); final int freeCapacity = Math.max(this.maxTotal - totalUsed, 0); if (freeCapacity == 0) { return false; } final int totalAvailable = this.available.size(); if (totalAvailable > freeCapacity - 1) { if (!this.available.isEmpty()) { final E lastUsed = this.available.removeLast(); lastUsed.close(); final RouteSpecificPool<T, C, E> otherpool = getPool(lastUsed.getRoute()); otherpool.remove(lastUsed); } } final SocketAddress localAddress; final SocketAddress remoteAddress; try { remoteAddress = this.addressResolver.resolveRemoteAddress(route); localAddress = this.addressResolver.resolveLocalAddress(route); } catch (final IOException ex) { request.failed(ex); return false; } final SessionRequest sessionRequest = this.ioreactor.connect( remoteAddress, localAddress, route, this.sessionRequestCallback); final int timout = request.getConnectTimeout() < Integer.MAX_VALUE ? (int) request.getConnectTimeout() : Integer.MAX_VALUE; sessionRequest.setConnectTimeout(timout); this.pending.add(sessionRequest); pool.addPending(sessionRequest, request.getFuture()); return true; } else { return false; } } private void fireCallbacks() { LeaseRequest<T, C, E> request; while ((request = this.completedRequests.poll()) != null) { final BasicFuture<E> future = request.getFuture(); final Exception ex = request.getException(); final E result = request.getResult(); if (ex != null) { future.failed(ex); } else if (result != null) { future.completed(result); } else { future.cancel(); } } } public void validatePendingRequests() { this.lock.lock(); try { final long now = System.currentTimeMillis(); final ListIterator<LeaseRequest<T, C, E>> it = this.leasingRequests.listIterator(); while (it.hasNext()) { final LeaseRequest<T, C, E> request = it.next(); final long deadline = request.getDeadline(); if (now > deadline) { it.remove(); request.failed(new TimeoutException()); this.completedRequests.add(request); } } } finally { this.lock.unlock(); } fireCallbacks(); } protected void requestCompleted(final SessionRequest request) { if (this.isShutDown.get()) { return; } @SuppressWarnings("unchecked") final T route = (T) request.getAttachment(); this.lock.lock(); try { this.pending.remove(request); final RouteSpecificPool<T, C, E> pool = getPool(route); final IOSession session = request.getSession(); try { final C conn = this.connFactory.create(route, session); final E entry = pool.createEntry(request, conn); this.leased.add(entry); pool.completed(request, entry); onLease(entry); } catch (final IOException ex) { pool.failed(request, ex); } } finally { this.lock.unlock(); } fireCallbacks(); } protected void requestCancelled(final SessionRequest request) { if (this.isShutDown.get()) { return; } @SuppressWarnings("unchecked") final T route = (T) request.getAttachment(); this.lock.lock(); try { this.pending.remove(request); final RouteSpecificPool<T, C, E> pool = getPool(route); pool.cancelled(request); if (this.ioreactor.getStatus().compareTo(IOReactorStatus.ACTIVE) <= 0) { processNextPendingRequest(); } } finally { this.lock.unlock(); } fireCallbacks(); } protected void requestFailed(final SessionRequest request) { if (this.isShutDown.get()) { return; } @SuppressWarnings("unchecked") final T route = (T) request.getAttachment(); this.lock.lock(); try { this.pending.remove(request); final RouteSpecificPool<T, C, E> pool = getPool(route); pool.failed(request, request.getException()); processNextPendingRequest(); } finally { this.lock.unlock(); } fireCallbacks(); } protected void requestTimeout(final SessionRequest request) { if (this.isShutDown.get()) { return; } @SuppressWarnings("unchecked") final T route = (T) request.getAttachment(); this.lock.lock(); try { this.pending.remove(request); final RouteSpecificPool<T, C, E> pool = getPool(route); pool.timeout(request); processNextPendingRequest(); } finally { this.lock.unlock(); } fireCallbacks(); } private int getMax(final T route) { final Integer v = this.maxPerRoute.get(route); if (v != null) { return v.intValue(); } else { return this.defaultMaxPerRoute; } } @Override public void setMaxTotal(final int max) { Args.positive(max, "Max value"); this.lock.lock(); try { this.maxTotal = max; } finally { this.lock.unlock(); } } @Override public int getMaxTotal() { this.lock.lock(); try { return this.maxTotal; } finally { this.lock.unlock(); } } @Override public void setDefaultMaxPerRoute(final int max) { Args.positive(max, "Max value"); this.lock.lock(); try { this.defaultMaxPerRoute = max; } finally { this.lock.unlock(); } } @Override public int getDefaultMaxPerRoute() { this.lock.lock(); try { return this.defaultMaxPerRoute; } finally { this.lock.unlock(); } } @Override public void setMaxPerRoute(final T route, final int max) { Args.notNull(route, "Route"); Args.positive(max, "Max value"); this.lock.lock(); try { this.maxPerRoute.put(route, Integer.valueOf(max)); } finally { this.lock.unlock(); } } @Override public int getMaxPerRoute(final T route) { Args.notNull(route, "Route"); this.lock.lock(); try { return getMax(route); } finally { this.lock.unlock(); } } @Override public PoolStats getTotalStats() { this.lock.lock(); try { return new PoolStats( this.leased.size(), this.pending.size(), this.available.size(), this.maxTotal); } finally { this.lock.unlock(); } } @Override public PoolStats getStats(final T route) { Args.notNull(route, "Route"); this.lock.lock(); try { final RouteSpecificPool<T, C, E> pool = getPool(route); return new PoolStats( pool.getLeasedCount(), pool.getPendingCount(), pool.getAvailableCount(), getMax(route)); } finally { this.lock.unlock(); } } /** * Returns snapshot of all knows routes * * @since 4.4 */ public Set<T> getRoutes() { this.lock.lock(); try { return new HashSet<T>(routeToPool.keySet()); } finally { this.lock.unlock(); } } /** * Enumerates all available connections. * * @since 4.3 */ protected void enumAvailable(final PoolEntryCallback<T, C> callback) { this.lock.lock(); try { final Iterator<E> it = this.available.iterator(); while (it.hasNext()) { final E entry = it.next(); callback.process(entry); if (entry.isClosed()) { final RouteSpecificPool<T, C, E> pool = getPool(entry.getRoute()); pool.remove(entry); it.remove(); } } processPendingRequests(); purgePoolMap(); } finally { this.lock.unlock(); } } /** * Enumerates all leased connections. * * @since 4.3 */ protected void enumLeased(final PoolEntryCallback<T, C> callback) { this.lock.lock(); try { final Iterator<E> it = this.leased.iterator(); while (it.hasNext()) { final E entry = it.next(); callback.process(entry); } processPendingRequests(); } finally { this.lock.unlock(); } } /** * Use {@link #enumLeased(org.apache.http.pool.PoolEntryCallback)} * or {@link #enumAvailable(org.apache.http.pool.PoolEntryCallback)} instead. * * @deprecated (4.3.2) */ @Deprecated protected void enumEntries(final Iterator<E> it, final PoolEntryCallback<T, C> callback) { while (it.hasNext()) { final E entry = it.next(); callback.process(entry); } processPendingRequests(); } private void purgePoolMap() { final Iterator<Map.Entry<T, RouteSpecificPool<T, C, E>>> it = this.routeToPool.entrySet().iterator(); while (it.hasNext()) { final Map.Entry<T, RouteSpecificPool<T, C, E>> entry = it.next(); final RouteSpecificPool<T, C, E> pool = entry.getValue(); if (pool.getAllocatedCount() == 0) { it.remove(); } } } public void closeIdle(final long idletime, final TimeUnit tunit) { Args.notNull(tunit, "Time unit"); long time = tunit.toMillis(idletime); if (time < 0) { time = 0; } final long deadline = System.currentTimeMillis() - time; enumAvailable(new PoolEntryCallback<T, C>() { @Override public void process(final PoolEntry<T, C> entry) { if (entry.getUpdated() <= deadline) { entry.close(); } } }); } public void closeExpired() { final long now = System.currentTimeMillis(); enumAvailable(new PoolEntryCallback<T, C>() { @Override public void process(final PoolEntry<T, C> entry) { if (entry.isExpired(now)) { entry.close(); } } }); } @Override public String toString() { final StringBuilder buffer = new StringBuilder(); buffer.append("[leased: "); buffer.append(this.leased); buffer.append("][available: "); buffer.append(this.available); buffer.append("][pending: "); buffer.append(this.pending); buffer.append("]"); return buffer.toString(); } class InternalSessionRequestCallback implements SessionRequestCallback { @Override public void completed(final SessionRequest request) { requestCompleted(request); } @Override public void cancelled(final SessionRequest request) { requestCancelled(request); } @Override public void failed(final SessionRequest request) { requestFailed(request); } @Override public void timeout(final SessionRequest request) { requestTimeout(request); } } }
apache-2.0
ity/pants
tests/java/org/pantsbuild/tools/junit/lib/AnnotationOverrideClass.java
619
// Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). package org.pantsbuild.tools.junit.lib; import org.pantsbuild.junit.annotations.TestParallel; import org.pantsbuild.junit.annotations.TestParallelBoth; import org.pantsbuild.junit.annotations.TestParallelMethods; import org.pantsbuild.junit.annotations.TestSerial; /** * Tests the annotation override behavior. * {@link TestSerial} should override all other annotations. */ @TestParallel @TestSerial @TestParallelMethods @TestParallelBoth public class AnnotationOverrideClass { }
apache-2.0
google-research/google-research
uflow/misc/convert_video_to_dataset_test.py
1658
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for convert_video_to_dataset.""" from absl.testing import absltest import tensorflow as tf from uflow.data import generic_flow_dataset from uflow.misc import convert_video_to_dataset class ConvertVideoToDatasetTest(absltest.TestCase): def test_video_parsing(self): """Test that we can convert a video to a dataset and load it correctly.""" filepath = 'uflow/files/billiard_clip.mp4' output_dir = '/tmp/dataset' convert_video_to_dataset.convert_video( video_file_path=filepath, output_folder=output_dir) dataset = generic_flow_dataset.make_dataset(path=output_dir, mode='test') data_iterator = tf.compat.v1.data.make_one_shot_iterator(dataset) count = 0 for element in data_iterator: image1, image2 = element count += 1 self.assertEqual(image1.shape[0], image2.shape[0]) self.assertEqual(image1.shape[1], image2.shape[1]) self.assertEqual(image1.shape[2], 3) self.assertEqual(count, 299) if __name__ == '__main__': absltest.main()
apache-2.0
openfoodfacts/OpenFoodFacts-androidApp
app/src/main/java/openfoodfacts/github/scrachx/openfood/utils/QuantityParserUtil.java
3801
package openfoodfacts.github.scrachx.openfood.utils; import android.util.Log; import android.widget.Spinner; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.apache.commons.lang.StringUtils; public class QuantityParserUtil { public enum EntryFormat { //value can start with <>~ WITH_KNOWN_PREFIX, //no prefix NO_PREFIX } private QuantityParserUtil() { } public static boolean isModifierEqualsToGreaterThan(@NonNull CustomValidatingEditTextView view) { return isModifierEqualsToGreaterThan(view.getModSpinner()); } public static boolean isModifierEqualsToGreaterThan(@NonNull Spinner text) { return Modifier.GREATER_THAN.equals(Modifier.MODIFIERS[text.getSelectedItemPosition()]); } public static boolean isBlank(@NonNull TextView editText) { return StringUtils.isBlank(editText.getText().toString()); } public static boolean isNotBlank(TextView editText) { return !isBlank(editText); } /** * @param editText the textview * @return the float value or null if not correct * @see #getFloatValue(String) */ @Nullable public static Float getFloatValue(@NonNull TextView editText) { if (editText.getText() == null) { return null; } final String text = editText.getText().toString(); return getFloatValue(text); } public static float getFloatValueOrDefault(TextView editText, float defaultValue) { Float res = getFloatValue(editText); return res == null ? defaultValue : res; } /** * @param editText the textview * @return the float value or null if not correct * @see #getFloatValue(String) */ @Nullable public static Double getDoubleValue(@NonNull TextView editText) { if (editText.getText() == null) { return null; } final String text = editText.getText().toString(); return getDoubleValue(text); } public static boolean containFloatValue(TextView editText) { return editText != null && containFloatValue(editText.getText().toString()); } public static boolean containFloatValue(String text) { return getFloatValue(text) != null; } public static boolean containDoubleValue(String text) { return getDoubleValue(text) != null; } /** * Retrieve the float value from strings like "> 1.03" * * @param initText value to parse * @return the float value or null if not correct */ @Nullable public static Float getFloatValue(String initText) { Double result = getDoubleValue(initText); if (result != null) { return result.floatValue(); } return null; } /** * Retrieve the float value from strings like "> 1.03" * * @param initText value to parse * @return the float value or null if not correct */ @Nullable public static Double getDoubleValue(String initText) { if (StringUtils.isBlank(initText)) { return null; } String text = StringUtils.trim(initText); text = replaceCommaByDot(text); try { return Double.parseDouble(text); } catch (NumberFormatException ex) { Log.d("Utils", "can't parse text: " + text); } return null; } /** * For french input "," is used instead of "." * * @param text * @return text with , replaced by . */ private static String replaceCommaByDot(@NonNull String text) { if (text.contains(",")) { text = StringUtils.replace(text, ",", "."); } return text; } }
apache-2.0
tasa95/Sudoku
app/controllers/tableSudoku.js
8724
// Function to test if device is iOS 7 or later function isIOS_Seven_Plus() { // iOS-specific test if (Titanium.Platform.name == 'iPhone OS') { var version = Titanium.Platform.version.split("."); var major = parseInt(version[0], 10); // Can only test this support on a 3.2+ device if (major >= 7) { return true; } } return false; } function createNewGame() { var c = Alloy.createController("newGame",{}); c.getView().addEventListener("restart",function(e){ $.windowTable.close(); $.windowTable.fireEvent('new_game', { retour : 0 }); }); c.getView().open() ; } function ExitGame() { var c = Alloy.createController("QuitGame",{}); c.getView().addEventListener("exit",function(e){ $.windowTable.close(); $.windowTable.fireEvent('quitGame', { retour : 0 }); }); c.getView().open() ; } function saveScore(){ var secondModel = parseInt($.Second.text, 10); var minuteModel = parseInt($.Minute.text, 10); var hourModel = parseInt($.Hour.text, 10); var scoreModel = Alloy.createModel('score',{ hour : hourModel, minute : minuteModel, second : secondModel, }); scoreModel.save(); } function timer(addTime) { var left_over = 0; var second = parseInt($.Second.text, 10); var minute = parseInt($.Minute.text, 10); var hour = parseInt($.Hour.text, 10); if (!addTime) { second++; } else { second = second + addTime; } if (second >= 60) { var left_over = second % 60; second = left_over; minute++; if (minute >= 60) { minute = 0; hour++; } } if (second >= 0 && second < 10) $.Second.text = "0" + second; else $.Second.text = second; if (minute >= 0 && minute < 10) $.Minute.text = "0" + minute; else $.Minute.text = minute; if (hour >= 0 && hour < 10) $.Hour.text = "0" + hour; else $.hour.text = hour; } var args = arguments[0]; var sudoku = []; var sudoku = args.table; /*************************************/ var width = Titanium.Platform.displayCaps.platformWidth; var height = Titanium.Platform.displayCaps.platformHeight * 0.60; var border = (width * 0.3) / 100; var tinyBorderHorizontal = (height * 0.005); var tinyBorderVertical = (width * 0.005); var row_height = (height * 0.94 ) / 9; var cell_width = (width * 0.94) / 9; var color_border = '#040430'; var second_color = '#D9F1FE'; var first_color = '#FFFFFF'; function stopGame(refreshIntervalId) { clearInterval(refreshIntervalId); saveScore(); createNewGame(); } function verify_valueElement(e) { var letters = /^[1-9]+$/; var testMultipleZero = /^0*$/; if (e.value != e.source.oldValue) { if (e.value.match(letters)) { e.value = e.value % 10; //Ti.API.info("aaa oldValue = " +e.source.oldValue + " newValue = "+ e.value ); e.source.oldValue = e.value; e.source.value = e.value; } else { if (e.value === "") { e.source.oldValue = e.value; e.source.value = e.value; } else { e.source.value = ""; } } } } var tableData = []; var table = Ti.UI.createTableView({ separatorStyle : 0, width : Ti.UI.FILL, height : Ti.UI.SIZE, bottom : "2%", moveable : false, moving : false, scrollable : false }); var number_line = sudoku.length - 1; var empty_cells = 0; listTextfield = []; for (var i = 0; i < number_line; i++) { var row = Ti.UI.createTableViewRow({ className : 'row', objName : 'row_' + i, textAlign : Titanium.UI.TEXT_ALIGNMENT_CENTER, layout : "vertical", height : row_height, moveable : false, moving : false, scrollable : false, focusable : false, editable : false, touchEnabled : false, allowsSelection : false, }); if (Titanium.Platform.name == 'iPhone OS') { row.selectionStyle = Titanium.UI.iPhone.TableViewCellSelectionStyle.NONE; } else { } var LineSudokuView = Ti.UI.createView({ backgroundColor : '#FFFFFF', objName : 'horizontalView', rowID : i, height : Ti.UI.FILL, layout : "horizontal", width : Ti.UI.FILL, }); if (sudoku[i]) { number_column = sudoku[i].length; for (var j = 0; j < number_column; j++) { var random = Math.floor(Math.random() * 1000); if ((Math.floor(j / 3) + Math.floor(i / 3) * 3) % 2 === 0) { var color = first_color; } else { var color = second_color; } var hide = (random % 5 == 0 || random % 7 == 0 || random % 13 == 0 || random % 17 == 00 || random % 19 == 0 || random % 23 == 0 || random % 29 == 0 ); if (!hide) { var textField = Ti.UI.createTextField({ value : sudoku[i][j], touchEnabled : false, editable : false, keyboardType : Titanium.UI.KEYBOARD_NUMBER_PAD, id : "textField_" + i + "_" + j }); } else { var textField = Ti.UI.createTextField({ keyboardType : Titanium.UI.KEYBOARD_NUMBER_PAD, value : "", id : "textField_" + i + "_" + j }); empty_cells++; //textField.returnKeyType = Titanium.UI.RETURNKEY_GO; if ( typeof Ti.Platform.name !== 'undefined' && Ti.Platform.name === 'iPhone OS') { } else { textField.returnKeyType = Titanium.UI.RETURNKEY_DONE; } } textField.height = row_height; textField.width = cell_width; textField.textAlign = Titanium.UI.TEXT_ALIGNMENT_CENTER; textField.backgroundColor = color; textField.focusable = true; listTextfield[j + (i * 9)] = textField; textField.addEventListener('change', function(e) { if (e.value != e.source.oldValue) { verify_valueElement(e); var element = e.source; var id = element.id + ""; var fields = id.split("_"); if (sudoku[fields[1]][fields[2]] == e.source.value) { element.color = "#1E6912"; empty_cells--; } else { element.color = "#801A15"; Ti.API.error("e.value : '"+e.source.value+"'"); if (e.source.value.length > 0 ) { timer(30); showMessageTimeout = function(customMessage, interval) { // window container indWin = Titanium.UI.createWindow(); // view var indView = Titanium.UI.createView({ height : 50, width : 250, borderRadius : 10, backgroundColor : '#aaa', opacity : .7 }); indWin.add(indView); // message var message = Titanium.UI.createLabel({ text : customMessage && typeof (customMessage !== 'undefined') ? customMessage : L('please_wait'), color : '#fff', width : 'auto', height : 'auto', textAlign : 'center', font : { fontFamily : 'Helvetica Neue', fontSize : 12, fontWeight : 'bold' } }); indView.add(message); indWin.open(); interval = interval ? interval : 3000; setTimeout(function() { indWin.close({ opacity : 0, duration : 1000 }); }, interval); }; showMessageTimeout("Pénalité de 30 sec", 200); } } Ti.API.info("empty_cells= " + empty_cells); if (empty_cells == 0) { stopGame(refreshId); for (var i = 0; i < listTextfield.length; i++) { listTextfield[i].touchEnabled = false; } } this.blur(); } }); // textField.top = tinyBorderHorizontal; LineSudokuView.add(textField); if (j < 8) { var VerticalBorder = Ti.UI.createView({ backgroundColor : color_border, width : tinyBorderVertical, top : 0, bottom : 0, right : 0, height : Ti.UI.FILL }); LineSudokuView.add(VerticalBorder); } } } row.add(LineSudokuView); var HorizontalBorder = Ti.UI.createView({ backgroundColor : color_border, width : Ti.UI.FILL, top : 0, bottom : 0, right : 0, height : tinyBorderHorizontal }); row.add(HorizontalBorder); tableData.push(row); } var HorizontalBorder = Ti.UI.createView({ backgroundColor : color_border, width : Ti.UI.FILL, top : 0, bottom : 0, right : 0, height : tinyBorderHorizontal }); row.add(HorizontalBorder); table.setData(tableData); $.Sudoku.add(table); refreshId = setInterval(timer, 1000); $.windowTable.addEventListener('click', function(e) { for (var index = 0; index < listTextfield.length; index++) { //Ti.API.info(index); listTextfield[index].blur(); //Hiding each keyboards } }); var iOS_seven = isIOS_Seven_Plus(); var theTop = iOS_seven ? 20 : 0; var window = $.windowTable; window.top = theTop; //********************************************LISTENER*******************************************/ /* Ti.App.addEventListener('restart', function(e) { // logs 'bar' Ti.App.removeEventListener('restart',function(e){ }); }); Ti.App.addEventListener('exit', function(e) { // logs 'bar' $.windowTable.close(); Ti.App.fireEvent('quitGame', { retour : 0 }); Ti.App.removeEventListener('exit',function(e){ }); }); */
apache-2.0
davidwhitney/ReallySimpleDynamo
ReallySimpleDynamo.Test.Unit/CredentialDetection/CredentialFactory.cs
1606
using System; using Moq; using NUnit.Framework; using ReallySimpleDynamo.CredentialDetection; using ReallySimpleDynamo.CredentialDetection.Providers; namespace ReallySimpleDynamo.Test.Unit.CredentialDetection { [TestFixture] public class CredentialFactoryTests { [Test] public void Ctor_NoProviderChainSupplied_CreatesDefault() { var factory = new CredentialFactory(); Assert.That(factory.Providers[0], Is.TypeOf<AppConfigCredentialProvider>()); Assert.That(factory.Providers[1], Is.TypeOf<InstanceMetadataCredentialProvider>()); } [Test] public void Retrieve_ReturnsFromFirstProviderThatHandsBackANotNullSetting() { var returnsNull = new Mock<IProvideCredentials>(); var returnsAnEntry = new Mock<IProvideCredentials>(); returnsAnEntry.Setup(x => x.Retrieve()).Returns(new Credentials()); var factory = new CredentialFactory(returnsNull.Object, returnsAnEntry.Object, returnsNull.Object); var creds = factory.Retrieve(); Assert.That(creds, Is.Not.Null); } [Test] public void Retrieve_WhenNoProvidersReturnAnything_ThrowsException() { var returnsNull = new Mock<IProvideCredentials>(); var factory = new CredentialFactory(returnsNull.Object); var ex = Assert.Throws<InvalidOperationException>(() => factory.Retrieve()); Assert.That(ex.Message, Is.EqualTo("No credential providers returned AWS credentials")); } } }
apache-2.0
tuddbresilience/coding_reliability
distance_distribution/legacy/Hamming/SSE_32.cpp
800
// Copyright 2017 Till Kolditz // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* * SSE_32.cpp * * Created on: 19.09.2017 * Author: Till Kolditz - [email protected] */ #ifdef __SSE4_2__ #include "SSE_32.hpp" template struct SIMD<__m128i, uint32_t>; #endif /* __SSE4_2__ */
apache-2.0
GoogleCloudPlatform/dotnet-docs-samples
spanner/api/Spanner.Samples.Tests/UpdateUsingDmlWithStructCoreAsyncTest.cs
1296
// Copyright 2020 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Threading.Tasks; using Xunit; [Collection(nameof(SpannerFixture))] public class UpdateUsingDmlWithStructCoreAsyncTest { private readonly SpannerFixture _spannerFixture; public UpdateUsingDmlWithStructCoreAsyncTest(SpannerFixture spannerFixture) { _spannerFixture = spannerFixture; } [Fact] public async Task TestUpdateUsingDmlWithStructCoreAsync() { UpdateUsingDmlWithStructCoreAsyncSample sample = new UpdateUsingDmlWithStructCoreAsyncSample(); var rowCount = await sample.UpdateUsingDmlWithStructCoreAsync(_spannerFixture.ProjectId, _spannerFixture.InstanceId, _spannerFixture.DatabaseId); Assert.True(rowCount >= 0); } }
apache-2.0
Djang0/limba
cgi/dao/TypeDocumentDAO.php
3745
<?php /** * @package limba.dao * @author Ludovic Reenaers * @since 24 nov. 2010 * * @link http://code.google.com/p/limba */ class TypeDocumentDAO extends DAO{ public function getById($id){ try { $id =StringHelper::escapeSql($id); $query="select * from TYPE_DOCUMENT where id=$id;"; $statement=$this->pdo->query($query); $array_obj=$statement->fetchAll(PDO::FETCH_OBJ); $propDAO = $this->factory->getPropertyDAO(); $thebean = null; foreach($array_obj as $Bean){ $thebean = new TypeDocument((int)$Bean->ID); $thebean->setLabel($Bean->LABEL); $thebean->setAvailable($Bean->AVAILABLE); $thebean->setProperties($propDAO->getByTypeDocument($thebean)); } } catch(Exception $e) { throw $e; } return $thebean; } public function getByLabel($label){ try { $label =strtolower(StringHelper::escapeSql($label)); $query="select * from TYPE_DOCUMENT where LCASE(LABEL)='$label';"; $statement=$this->pdo->query($query); $array_obj=$statement->fetchAll(PDO::FETCH_OBJ); $thebean = null; foreach($array_obj as $Bean){ $thebean = $this->getById((int)$Bean->ID); } } catch(Exception $e) { throw $e; } return $thebean; } // function getByIdWithValues($id,$Document){ // try // { // $id =StringHelper::escapeSql($id); // $query="select * from TYPE_DOCUMENT where id=$id;"; // $statement=$this->pdo->query($query); // $array_obj=$statement->fetchAll(PDO::FETCH_OBJ); // $propDAO = $this->factory->getPropertyDAO(); // $thebean = null; // foreach($array_obj as $Bean){ // // $thebean = new TypeDocument((int)$Bean->ID); // // $thebean->setLabel($Bean->LABEL); // // $thebean->setAvailable($Bean->AVAILABLE); // // $thebean->setProperties($propDAO->getByDocument($Document,$id)); // // } // } // catch(Exception $e) { // throw $e; // } // // return $thebean; // // } function remove($Bean){ try{ $query="update TYPE_DOCUMENTS set AVAILABLE= false where id=".StringHelper::escapeSql($Bean->getId())."';"; $this->pdo->exec($query); $bool=true; }catch(Exception $e) { $bool=false; } return $bool; } function update($Bean){ try{ $propDAO = $this->factory->getPropertyDAO(); foreach ($Bean->getProperties() as $Prop){ $propDAO->update($Prop); } $query = "update TYPE_DOCUMENT set LABEL='".StringHelper::escapeSql($Bean->getLabel())."',"; $query.= "AVAILABLE=".StringHelper::escapeSql($Bean->isAvailable())." where ID=".StringHelper::escapeSql($Bean->getId()).";"; $this->pdo->exec($query); $bool=true; } catch(Exception $e) { $bool=false; } return $bool; } function add($Bean){ try{ if (is_null($Bean->getId())){ $thebean = null; $propDAO = $this->factory->getPropertyDAO(); foreach ($Bean->getProperties() as $Prop){ $propDAO->add($Prop); } $insertQuery = "insert into TYPE_DOCUMENT (LABEL,AVAILABLE) values ('".StringHelper::escapeSql($Bean->getLabel())."',".StringHelper::escapeSql($Bean->getAvailable()).");"; $entiteDAO = $this->factory->getEntiteDAO(); $entiteDAO->add($Bean->getEntite()); $this->pdo->exec($insertQuery); $thebean = $this->getById((int)$this->pdo->lastInsertId()); } }catch(Exception $e) { $this->pdo->message; } return $thebean; } public function getAll(){ try { $query="select * from TYPE_DOCUMENT;"; $statement=$this->pdo->query($query); $array_obj=$statement->fetchAll(PDO::FETCH_OBJ); $tab = array(); foreach($array_obj as $Bean){ $bean = $this->getById((int)$Bean->ID); array_push($tab, $bean); } } catch(Exception $e) { throw $e; } return $tab; } } ?>
apache-2.0
yanzhenjie/Album
album/src/main/java/com/yanzhenjie/album/impl/OnCheckedClickListener.java
961
/* * Copyright 2018 Yan Zhenjie. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yanzhenjie.album.impl; import android.widget.CompoundButton; /** * Created by YanZhenjie on 2018/4/11. */ public interface OnCheckedClickListener { /** * Compound button is clicked. * * @param button view. * @param position the position in the list. */ void onCheckedClick(CompoundButton button, int position); }
apache-2.0
shred/commons-suncalc
src/test/java/org/shredzone/commons/suncalc/util/VectorTest.java
8772
/* * Shredzone Commons - suncalc * * Copyright (C) 2017 Richard "Shred" Körber * http://commons.shredzone.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package org.shredzone.commons.suncalc.util; import static java.lang.Math.PI; import static org.assertj.core.api.Assertions.assertThat; import org.assertj.core.data.Offset; import org.junit.Test; /** * Unit tests for {@link Vector}. */ public class VectorTest { private static final Offset<Double> ERROR = Offset.offset(0.001); private static final double PI_HALF = PI / 2.0; @Test public void testConstructors() { Vector v1 = new Vector(20.0, 10.0, 5.0); assertThat(v1.getX()).isEqualTo(20.0); assertThat(v1.getY()).isEqualTo(10.0); assertThat(v1.getZ()).isEqualTo(5.0); Vector v2 = new Vector(new double[] { 20.0, 10.0, 5.0 }); assertThat(v2.getX()).isEqualTo(20.0); assertThat(v2.getY()).isEqualTo(10.0); assertThat(v2.getZ()).isEqualTo(5.0); Vector v3 = Vector.ofPolar(0.5, 0.25); assertThat(v3.getPhi()).isEqualTo(0.5); assertThat(v3.getTheta()).isEqualTo(0.25); assertThat(v3.getR()).isEqualTo(1.0); Vector v4 = Vector.ofPolar(0.5, 0.25, 50.0); assertThat(v4.getPhi()).isEqualTo(0.5); assertThat(v4.getTheta()).isEqualTo(0.25); assertThat(v4.getR()).isEqualTo(50.0); } @Test(expected = IllegalArgumentException.class) public void testBadConstructor() { new Vector(new double[] { 20.0, 10.0 }); } @Test public void testAdd() { Vector v1 = new Vector(20.0, 10.0, 5.0); Vector v2 = new Vector(10.0, 25.0, 15.0); Vector r1 = v1.add(v2); assertThat(r1.getX()).isEqualTo(30.0); assertThat(r1.getY()).isEqualTo(35.0); assertThat(r1.getZ()).isEqualTo(20.0); Vector r2 = v2.add(v1); assertThat(r2.getX()).isEqualTo(30.0); assertThat(r2.getY()).isEqualTo(35.0); assertThat(r2.getZ()).isEqualTo(20.0); } @Test public void testSubtract() { Vector v1 = new Vector(20.0, 10.0, 5.0); Vector v2 = new Vector(10.0, 25.0, 15.0); Vector r1 = v1.subtract(v2); assertThat(r1.getX()).isEqualTo(10.0); assertThat(r1.getY()).isEqualTo(-15.0); assertThat(r1.getZ()).isEqualTo(-10.0); Vector r2 = v2.subtract(v1); assertThat(r2.getX()).isEqualTo(-10.0); assertThat(r2.getY()).isEqualTo(15.0); assertThat(r2.getZ()).isEqualTo(10.0); } @Test public void testMultiply() { Vector v1 = new Vector(20.0, 10.0, 5.0); Vector r1 = v1.multiply(5.0); assertThat(r1.getX()).isEqualTo(100.0); assertThat(r1.getY()).isEqualTo(50.0); assertThat(r1.getZ()).isEqualTo(25.0); } @Test public void testNegate() { Vector v1 = new Vector(20.0, 10.0, 5.0); Vector r1 = v1.negate(); assertThat(r1.getX()).isEqualTo(-20.0); assertThat(r1.getY()).isEqualTo(-10.0); assertThat(r1.getZ()).isEqualTo(-5.0); } @Test public void testCross() { Vector v1 = new Vector(3.0, -3.0, 1.0); Vector v2 = new Vector(4.0, 9.0, 2.0); Vector r1 = v1.cross(v2); assertThat(r1.getX()).isEqualTo(-15.0); assertThat(r1.getY()).isEqualTo(-2.0); assertThat(r1.getZ()).isEqualTo(39.0); } @Test public void testDot() { Vector v1 = new Vector(1.0, 2.0, 3.0); Vector v2 = new Vector(4.0, -5.0, 6.0); double r1 = v1.dot(v2); assertThat(r1).isCloseTo(12.0, ERROR); } @Test public void testNorm() { Vector v1 = new Vector(5.0, -6.0, 7.0); double r1 = v1.norm(); assertThat(r1).isCloseTo(10.488, ERROR); } @Test public void testEquals() { Vector v1 = new Vector(3.0, -3.0, 1.0); Vector v2 = new Vector(4.0, 9.0, 2.0); Vector v3 = new Vector(3.0, -3.0, 1.0); assertThat(v1.equals(v2)).isFalse(); assertThat(v1.equals(v3)).isTrue(); assertThat(v2.equals(v3)).isFalse(); assertThat(v3.equals(v1)).isTrue(); assertThat(v1.equals(null)).isFalse(); assertThat(v1.equals(new Object())).isFalse(); } @Test public void testHashCode() { int h1 = new Vector(3.0, -3.0, 1.0).hashCode(); int h2 = new Vector(4.0, 9.0, 2.0).hashCode(); int h3 = new Vector(3.0, -3.0, 1.0).hashCode(); assertThat(h1).isNotZero(); assertThat(h2).isNotZero(); assertThat(h3).isNotZero(); assertThat(h1).isNotEqualTo(h2); assertThat(h1).isEqualTo(h3); } @Test public void testToString() { Vector v1 = new Vector(3.0, -3.0, 1.0); assertThat(v1.toString()).isEqualTo("(x=3.0, y=-3.0, z=1.0)"); } @Test public void testToCartesian() { Vector v1 = Vector.ofPolar(0.0, 0.0); assertThat(v1.getX()).isCloseTo(1.0, ERROR); assertThat(v1.getY()).isCloseTo(0.0, ERROR); assertThat(v1.getZ()).isCloseTo(0.0, ERROR); Vector v2 = Vector.ofPolar(PI_HALF, 0.0); assertThat(v2.getX()).isCloseTo(0.0, ERROR); assertThat(v2.getY()).isCloseTo(1.0, ERROR); assertThat(v2.getZ()).isCloseTo(0.0, ERROR); Vector v3 = Vector.ofPolar(0.0, PI_HALF); assertThat(v3.getX()).isCloseTo(0.0, ERROR); assertThat(v3.getY()).isCloseTo(0.0, ERROR); assertThat(v3.getZ()).isCloseTo(1.0, ERROR); Vector v4 = Vector.ofPolar(PI_HALF, PI_HALF); assertThat(v4.getX()).isCloseTo(0.0, ERROR); assertThat(v4.getY()).isCloseTo(0.0, ERROR); assertThat(v4.getZ()).isCloseTo(1.0, ERROR); Vector v5 = Vector.ofPolar(PI_HALF, -PI_HALF); assertThat(v5.getX()).isCloseTo(0.0, ERROR); assertThat(v5.getY()).isCloseTo(0.0, ERROR); assertThat(v5.getZ()).isCloseTo(-1.0, ERROR); Vector v6 = Vector.ofPolar(0.0, 0.0, 5.0); assertThat(v6.getX()).isCloseTo(5.0, ERROR); assertThat(v6.getY()).isCloseTo(0.0, ERROR); assertThat(v6.getZ()).isCloseTo(0.0, ERROR); Vector v7 = Vector.ofPolar(PI_HALF, 0.0, 5.0); assertThat(v7.getX()).isCloseTo(0.0, ERROR); assertThat(v7.getY()).isCloseTo(5.0, ERROR); assertThat(v7.getZ()).isCloseTo(0.0, ERROR); Vector v8 = Vector.ofPolar(0.0, PI_HALF, 5.0); assertThat(v8.getX()).isCloseTo(0.0, ERROR); assertThat(v8.getY()).isCloseTo(0.0, ERROR); assertThat(v8.getZ()).isCloseTo(5.0, ERROR); Vector v9 = Vector.ofPolar(PI_HALF, PI_HALF, 5.0); assertThat(v9.getX()).isCloseTo(0.0, ERROR); assertThat(v9.getY()).isCloseTo(0.0, ERROR); assertThat(v9.getZ()).isCloseTo(5.0, ERROR); Vector v10 = Vector.ofPolar(PI_HALF, -PI_HALF, 5.0); assertThat(v10.getX()).isCloseTo(0.0, ERROR); assertThat(v10.getY()).isCloseTo(0.0, ERROR); assertThat(v10.getZ()).isCloseTo(-5.0, ERROR); } @Test public void testToPolar() { Vector v1 = new Vector(20.0, 0.0, 0.0); assertThat(v1.getPhi()).isEqualTo(0.0); assertThat(v1.getTheta()).isEqualTo(0.0); assertThat(v1.getR()).isEqualTo(20.0); Vector v2 = new Vector(0.0, 20.0, 0.0); assertThat(v2.getPhi()).isEqualTo(PI_HALF); assertThat(v2.getTheta()).isEqualTo(0.0); assertThat(v2.getR()).isEqualTo(20.0); Vector v3 = new Vector(0.0, 0.0, 20.0); assertThat(v3.getPhi()).isEqualTo(0.0); assertThat(v3.getTheta()).isEqualTo(PI_HALF); assertThat(v3.getR()).isEqualTo(20.0); Vector v4 = new Vector(-20.0, 0.0, 0.0); assertThat(v4.getPhi()).isEqualTo(PI); assertThat(v4.getTheta()).isEqualTo(0.0); assertThat(v4.getR()).isEqualTo(20.0); Vector v5 = new Vector(0.0, -20.0, 0.0); assertThat(v5.getPhi()).isEqualTo(PI + PI_HALF); assertThat(v5.getTheta()).isEqualTo(0.0); assertThat(v5.getR()).isEqualTo(20.0); Vector v6 = new Vector(0.0, 0.0, -20.0); assertThat(v6.getPhi()).isEqualTo(0.0); assertThat(v6.getTheta()).isEqualTo(-PI_HALF); assertThat(v6.getR()).isEqualTo(20.0); Vector v7 = new Vector(0.0, 0.0, 0.0); assertThat(v7.getPhi()).isEqualTo(0.0); assertThat(v7.getTheta()).isEqualTo(0.0); assertThat(v7.getR()).isEqualTo(0.0); } }
apache-2.0
lucasvss/CallRangers
app/src/main/java/br/quixada/ufc/callrangers/util/UsuarioDes.java
832
package br.quixada.ufc.callrangers.util; import com.google.gson.Gson; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import java.lang.reflect.Type; import br.quixada.ufc.callrangers.model.Usuario; /** * Created by lucas-vss on 29/11/16. */ public class UsuarioDes implements JsonDeserializer<Object> { @Override public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonElement usuario = json.getAsJsonObject(); if(json.getAsJsonObject().get("usuario") != null) { usuario = json.getAsJsonObject().get("usuario"); } return (new Gson().fromJson(usuario, Usuario.class)); } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-gamelift/src/main/java/com/amazonaws/services/gamelift/model/PutScalingPolicyResult.java
4148
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.gamelift.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * Represents the returned data in response to a request action. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/gamelift-2015-10-01/PutScalingPolicy" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PutScalingPolicyResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * Descriptive label that is associated with a scaling policy. Policy names do not need to be unique. * </p> */ private String name; /** * <p> * Descriptive label that is associated with a scaling policy. Policy names do not need to be unique. * </p> * * @param name * Descriptive label that is associated with a scaling policy. Policy names do not need to be unique. */ public void setName(String name) { this.name = name; } /** * <p> * Descriptive label that is associated with a scaling policy. Policy names do not need to be unique. * </p> * * @return Descriptive label that is associated with a scaling policy. Policy names do not need to be unique. */ public String getName() { return this.name; } /** * <p> * Descriptive label that is associated with a scaling policy. Policy names do not need to be unique. * </p> * * @param name * Descriptive label that is associated with a scaling policy. Policy names do not need to be unique. * @return Returns a reference to this object so that method calls can be chained together. */ public PutScalingPolicyResult withName(String name) { setName(name); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getName() != null) sb.append("Name: ").append(getName()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof PutScalingPolicyResult == false) return false; PutScalingPolicyResult other = (PutScalingPolicyResult) obj; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); return hashCode; } @Override public PutScalingPolicyResult clone() { try { return (PutScalingPolicyResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
b002368/chef-repo
lib/chef/chef_fs/file_system/chef_server/nodes_dir.rb
2016
# # Author:: John Keiser (<[email protected]>) # Copyright:: Copyright 2012-2016, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "chef/chef_fs/file_system/base_fs_dir" require "chef/chef_fs/file_system/chef_server/rest_list_entry" require "chef/chef_fs/file_system/exceptions" require "chef/chef_fs/data_handler/node_data_handler" class Chef module ChefFS module FileSystem module ChefServer class NodesDir < RestListDir # Identical to RestListDir.children, except supports environments def children begin @children ||= root.get_json(env_api_path).keys.sort.map do |key| make_child_entry(key, true) end rescue Timeout::Error => e raise Chef::ChefFS::FileSystem::OperationFailedError.new(:children, self, e, "Timeout retrieving children: #{e}") rescue Net::HTTPServerException => e if $!.response.code == "404" raise Chef::ChefFS::FileSystem::NotFoundError.new(self, $!) else raise Chef::ChefFS::FileSystem::OperationFailedError.new(:children, self, e, "HTTP error retrieving children: #{e}") end end end def env_api_path environment ? "environments/#{environment}/#{api_path}" : api_path end end end end end end
apache-2.0
mikegehard/lattice
ltc/test_helpers/matchers/contain_exactly_matcher_test.go
3764
package matchers_test import ( "fmt" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/cloudfoundry-incubator/lattice/ltc/test_helpers/matchers" ) type woohoo struct { Flag bool } type woomap map[woohoo]string var _ = Describe("ContainExactlyMatcher", func() { It("matches if the array contains exactly the elements in the expected array, but is order independent.", func() { Expect([]string{"hi there", "ho there", "hallo"}).To(matchers.ContainExactly([]string{"hi there", "ho there", "hallo"})) Expect([]string{"hi there", "ho there", "hallo"}).To(matchers.ContainExactly([]string{"ho there", "hallo", "hi there"})) Expect([]woohoo{woohoo{Flag: true}}).To(matchers.ContainExactly([]woohoo{woohoo{Flag: true}})) Expect([]woohoo{woohoo{Flag: true}, woohoo{Flag: false}}).To(matchers.ContainExactly([]woohoo{woohoo{Flag: true}, woohoo{Flag: false}})) Expect([]string{"hi there", "ho there", "hallo"}).ToNot(matchers.ContainExactly([]string{"hi there", "bye bye"})) Expect([]string{"hi there", "ho there", "hallo"}).ToNot(matchers.ContainExactly([]string{"ho there", "hi there"})) Expect([]string{"ho there", "hallo"}).ToNot(matchers.ContainExactly([]string{"ho there", "hi there", "hallo"})) Expect([]string{"hi there", "ho there", "hallo"}).ToNot(matchers.ContainExactly([]string{"buhbye"})) Expect([]string{"hi there", "ho there", "hallo"}).ToNot(matchers.ContainExactly([]string{})) Expect([]woohoo{woohoo{Flag: false}}).ToNot(matchers.ContainExactly([]woohoo{woohoo{Flag: true}})) Expect([]woohoo{woohoo{Flag: false}, woohoo{Flag: false}}).ToNot(matchers.ContainExactly([]woohoo{woohoo{Flag: true}, woohoo{Flag: false}})) }) It("handles map types", func() { Expect(woomap{woohoo{true}: "fun", woohoo{false}: "not fun"}).To(matchers.ContainExactly(woomap{woohoo{false}: "not fun", woohoo{true}: "fun"})) }) It("handles duplicate elements", func() { Expect([]int{-7, -7, 9, 4}).To(matchers.ContainExactly([]int{4, 9, -7, -7})) Expect([]int{-7, -7, 9, 4}).ToNot(matchers.ContainExactly([]int{4, 9, -7, 44})) Expect([]int{4, -7, 9, 44}).ToNot(matchers.ContainExactly([]int{4, 9, -7, -7})) }) It("fails for non-array or slices", func() { failures := InterceptGomegaFailures(func() { Expect([]string{"hi there", "ho there", "hallo"}).ToNot(matchers.ContainExactly(46)) Expect(23).ToNot(matchers.ContainExactly([]string{"hi there", "ho there", "hallo"})) Expect("woo").ToNot(matchers.ContainExactly([]woohoo{woohoo{Flag: true}, woohoo{Flag: false}})) Expect([]string{"hi there", "ho there", "hallo"}).ToNot(matchers.ContainExactly(nil)) }) Expect(failures[0]).To(Equal("Matcher can only take an array, slice or map")) Expect(failures[1]).To(Equal("Matcher can only take an array, slice or map")) Expect(failures[2]).To(Equal("Matcher can only take an array, slice or map")) Expect(failures[3]).To(Equal("Matcher can only take an array, slice or map")) }) Context("when the matcher assertion fails", func() { var ( sliceA, sliceB []string ) BeforeEach(func() { sliceA = []string{"hi there", "ho there", "hallo"} sliceB = []string{"goodbye"} }) It("prints a failure message for the matcher", func() { failures := InterceptGomegaFailures(func() { Expect(sliceA).To(matchers.ContainExactly(sliceB)) }) Expect(failures[0]).To(Equal(fmt.Sprintf("Expected %#v\n to contain exactly: %#v\n but it did not.", sliceA, sliceB))) }) It("prints a negated failure meessage for the matcher", func() { failures := InterceptGomegaFailures(func() { Expect(sliceA).ToNot(matchers.ContainExactly(sliceA)) }) Expect(failures[0]).To(Equal(fmt.Sprintf("Expected %#v\n not to contain exactly: %#v\n but it did!", sliceA, sliceA))) }) }) })
apache-2.0
tsavas/portfolio
09_bio_time_lapse.php
315
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>bio lapse</title> <?php include("inc/htmlhead.php"); ?> </head> <body> <?php include("inc/script.php"); ?> <?php include("inc/header.php"); ?> <?php include("inc/nav.php"); ?> <?php include("inc/content09.php"); ?> </body> </html>
apache-2.0
vespa-engine/vespa
node-repository/src/main/java/com/yahoo/vespa/hosted/provision/maintenance/NodeMetricsDbMaintainer.java
3338
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.provision.maintenance; import com.yahoo.config.provision.ApplicationId; import com.yahoo.jdisc.Metric; import com.yahoo.lang.MutableInteger; import com.yahoo.vespa.hosted.provision.NodeRepository; import com.yahoo.vespa.hosted.provision.autoscale.MetricsFetcher; import com.yahoo.vespa.hosted.provision.autoscale.MetricsResponse; import com.yahoo.yolean.Exceptions; import java.time.Duration; import java.util.Set; import java.util.logging.Level; /** * Maintainer which keeps the node metric db up to date by periodically fetching metrics from all active nodes. * * @author bratseth */ public class NodeMetricsDbMaintainer extends NodeRepositoryMaintainer { private static final int maxWarningsPerInvocation = 2; private final MetricsFetcher metricsFetcher; public NodeMetricsDbMaintainer(NodeRepository nodeRepository, MetricsFetcher metricsFetcher, Duration interval, Metric metric) { super(nodeRepository, interval, metric); this.metricsFetcher = metricsFetcher; } @Override protected double maintain() { int attempts = 0; var failures = new MutableInteger(0); try { Set<ApplicationId> applications = activeNodesByApplication().keySet(); if (applications.isEmpty()) return 1.0; long pauseMs = interval().toMillis() / applications.size() - 1; // spread requests over interval int done = 0; for (ApplicationId application : applications) { attempts++; metricsFetcher.fetchMetrics(application) .whenComplete((metricsResponse, exception) -> handleResponse(metricsResponse, exception, failures, application)); if (++done < applications.size()) Thread.sleep(pauseMs); } nodeRepository().metricsDb().gc(); return asSuccessFactor(attempts, failures.get()); } catch (InterruptedException e) { return asSuccessFactor(attempts, failures.get()); } } private void handleResponse(MetricsResponse response, Throwable exception, MutableInteger failures, ApplicationId application) { if (exception != null) { if (failures.get() < maxWarningsPerInvocation) log.log(Level.WARNING, "Could not update metrics for " + application + ": " + Exceptions.toMessageString(exception)); failures.add(1); } else if (response != null) { nodeRepository().metricsDb().addNodeMetrics(response.nodeMetrics()); nodeRepository().metricsDb().addClusterMetrics(application, response.clusterMetrics()); } } }
apache-2.0
noorq/casser
src/main/java/com/noorq/casser/mapping/javatype/SimpleJavaTypes.java
1916
/* * Copyright (C) 2015 The Casser Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.noorq.casser.mapping.javatype; import java.util.HashMap; import java.util.Map; import com.datastax.driver.core.DataType; public final class SimpleJavaTypes { private static final Map<Class<?>, DataType> javaClassToDataTypeMap = new HashMap<Class<?>, DataType>(); private static final Map<DataType.Name, DataType> nameToDataTypeMap = new HashMap<DataType.Name, DataType>(); static { for (DataType dataType : DataType.allPrimitiveTypes()) { nameToDataTypeMap.put(dataType.getName(), dataType); if (dataType.equals(DataType.counter()) || dataType.equals(DataType.ascii()) || dataType.equals(DataType.timeuuid() )) { continue; } Class<?> javaClass = dataType.asJavaClass(); DataType dt = javaClassToDataTypeMap.putIfAbsent(javaClass, dataType); if (dt != null) { throw new IllegalStateException("java type " + javaClass + " is has two datatypes " + dt + " and " + dataType); } } javaClassToDataTypeMap.put(String.class, DataType.text()); } private SimpleJavaTypes() { } public static DataType getDataTypeByName(DataType.Name name) { return nameToDataTypeMap.get(name); } public static DataType getDataTypeByJavaClass(Class<?> javaType) { return javaClassToDataTypeMap.get(javaType); } }
apache-2.0
yuri0x7c1/ofbiz-explorer
src/test/resources/apache-ofbiz-17.12.04/framework/webapp/src/main/java/org/apache/ofbiz/webapp/control/ConfigXMLReader.java
32881
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. *******************************************************************************/ package org.apache.ofbiz.webapp.control; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.ServletContext; import org.apache.ofbiz.base.component.ComponentConfig.WebappInfo; import org.apache.ofbiz.base.location.FlexibleLocation; import org.apache.ofbiz.base.metrics.Metrics; import org.apache.ofbiz.base.metrics.MetricsFactory; import org.apache.ofbiz.base.util.Assert; import org.apache.ofbiz.base.util.Debug; import org.apache.ofbiz.base.util.FileUtil; import org.apache.ofbiz.base.util.GeneralException; import org.apache.ofbiz.base.util.StringUtil; import org.apache.ofbiz.base.util.UtilHttp; import org.apache.ofbiz.base.util.UtilProperties; import org.apache.ofbiz.base.util.UtilValidate; import org.apache.ofbiz.base.util.UtilXml; import org.apache.ofbiz.base.util.cache.UtilCache; import org.apache.ofbiz.base.util.collections.MapContext; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * ConfigXMLReader.java - Reads and parses the XML site config files. */ public class ConfigXMLReader { public static final String module = ConfigXMLReader.class.getName(); public static final String controllerXmlFileName = "/WEB-INF/controller.xml"; private static final UtilCache<URL, ControllerConfig> controllerCache = UtilCache.createUtilCache("webapp.ControllerConfig"); private static final UtilCache<String, List<ControllerConfig>> controllerSearchResultsCache = UtilCache.createUtilCache("webapp.ControllerSearchResults"); public static final RequestResponse emptyNoneRequestResponse = RequestResponse.createEmptyNoneRequestResponse(); public static Set<String> findControllerFilesWithRequest(String requestUri, String controllerPartialPath) throws GeneralException { Set<String> allControllerRequestSet = new HashSet<String>(); if (UtilValidate.isEmpty(requestUri)) { return allControllerRequestSet; } String cacheId = controllerPartialPath != null ? controllerPartialPath : "NOPARTIALPATH"; List<ControllerConfig> controllerConfigs = controllerSearchResultsCache.get(cacheId); if (controllerConfigs == null) { try { // find controller.xml file with webappMountPoint + "/WEB-INF" in the path List<File> controllerFiles = FileUtil.findXmlFiles(null, controllerPartialPath, "site-conf", "site-conf.xsd"); controllerConfigs = new LinkedList<ControllerConfig>(); for (File controllerFile : controllerFiles) { URL controllerUrl = null; try { controllerUrl = controllerFile.toURI().toURL(); } catch (MalformedURLException mue) { throw new GeneralException(mue); } ControllerConfig cc = ConfigXMLReader.getControllerConfig(controllerUrl); controllerConfigs.add(cc); } controllerConfigs = controllerSearchResultsCache.putIfAbsentAndGet(cacheId, controllerConfigs); } catch (IOException e) { throw new GeneralException("Error finding controller XML files to lookup request references: " + e.toString(), e); } } if (controllerConfigs != null) { for (ControllerConfig cc : controllerConfigs) { // make sure it has the named request in it if (cc.requestMapMap.get(requestUri) != null) { String requestUniqueId = cc.url.toExternalForm() + "#" + requestUri; allControllerRequestSet.add(requestUniqueId); // Debug.logInfo("========== In findControllerFilesWithRequest found controller with request here [" + requestUniqueId + "]", module); } } } return allControllerRequestSet; } public static Set<String> findControllerRequestUniqueForTargetType(String target, String urlMode) throws GeneralException { if (UtilValidate.isEmpty(urlMode)) { urlMode = "intra-app"; } int indexOfDollarSignCurlyBrace = target.indexOf("${"); int indexOfQuestionMark = target.indexOf("?"); if (indexOfDollarSignCurlyBrace >= 0 && (indexOfQuestionMark < 0 || indexOfQuestionMark > indexOfDollarSignCurlyBrace)) { // we have an expanded string in the requestUri part of the target, not much we can do about that... return null; } if ("intra-app".equals(urlMode)) { // look through all controller.xml files and find those with the request-uri referred to by the target String requestUri = UtilHttp.getRequestUriFromTarget(target); Set<String> controllerLocAndRequestSet = ConfigXMLReader.findControllerFilesWithRequest(requestUri, null); // if (controllerLocAndRequestSet.size() > 0) Debug.logInfo("============== In findRequestNamesLinkedtoInWidget, controllerLocAndRequestSet: " + controllerLocAndRequestSet, module); return controllerLocAndRequestSet; } else if ("inter-app".equals(urlMode)) { String webappMountPoint = UtilHttp.getWebappMountPointFromTarget(target); if (webappMountPoint != null) webappMountPoint += "/WEB-INF"; String requestUri = UtilHttp.getRequestUriFromTarget(target); Set<String> controllerLocAndRequestSet = ConfigXMLReader.findControllerFilesWithRequest(requestUri, webappMountPoint); // if (controllerLocAndRequestSet.size() > 0) Debug.logInfo("============== In findRequestNamesLinkedtoInWidget, controllerLocAndRequestSet: " + controllerLocAndRequestSet, module); return controllerLocAndRequestSet; } else { return new HashSet<String>(); } } public static ControllerConfig getControllerConfig(WebappInfo webAppInfo) throws WebAppConfigurationException, MalformedURLException { Assert.notNull("webAppInfo", webAppInfo); String filePath = webAppInfo.getLocation().concat(controllerXmlFileName); File configFile = new File(filePath); return getControllerConfig(configFile.toURI().toURL()); } public static ControllerConfig getControllerConfig(URL url) throws WebAppConfigurationException { ControllerConfig controllerConfig = controllerCache.get(url); if (controllerConfig == null) { controllerConfig = controllerCache.putIfAbsentAndGet(url, new ControllerConfig(url)); } return controllerConfig; } public static URL getControllerConfigURL(ServletContext context) { try { return context.getResource(controllerXmlFileName); } catch (MalformedURLException e) { Debug.logError(e, "Error Finding XML Config File: " + controllerXmlFileName, module); return null; } } /** Loads the XML file and returns the root element * @throws WebAppConfigurationException */ private static Element loadDocument(URL location) throws WebAppConfigurationException { try { Document document = UtilXml.readXmlDocument(location, true); Element rootElement = document.getDocumentElement(); if (!"site-conf".equalsIgnoreCase(rootElement.getTagName())) { rootElement = UtilXml.firstChildElement(rootElement, "site-conf"); } if (Debug.verboseOn()) { Debug.logVerbose("Loaded XML Config - " + location, module); } return rootElement; } catch (Exception e) { Debug.logError(e, module); throw new WebAppConfigurationException(e); } } public static class ControllerConfig { public URL url; private String errorpage; private String protectView; private String owner; private String securityClass; private String defaultRequest; private String statusCode; private List<URL> includes = new ArrayList<URL>(); private Map<String, Event> firstVisitEventList = new LinkedHashMap<String, Event>(); private Map<String, Event> preprocessorEventList = new LinkedHashMap<String, Event>(); private Map<String, Event> postprocessorEventList = new LinkedHashMap<String, Event>(); private Map<String, Event> afterLoginEventList = new LinkedHashMap<String, Event>(); private Map<String, Event> beforeLogoutEventList = new LinkedHashMap<String, Event>(); private Map<String, String> eventHandlerMap = new HashMap<String, String>(); private Map<String, String> viewHandlerMap = new HashMap<String, String>(); private Map<String, RequestMap> requestMapMap = new HashMap<String, RequestMap>(); private Map<String, ViewMap> viewMapMap = new HashMap<String, ViewMap>(); public ControllerConfig(URL url) throws WebAppConfigurationException { this.url = url; Element rootElement = loadDocument(url); if (rootElement != null) { long startTime = System.currentTimeMillis(); loadIncludes(rootElement); loadGeneralConfig(rootElement); loadHandlerMap(rootElement); loadRequestMap(rootElement); loadViewMap(rootElement); if (Debug.infoOn()) { double totalSeconds = (System.currentTimeMillis() - startTime) / 1000.0; String locString = this.url.toExternalForm(); Debug.logInfo("controller loaded: " + totalSeconds + "s, " + this.requestMapMap.size() + " requests, " + this.viewMapMap.size() + " views in " + locString, module); } } } public Map<String, Event> getAfterLoginEventList() throws WebAppConfigurationException { MapContext<String, Event> result = MapContext.getMapContext(); for (URL includeLocation : includes) { ControllerConfig controllerConfig = getControllerConfig(includeLocation); result.push(controllerConfig.getAfterLoginEventList()); } result.push(afterLoginEventList); return result; } public Map<String, Event> getBeforeLogoutEventList() throws WebAppConfigurationException { MapContext<String, Event> result = MapContext.getMapContext(); for (URL includeLocation : includes) { ControllerConfig controllerConfig = getControllerConfig(includeLocation); result.push(controllerConfig.getBeforeLogoutEventList()); } result.push(beforeLogoutEventList); return result; } public String getDefaultRequest() throws WebAppConfigurationException { if (defaultRequest != null) { return defaultRequest; } for (URL includeLocation : includes) { ControllerConfig controllerConfig = getControllerConfig(includeLocation); String defaultRequest = controllerConfig.getDefaultRequest(); if (defaultRequest != null) { return defaultRequest; } } return null; } public String getErrorpage() throws WebAppConfigurationException { if (errorpage != null) { return errorpage; } for (URL includeLocation : includes) { ControllerConfig controllerConfig = getControllerConfig(includeLocation); String errorpage = controllerConfig.getErrorpage(); if (errorpage != null) { return errorpage; } } return null; } public Map<String, String> getEventHandlerMap() throws WebAppConfigurationException { MapContext<String, String> result = MapContext.getMapContext(); for (URL includeLocation : includes) { ControllerConfig controllerConfig = getControllerConfig(includeLocation); result.push(controllerConfig.getEventHandlerMap()); } result.push(eventHandlerMap); return result; } public Map<String, Event> getFirstVisitEventList() throws WebAppConfigurationException { MapContext<String, Event> result = MapContext.getMapContext(); for (URL includeLocation : includes) { ControllerConfig controllerConfig = getControllerConfig(includeLocation); result.push(controllerConfig.getFirstVisitEventList()); } result.push(firstVisitEventList); return result; } public String getOwner() throws WebAppConfigurationException { if (owner != null) { return owner; } for (URL includeLocation : includes) { ControllerConfig controllerConfig = getControllerConfig(includeLocation); String owner = controllerConfig.getOwner(); if (owner != null) { return owner; } } return null; } public Map<String, Event> getPostprocessorEventList() throws WebAppConfigurationException { MapContext<String, Event> result = MapContext.getMapContext(); for (URL includeLocation : includes) { ControllerConfig controllerConfig = getControllerConfig(includeLocation); result.push(controllerConfig.getPostprocessorEventList()); } result.push(postprocessorEventList); return result; } public Map<String, Event> getPreprocessorEventList() throws WebAppConfigurationException { MapContext<String, Event> result = MapContext.getMapContext(); for (URL includeLocation : includes) { ControllerConfig controllerConfig = getControllerConfig(includeLocation); result.push(controllerConfig.getPreprocessorEventList()); } result.push(preprocessorEventList); return result; } public String getProtectView() throws WebAppConfigurationException { if (protectView != null) { return protectView; } for (URL includeLocation : includes) { ControllerConfig controllerConfig = getControllerConfig(includeLocation); String protectView = controllerConfig.getProtectView(); if (protectView != null) { return protectView; } } return null; } public Map<String, RequestMap> getRequestMapMap() throws WebAppConfigurationException { MapContext<String, RequestMap> result = MapContext.getMapContext(); for (URL includeLocation : includes) { ControllerConfig controllerConfig = getControllerConfig(includeLocation); result.push(controllerConfig.getRequestMapMap()); } result.push(requestMapMap); return result; } public String getSecurityClass() throws WebAppConfigurationException { if (securityClass != null) { return securityClass; } for (URL includeLocation : includes) { ControllerConfig controllerConfig = getControllerConfig(includeLocation); String securityClass = controllerConfig.getSecurityClass(); if (securityClass != null) { return securityClass; } } return null; } public String getStatusCode() throws WebAppConfigurationException { if (statusCode != null) { return statusCode; } for (URL includeLocation : includes) { ControllerConfig controllerConfig = getControllerConfig(includeLocation); String statusCode = controllerConfig.getStatusCode(); if (statusCode != null) { return statusCode; } } return null; } public Map<String, String> getViewHandlerMap() throws WebAppConfigurationException { MapContext<String, String> result = MapContext.getMapContext(); for (URL includeLocation : includes) { ControllerConfig controllerConfig = getControllerConfig(includeLocation); result.push(controllerConfig.getViewHandlerMap()); } result.push(viewHandlerMap); return result; } public Map<String, ViewMap> getViewMapMap() throws WebAppConfigurationException { MapContext<String, ViewMap> result = MapContext.getMapContext(); for (URL includeLocation : includes) { ControllerConfig controllerConfig = getControllerConfig(includeLocation); result.push(controllerConfig.getViewMapMap()); } result.push(viewMapMap); return result; } private void loadGeneralConfig(Element rootElement) { this.errorpage = UtilXml.childElementValue(rootElement, "errorpage"); this.statusCode = UtilXml.childElementValue(rootElement, "status-code"); Element protectElement = UtilXml.firstChildElement(rootElement, "protect"); if (protectElement != null) { this.protectView = protectElement.getAttribute("view"); } this.owner = UtilXml.childElementValue(rootElement, "owner"); this.securityClass = UtilXml.childElementValue(rootElement, "security-class"); Element defaultRequestElement = UtilXml.firstChildElement(rootElement, "default-request"); if (defaultRequestElement != null) { this.defaultRequest = defaultRequestElement.getAttribute("request-uri"); } // first visit event Element firstvisitElement = UtilXml.firstChildElement(rootElement, "firstvisit"); if (firstvisitElement != null) { for (Element eventElement : UtilXml.childElementList(firstvisitElement, "event")) { String eventName = eventElement.getAttribute("name"); if (eventName.isEmpty()) { eventName = eventElement.getAttribute("type") + "::" + eventElement.getAttribute("path") + "::" + eventElement.getAttribute("invoke"); } this.firstVisitEventList.put(eventName, new Event(eventElement)); } } // preprocessor events Element preprocessorElement = UtilXml.firstChildElement(rootElement, "preprocessor"); if (preprocessorElement != null) { for (Element eventElement : UtilXml.childElementList(preprocessorElement, "event")) { String eventName = eventElement.getAttribute("name"); if (eventName.isEmpty()) { eventName = eventElement.getAttribute("type") + "::" + eventElement.getAttribute("path") + "::" + eventElement.getAttribute("invoke"); } this.preprocessorEventList.put(eventName, new Event(eventElement)); } } // postprocessor events Element postprocessorElement = UtilXml.firstChildElement(rootElement, "postprocessor"); if (postprocessorElement != null) { for (Element eventElement : UtilXml.childElementList(postprocessorElement, "event")) { String eventName = eventElement.getAttribute("name"); if (eventName.isEmpty()) { eventName = eventElement.getAttribute("type") + "::" + eventElement.getAttribute("path") + "::" + eventElement.getAttribute("invoke"); } this.postprocessorEventList.put(eventName, new Event(eventElement)); } } // after-login events Element afterLoginElement = UtilXml.firstChildElement(rootElement, "after-login"); if (afterLoginElement != null) { for (Element eventElement : UtilXml.childElementList(afterLoginElement, "event")) { String eventName = eventElement.getAttribute("name"); if (eventName.isEmpty()) { eventName = eventElement.getAttribute("type") + "::" + eventElement.getAttribute("path") + "::" + eventElement.getAttribute("invoke"); } this.afterLoginEventList.put(eventName, new Event(eventElement)); } } // before-logout events Element beforeLogoutElement = UtilXml.firstChildElement(rootElement, "before-logout"); if (beforeLogoutElement != null) { for (Element eventElement : UtilXml.childElementList(beforeLogoutElement, "event")) { String eventName = eventElement.getAttribute("name"); if (eventName.isEmpty()) { eventName = eventElement.getAttribute("type") + "::" + eventElement.getAttribute("path") + "::" + eventElement.getAttribute("invoke"); } this.beforeLogoutEventList.put(eventName, new Event(eventElement)); } } } private void loadHandlerMap(Element rootElement) { for (Element handlerElement : UtilXml.childElementList(rootElement, "handler")) { String name = handlerElement.getAttribute("name"); String type = handlerElement.getAttribute("type"); String className = handlerElement.getAttribute("class"); if ("view".equals(type)) { this.viewHandlerMap.put(name, className); } else { this.eventHandlerMap.put(name, className); } } } protected void loadIncludes(Element rootElement) { for (Element includeElement : UtilXml.childElementList(rootElement, "include")) { String includeLocation = includeElement.getAttribute("location"); if (!includeLocation.isEmpty()) { try { URL urlLocation = FlexibleLocation.resolveLocation(includeLocation); includes.add(urlLocation); } catch (MalformedURLException mue) { Debug.logError(mue, "Error processing include at [" + includeLocation + "]:" + mue.toString(), module); } } } } private void loadRequestMap(Element root) { for (Element requestMapElement : UtilXml.childElementList(root, "request-map")) { RequestMap requestMap = new RequestMap(requestMapElement); this.requestMapMap.put(requestMap.uri, requestMap); } } private void loadViewMap(Element rootElement) { for (Element viewMapElement : UtilXml.childElementList(rootElement, "view-map")) { ViewMap viewMap = new ViewMap(viewMapElement); this.viewMapMap.put(viewMap.name, viewMap); } } } public static class Event { public String type; public String path; public String invoke; public boolean globalTransaction = true; public int transactionTimeout; public Metrics metrics = null; public Event(Element eventElement) { this.type = eventElement.getAttribute("type"); this.path = eventElement.getAttribute("path"); this.invoke = eventElement.getAttribute("invoke"); this.globalTransaction = !"false".equals(eventElement.getAttribute("global-transaction")); String tt = eventElement.getAttribute("transaction-timeout"); if(!tt.isEmpty()) { this.transactionTimeout = Integer.valueOf(tt); } // Get metrics. Element metricsElement = UtilXml.firstChildElement(eventElement, "metric"); if (metricsElement != null) { this.metrics = MetricsFactory.getInstance(metricsElement); } } public Event(String type, String path, String invoke, boolean globalTransaction) { this.type = type; this.path = path; this.invoke = invoke; this.globalTransaction = globalTransaction; } } public static class RequestMap { public String uri; public boolean edit = true; public boolean trackVisit = true; public boolean trackServerHit = true; public String description; public Event event; public boolean securityHttps = true; public boolean securityAuth = false; public boolean securityCert = false; public boolean securityExternalView = true; public boolean securityDirectRequest = true; public Map<String, RequestResponse> requestResponseMap = new HashMap<String, RequestResponse>(); public Metrics metrics = null; public RequestMap(Element requestMapElement) { // Get the URI info this.uri = requestMapElement.getAttribute("uri"); this.edit = !"false".equals(requestMapElement.getAttribute("edit")); this.trackServerHit = !"false".equals(requestMapElement.getAttribute("track-serverhit")); this.trackVisit = !"false".equals(requestMapElement.getAttribute("track-visit")); // Check for security Element securityElement = UtilXml.firstChildElement(requestMapElement, "security"); if (securityElement != null) { if (!UtilProperties.propertyValueEqualsIgnoreCase("url", "no.http", "Y")) { this.securityHttps = "true".equals(securityElement.getAttribute("https")); } else { String httpRequestMapList = UtilProperties.getPropertyValue("url", "http.request-map.list"); if (UtilValidate.isNotEmpty(httpRequestMapList)) { List<String> reqList = StringUtil.split(httpRequestMapList, ","); if (reqList.contains(this.uri)) { this.securityHttps = "true".equals(securityElement.getAttribute("https")); } } } this.securityAuth = "true".equals(securityElement.getAttribute("auth")); this.securityCert = "true".equals(securityElement.getAttribute("cert")); this.securityExternalView = !"false".equals(securityElement.getAttribute("external-view")); this.securityDirectRequest = !"false".equals(securityElement.getAttribute("direct-request")); } // Check for event Element eventElement = UtilXml.firstChildElement(requestMapElement, "event"); if (eventElement != null) { this.event = new Event(eventElement); } // Check for description this.description = UtilXml.childElementValue(requestMapElement, "description"); // Get the response(s) for (Element responseElement : UtilXml.childElementList(requestMapElement, "response")) { RequestResponse response = new RequestResponse(responseElement); requestResponseMap.put(response.name, response); } // Get metrics. Element metricsElement = UtilXml.firstChildElement(requestMapElement, "metric"); if (metricsElement != null) { this.metrics = MetricsFactory.getInstance(metricsElement); } } } public static class RequestResponse { public static RequestResponse createEmptyNoneRequestResponse() { RequestResponse requestResponse = new RequestResponse(); requestResponse.name = "empty-none"; requestResponse.type = "none"; requestResponse.value = null; return requestResponse; } public String name; public String type; public String value; public String statusCode; public boolean saveLastView = false; public boolean saveCurrentView = false; public boolean saveHomeView = false; public Map<String, String> redirectParameterMap = new HashMap<String, String>(); public Map<String, String> redirectParameterValueMap = new HashMap<String, String>(); public RequestResponse() { } public RequestResponse(Element responseElement) { this.name = responseElement.getAttribute("name"); this.type = responseElement.getAttribute("type"); this.value = responseElement.getAttribute("value"); this.statusCode = responseElement.getAttribute("status-code"); this.saveLastView = "true".equals(responseElement.getAttribute("save-last-view")); this.saveCurrentView = "true".equals(responseElement.getAttribute("save-current-view")); this.saveHomeView = "true".equals(responseElement.getAttribute("save-home-view")); for (Element redirectParameterElement : UtilXml.childElementList(responseElement, "redirect-parameter")) { if (UtilValidate.isNotEmpty(redirectParameterElement.getAttribute("value"))) { this.redirectParameterValueMap.put(redirectParameterElement.getAttribute("name"), redirectParameterElement.getAttribute("value")); } else { String from = redirectParameterElement.getAttribute("from"); if (from.isEmpty()) from = redirectParameterElement.getAttribute("name"); this.redirectParameterMap.put(redirectParameterElement.getAttribute("name"), from); } } } } public static class ViewMap { public String viewMap; public String name; public String page; public String type; public String info; public String contentType; public String encoding; public String xFrameOption; public String strictTransportSecurity; public String description; public boolean noCache = false; public ViewMap(Element viewMapElement) { this.name = viewMapElement.getAttribute("name"); this.page = viewMapElement.getAttribute("page"); this.type = viewMapElement.getAttribute("type"); this.info = viewMapElement.getAttribute("info"); this.contentType = viewMapElement.getAttribute("content-type"); this.noCache = "true".equals(viewMapElement.getAttribute("no-cache")); this.encoding = viewMapElement.getAttribute("encoding"); this.xFrameOption = viewMapElement.getAttribute("x-frame-options"); this.strictTransportSecurity = viewMapElement.getAttribute("strict-transport-security"); this.description = UtilXml.childElementValue(viewMapElement, "description"); if (UtilValidate.isEmpty(this.page)) { this.page = this.name; } } } }
apache-2.0
zhangleidaniejian/bluemmSite
src/main/java/cn/com/bluemoon/jeesite/modules/cms/entity/FileTpl.java
2211
package cn.com.bluemoon.jeesite.modules.cms.entity; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.sql.Timestamp; import java.util.Date; /** * User: songlai * Date: 13-8-22 * Time: 上午9:44 */ public class FileTpl { private File file; // 应用的根目录 private String root; public FileTpl(File file, String root) { this.file = file; this.root = root; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getRoot() { return root; } public void setRoot(String root) { this.root = root; } public String getName() { String ap = file.getAbsolutePath().substring(root.length()); ap = ap.replace(File.separatorChar, '/'); // 在resin里root的结尾是带'/'的,这样会导致getName返回的名称不以'/'开头。 if (!ap.startsWith("/")) { ap = "/" + ap; } return ap; } public String getParent(){ String ap = file.getParent().substring(root.length()); ap = ap.replace(File.separatorChar, '/'); // 在resin里root的结尾是带'/'的,这样会导致getName返回的名称不以'/'开头。 if (!ap.startsWith("/")) { ap = "/" + ap; } return ap; } public String getPath() { String name = getName(); return name.substring(0, name.lastIndexOf('/')); } public String getFilename() { return file.getName(); } public String getSource() { if (file.isDirectory()) { return null; } try { return FileUtils.readFileToString(this.file, "UTF-8"); } catch (IOException e) { throw new RuntimeException(e); } } public long getLastModified() { return file.lastModified(); } public Date getLastModifiedDate() { return new Timestamp(getLastModified()); } public long getLength() { return file.length(); } public int getSize() { return (int) (getLength() / 1024) + 1; } public boolean isDirectory() { return file.isDirectory(); } }
apache-2.0
emory-libraries/eulcore-history
src/eulcore/django/fedora/models.py
59
# place-holder so django recognizes as an app & runs tests
apache-2.0
J-Pi/pitch-it
pitch-it-ui/asset/lib/DrawApi.js
1770
/** * Copyright 2016-2017, the creators of pitch-it * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * be found in the LICENSE file in the root directory * */ import Message from '../../../shared/Message'; export default class DrawApi { constructor(socket) { this._socket = socket; this._socket.on(Message.DRAW_PATH, (msg) => this._remoteDraw(msg)); this._socket.on(Message.DRAW_CLEAR, () => this._remoteClear()); } static get CLOSE() { return 'close'; } static get KEEEP() { return 'keep'; } set remoteDrawCallback(callback) { this._remoteDrawCallback = callback; } set remoteClearCallback(callback) { this._remoteClearCallback = callback; } _remoteDraw(msg) { if(this._remoteDrawCallback) { this._remoteDrawCallback(msg.data.position.x, msg.data.position.y, msg.data.close); } } _remoteClear() { if (this._remoteClearCallback) { this._remoteClearCallback(); } } sendPathData(target, x, y, closeType) { let msg = new Message(Message.DRAW_PATH,{position: {x:x, y:y}, close: closeType, target: target}); this._socket.send(msg); } sendClear(target) { let msg = new Message(Message.DRAW_CLEAR, {target: target}); this._socket.send(msg); } }
apache-2.0
goxhaj/gastronomee
src/main/webapp/app/entities/location/location-delete-dialog.controller.js
726
(function() { 'use strict'; angular .module('gastronomeeApp') .controller('LocationDeleteController',LocationDeleteController); LocationDeleteController.$inject = ['$uibModalInstance', 'entity', 'Location']; function LocationDeleteController($uibModalInstance, entity, Location) { var vm = this; vm.location = entity; vm.clear = clear; vm.confirmDelete = confirmDelete; function clear () { $uibModalInstance.dismiss('cancel'); } function confirmDelete (id) { Location.delete({id: id}, function () { $uibModalInstance.close(true); }); } } })();
apache-2.0
mttkay/RxJava
rxjava-core/src/main/java/rx/Observable.java
449935
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package rx; import static rx.functions.Functions.alwaysFalse; import java.util.*; import java.util.concurrent.*; import rx.exceptions.*; import rx.functions.*; import rx.internal.operators.*; import rx.internal.util.ScalarSynchronousObservable; import rx.observables.*; import rx.observers.SafeSubscriber; import rx.plugins.*; import rx.schedulers.*; import rx.subjects.*; import rx.subscriptions.Subscriptions; /** * The Observable class that implements the Reactive Pattern. * <p> * This class provides methods for subscribing to the Observable as well as delegate methods to the various * Observers. * <p> * The documentation for this class makes use of marble diagrams. The following legend explains these diagrams: * <p> * <img width="640" height="301" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/legend.png"> * <p> * For more information see the <a href="https://github.com/Netflix/RxJava/wiki/Observable">RxJava Wiki</a> * * @param <T> * the type of the items emitted by the Observable */ public class Observable<T> { final OnSubscribe<T> onSubscribe; /** * Creates an Observable with a Function to execute when it is subscribed to. * <p> * <em>Note:</em> Use {@link #create(OnSubscribe)} to create an Observable, instead of this constructor, * unless you specifically have a need for inheritance. * * @param f * {@link OnSubscribe} to be executed when {@link #subscribe(Subscriber)} is called */ protected Observable(OnSubscribe<T> f) { this.onSubscribe = f; } private static final RxJavaObservableExecutionHook hook = RxJavaPlugins.getInstance().getObservableExecutionHook(); /** * Returns an Observable that will execute the specified function when a {@link Subscriber} subscribes to * it. * <p> * <img width="640" height="200" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/create.png"> * <p> * Write the function you pass to {@code create} so that it behaves as an Observable: It should invoke the * Subscriber's {@link Subscriber#onNext onNext}, {@link Subscriber#onError onError}, and * {@link Subscriber#onCompleted onCompleted} methods appropriately. * <p> * A well-formed Observable must invoke either the Subscriber's {@code onCompleted} method exactly once or * its {@code onError} method exactly once. * <p> * See <a href="http://go.microsoft.com/fwlink/?LinkID=205219">Rx Design Guidelines (PDF)</a> for detailed * information. * <p> * {@code create} does not operate by default on a particular {@link Scheduler}. * * @param <T> * the type of the items that this Observable emits * @param f * a function that accepts an {@code Subscriber<T>}, and invokes its {@code onNext}, {@code onError}, and {@code onCompleted} methods as appropriate * @return an Observable that, when a {@link Subscriber} subscribes to it, will execute the specified * function * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#create">RxJava Wiki: create()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.create.aspx">MSDN: Observable.Create</a> */ public final static <T> Observable<T> create(OnSubscribe<T> f) { return new Observable<T>(hook.onCreate(f)); } /** * Invoked when Obserable.subscribe is called. */ public static interface OnSubscribe<T> extends Action1<Subscriber<? super T>> { // cover for generics insanity } /** * Operator function for lifting into an Observable. */ public interface Operator<R, T> extends Func1<Subscriber<? super R>, Subscriber<? super T>> { // cover for generics insanity } /** * @deprecated use {@link #create(OnSubscribe)} */ @Deprecated public final static <T> Observable<T> create(final OnSubscribeFunc<T> f) { return new Observable<T>(new OnSubscribe<T>() { @Override public void call(Subscriber<? super T> observer) { Subscription s = f.onSubscribe(observer); if (s != null && s != observer) { observer.add(s); } } }); } /** * @deprecated use {@link OnSubscribe} */ @Deprecated public static interface OnSubscribeFunc<T> extends Function { public Subscription onSubscribe(Observer<? super T> op); } /** * Lifts a function to the current Observable and returns a new Observable that when subscribed to will pass * the values of the current Observable through the Operator function. * <p> * In other words, this allows chaining Observers together on an Observable for acting on the values within * the Observable. * <p> {@code * observable.map(...).filter(...).take(5).lift(new OperatorA()).lift(new OperatorB(...)).subscribe() * } * <p> * {@code lift} does not operate by default on a particular {@link Scheduler}. * * @param lift the Operator that implements the Observable-operating function to be applied to the source * Observable * @return an Observable that is the result of applying the lifted Operator to the source Observable * @since 0.17 */ public final <R> Observable<R> lift(final Operator<? extends R, ? super T> lift) { return new Observable<R>(new OnSubscribe<R>() { @Override public void call(Subscriber<? super R> o) { try { Subscriber<? super T> st = hook.onLift(lift).call(o); // new Subscriber created and being subscribed with so 'onStart' it st.onStart(); onSubscribe.call(st); } catch (Throwable e) { // localized capture of errors rather than it skipping all operators // and ending up in the try/catch of the subscribe method which then // prevents onErrorResumeNext and other similar approaches to error handling if (e instanceof OnErrorNotImplementedException) { throw (OnErrorNotImplementedException) e; } o.onError(e); } } }); } /* ********************************************************************************************************* * Observers Below Here * ********************************************************************************************************* */ /** * Mirrors the one Observable in an Iterable of several Observables that first emits an item. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png"> * <p> * {@code amb} does not operate by default on a particular {@link Scheduler}. * * @param sources * an Iterable of Observable sources competing to react first * @return an Observable that emits the same sequence of items as whichever of the source Observables first * emitted an item * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#amb">RxJava Wiki: amb()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229115.aspx">MSDN: Observable.Amb</a> */ public final static <T> Observable<T> amb(Iterable<? extends Observable<? extends T>> sources) { return create(OnSubscribeAmb.amb(sources)); } /** * Given two Observables, mirrors the one that first emits an item. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png"> * <p> * {@code amb} does not operate by default on a particular {@link Scheduler}. * * @param o1 * an Observable competing to react first * @param o2 * an Observable competing to react first * @return an Observable that emits the same sequence of items as whichever of the source Observables first * emitted an item * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#amb">RxJava Wiki: amb()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a> */ public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2) { return create(OnSubscribeAmb.amb(o1, o2)); } /** * Given three Observables, mirrors the one that first emits an item. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png"> * <p> * {@code amb} does not operate by default on a particular {@link Scheduler}. * * @param o1 * an Observable competing to react first * @param o2 * an Observable competing to react first * @param o3 * an Observable competing to react first * @return an Observable that emits the same sequence of items as whichever of the source Observables first * emitted an item * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#amb">RxJava Wiki: amb()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a> */ public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3) { return create(OnSubscribeAmb.amb(o1, o2, o3)); } /** * Given four Observables, mirrors the one that first emits an item. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png"> * <p> * {@code amb} does not operate by default on a particular {@link Scheduler}. * * @param o1 * an Observable competing to react first * @param o2 * an Observable competing to react first * @param o3 * an Observable competing to react first * @param o4 * an Observable competing to react first * @return an Observable that emits the same sequence of items as whichever of the source Observables first * emitted an item * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#amb">RxJava Wiki: amb()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a> */ public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4) { return create(OnSubscribeAmb.amb(o1, o2, o3, o4)); } /** * Given five Observables, mirrors the one that first emits an item. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png"> * <p> * {@code amb} does not operate by default on a particular {@link Scheduler}. * * @param o1 * an Observable competing to react first * @param o2 * an Observable competing to react first * @param o3 * an Observable competing to react first * @param o4 * an Observable competing to react first * @param o5 * an Observable competing to react first * @return an Observable that emits the same sequence of items as whichever of the source Observables first * emitted an item * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#amb">RxJava Wiki: amb()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a> */ public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5) { return create(OnSubscribeAmb.amb(o1, o2, o3, o4, o5)); } /** * Given six Observables, mirrors the one that first emits an item. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png"> * <p> * {@code amb} does not operate by default on a particular {@link Scheduler}. * * @param o1 * an Observable competing to react first * @param o2 * an Observable competing to react first * @param o3 * an Observable competing to react first * @param o4 * an Observable competing to react first * @param o5 * an Observable competing to react first * @param o6 * an Observable competing to react first * @return an Observable that emits the same sequence of items as whichever of the source Observables first * emitted an item * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#amb">RxJava Wiki: amb()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a> */ public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6) { return create(OnSubscribeAmb.amb(o1, o2, o3, o4, o5, o6)); } /** * Given seven Observables, mirrors the one that first emits an item. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png"> * <p> * {@code amb} does not operate by default on a particular {@link Scheduler}. * * @param o1 * an Observable competing to react first * @param o2 * an Observable competing to react first * @param o3 * an Observable competing to react first * @param o4 * an Observable competing to react first * @param o5 * an Observable competing to react first * @param o6 * an Observable competing to react first * @param o7 * an Observable competing to react first * @return an Observable that emits the same sequence of items as whichever of the source Observables first * emitted an item * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#amb">RxJava Wiki: amb()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a> */ public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6, Observable<? extends T> o7) { return create(OnSubscribeAmb.amb(o1, o2, o3, o4, o5, o6, o7)); } /** * Given eight Observables, mirrors the one that first emits an item. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png"> * <p> * {@code amb} does not operate by default on a particular {@link Scheduler}. * * @param o1 * an Observable competing to react first * @param o2 * an Observable competing to react first * @param o3 * an Observable competing to react first * @param o4 * an Observable competing to react first * @param o5 * an Observable competing to react first * @param o6 * an Observable competing to react first * @param o7 * an Observable competing to react first * @param o8 * an observable competing to react first * @return an Observable that emits the same sequence of items as whichever of the source Observables first * emitted an item * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#amb">RxJava Wiki: amb()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a> */ public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6, Observable<? extends T> o7, Observable<? extends T> o8) { return create(OnSubscribeAmb.amb(o1, o2, o3, o4, o5, o6, o7, o8)); } /** * Given nine Observables, mirrors the one that first emits an item. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png"> * <p> * {@code amb} does not operate by default on a particular {@link Scheduler}. * * @param o1 * an Observable competing to react first * @param o2 * an Observable competing to react first * @param o3 * an Observable competing to react first * @param o4 * an Observable competing to react first * @param o5 * an Observable competing to react first * @param o6 * an Observable competing to react first * @param o7 * an Observable competing to react first * @param o8 * an Observable competing to react first * @param o9 * an Observable competing to react first * @return an Observable that emits the same sequence of items as whichever of the source Observables first * emitted an item * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#amb">RxJava Wiki: amb()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a> */ public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6, Observable<? extends T> o7, Observable<? extends T> o8, Observable<? extends T> o9) { return create(OnSubscribeAmb.amb(o1, o2, o3, o4, o5, o6, o7, o8, o9)); } /** * Combines two source Observables by emitting an item that aggregates the latest values of each of the * source Observables each time an item is received from either of the source Observables, where this * aggregation is defined by a specified function. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png"> * <p> * {@code combineLatest} does not operate by default on a particular {@link Scheduler}. * * @param o1 * the first source Observable * @param o2 * the second source Observable * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#combinelatest">RxJava Wiki: combineLatest()</a> */ @SuppressWarnings("unchecked") public static final <T1, T2, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Func2<? super T1, ? super T2, ? extends R> combineFunction) { return combineLatest(Arrays.asList(o1, o2), Functions.fromFunc(combineFunction)); } /** * Combines three source Observables by emitting an item that aggregates the latest values of each of the * source Observables each time an item is received from any of the source Observables, where this * aggregation is defined by a specified function. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png"> * <p> * {@code combineLatest} does not operate by default on a particular {@link Scheduler}. * * @param o1 * the first source Observable * @param o2 * the second source Observable * @param o3 * the third source Observable * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#combinelatest">RxJava Wiki: combineLatest()</a> */ @SuppressWarnings("unchecked") public static final <T1, T2, T3, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Func3<? super T1, ? super T2, ? super T3, ? extends R> combineFunction) { return combineLatest(Arrays.asList(o1, o2, o3), Functions.fromFunc(combineFunction)); } /** * Combines four source Observables by emitting an item that aggregates the latest values of each of the * source Observables each time an item is received from any of the source Observables, where this * aggregation is defined by a specified function. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png"> * <p> * {@code combineLatest} does not operate by default on a particular {@link Scheduler}. * * @param o1 * the first source Observable * @param o2 * the second source Observable * @param o3 * the third source Observable * @param o4 * the fourth source Observable * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#combinelatest">RxJava Wiki: combineLatest()</a> */ @SuppressWarnings("unchecked") public static final <T1, T2, T3, T4, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Func4<? super T1, ? super T2, ? super T3, ? super T4, ? extends R> combineFunction) { return combineLatest(Arrays.asList(o1, o2, o3, o4), Functions.fromFunc(combineFunction)); } /** * Combines five source Observables by emitting an item that aggregates the latest values of each of the * source Observables each time an item is received from any of the source Observables, where this * aggregation is defined by a specified function. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png"> * <p> * {@code combineLatest} does not operate by default on a particular {@link Scheduler}. * * @param o1 * the first source Observable * @param o2 * the second source Observable * @param o3 * the third source Observable * @param o4 * the fourth source Observable * @param o5 * the fifth source Observable * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#combinelatest">RxJava Wiki: combineLatest()</a> */ @SuppressWarnings("unchecked") public static final <T1, T2, T3, T4, T5, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Func5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> combineFunction) { return combineLatest(Arrays.asList(o1, o2, o3, o4, o5), Functions.fromFunc(combineFunction)); } /** * Combines six source Observables by emitting an item that aggregates the latest values of each of the * source Observables each time an item is received from any of the source Observables, where this * aggregation is defined by a specified function. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png"> * <p> * {@code combineLatest} does not operate by default on a particular {@link Scheduler}. * * @param o1 * the first source Observable * @param o2 * the second source Observable * @param o3 * the third source Observable * @param o4 * the fourth source Observable * @param o5 * the fifth source Observable * @param o6 * the sixth source Observable * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#combinelatest">RxJava Wiki: combineLatest()</a> */ @SuppressWarnings("unchecked") public static final <T1, T2, T3, T4, T5, T6, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Func6<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? extends R> combineFunction) { return combineLatest(Arrays.asList(o1, o2, o3, o4, o5, o6), Functions.fromFunc(combineFunction)); } /** * Combines seven source Observables by emitting an item that aggregates the latest values of each of the * source Observables each time an item is received from any of the source Observables, where this * aggregation is defined by a specified function. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png"> * <p> * {@code combineLatest} does not operate by default on a particular {@link Scheduler}. * * @param o1 * the first source Observable * @param o2 * the second source Observable * @param o3 * the third source Observable * @param o4 * the fourth source Observable * @param o5 * the fifth source Observable * @param o6 * the sixth source Observable * @param o7 * the seventh source Observable * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#combinelatest">RxJava Wiki: combineLatest()</a> */ @SuppressWarnings("unchecked") public static final <T1, T2, T3, T4, T5, T6, T7, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Func7<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? extends R> combineFunction) { return combineLatest(Arrays.asList(o1, o2, o3, o4, o5, o6, o7), Functions.fromFunc(combineFunction)); } /** * Combines eight source Observables by emitting an item that aggregates the latest values of each of the * source Observables each time an item is received from any of the source Observables, where this * aggregation is defined by a specified function. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png"> * <p> * {@code combineLatest} does not operate by default on a particular {@link Scheduler}. * * @param o1 * the first source Observable * @param o2 * the second source Observable * @param o3 * the third source Observable * @param o4 * the fourth source Observable * @param o5 * the fifth source Observable * @param o6 * the sixth source Observable * @param o7 * the seventh source Observable * @param o8 * the eighth source Observable * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#combinelatest">RxJava Wiki: combineLatest()</a> */ @SuppressWarnings("unchecked") public static final <T1, T2, T3, T4, T5, T6, T7, T8, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Observable<? extends T8> o8, Func8<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? extends R> combineFunction) { return combineLatest(Arrays.asList(o1, o2, o3, o4, o5, o6, o7, o8), Functions.fromFunc(combineFunction)); } /** * Combines nine source Observables by emitting an item that aggregates the latest values of each of the * source Observables each time an item is received from any of the source Observables, where this * aggregation is defined by a specified function. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/combineLatest.png"> * <p> * {@code combineLatest} does not operate by default on a particular {@link Scheduler}. * * @param o1 * the first source Observable * @param o2 * the second source Observable * @param o3 * the third source Observable * @param o4 * the fourth source Observable * @param o5 * the fifth source Observable * @param o6 * the sixth source Observable * @param o7 * the seventh source Observable * @param o8 * the eighth source Observable * @param o9 * the ninth source Observable * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#combinelatest">RxJava Wiki: combineLatest()</a> */ @SuppressWarnings("unchecked") public static final <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Observable<? extends T8> o8, Observable<? extends T9> o9, Func9<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? super T9, ? extends R> combineFunction) { return combineLatest(Arrays.asList(o1, o2, o3, o4, o5, o6, o7, o8, o9), Functions.fromFunc(combineFunction)); } /** * Combines a list of source Observables by emitting an item that aggregates the latest values of each of * the source Observables each time an item is received from any of the source Observables, where this * aggregation is defined by a specified function. * <p> * {@code combineLatest} does not operate by default on a particular {@link Scheduler}. * * @param <T> * the common base type of source values * @param <R> * the result type * @param sources * the list of source Observables * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#combinelatest">RxJava Wiki: combineLatest()</a> */ public static final <T, R> Observable<R> combineLatest(List<? extends Observable<? extends T>> sources, FuncN<? extends R> combineFunction) { return create(new OnSubscribeCombineLatest<T, R>(sources, combineFunction)); } /** * Returns an Observable that emits the items emitted by each of the Observables emitted by the source * Observable, one after the other, without interleaving them. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png"> * <p> * {@code concat} does not operate by default on a particular {@link Scheduler}. * * @param observables * an Observable that emits Observables * @return an Observable that emits items all of the items emitted by the Observables emitted by * {@code observables}, one after the other, without interleaving them * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#concat">RxJava Wiki: concat()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends Observable<? extends T>> observables) { return observables.lift(new OperatorConcat<T>()); } /** * Returns an Observable that emits the items emitted by two Observables, one after the other, without * interleaving them. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png"> * <p> * {@code concat} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be concatenated * @param t2 * an Observable to be concatenated * @return an Observable that emits items emitted by the two source Observables, one after the other, * without interleaving them * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#concat">RxJava Wiki: concat()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2) { return concat(from(t1, t2)); } /** * Returns an Observable that emits the items emitted by three Observables, one after the other, without * interleaving them. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png"> * <p> * {@code concat} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be concatenated * @param t2 * an Observable to be concatenated * @param t3 * an Observable to be concatenated * @return an Observable that emits items emitted by the three source Observables, one after the other, * without interleaving them * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#concat">RxJava Wiki: concat()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3) { return concat(from(t1, t2, t3)); } /** * Returns an Observable that emits the items emitted by four Observables, one after the other, without * interleaving them. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png"> * <p> * {@code concat} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be concatenated * @param t2 * an Observable to be concatenated * @param t3 * an Observable to be concatenated * @param t4 * an Observable to be concatenated * @return an Observable that emits items emitted by the four source Observables, one after the other, * without interleaving them * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#concat">RxJava Wiki: concat()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4) { return concat(from(t1, t2, t3, t4)); } /** * Returns an Observable that emits the items emitted by five Observables, one after the other, without * interleaving them. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png"> * <p> * {@code concat} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be concatenated * @param t2 * an Observable to be concatenated * @param t3 * an Observable to be concatenated * @param t4 * an Observable to be concatenated * @param t5 * an Observable to be concatenated * @return an Observable that emits items emitted by the five source Observables, one after the other, * without interleaving them * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#concat">RxJava Wiki: concat()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5) { return concat(from(t1, t2, t3, t4, t5)); } /** * Returns an Observable that emits the items emitted by six Observables, one after the other, without * interleaving them. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png"> * <p> * {@code concat} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be concatenated * @param t2 * an Observable to be concatenated * @param t3 * an Observable to be concatenated * @param t4 * an Observable to be concatenated * @param t5 * an Observable to be concatenated * @param t6 * an Observable to be concatenated * @return an Observable that emits items emitted by the six source Observables, one after the other, * without interleaving them * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#concat">RxJava Wiki: concat()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6) { return concat(from(t1, t2, t3, t4, t5, t6)); } /** * Returns an Observable that emits the items emitted by seven Observables, one after the other, without * interleaving them. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png"> * <p> * {@code concat} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be concatenated * @param t2 * an Observable to be concatenated * @param t3 * an Observable to be concatenated * @param t4 * an Observable to be concatenated * @param t5 * an Observable to be concatenated * @param t6 * an Observable to be concatenated * @param t7 * an Observable to be concatenated * @return an Observable that emits items emitted by the seven source Observables, one after the other, * without interleaving them * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#concat">RxJava Wiki: concat()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7) { return concat(from(t1, t2, t3, t4, t5, t6, t7)); } /** * Returns an Observable that emits the items emitted by eight Observables, one after the other, without * interleaving them. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png"> * <p> * {@code concat} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be concatenated * @param t2 * an Observable to be concatenated * @param t3 * an Observable to be concatenated * @param t4 * an Observable to be concatenated * @param t5 * an Observable to be concatenated * @param t6 * an Observable to be concatenated * @param t7 * an Observable to be concatenated * @param t8 * an Observable to be concatenated * @return an Observable that emits items emitted by the eight source Observables, one after the other, * without interleaving them * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#concat">RxJava Wiki: concat()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8) { return concat(from(t1, t2, t3, t4, t5, t6, t7, t8)); } /** * Returns an Observable that emits the items emitted by nine Observables, one after the other, without * interleaving them. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png"> * <p> * {@code concat} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be concatenated * @param t2 * an Observable to be concatenated * @param t3 * an Observable to be concatenated * @param t4 * an Observable to be concatenated * @param t5 * an Observable to be concatenated * @param t6 * an Observable to be concatenated * @param t7 * an Observable to be concatenated * @param t8 * an Observable to be concatenated * @param t9 * an Observable to be concatenated * @return an Observable that emits items emitted by the nine source Observables, one after the other, * without interleaving them * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#concat">RxJava Wiki: concat()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8, Observable<? extends T> t9) { return concat(from(t1, t2, t3, t4, t5, t6, t7, t8, t9)); } /** * Returns an Observable that calls an Observable factory to create an Observable for each new Observer * that subscribes. That is, for each subscriber, the actual Observable that subscriber observes is * determined by the factory function. * <p> * <img width="640" height="340" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/defer.png"> * <p> * The defer Observer allows you to defer or delay emitting items from an Observable until such time as an * Observer subscribes to the Observable. This allows an {@link Observer} to easily obtain updates or a * refreshed version of the sequence. * <p> * {@code defer} does not operate by default on a particular {@link Scheduler}. * * @param observableFactory * the Observable factory function to invoke for each {@link Observer} that subscribes to the * resulting Observable * @param <T> * the type of the items emitted by the Observable * @return an Observable whose {@link Observer}s' subscriptions trigger an invocation of the given * Observable factory function * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#defer">RxJava Wiki: defer()</a> */ public final static <T> Observable<T> defer(Func0<? extends Observable<? extends T>> observableFactory) { return create(new OnSubscribeDefer<T>(observableFactory)); } /** * Returns an Observable that emits no items to the {@link Observer} and immediately invokes its * {@link Observer#onCompleted onCompleted} method. * <p> * <img width="640" height="190" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/empty.png"> * <p> * {@code empty} does not operate by default on a particular {@link Scheduler}. * * @param <T> * the type of the items (ostensibly) emitted by the Observable * @return an Observable that emits no items to the {@link Observer} but immediately invokes the * {@link Observer}'s {@link Observer#onCompleted() onCompleted} method * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#empty-error-and-never">RxJava Wiki: empty()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229670.aspx">MSDN: Observable.Empty</a> */ public final static <T> Observable<T> empty() { return from(new ArrayList<T>()); } /** * Returns an Observable that emits no items to the {@link Observer} and immediately invokes its * {@link Observer#onCompleted onCompleted} method on the specified Scheduler. * <p> * <img width="640" height="190" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/empty.s.png"> * * @param scheduler * the Scheduler to use to call the {@link Observer#onCompleted onCompleted} method * @param <T> * the type of the items (ostensibly) emitted by the Observable * @return an Observable that emits no items to the {@link Observer} but immediately invokes the * {@link Observer}'s {@link Observer#onCompleted() onCompleted} method with the specified * {@code scheduler} * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#empty-error-and-never">RxJava Wiki: empty()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229066.aspx">MSDN: Observable.Empty Method (IScheduler)</a> */ public final static <T> Observable<T> empty(Scheduler scheduler) { return Observable.<T> empty().subscribeOn(scheduler); } /** * Returns an Observable that invokes an {@link Observer}'s {@link Observer#onError onError} method when the * Observer subscribes to it. * <p> * <img width="640" height="190" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/error.png"> * <p> * {@code error} does not operate by default on a particular {@link Scheduler}. * * @param exception * the particular Throwable to pass to {@link Observer#onError onError} * @param <T> * the type of the items (ostensibly) emitted by the Observable * @return an Observable that invokes the {@link Observer}'s {@link Observer#onError onError} method when * the Observer subscribes to it * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#empty-error-and-never">RxJava Wiki: error()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh244299.aspx">MSDN: Observable.Throw</a> */ public final static <T> Observable<T> error(Throwable exception) { return new ThrowObservable<T>(exception); } /** * Returns an Observable that invokes an {@link Observer}'s {@link Observer#onError onError} method on the * specified Scheduler. * <p> * <img width="640" height="190" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/error.s.png"> * * @param exception * the particular Throwable to pass to {@link Observer#onError onError} * @param scheduler * the Scheduler on which to call {@link Observer#onError onError} * @param <T> * the type of the items (ostensibly) emitted by the Observable * @return an Observable that invokes the {@link Observer}'s {@link Observer#onError onError} method, on * the specified Scheduler * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#empty-error-and-never">RxJava Wiki: error()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211711.aspx">MSDN: Observable.Throw</a> */ public final static <T> Observable<T> error(Throwable exception, Scheduler scheduler) { return Observable.<T> error(exception).subscribeOn(scheduler); } /** * Converts a {@link Future} into an Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.Future.png"> * <p> * You can convert any object that supports the {@link Future} interface into an Observable that emits the * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} * method. * <p> * <em>Important note:</em> This Observable is blocking; you cannot unsubscribe from it. * <p> * {@code from} does not operate by default on a particular {@link Scheduler}. * * @param future * the source {@link Future} * @param <T> * the type of object that the {@link Future} returns, and also the type of item to be emitted by * the resulting Observable * @return an Observable that emits the item from the source {@link Future} * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#from">RxJava Wiki: from()</a> */ public final static <T> Observable<T> from(Future<? extends T> future) { return create(OnSubscribeToObservableFuture.toObservableFuture(future)); } /** * Converts a {@link Future} into an Observable, with a timeout on the Future. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.Future.png"> * <p> * You can convert any object that supports the {@link Future} interface into an Observable that emits the * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} * method. * <p> * <em>Important note:</em> This Observable is blocking; you cannot unsubscribe from it. * <p> * {@code from} does not operate by default on a particular {@link Scheduler}. * * @param future * the source {@link Future} * @param timeout * the maximum time to wait before calling {@code get} * @param unit * the {@link TimeUnit} of the {@code timeout} argument * @param <T> * the type of object that the {@link Future} returns, and also the type of item to be emitted by * the resulting Observable * @return an Observable that emits the item from the source {@link Future} * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#from">RxJava Wiki: from()</a> */ public final static <T> Observable<T> from(Future<? extends T> future, long timeout, TimeUnit unit) { return create(OnSubscribeToObservableFuture.toObservableFuture(future, timeout, unit)); } /** * Converts a {@link Future}, operating on a specified {@link Scheduler}, into an Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.Future.s.png"> * <p> * You can convert any object that supports the {@link Future} interface into an Observable that emits the * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} * method. * <p> * {@code from} does not operate by default on a particular {@link Scheduler}. * * @param future * the source {@link Future} * @param scheduler * the {@link Scheduler} to wait for the Future on. Use a Scheduler such as * {@link Schedulers#io()} that can block and wait on the Future * @param <T> * the type of object that the {@link Future} returns, and also the type of item to be emitted by * the resulting Observable * @return an Observable that emits the item from the source {@link Future} * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#from">RxJava Wiki: from()</a> */ public final static <T> Observable<T> from(Future<? extends T> future, Scheduler scheduler) { return create(OnSubscribeToObservableFuture.toObservableFuture(future)).subscribeOn(scheduler); } /** * Converts an {@link Iterable} sequence into an Observable that emits the items in the sequence. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png"> * <p> * {@code from} does not operate by default on a particular {@link Scheduler}. * * @param iterable * the source {@link Iterable} sequence * @param <T> * the type of items in the {@link Iterable} sequence and the type of items to be emitted by the * resulting Observable * @return an Observable that emits each item in the source {@link Iterable} sequence * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#from">RxJava Wiki: from()</a> */ public final static <T> Observable<T> from(Iterable<? extends T> iterable) { return create(new OnSubscribeFromIterable<T>(iterable)); } /** * Converts an {@link Iterable} sequence into an Observable that operates on the specified Scheduler, * emitting each item from the sequence. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.s.png"> * * @param iterable * the source {@link Iterable} sequence * @param scheduler * the Scheduler on which the Observable is to emit the items of the Iterable * @param <T> * the type of items in the {@link Iterable} sequence and the type of items to be emitted by the * resulting Observable * @return an Observable that emits each item in the source {@link Iterable} sequence, on the specified * Scheduler * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#from">RxJava Wiki: from()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh212140.aspx">MSDN: Observable.ToObservable</a> */ public final static <T> Observable<T> from(Iterable<? extends T> iterable, Scheduler scheduler) { return from(iterable).subscribeOn(scheduler); } /** * Converts an item into an Observable that emits that item. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png"> * <p> * {@code from} does not operate by default on a particular {@link Scheduler}. * * @param t1 * the item * @param <T> * the type of the item * @return an Observable that emits the item * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#from">RxJava Wiki: from()</a> */ public final static <T> Observable<T> from(T t1) { return just(t1); } /** * Converts two items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png"> * <p> * {@code from} does not operate by default on a particular {@link Scheduler}. * * @param t1 * first item * @param t2 * second item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#from">RxJava Wiki: from()</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> from(T t1, T t2) { return from(Arrays.asList(t1, t2)); } /** * Converts three items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png"> * <p> * {@code from} does not operate by default on a particular {@link Scheduler}. * * @param t1 * first item * @param t2 * second item * @param t3 * third item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#from">RxJava Wiki: from()</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> from(T t1, T t2, T t3) { return from(Arrays.asList(t1, t2, t3)); } /** * Converts four items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png"> * <p> * {@code from} does not operate by default on a particular {@link Scheduler}. * * @param t1 * first item * @param t2 * second item * @param t3 * third item * @param t4 * fourth item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#from">RxJava Wiki: from()</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> from(T t1, T t2, T t3, T t4) { return from(Arrays.asList(t1, t2, t3, t4)); } /** * Converts five items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png"> * <p> * {@code from} does not operate by default on a particular {@link Scheduler}. * * @param t1 * first item * @param t2 * second item * @param t3 * third item * @param t4 * fourth item * @param t5 * fifth item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#from">RxJava Wiki: from()</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5) { return from(Arrays.asList(t1, t2, t3, t4, t5)); } /** * Converts six items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png"> * <p> * {@code from} does not operate by default on a particular {@link Scheduler}. * * @param t1 * first item * @param t2 * second item * @param t3 * third item * @param t4 * fourth item * @param t5 * fifth item * @param t6 * sixth item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#from">RxJava Wiki: from()</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5, T t6) { return from(Arrays.asList(t1, t2, t3, t4, t5, t6)); } /** * Converts seven items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png"> * <p> * {@code from} does not operate by default on a particular {@link Scheduler}. * * @param t1 * first item * @param t2 * second item * @param t3 * third item * @param t4 * fourth item * @param t5 * fifth item * @param t6 * sixth item * @param t7 * seventh item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#from">RxJava Wiki: from()</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5, T t6, T t7) { return from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7)); } /** * Converts eight items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png"> * <p> * {@code from} does not operate by default on a particular {@link Scheduler}. * * @param t1 * first item * @param t2 * second item * @param t3 * third item * @param t4 * fourth item * @param t5 * fifth item * @param t6 * sixth item * @param t7 * seventh item * @param t8 * eighth item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#from">RxJava Wiki: from()</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8) { return from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8)); } /** * Converts nine items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png"> * <p> * {@code from} does not operate by default on a particular {@link Scheduler}. * * @param t1 * first item * @param t2 * second item * @param t3 * third item * @param t4 * fourth item * @param t5 * fifth item * @param t6 * sixth item * @param t7 * seventh item * @param t8 * eighth item * @param t9 * ninth item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#from">RxJava Wiki: from()</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8, T t9) { return from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8, t9)); } /** * Converts ten items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png"> * <p> * {@code from} does not operate by default on a particular {@link Scheduler}. * * @param t1 * first item * @param t2 * second item * @param t3 * third item * @param t4 * fourth item * @param t5 * fifth item * @param t6 * sixth item * @param t7 * seventh item * @param t8 * eighth item * @param t9 * ninth item * @param t10 * tenth item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#from">RxJava Wiki: from()</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> from(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8, T t9, T t10) { return from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10)); } /** * Converts an Array into an Observable that emits the items in the Array. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png"> * <p> * {@code from} does not operate by default on a particular {@link Scheduler}. * * @param t1 * the source Array * @param <T> * the type of items in the Array and the type of items to be emitted by the resulting Observable * @return an Observable that emits each item in the source Array * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#from">RxJava Wiki: from()</a> */ public final static <T> Observable<T> from(T... t1) { return from(Arrays.asList(t1)); } /** * Converts an Array into an Observable that emits the items in the Array on a specified Scheduler. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/from.png"> * * @param items * the source Array * @param scheduler * the Scheduler on which the Observable emits the items of the Array * @param <T> * the type of items in the Array and the type of items to be emitted by the resulting Observable * @return an Observable that emits each item in the source Array * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#from">RxJava Wiki: from()</a> */ public final static <T> Observable<T> from(T[] items, Scheduler scheduler) { return from(Arrays.asList(items), scheduler); } /** * Returns an Observable that emits a sequential number every specified interval of time. * <p> * <img width="640" height="195" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/interval.png"> * <p> * {@code interval} operates by default on the {@code computation} {@link Scheduler}. * * @param interval * interval size in time units (see below) * @param unit * time units to use for the interval size * @return an Observable that emits a sequential number each time interval * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#interval">RxJava Wiki: interval()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229027.aspx">MSDN: Observable.Interval</a> */ public final static Observable<Long> interval(long interval, TimeUnit unit) { return create(new OnSubscribeTimerPeriodically(interval, interval, unit, Schedulers.computation())); } /** * Returns an Observable that emits a sequential number every specified interval of time, on a * specified Scheduler. * <p> * <img width="640" height="200" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/interval.s.png"> * * @param interval * interval size in time units (see below) * @param unit * time units to use for the interval size * @param scheduler * the Scheduler to use for scheduling the items * @return an Observable that emits a sequential number each time interval * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#interval">RxJava Wiki: interval()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh228911.aspx">MSDN: Observable.Interval</a> */ public final static Observable<Long> interval(long interval, TimeUnit unit, Scheduler scheduler) { return create(new OnSubscribeTimerPeriodically(interval, interval, unit, scheduler)); } /** * Returns an Observable that emits a single item and then completes. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/just.png"> * <p> * To convert any object into an Observable that emits that object, pass that object into the {@code just} * method. * <p> * This is similar to the {@link #from(java.lang.Object[])} method, except that {@code from} will convert * an {@link Iterable} object into an Observable that emits each of the items in the Iterable, one at a * time, while the {@code just} method converts an Iterable into an Observable that emits the entire * Iterable as a single item. * <p> * {@code just} does not operate by default on a particular {@link Scheduler}. * * @param value * the item to emit * @param <T> * the type of that item * @return an Observable that emits {@code value} as a single item and then completes * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#just">RxJava Wiki: just()</a> */ public final static <T> Observable<T> just(final T value) { return ScalarSynchronousObservable.create(value); } /** * Returns an Observable that emits a single item and then completes, on a specified Scheduler. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/just.s.png"> * * @param value * the item to emit * @param <T> * the type of that item * @param scheduler * the Scheduler to emit the single item on * @return an Observable that emits {@code value} as a single item and then completes, on a specified * Scheduler * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#just">RxJava Wiki: just()</a> */ public final static <T> Observable<T> just(T value, Scheduler scheduler) { return just(value).subscribeOn(scheduler); } /** * Flattens an Iterable of Observables into one Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png"> * <p> * You can combine the items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. * <p> * {@code merge} does not operate by default on a particular {@link Scheduler}. * * @param sequences * the Iterable of Observables * @return an Observable that emits items that are the result of flattening the items emitted by the * Observables in the Iterable * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#merge">RxJava Wiki: merge()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229590.aspx">MSDN: Observable.Merge</a> */ public final static <T> Observable<T> merge(Iterable<? extends Observable<? extends T>> sequences) { return merge(from(sequences)); } /** * Flattens an Iterable of Observables into one Observable, without any transformation, while limiting the * number of concurrent subscriptions to these Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png"> * <p> * You can combine the items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. * <p> * {@code merge} does not operate by default on a particular {@link Scheduler}. * * @param sequences * the Iterable of Observables * @param maxConcurrent * the maximum number of Observables that may be subscribed to concurrently * @return an Observable that emits items that are the result of flattening the items emitted by the * Observables in the Iterable * @throws IllegalArgumentException * if {@code maxConcurrent} is less than or equal to 0 * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#merge">RxJava Wiki: merge()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229923.aspx">MSDN: Observable.Merge</a> */ public final static <T> Observable<T> merge(Iterable<? extends Observable<? extends T>> sequences, int maxConcurrent) { return merge(from(sequences), maxConcurrent); } /** * Flattens an Iterable of Observables into one Observable, without any transformation, while limiting the * number of concurrent subscriptions to these Observables, and subscribing to these Observables on a * specified Scheduler. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png"> * <p> * You can combine the items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. * * @param sequences * the Iterable of Observables * @param maxConcurrent * the maximum number of Observables that may be subscribed to concurrently * @param scheduler * the Scheduler on which to traverse the Iterable of Observables * @return an Observable that emits items that are the result of flattening the items emitted by the * Observables in the Iterable * @throws IllegalArgumentException * if {@code maxConcurrent} is less than or equal to 0 * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#merge">RxJava Wiki: merge()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh244329.aspx">MSDN: Observable.Merge</a> */ public final static <T> Observable<T> merge(Iterable<? extends Observable<? extends T>> sequences, int maxConcurrent, Scheduler scheduler) { return merge(from(sequences, scheduler), maxConcurrent); } /** * Flattens an Iterable of Observables into one Observable, without any transformation, subscribing to these * Observables on a specified Scheduler. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png"> * <p> * You can combine the items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. * * @param sequences * the Iterable of Observables * @param scheduler * the Scheduler on which to traverse the Iterable of Observables * @return an Observable that emits items that are the result of flattening the items emitted by the * Observables in the Iterable * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#merge">RxJava Wiki: merge()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh244336.aspx">MSDN: Observable.Merge</a> */ public final static <T> Observable<T> merge(Iterable<? extends Observable<? extends T>> sequences, Scheduler scheduler) { return merge(from(sequences, scheduler)); } /** * Flattens an Observable that emits Observables into a single Observable that emits the items emitted by * those Observables, without any transformation. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.oo.png"> * <p> * You can combine the items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. * <p> * {@code merge} does not operate by default on a particular {@link Scheduler}. * * @param source * an Observable that emits Observables * @return an Observable that emits items that are the result of flattening the Observables emitted by the * {@code source} Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#merge">RxJava Wiki: merge()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ public final static <T> Observable<T> merge(Observable<? extends Observable<? extends T>> source) { return source.lift(new OperatorMerge<T>()); } /** * Flattens an Observable that emits Observables into a single Observable that emits the items emitted by * those Observables, without any transformation, while limiting the maximum number of concurrent * subscriptions to these Observables. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.oo.png"> * <p> * You can combine the items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. * <p> * {@code merge} does not operate by default on a particular {@link Scheduler}. * * @param source * an Observable that emits Observables * @param maxConcurrent * the maximum number of Observables that may be subscribed to concurrently * @return an Observable that emits items that are the result of flattening the Observables emitted by the * {@code source} Observable * @throws IllegalArgumentException * if {@code maxConcurrent} is less than or equal to 0 * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#merge">RxJava Wiki: merge()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211914.aspx">MSDN: Observable.Merge</a> */ public final static <T> Observable<T> merge(Observable<? extends Observable<? extends T>> source, int maxConcurrent) { return source.lift(new OperatorMergeMaxConcurrent<T>(maxConcurrent)); } /** * Flattens two Observables into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png"> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. * <p> * {@code merge} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#merge">RxJava Wiki: merge()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ @SuppressWarnings("unchecked") public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2) { return merge(from(Arrays.asList(t1, t2))); } /** * Flattens three Observables into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png"> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. * <p> * {@code merge} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#merge">RxJava Wiki: merge()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ @SuppressWarnings("unchecked") public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3) { return merge(from(Arrays.asList(t1, t2, t3))); } /** * Flattens four Observables into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png"> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. * <p> * {@code merge} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#merge">RxJava Wiki: merge()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ @SuppressWarnings("unchecked") public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4) { return merge(from(Arrays.asList(t1, t2, t3, t4))); } /** * Flattens five Observables into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png"> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. * <p> * {@code merge} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#merge">RxJava Wiki: merge()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ @SuppressWarnings("unchecked") public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5) { return merge(from(Arrays.asList(t1, t2, t3, t4, t5))); } /** * Flattens six Observables into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png"> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. * <p> * {@code merge} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @param t6 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#merge">RxJava Wiki: merge()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ @SuppressWarnings("unchecked") public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6) { return merge(from(Arrays.asList(t1, t2, t3, t4, t5, t6))); } /** * Flattens seven Observables into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png"> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. * <p> * {@code merge} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @param t6 * an Observable to be merged * @param t7 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#merge">RxJava Wiki: merge()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ @SuppressWarnings("unchecked") public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7) { return merge(from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7))); } /** * Flattens eight Observables into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png"> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. * <p> * {@code merge} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @param t6 * an Observable to be merged * @param t7 * an Observable to be merged * @param t8 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ @SuppressWarnings("unchecked") public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8) { return merge(from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8))); } /** * Flattens nine Observables into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png"> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. * <p> * {@code merge} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @param t6 * an Observable to be merged * @param t7 * an Observable to be merged * @param t8 * an Observable to be merged * @param t9 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#merge">RxJava Wiki: merge()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ @SuppressWarnings("unchecked") public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8, Observable<? extends T> t9) { return merge(from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8, t9))); } /** * Flattens an Array of Observables into one Observable, without any transformation. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.io.png"> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. * <p> * {@code merge} does not operate by default on a particular {@link Scheduler}. * * @param sequences * the Array of Observables * @return an Observable that emits all of the items emitted by the Observables in the Array * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#merge">RxJava Wiki: merge()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ public final static <T> Observable<T> merge(Observable<? extends T>[] sequences) { return merge(from(sequences)); } /** * Flattens an Array of Observables into one Observable, without any transformation, traversing the array on * a specified Scheduler. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.ios.png"> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. * * @param sequences * the Array of Observables * @param scheduler * the Scheduler on which to traverse the Array * @return an Observable that emits all of the items emitted by the Observables in the Array * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#merge">RxJava Wiki: merge()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229061.aspx">MSDN: Observable.Merge</a> */ public final static <T> Observable<T> merge(Observable<? extends T>[] sequences, Scheduler scheduler) { return merge(from(sequences, scheduler)); } /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * <p> * This behaves like {@link #merge(Observable)} except that if any of the merged Observables notify of an * error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png"> * <p> * Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <p> * {@code mergeDelayError} does not operate by default on a particular {@link Scheduler}. * * @param source * an Observable that emits Observables * @return an Observable that emits all of the items emitted by the Observables emitted by the * {@code source} Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#mergedelayerror">RxJava Wiki: mergeDelayError()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ public final static <T> Observable<T> mergeDelayError(Observable<? extends Observable<? extends T>> source) { return source.lift(new OperatorMergeDelayError<T>()); } /** * Flattens two Observables into one Observable, in a way that allows an Observer to receive all * successfully emitted items from each of the source Observables without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(Observable, Observable)} except that if any of the merged Observables * notify of an error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from * propagating that error notification until all of the merged Observables have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png"> * <p> * Even if both merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <p> * {@code mergeDelayError} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @return an Observable that emits all of the items that are emitted by the two source Observables * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#mergedelayerror">RxJava Wiki: mergeDelayError()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2) { return mergeDelayError(from(t1, t2)); } /** * Flattens three Observables into one Observable, in a way that allows an Observer to receive all * successfully emitted items from all of the source Observables without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(Observable, Observable, Observable)} except that if any of the merged * Observables notify of an error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain * from propagating that error notification until all of the merged Observables have finished emitting * items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png"> * <p> * Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <p> * {@code mergeDelayError} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @return an Observable that emits all of the items that are emitted by the source Observables * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#mergedelayerror">RxJava Wiki: mergeDelayError()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3) { return mergeDelayError(from(t1, t2, t3)); } /** * Flattens four Observables into one Observable, in a way that allows an Observer to receive all * successfully emitted items from all of the source Observables without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(Observable, Observable, Observable, Observable)} except that if any of * the merged Observables notify of an error via {@link Observer#onError onError}, {@code mergeDelayError} * will refrain from propagating that error notification until all of the merged Observables have finished * emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png"> * <p> * Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <p> * {@code mergeDelayError} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @return an Observable that emits all of the items that are emitted by the source Observables * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#mergedelayerror">RxJava Wiki: mergeDelayError()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4) { return mergeDelayError(from(t1, t2, t3, t4)); } /** * Flattens five Observables into one Observable, in a way that allows an Observer to receive all * successfully emitted items from all of the source Observables without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable)} except that * if any of the merged Observables notify of an error via {@link Observer#onError onError}, * {@code mergeDelayError} will refrain from propagating that error notification until all of the merged * Observables have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png"> * <p> * Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <p> * {@code mergeDelayError} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @return an Observable that emits all of the items that are emitted by the source Observables * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#mergedelayerror">RxJava Wiki: mergeDelayError()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5) { return mergeDelayError(from(t1, t2, t3, t4, t5)); } /** * Flattens six Observables into one Observable, in a way that allows an Observer to receive all * successfully emitted items from all of the source Observables without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable, Observable)} * except that if any of the merged Observables notify of an error via {@link Observer#onError onError}, * {@code mergeDelayError} will refrain from propagating that error notification until all of the merged * Observables have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png"> * <p> * Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <p> * {@code mergeDelayError} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @param t6 * an Observable to be merged * @return an Observable that emits all of the items that are emitted by the source Observables * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#mergedelayerror">RxJava Wiki: mergeDelayError()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6) { return mergeDelayError(from(t1, t2, t3, t4, t5, t6)); } /** * Flattens seven Observables into one Observable, in a way that allows an Observer to receive all * successfully emitted items from all of the source Observables without being interrupted by an error * notification from one of them. * <p> * This behaves like * {@link #merge(Observable, Observable, Observable, Observable, Observable, Observable, Observable)} * except that if any of the merged Observables notify of an error via {@link Observer#onError onError}, * {@code mergeDelayError} will refrain from propagating that error notification until all of the merged * Observables have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png"> * <p> * Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <p> * {@code mergeDelayError} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @param t6 * an Observable to be merged * @param t7 * an Observable to be merged * @return an Observable that emits all of the items that are emitted by the source Observables * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#mergedelayerror">RxJava Wiki: mergeDelayError()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7) { return mergeDelayError(from(t1, t2, t3, t4, t5, t6, t7)); } /** * Flattens eight Observables into one Observable, in a way that allows an Observer to receive all * successfully emitted items from all of the source Observables without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable)} * except that if any of the merged Observables notify of an error via {@link Observer#onError onError}, * {@code mergeDelayError} will refrain from propagating that error notification until all of the merged * Observables have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png"> * <p> * Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <p> * {@code mergeDelayError} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @param t6 * an Observable to be merged * @param t7 * an Observable to be merged * @param t8 * an Observable to be merged * @return an Observable that emits all of the items that are emitted by the source Observables * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#mergedelayerror">RxJava Wiki: mergeDelayError()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ // suppress because the types are checked by the method signature before using a vararg public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8) { return mergeDelayError(from(t1, t2, t3, t4, t5, t6, t7, t8)); } /** * Flattens nine Observables into one Observable, in a way that allows an Observer to receive all * successfully emitted items from all of the source Observables without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable)} * except that if any of the merged Observables notify of an error via {@link Observer#onError onError}, * {@code mergeDelayError} will refrain from propagating that error notification until all of the merged * Observables have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeDelayError.png"> * <p> * Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <p> * {@code mergeDelayError} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @param t6 * an Observable to be merged * @param t7 * an Observable to be merged * @param t8 * an Observable to be merged * @param t9 * an Observable to be merged * @return an Observable that emits all of the items that are emitted by the source Observables * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#mergedelayerror">RxJava Wiki: mergeDelayError()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> */ public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8, Observable<? extends T> t9) { return mergeDelayError(from(t1, t2, t3, t4, t5, t6, t7, t8, t9)); } /** * Converts the source {@code Observable<T>} into an {@code Observable<Observable<T>>} that emits the * source Observable as its single emission. * <p> * <img width="640" height="350" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/nest.png"> * <p> * {@code nest} does not operate by default on a particular {@link Scheduler}. * * @return an Observable that emits a single item: the source Observable * @since 0.17 */ public final Observable<Observable<T>> nest() { return just(this); } /** * Returns an Observable that never sends any items or notifications to an {@link Observer}. * <p> * <img width="640" height="185" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/never.png"> * <p> * This Observable is useful primarily for testing purposes. * <p> * {@code never} does not operate by default on a particular {@link Scheduler}. * * @param <T> * the type of items (not) emitted by the Observable * @return an Observable that never emits any items or sends any notifications to an {@link Observer} * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#empty-error-and-never">RxJava Wiki: never()</a> */ public final static <T> Observable<T> never() { return new NeverObservable<T>(); } /** * Converts an {@code Observable<Observable<T>>} into another {@code Observable<Observable<T>>} whose * emitted Observables emit the same items as those emitted by the source Observable, but where the number * of such Observables is restricted by {@code parallelObservables}. * <p> * For example, if the original {@code Observable<Observable<T>>} emits 100 Observables and * {@code parallelObservables} is 8, the items emitted by the 100 original Observables will be distributed * among 8 Observables emitted by the resulting Observable. * <p> * <img width="640" height="535" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/parallelMerge.png"> * <p> * This is a mechanism for efficiently processing <i>n</i> number of Observables on a smaller <i>m</i> * number of resources (typically CPU cores). * <p> * {@code parallelMerge} by default operates on the {@code immediate} {@link Scheduler}. * * @param parallelObservables * the number of Observables to merge into * @return an Observable of Observables constrained in number by {@code parallelObservables} * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#parallelmerge">RxJava Wiki: parallelMerge()</a> */ public final static <T> Observable<Observable<T>> parallelMerge(Observable<Observable<T>> source, int parallelObservables) { return OperatorParallelMerge.parallelMerge(source, parallelObservables); } /** * Converts an {@code Observable<Observable<T>>} into another {@code Observable<Observable<T>>} whose * emitted Observables emit the same items as those emitted by the source Observable, but where the number * of such Observables is restricted by {@code parallelObservables}, and each runs on a defined Scheduler. * <p> * For example, if the original {@code Observable<Observable<T>>} emits 100 Observables and * {@code parallelObservables} is 8, the items emitted by the 100 original Observables will be distributed * among 8 Observables emitted by the resulting Observable. * <p> * <img width="640" height="535" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/parallelMerge.png"> * <p> * This is a mechanism for efficiently processing <i>n</i> number of Observables on a smaller <i>m</i> * number of resources (typically CPU cores). * * @param parallelObservables * the number of Observables to merge into * @param scheduler * the {@link Scheduler} to run each Observable on * @return an Observable of Observables constrained in number by {@code parallelObservables} * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#parallelmerge">RxJava Wiki: parallelMerge()</a> */ public final static <T> Observable<Observable<T>> parallelMerge(Observable<Observable<T>> source, int parallelObservables, Scheduler scheduler) { return OperatorParallelMerge.parallelMerge(source, parallelObservables, scheduler); } /** * Pivots a sequence of {@code GroupedObservable}s emitted by an {@code Observable} so as to swap the group * and and the set on which their items are grouped. * <p> * <img width="640" height="580" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/pivot.png"> * * For example an {@code Observable} such as this =&gt; * * {@code Observable<GroupedObservable<String, GroupedObservable<Boolean, Integer>>>}: * <ul> * <li>o1.odd: 1, 3, 5, 7, 9 on Thread 1</li> * <li>o1.even: 2, 4, 6, 8, 10 on Thread 1</li> * <li>o2.odd: 11, 13, 15, 17, 19 on Thread 2</li> * <li>o2.even: 12, 14, 16, 18, 20 on Thread 2</li> * </ul> * is pivoted to become this =&gt; * * {@code Observable<GroupedObservable<Boolean, GroupedObservable<String, Integer>>>}: * <ul> * <li>odd.o1: 1, 3, 5, 7, 9 on Thread 1</li> * <li>odd.o2: 11, 13, 15, 17, 19 on Thread 2</li> * <li>even.o1: 2, 4, 6, 8, 10 on Thread 1</li> * <li>even.o2: 12, 14, 16, 18, 20 on Thread 2</li> * </ul> * <p> * <img width="640" height="1140" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/pivot.ex.png"> * <p> * <em>Note:</em> A {@link GroupedObservable} will cache the items it is to emit until such time as it * is subscribed to. For this reason, in order to avoid memory leaks, you should not simply ignore those * {@code GroupedObservable}s that do not concern you. Instead, you can signal to them that they may * discard their buffers by applying an operator like {@link #take}{@code (0)} to them. * <p> * {@code pivot} does not operate by default on a particular {@link Scheduler}. * * @param groups the {@link GroupedObservable} to pivot * @return an {@code Observable} containing a stream of nested {@code GroupedObservable}s with swapped * inner-outer keys. * @since 0.17 */ public static final <K1, K2, T> Observable<GroupedObservable<K2, GroupedObservable<K1, T>>> pivot(Observable<GroupedObservable<K1, GroupedObservable<K2, T>>> groups) { return groups.lift(new OperatorPivot<K1, K2, T>()); } /** * Returns an Observable that emits a sequence of Integers within a specified range. * <p> * <img width="640" height="195" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/range.png"> * <p> * {@code range} does not operate by default on a particular {@link Scheduler}. * * @param start * the value of the first Integer in the sequence * @param count * the number of sequential Integers to generate * @return an Observable that emits a range of sequential Integers * @throws IllegalArgumentException * if {@code count} is less than zero, or if {@code start} + {@code count} &minus; 1 exceeds * {@code Integer.MAX_VALUE} * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#range">RxJava Wiki: range()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229460.aspx">MSDN: Observable.Range</a> */ public final static Observable<Integer> range(int start, int count) { if (count < 0) { throw new IllegalArgumentException("Count can not be negative"); } if (count == 0) { return Observable.empty(); } if (start > Integer.MAX_VALUE - count + 1) { throw new IllegalArgumentException("start + count can not exceed Integer.MAX_VALUE"); } if(count == 1) { return Observable.just(start); } return Observable.create(new OnSubscribeRange(start, start + (count - 1))); } /** * Returns an Observable that emits a sequence of Integers within a specified range, on a specified * Scheduler. * <p> * <img width="640" height="195" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/range.s.png"> * * @param start * the value of the first Integer in the sequence * @param count * the number of sequential Integers to generate * @param scheduler * the Scheduler to run the generator loop on * @return an Observable that emits a range of sequential Integers * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#range">RxJava Wiki: range()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211896.aspx">MSDN: Observable.Range</a> */ public final static Observable<Integer> range(int start, int count, Scheduler scheduler) { return range(start, count).subscribeOn(scheduler); } /** * Returns an Observable that emits a Boolean value that indicates whether two Observable sequences are the * same by comparing the items emitted by each Observable pairwise. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/sequenceEqual.png"> * <p> * {@code sequenceEqual} does not operate by default on a particular {@link Scheduler}. * * @param first * the first Observable to compare * @param second * the second Observable to compare * @param <T> * the type of items emitted by each Observable * @return an Observable that emits a Boolean value that indicates whether the two sequences are the same * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#sequenceequal">RxJava Wiki: sequenceEqual()</a> */ public final static <T> Observable<Boolean> sequenceEqual(Observable<? extends T> first, Observable<? extends T> second) { return sequenceEqual(first, second, new Func2<T, T, Boolean>() { @Override public final Boolean call(T first, T second) { if (first == null) { return second == null; } return first.equals(second); } }); } /** * Returns an Observable that emits a Boolean value that indicates whether two Observable sequences are the * same by comparing the items emitted by each Observable pairwise based on the results of a specified * equality function. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/sequenceEqual.png"> * <p> * {@code sequenceEqual} does not operate by default on a particular {@link Scheduler}. * * @param first * the first Observable to compare * @param second * the second Observable to compare * @param equality * a function used to compare items emitted by each Observable * @param <T> * the type of items emitted by each Observable * @return an Observable that emits a Boolean value that indicates whether the two Observable two sequences * are the same according to the specified function * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#sequenceequal">RxJava Wiki: sequenceEqual()</a> */ public final static <T> Observable<Boolean> sequenceEqual(Observable<? extends T> first, Observable<? extends T> second, Func2<? super T, ? super T, Boolean> equality) { return OperatorSequenceEqual.sequenceEqual(first, second, equality); } /** * Converts an Observable that emits Observables into an Observable that emits the items emitted by the * most recently emitted of those Observables. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/switchDo.png"> * <p> * {@code switchOnNext} subscribes to an Observable that emits Observables. Each time it observes one of * these emitted Observables, the Observable returned by {@code switchOnNext} begins emitting the items * emitted by that Observable. When a new Observable is emitted, {@code switchOnNext} stops emitting items * from the earlier-emitted Observable and begins emitting items from the new one. * <p> * {@code switchOnNext} does not operate by default on a particular {@link Scheduler}. * * @param <T> the item type * @param sequenceOfSequences * the source Observable that emits Observables * @return an Observable that emits the items emitted by the Observable most recently emitted by the source * Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#switchonnext">RxJava Wiki: switchOnNext()</a> */ public final static <T> Observable<T> switchOnNext(Observable<? extends Observable<? extends T>> sequenceOfSequences) { return sequenceOfSequences.lift(new OperatorSwitch<T>()); } /** * Returns an Observable that emits a {@code 0L} after the {@code initialDelay} and ever increasing numbers * after each {@code period} of time thereafter. * <p> * <img width="640" height="200" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timer.p.png"> * <p> * {@code timer} operates by default on the {@code computation} {@link Scheduler}. * * @param initialDelay * the initial delay time to wait before emitting the first value of 0L * @param period * the period of time between emissions of the subsequent numbers * @param unit * the time unit for both {@code initialDelay} and {@code period} * @return an Observable that emits a 0L after the {@code initialDelay} and ever increasing numbers after * each {@code period} of time thereafter * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#timer">RxJava Wiki: timer()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229435.aspx">MSDN: Observable.Timer</a> */ public final static Observable<Long> timer(long initialDelay, long period, TimeUnit unit) { return timer(initialDelay, period, unit, Schedulers.computation()); } /** * Returns an Observable that emits a {@code 0L} after the {@code initialDelay} and ever increasing numbers * after each {@code period} of time thereafter, on a specified {@link Scheduler}. * <p> * <img width="640" height="200" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timer.ps.png"> * * @param initialDelay * the initial delay time to wait before emitting the first value of 0L * @param period * the period of time between emissions of the subsequent numbers * @param unit * the time unit for both {@code initialDelay} and {@code period} * @param scheduler * the Scheduler on which the waiting happens and items are emitted * @return an Observable that emits a 0L after the {@code initialDelay} and ever increasing numbers after * each {@code period} of time thereafter, while running on the given Scheduler * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#timer">RxJava Wiki: timer()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229652.aspx">MSDN: Observable.Timer</a> */ public final static Observable<Long> timer(long initialDelay, long period, TimeUnit unit, Scheduler scheduler) { return create(new OnSubscribeTimerPeriodically(initialDelay, period, unit, scheduler)); } /** * Returns an Observable that emits one item after a specified delay, and then completes. * <p> * <img width="640" height="200" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timer.png"> * <p> * {@code timer} operates by default on the {@code computation} {@link Scheduler}. * * @param delay * the initial delay before emitting a single {@code 0L} * @param unit * time units to use for {@code delay} * @return an Observable that emits one item after a specified delay, and then completes * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#timer">RxJava wiki: timer()</a> */ public final static Observable<Long> timer(long delay, TimeUnit unit) { return timer(delay, unit, Schedulers.computation()); } /** * Returns an Observable that emits one item after a specified delay, on a specified Scheduler, and then * completes. * <p> * <img width="640" height="200" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timer.s.png"> * * @param delay * the initial delay before emitting a single 0L * @param unit * time units to use for {@code delay} * @param scheduler * the {@link Scheduler} to use for scheduling the item * @return an Observable that emits one item after a specified delay, on a specified Scheduler, and then * completes * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#timer">RxJava wiki: timer()</a> */ public final static Observable<Long> timer(long delay, TimeUnit unit, Scheduler scheduler) { return create(new OnSubscribeTimerOnce(delay, unit, scheduler)); } /** * Constructs an Observable that creates a dependent resource object. * <p> * <img width="640" height="400" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/using.png"> * <p> * {@code using} does not operate by default on a particular {@link Scheduler}. * * @param resourceFactory * the factory function to create a resource object that depends on the Observable * @param observableFactory * the factory function to create an Observable * @return the Observable whose lifetime controls the lifetime of the dependent resource object * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#using">RxJava Wiki: using()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229585.aspx">MSDN: Observable.Using</a> */ public final static <T, Resource extends Subscription> Observable<T> using(Func0<Resource> resourceFactory, Func1<Resource, ? extends Observable<? extends T>> observableFactory) { return create(new OnSubscribeUsing<T, Resource>(resourceFactory, observableFactory)); } /** * Returns an Observable that emits the results of a function of your choosing applied to combinations of * items emitted, in sequence, by an Iterable of other Observables. * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by each of the source Observables; * the second item emitted by the new Observable will be the result of the function applied to the second * item emitted by each of those Observables; and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@code onNext} as many times as * the number of {@code onNext} invokations of the source Observable that emits the fewest items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png"> * <p> * {@code zip} does not operate by default on a particular {@link Scheduler}. * * @param ws * an Iterable of source Observables * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results in * an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#zip">RxJava Wiki: zip()</a> */ public final static <R> Observable<R> zip(Iterable<? extends Observable<?>> ws, FuncN<? extends R> zipFunction) { List<Observable<?>> os = new ArrayList<Observable<?>>(); for (Observable<?> o : ws) { os.add(o); } return Observable.just(os.toArray(new Observable<?>[os.size()])).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a function of your choosing applied to combinations of * <i>n</i> items emitted, in sequence, by the <i>n</i> Observables emitted by a specified Observable. * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by each of the Observables emitted * by the source Observable; the second item emitted by the new Observable will be the result of the * function applied to the second item emitted by each of those Observables; and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@code onNext} as many times as * the number of {@code onNext} invokations of the source Observable that emits the fewest items. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.o.png"> * <p> * {@code zip} does not operate by default on a particular {@link Scheduler}. * * @param ws * an Observable of source Observables * @param zipFunction * a function that, when applied to an item emitted by each of the Observables emitted by * {@code ws}, results in an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#zip">RxJava Wiki: zip()</a> */ public final static <R> Observable<R> zip(Observable<? extends Observable<?>> ws, final FuncN<? extends R> zipFunction) { return ws.toList().map(new Func1<List<? extends Observable<?>>, Observable<?>[]>() { @Override public Observable<?>[] call(List<? extends Observable<?>> o) { return o.toArray(new Observable<?>[o.size()]); } }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a function of your choosing applied to combinations of * two items emitted, in sequence, by two other Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png"> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by {@code o1} and the first item * emitted by {@code o2}; the second item emitted by the new Observable will be the result of the function * applied to the second item emitted by {@code o1} and the second item emitted by {@code o2}; and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the source Observable that emits the fewest * items. * <p> * {@code zip} does not operate by default on a particular {@link Scheduler}. * * @param o1 * the first source Observable * @param o2 * a second source Observable * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results * in an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#zip">RxJava Wiki: zip()</a> */ public final static <T1, T2, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, final Func2<? super T1, ? super T2, ? extends R> zipFunction) { return just(new Observable<?>[] { o1, o2 }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a function of your choosing applied to combinations of * three items emitted, in sequence, by three other Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png"> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by {@code o1}, the first item * emitted by {@code o2}, and the first item emitted by {@code o3}; the second item emitted by the new * Observable will be the result of the function applied to the second item emitted by {@code o1}, the * second item emitted by {@code o2}, and the second item emitted by {@code o3}; and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the source Observable that emits the fewest * items. * <p> * {@code zip} does not operate by default on a particular {@link Scheduler}. * * @param o1 * the first source Observable * @param o2 * a second source Observable * @param o3 * a third source Observable * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results in * an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#zip">RxJava Wiki: zip()</a> */ public final static <T1, T2, T3, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Func3<? super T1, ? super T2, ? super T3, ? extends R> zipFunction) { return just(new Observable<?>[] { o1, o2, o3 }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a function of your choosing applied to combinations of * four items emitted, in sequence, by four other Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png"> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by {@code o1}, the first item * emitted by {@code o2}, the first item emitted by {@code o3}, and the first item emitted by {@code 04}; * the second item emitted by the new Observable will be the result of the function applied to the second * item emitted by each of those Observables; and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the source Observable that emits the fewest * items. * <p> * {@code zip} does not operate by default on a particular {@link Scheduler}. * * @param o1 * the first source Observable * @param o2 * a second source Observable * @param o3 * a third source Observable * @param o4 * a fourth source Observable * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results in * an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#zip">RxJava Wiki: zip()</a> */ public final static <T1, T2, T3, T4, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Func4<? super T1, ? super T2, ? super T3, ? super T4, ? extends R> zipFunction) { return just(new Observable<?>[] { o1, o2, o3, o4 }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a function of your choosing applied to combinations of * five items emitted, in sequence, by five other Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png"> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by {@code o1}, the first item * emitted by {@code o2}, the first item emitted by {@code o3}, the first item emitted by {@code o4}, and * the first item emitted by {@code o5}; the second item emitted by the new Observable will be the result of * the function applied to the second item emitted by each of those Observables; and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the source Observable that emits the fewest * items. * <p> * {@code zip} does not operate by default on a particular {@link Scheduler}. * * @param o1 * the first source Observable * @param o2 * a second source Observable * @param o3 * a third source Observable * @param o4 * a fourth source Observable * @param o5 * a fifth source Observable * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results in * an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#zip">RxJava Wiki: zip()</a> */ public final static <T1, T2, T3, T4, T5, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Func5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> zipFunction) { return just(new Observable<?>[] { o1, o2, o3, o4, o5 }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a function of your choosing applied to combinations of * six items emitted, in sequence, by six other Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png"> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by each source Observable, the * second item emitted by the new Observable will be the result of the function applied to the second item * emitted by each of those Observables, and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the source Observable that emits the fewest * items. * <p> * {@code zip} does not operate by default on a particular {@link Scheduler}. * * @param o1 * the first source Observable * @param o2 * a second source Observable * @param o3 * a third source Observable * @param o4 * a fourth source Observable * @param o5 * a fifth source Observable * @param o6 * a sixth source Observable * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results in * an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#zip">RxJava Wiki: zip()</a> */ public final static <T1, T2, T3, T4, T5, T6, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Func6<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? extends R> zipFunction) { return just(new Observable<?>[] { o1, o2, o3, o4, o5, o6 }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a function of your choosing applied to combinations of * seven items emitted, in sequence, by seven other Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png"> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by each source Observable, the * second item emitted by the new Observable will be the result of the function applied to the second item * emitted by each of those Observables, and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the source Observable that emits the fewest * items. * <p> * {@code zip} does not operate by default on a particular {@link Scheduler}. * * @param o1 * the first source Observable * @param o2 * a second source Observable * @param o3 * a third source Observable * @param o4 * a fourth source Observable * @param o5 * a fifth source Observable * @param o6 * a sixth source Observable * @param o7 * a seventh source Observable * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results in * an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#zip">RxJava Wiki: zip()</a> */ public final static <T1, T2, T3, T4, T5, T6, T7, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Func7<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? extends R> zipFunction) { return just(new Observable<?>[] { o1, o2, o3, o4, o5, o6, o7 }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a function of your choosing applied to combinations of * eight items emitted, in sequence, by eight other Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png"> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by each source Observable, the * second item emitted by the new Observable will be the result of the function applied to the second item * emitted by each of those Observables, and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the source Observable that emits the fewest * items. * <p> * {@code zip} does not operate by default on a particular {@link Scheduler}. * * @param o1 * the first source Observable * @param o2 * a second source Observable * @param o3 * a third source Observable * @param o4 * a fourth source Observable * @param o5 * a fifth source Observable * @param o6 * a sixth source Observable * @param o7 * a seventh source Observable * @param o8 * an eighth source Observable * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results in * an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#zip">RxJava Wiki: zip()</a> */ public final static <T1, T2, T3, T4, T5, T6, T7, T8, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Observable<? extends T8> o8, Func8<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? extends R> zipFunction) { return just(new Observable<?>[] { o1, o2, o3, o4, o5, o6, o7, o8 }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a function of your choosing applied to combinations of * nine items emitted, in sequence, by nine other Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png"> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by each source Observable, the * second item emitted by the new Observable will be the result of the function applied to the second item * emitted by each of those Observables, and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the source Observable that emits the fewest * items. * <p> * {@code zip} does not operate by default on a particular {@link Scheduler}. * * @param o1 * the first source Observable * @param o2 * a second source Observable * @param o3 * a third source Observable * @param o4 * a fourth source Observable * @param o5 * a fifth source Observable * @param o6 * a sixth source Observable * @param o7 * a seventh source Observable * @param o8 * an eighth source Observable * @param o9 * a ninth source Observable * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results in * an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#zip">RxJava Wiki: zip()</a> */ public final static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Observable<? extends T8> o8, Observable<? extends T9> o9, Func9<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? super T9, ? extends R> zipFunction) { return just(new Observable<?>[] { o1, o2, o3, o4, o5, o6, o7, o8, o9 }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits a Boolean that indicates whether all of the items emitted by the source * Observable satisfy a condition. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/all.png"> * <p> * {@code all} does not operate by default on a particular {@link Scheduler}. * * @param predicate * a function that evaluates an item and returns a Boolean * @return an Observable that emits {@code true} if all items emitted by the source Observable satisfy the * predicate; otherwise, {@code false} * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#all">RxJava Wiki: all()</a> */ public final Observable<Boolean> all(Func1<? super T, Boolean> predicate) { return lift(new OperatorAll<T>(predicate)); } /** * Mirrors the first Observable (current or provided) that emits an item. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/amb.png"> * <p> * {@code amb} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable competing to react first * @return an Observable that emits the same sequence of items as whichever of the source Observables first * emitted an item * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#amb">RxJava Wiki: amb()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229733.aspx">MSDN: Observable.Amb</a> * @since 0.20 */ public final Observable<T> ambWith(Observable<? extends T> t1) { return amb(this, t1); } /** * Disguises a object of an Observable subclass as a simple Observable object. Useful for instance when you * have an implementation of a subclass of Observable but you want to hide the properties and methods of * this subclass from whomever you are passing the Observable to. * <p> * {@code asObservable} does not operate by default on a particular {@link Scheduler}. * * @return an Observable that hides the identity of this Observable */ public final Observable<T> asObservable() { return lift(new OperatorAsObservable<T>()); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping buffers. It emits the current buffer and replaces it with a * new buffer whenever the Observable produced by the specified {@code bufferClosingSelector} emits an item. * <p> * <img width="640" height="395" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer1.png"> * <p> * This version of {@code buffer} does not operate by default on a particular {@link Scheduler}. * * @param bufferClosingSelector * a {@link Func0} that produces an Observable that governs the boundary between buffers. * Whenever this {@code Observable} emits an item, {@code buffer} emits the current buffer and * begins to fill a new one * @return an Observable that emits a connected, non-overlapping buffer of items from the source Observable * each time the Observable created with the {@code bufferClosingSelector} argument emits an item * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#buffer">RxJava Wiki: buffer()</a> */ public final <TClosing> Observable<List<T>> buffer(Func0<? extends Observable<? extends TClosing>> bufferClosingSelector) { return lift(new OperatorBufferWithSingleObservable<T, TClosing>(bufferClosingSelector, 16)); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping buffers, each containing {@code count} items. When the source * Observable completes or encounters an error, the resulting Observable emits the current buffer and * propagates the notification from the source Observable. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer3.png"> * <p> * This version of {@code buffer} does not operate by default on a particular {@link Scheduler}. * * @param count * the maximum number of items in each buffer before it should be emitted * @return an Observable that emits connected, non-overlapping buffers, each containing at most * {@code count} items from the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#buffer">RxJava Wiki: buffer()</a> */ public final Observable<List<T>> buffer(int count) { return lift(new OperatorBufferWithSize<T>(count, count)); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * Observable emits buffers every {@code skip} items, each containing {@code count} items. When the source * Observable completes or encounters an error, the resulting Observable emits the current buffer and * propagates the notification from the source Observable. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer4.png"> * <p> * This version of {@code buffer} does not operate by default on a particular {@link Scheduler}. * * @param count * the maximum size of each buffer before it should be emitted * @param skip * how many items emitted by the source Observable should be skipped before starting a new * buffer. Note that when {@code skip} and {@code count} are equal, this is the same operation as * {@link #buffer(int)}. * @return an Observable that emits buffers for every {@code skip} item from the source Observable and * containing at most {@code count} items * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#buffer">RxJava Wiki: buffer()</a> */ public final Observable<List<T>> buffer(int count, int skip) { return lift(new OperatorBufferWithSize<T>(count, skip)); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * Observable starts a new buffer periodically, as determined by the {@code timeshift} argument. It emits * each buffer after a fixed timespan, specified by the {@code timespan} argument. When the source * Observable completes or encounters an error, the resulting Observable emits the current buffer and * propagates the notification from the source Observable. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer7.png"> * <p> * This version of {@code buffer} operates by default on the {@code computation} {@link Scheduler}. * * @param timespan * the period of time each buffer collects items before it is emitted * @param timeshift * the period of time after which a new buffer will be created * @param unit * the unit of time that applies to the {@code timespan} and {@code timeshift} arguments * @return an Observable that emits new buffers of items emitted by the source Observable periodically after * a fixed timespan has elapsed * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#buffer">RxJava Wiki: buffer()</a> */ public final Observable<List<T>> buffer(long timespan, long timeshift, TimeUnit unit) { return lift(new OperatorBufferWithTime<T>(timespan, timeshift, unit, Integer.MAX_VALUE, Schedulers.computation())); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * Observable starts a new buffer periodically, as determined by the {@code timeshift} argument, and on the * specified {@code scheduler}. It emits each buffer after a fixed timespan, specified by the * {@code timespan} argument. When the source Observable completes or encounters an error, the resulting * Observable emits the current buffer and propagates the notification from the source Observable. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer7.s.png"> * * @param timespan * the period of time each buffer collects items before it is emitted * @param timeshift * the period of time after which a new buffer will be created * @param unit * the unit of time that applies to the {@code timespan} and {@code timeshift} arguments * @param scheduler * the {@link Scheduler} to use when determining the end and start of a buffer * @return an Observable that emits new buffers of items emitted by the source Observable periodically after * a fixed timespan has elapsed * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#buffer">RxJava Wiki: buffer()</a> */ public final Observable<List<T>> buffer(long timespan, long timeshift, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorBufferWithTime<T>(timespan, timeshift, unit, Integer.MAX_VALUE, scheduler)); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping buffers, each of a fixed duration specified by the * {@code timespan} argument. When the source Observable completes or encounters an error, the resulting * Observable emits the current buffer and propagates the notification from the source Observable. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer5.png"> * <p> * This version of {@code buffer} operates by default on the {@code computation} {@link Scheduler}. * * @param timespan * the period of time each buffer collects items before it is emitted and replaced with a new * buffer * @param unit * the unit of time that applies to the {@code timespan} argument * @return an Observable that emits connected, non-overlapping buffers of items emitted by the source * Observable within a fixed duration * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#buffer">RxJava Wiki: buffer()</a> */ public final Observable<List<T>> buffer(long timespan, TimeUnit unit) { return lift(new OperatorBufferWithTime<T>(timespan, timespan, unit, Integer.MAX_VALUE, Schedulers.computation())); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping buffers, each of a fixed duration specified by the * {@code timespan} argument or a maximum size specified by the {@code count} argument (whichever is reached * first). When the source Observable completes or encounters an error, the resulting Observable emits the * current buffer and propagates the notification from the source Observable. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer6.png"> * <p> * This version of {@code buffer} operates by default on the {@code computation} {@link Scheduler}. * * @param timespan * the period of time each buffer collects items before it is emitted and replaced with a new * buffer * @param unit * the unit of time which applies to the {@code timespan} argument * @param count * the maximum size of each buffer before it is emitted * @return an Observable that emits connected, non-overlapping buffers of items emitted by the source * Observable, after a fixed duration or when the buffer reaches maximum capacity (whichever occurs * first) * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#buffer">RxJava Wiki: buffer()</a> */ public final Observable<List<T>> buffer(long timespan, TimeUnit unit, int count) { return lift(new OperatorBufferWithTime<T>(timespan, timespan, unit, count, Schedulers.computation())); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping buffers, each of a fixed duration specified by the * {@code timespan} argument as measured on the specified {@code scheduler}, or a maximum size specified by * the {@code count} argument (whichever is reached first). When the source Observable completes or * encounters an error, the resulting Observable emits the current buffer and propagates the notification * from the source Observable. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer6.s.png"> * * @param timespan * the period of time each buffer collects items before it is emitted and replaced with a new * buffer * @param unit * the unit of time which applies to the {@code timespan} argument * @param count * the maximum size of each buffer before it is emitted * @param scheduler * the {@link Scheduler} to use when determining the end and start of a buffer * @return an Observable that emits connected, non-overlapping buffers of items emitted by the source * Observable after a fixed duration or when the buffer reaches maximum capacity (whichever occurs * first) * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#buffer">RxJava Wiki: buffer()</a> */ public final Observable<List<T>> buffer(long timespan, TimeUnit unit, int count, Scheduler scheduler) { return lift(new OperatorBufferWithTime<T>(timespan, timespan, unit, count, scheduler)); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping buffers, each of a fixed duration specified by the * {@code timespan} argument and on the specified {@code scheduler}. When the source Observable completes or * encounters an error, the resulting Observable emits the current buffer and propagates the notification * from the source Observable. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer5.s.png"> * * @param timespan * the period of time each buffer collects items before it is emitted and replaced with a new * buffer * @param unit * the unit of time which applies to the {@code timespan} argument * @param scheduler * the {@link Scheduler} to use when determining the end and start of a buffer * @return an Observable that emits connected, non-overlapping buffers of items emitted by the source * Observable within a fixed duration * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#buffer">RxJava Wiki: buffer()</a> */ public final Observable<List<T>> buffer(long timespan, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorBufferWithTime<T>(timespan, timespan, unit, Integer.MAX_VALUE, scheduler)); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * Observable emits buffers that it creates when the specified {@code bufferOpenings} Observable emits an * item, and closes when the Observable returned from {@code bufferClosingSelector} emits an item. * <p> * <img width="640" height="470" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer2.png"> * <p> * This version of {@code buffer} does not operate by default on a particular {@link Scheduler}. * * @param bufferOpenings * the Observable that, when it emits an item, causes a new buffer to be created * @param bufferClosingSelector * the {@link Func1} that is used to produce an Observable for every buffer created. When this * Observable emits an item, the associated buffer is emitted. * @return an Observable that emits buffers, containing items from the source Observable, that are created * and closed when the specified Observables emit items * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#buffer">RxJava Wiki: buffer()</a> */ public final <TOpening, TClosing> Observable<List<T>> buffer(Observable<? extends TOpening> bufferOpenings, Func1<? super TOpening, ? extends Observable<? extends TClosing>> bufferClosingSelector) { return lift(new OperatorBufferWithStartEndObservable<T, TOpening, TClosing>(bufferOpenings, bufferClosingSelector)); } /** * Returns an Observable that emits non-overlapping buffered items from the source Observable each time the * specified boundary Observable emits an item. * <p> * <img width="640" height="395" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer8.png"> * <p> * Completion of either the source or the boundary Observable causes the returned Observable to emit the * latest buffer and complete. * <p> * This version of {@code buffer} does not operate by default on a particular {@link Scheduler}. * * @param <B> * the boundary value type (ignored) * @param boundary * the boundary Observable * @return an Observable that emits buffered items from the source Observable when the boundary Observable * emits an item * @see #buffer(rx.Observable, int) * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#buffer">RxJava Wiki: buffer()</a> */ public final <B> Observable<List<T>> buffer(Observable<B> boundary) { return lift(new OperatorBufferWithSingleObservable<T, B>(boundary, 16)); } /** * Returns an Observable that emits non-overlapping buffered items from the source Observable each time the * specified boundary Observable emits an item. * <p> * <img width="640" height="395" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/buffer8.png"> * <p> * Completion of either the source or the boundary Observable causes the returned Observable to emit the * latest buffer and complete. * <p> * This version of {@code buffer} does not operate by default on a particular {@link Scheduler}. * * @param <B> * the boundary value type (ignored) * @param boundary * the boundary Observable * @param initialCapacity * the initial capacity of each buffer chunk * @return an Observable that emits buffered items from the source Observable when the boundary Observable * emits an item * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#buffer">RxJava Wiki: buffer()</a> * @see #buffer(rx.Observable, int) */ public final <B> Observable<List<T>> buffer(Observable<B> boundary, int initialCapacity) { return lift(new OperatorBufferWithSingleObservable<T, B>(boundary, initialCapacity)); } /** * Caches the emissions from the source Observable and replays them in order to any subsequent Subscribers. * This method has similar behavior to {@link #replay} except that this auto-subscribes to the source * Observable rather than returning a {@link ConnectableObservable} for which you must call * {@code connect} to activate the subscription. * <p> * <img width="640" height="410" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/cache.png"> * <p> * This is useful when you want an Observable to cache responses and you can't control the * subscribe/unsubscribe behavior of all the {@link Subscriber}s. * <p> * When you call {@code cache}, it does not yet subscribe to the source Observable and so does not yet * begin cacheing items. This only happens when the first Subscriber calls the resulting Observable's * {@code subscribe} method. * <p> * * <!-- IS THE FOLLOWING NOTE STILL VALID??? --> * * <em>Note:</em> You sacrifice the ability to unsubscribe from the origin when you use the {@code cache} * Observer so be careful not to use this Observer on Observables that emit an infinite or very large number * of items that will use up memory. * <p> * {@code cache} does not operate by default on a particular {@link Scheduler}. * * @warn description may be out-of-date * @return an Observable that, when first subscribed to, caches all of its items and notifications for the * benefit of subsequent subscribers * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#cache">RxJava Wiki: cache()</a> */ public final Observable<T> cache() { return create(new OnSubscribeCache<T>(this)); } /** * Returns an Observable that emits the items emitted by the source Observable, converted to the specified * type. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/cast.png"> * <p> * {@code cast} does not operate by default on a particular {@link Scheduler}. * * @param klass * the target class type that {@code cast} will cast the items emitted by the source Observable * into before emitting them from the resulting Observable * @return an Observable that emits each item from the source Observable after converting it to the * specified type * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#cast">RxJava Wiki: cast()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211842.aspx">MSDN: Observable.Cast</a> */ public final <R> Observable<R> cast(final Class<R> klass) { return lift(new OperatorCast<T, R>(klass)); } /** * Collects items emitted by the source Observable into a single mutable data structure and returns an * Observable that emits this structure. * <p> * <img width="640" height="330" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/collect.png"> * <p> * This is a simplified version of {@code reduce} that does not need to return the state on each pass. * <p> * {@code collect} does not operate by default on a particular {@link Scheduler}. * * @param state * the mutable data structure that will collect the items * @param collector * a function that accepts the {@code state} and an emitted item, and modifies {@code state} * accordingly * @return an Observable that emits the result of collecting the values emitted by the source Observable * into a single mutable data structure */ public final <R> Observable<R> collect(R state, final Action2<R, ? super T> collector) { Func2<R, T, R> accumulator = new Func2<R, T, R>() { @Override public final R call(R state, T value) { collector.call(state, value); return state; } }; return reduce(state, accumulator); } /** * Returns a new Observable that emits items resulting from applying a function that you supply to each item * emitted by the source Observable, where that function returns an Observable, and then emitting the items * that result from concatinating those resulting Observables. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concatMap.png"> * <p> * {@code concatMap} does not operate by default on a particular {@link Scheduler}. * * @param func * a function that, when applied to an item emitted by the source Observable, returns an * Observable * @return an Observable that emits the result of applying the transformation function to each item emitted * by the source Observable and concatinating the Observables obtained from this transformation */ public final <R> Observable<R> concatMap(Func1<? super T, ? extends Observable<? extends R>> func) { return concat(map(func)); } /** * Returns an Observable that emits the items emitted from the current Observable, then the next, one after * the other, without interleaving them. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/concat.png"> * <p> * {@code concat} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be concatenated after the current * @return an Observable that emits items emitted by the two source Observables, one after the other, * without interleaving them * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#concat">RxJava Wiki: concat()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat.aspx">MSDN: Observable.Concat</a> * @since 0.20 */ public final Observable<T> concatWith(Observable<? extends T> t1) { return concat(this, t1); } /** * Returns an Observable that emits a Boolean that indicates whether the source Observable emitted a * specified item. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/contains.png"> * <p> * {@code contains} does not operate by default on a particular {@link Scheduler}. * * @param element * the item to search for in the emissions from the source Observable * @return an Observable that emits {@code true} if the specified item is emitted by the source Observable, * or {@code false} if the source Observable completes without emitting that item * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#contains">RxJava Wiki: contains()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh228965.aspx">MSDN: Observable.Contains</a> */ public final Observable<Boolean> contains(final Object element) { return exists(new Func1<T, Boolean>() { public final Boolean call(T t1) { return element == null ? t1 == null : element.equals(t1); } }); } /** * Returns an Observable that emits the count of the total number of items emitted by the source Observable. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/count.png"> * <p> * {@code count} does not operate by default on a particular {@link Scheduler}. * * @return an Observable that emits a single item: the number of elements emitted by the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#count-and-longcount">RxJava Wiki: count()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229470.aspx">MSDN: Observable.Count</a> * @see #longCount() */ public final Observable<Integer> count() { return reduce(0, new Func2<Integer, T, Integer>() { @Override public final Integer call(Integer t1, T t2) { return t1 + 1; } }); } /** * Returns an Observable that mirrors the source Observable, except that it drops items emitted by the * source Observable that are followed by another item within a computed debounce duration. * <p> * <img width="640" height="425" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/debounce.f.png"> * <p> * This version of {@code debounce} does not operate by default on a particular {@link Scheduler}. * * @param <U> * the debounce value type (ignored) * @param debounceSelector * function to retrieve a sequence that indicates the throttle duration for each item * @return an Observable that omits items emitted by the source Observable that are followed by another item * within a computed debounce duration */ public final <U> Observable<T> debounce(Func1<? super T, ? extends Observable<U>> debounceSelector) { return lift(new OperatorDebounceWithSelector<T, U>(debounceSelector)); } /** * Returns an Observable that mirrors the source Observable, except that it drops items emitted by the * source Observable that are followed by newer items before a timeout value expires. The timer resets on * each emission. * <p> * <em>Note:</em> If items keep being emitted by the source Observable faster than the timeout then no items * will be emitted by the resulting Observable. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/debounce.png"> * <p> * Information on debounce vs throttle: * <p> * <ul> * <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li> * <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li> * <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li> * </ul> * <p> * This version of {@code debounce} operates by default on the {@code computation} {@link Scheduler}. * * @param timeout * the time each item has to be "the most recent" of those emitted by the source Observable to * ensure that it's not dropped * @param unit * the {@link TimeUnit} for the timeout * @return an Observable that filters out items from the source Observable that are too quickly followed by * newer items * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#throttlewithtimeout-or-debounce">RxJava Wiki: debounce()</a> * @see #throttleWithTimeout(long, TimeUnit) */ public final Observable<T> debounce(long timeout, TimeUnit unit) { return lift(new OperatorDebounceWithTime<T>(timeout, unit, Schedulers.computation())); } /** * Returns an Observable that mirrors the source Observable, except that it drops items emitted by the * source Observable that are followed by newer items before a timeout value expires on a specified * Scheduler. The timer resets on each emission. * <p> * <em>Note:</em> If items keep being emitted by the source Observable faster than the timeout then no items * will be emitted by the resulting Observable. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/debounce.s.png"> * <p> * Information on debounce vs throttle: * <p> * <ul> * <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li> * <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li> * <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li> * </ul> * * @param timeout * the time each item has to be "the most recent" of those emitted by the source Observable to * ensure that it's not dropped * @param unit * the unit of time for the specified timeout * @param scheduler * the {@link Scheduler} to use internally to manage the timers that handle the timeout for each * item * @return an Observable that filters out items from the source Observable that are too quickly followed by * newer items * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#throttlewithtimeout-or-debounce">RxJava Wiki: debounce()</a> * @see #throttleWithTimeout(long, TimeUnit, Scheduler) */ public final Observable<T> debounce(long timeout, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorDebounceWithTime<T>(timeout, unit, scheduler)); } /** * Returns an Observable that emits the items emitted by the source Observable or a specified default item * if the source Observable is empty. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/defaultIfEmpty.png"> * <p> * {@code defaultIfEmpty} does not operate by default on a particular {@link Scheduler}. * * @param defaultValue * the item to emit if the source Observable emits no items * @return an Observable that emits either the specified default item if the source Observable emits no * items, or the items emitted by the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#defaultifempty">RxJava Wiki: defaultIfEmpty()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229624.aspx">MSDN: Observable.DefaultIfEmpty</a> */ public final Observable<T> defaultIfEmpty(T defaultValue) { return lift(new OperatorDefaultIfEmpty<T>(defaultValue)); } /** * Returns an Observable that delays the subscription to and emissions from the souce Observable via another * Observable on a per-item basis. * <p> * <img width="640" height="450" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delay.oo.png"> * <p> * <em>Note:</em> the resulting Observable will immediately propagate any {@code onError} notification * from the source Observable. * <p> * This version of {@code delay} does not operate by default on a particular {@link Scheduler}. * * @param <U> * the subscription delay value type (ignored) * @param <V> * the item delay value type (ignored) * @param subscriptionDelay * a function that returns an Observable that triggers the subscription to the source Observable * once it emits any item * @param itemDelay * a function that returns an Observable for each item emitted by the source Observable, which is * then used to delay the emission of that item by the resulting Observable until the Observable * returned from {@code itemDelay} emits an item * @return an Observable that delays the subscription and emissions of the source Observable via another * Observable on a per-item basis */ public final <U, V> Observable<T> delay( Func0<? extends Observable<U>> subscriptionDelay, Func1<? super T, ? extends Observable<V>> itemDelay) { return create(new OnSubscribeDelayWithSelector<T, U, V>(this, subscriptionDelay, itemDelay)); } /** * Returns an Observable that delays the emissions of the source Observable via another Observable on a * per-item basis. * <p> * <img width="640" height="450" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delay.o.png"> * <p> * <em>Note:</em> the resulting Observable will immediately propagate any {@code onError} notification * from the source Observable. * <p> * This version of {@code delay} does not operate by default on a particular {@link Scheduler}. * * @param <U> * the item delay value type (ignored) * @param itemDelay * a function that returns an Observable for each item emitted by the source Observable, which is * then used to delay the emission of that item by the resulting Observable until the Observable * returned from {@code itemDelay} emits an item * @return an Observable that delays the emissions of the source Observable via another Observable on a * per-item basis */ public final <U> Observable<T> delay(Func1<? super T, ? extends Observable<U>> itemDelay) { return create(new OnSubscribeDelayWithSelector<T, U, U>(this, itemDelay)); } /** * Returns an Observable that emits the items emitted by the source Observable shifted forward in time by a * specified delay. Error notifications from the source Observable are not delayed. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delay.png"> * <p> * This version of {@code delay} operates by default on the {@code compuation} {@link Scheduler}. * * @param delay * the delay to shift the source by * @param unit * the {@link TimeUnit} in which {@code period} is defined * @return the source Observable shifted in time by the specified delay * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#delay">RxJava Wiki: delay()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229810.aspx">MSDN: Observable.Delay</a> */ public final Observable<T> delay(long delay, TimeUnit unit) { return create(new OnSubscribeDelay<T>(this, delay, unit, Schedulers.computation())); } /** * Returns an Observable that emits the items emitted by the source Observable shifted forward in time by a * specified delay. Error notifications from the source Observable are not delayed. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delay.s.png"> * * @param delay * the delay to shift the source by * @param unit * the time unit of {@code delay} * @param scheduler * the {@link Scheduler} to use for delaying * @return the source Observable shifted in time by the specified delay * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#delay">RxJava Wiki: delay()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229280.aspx">MSDN: Observable.Delay</a> */ public final Observable<T> delay(long delay, TimeUnit unit, Scheduler scheduler) { return create(new OnSubscribeDelay<T>(this, delay, unit, scheduler)); } /** * Returns an Observable that delays the subscription to the source Observable by a given amount of time. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delaySubscription.png"> * <p> * This version of {@code delay} operates by default on the {@code compuation} {@link Scheduler}. * * @param delay * the time to delay the subscription * @param unit * the time unit of {@code delay} * @return an Observable that delays the subscription to the source Observable by the given amount */ public final Observable<T> delaySubscription(long delay, TimeUnit unit) { return delaySubscription(delay, unit, Schedulers.computation()); } /** * Returns an Observable that delays the subscription to the source Observable by a given amount of time, * both waiting and subscribing on a given Scheduler. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/delaySubscription.s.png"> * * @param delay * the time to delay the subscription * @param unit * the time unit of {@code delay} * @param scheduler * the Scheduler on which the waiting and subscription will happen * @return an Observable that delays the subscription to the source Observable by a given * amount, waiting and subscribing on the given Scheduler */ public final Observable<T> delaySubscription(long delay, TimeUnit unit, Scheduler scheduler) { return create(new OnSubscribeDelaySubscription<T>(this, delay, unit, scheduler)); } /** * Returns an Observable that reverses the effect of {@link #materialize materialize} by transforming the * {@link Notification} objects emitted by the source Observable into the items or notifications they * represent. * <p> * <img width="640" height="335" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/dematerialize.png"> * <p> * {@code dematerialize} does not operate by default on a particular {@link Scheduler}. * * @return an Observable that emits the items and notifications embedded in the {@link Notification} objects * emitted by the source Observable * @throws OnErrorNotImplementedException * if the source Observable is not of type {@code Observable<Notification<T>>} * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#dematerialize">RxJava Wiki: dematerialize()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229047.aspx">MSDN: Observable.dematerialize</a> */ @SuppressWarnings({"unchecked", "rawtypes"}) public final <T2> Observable<T2> dematerialize() { return lift(new OperatorDematerialize()); } /** * Returns an Observable that emits all items emitted by the source Observable that are distinct. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/distinct.png"> * <p> * {@code distinct} does not operate by default on a particular {@link Scheduler}. * * @return an Observable that emits only those items emitted by the source Observable that are distinct from * each other * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#distinct">RxJava Wiki: distinct()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229764.aspx">MSDN: Observable.distinct</a> */ public final Observable<T> distinct() { return lift(new OperatorDistinct<T, T>(Functions.<T>identity())); } /** * Returns an Observable that emits all items emitted by the source Observable that are distinct according * to a key selector function. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/distinct.key.png"> * <p> * {@code distinct} does not operate by default on a particular {@link Scheduler}. * * @param keySelector * a function that projects an emitted item to a key value that is used to decide whether an item * is distinct from another one or not * @return an Observable that emits those items emitted by the source Observable that have distinct keys * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#distinct">RxJava Wiki: distinct()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh244310.aspx">MSDN: Observable.distinct</a> */ public final <U> Observable<T> distinct(Func1<? super T, ? extends U> keySelector) { return lift(new OperatorDistinct<T, U>(keySelector)); } /** * Returns an Observable that emits all items emitted by the source Observable that are distinct from their * immediate predecessors. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/distinctUntilChanged.png"> * <p> * {@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}. * * @return an Observable that emits those items from the source Observable that are distinct from their * immediate predecessors * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#distinctuntilchanged">RxJava Wiki: distinctUntilChanged()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229494.aspx">MSDN: Observable.distinctUntilChanged</a> */ public final Observable<T> distinctUntilChanged() { return lift(new OperatorDistinctUntilChanged<T, T>(Functions.<T>identity())); } /** * Returns an Observable that emits all items emitted by the source Observable that are distinct from their * immediate predecessors, according to a key selector function. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/distinctUntilChanged.key.png"> * <p> * {@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}. * * @param keySelector * a function that projects an emitted item to a key value that is used to decide whether an item * is distinct from another one or not * @return an Observable that emits those items from the source Observable whose keys are distinct from * those of their immediate predecessors * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#distinctuntilchanged">RxJava Wiki: distinctUntilChanged()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229508.aspx">MSDN: Observable.distinctUntilChanged</a> */ public final <U> Observable<T> distinctUntilChanged(Func1<? super T, ? extends U> keySelector) { return lift(new OperatorDistinctUntilChanged<T, U>(keySelector)); } /** * Modifies the source Observable so that it invokes an action when it calls {@code onCompleted}. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnCompleted.png"> * <p> * {@code doOnCompleted} does not operate by default on a particular {@link Scheduler}. * * @param onCompleted * the action to invoke when the source Observable calls {@code onCompleted} * @return the source Observable with the side-effecting behavior applied * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#dooncompleted">RxJava Wiki: doOnCompleted()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229804.aspx">MSDN: Observable.Do</a> */ public final Observable<T> doOnCompleted(final Action0 onCompleted) { Observer<T> observer = new Observer<T>() { @Override public final void onCompleted() { onCompleted.call(); } @Override public final void onError(Throwable e) { } @Override public final void onNext(T args) { } }; return lift(new OperatorDoOnEach<T>(observer)); } /** * Modifies the source Observable so that it invokes an action for each item it emits. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnEach.png"> * <p> * {@code doOnEach} does not operate by default on a particular {@link Scheduler}. * * @param onNotification * the action to invoke for each item emitted by the source Observable * @return the source Observable with the side-effecting behavior applied * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#dooneach">RxJava Wiki: doOnEach()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229307.aspx">MSDN: Observable.Do</a> */ public final Observable<T> doOnEach(final Action1<Notification<? super T>> onNotification) { Observer<T> observer = new Observer<T>() { @Override public final void onCompleted() { onNotification.call(Notification.createOnCompleted()); } @Override public final void onError(Throwable e) { onNotification.call(Notification.createOnError(e)); } @Override public final void onNext(T v) { onNotification.call(Notification.createOnNext(v)); } }; return lift(new OperatorDoOnEach<T>(observer)); } /** * Modifies the source Observable so that it notifies an Observer for each item it emits. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnEach.png"> * <p> * {@code doOnEach} does not operate by default on a particular {@link Scheduler}. * * @param observer * the action to invoke for each item emitted by the source Observable * @return the source Observable with the side-effecting behavior applied * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#dooneach">RxJava Wiki: doOnEach()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229307.aspx">MSDN: Observable.Do</a> */ public final Observable<T> doOnEach(Observer<? super T> observer) { return lift(new OperatorDoOnEach<T>(observer)); } /** * Modifies the source Observable so that it invokes an action if it calls {@code onError}. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnError.png"> * <p> * {@code doOnError} does not operate by default on a particular {@link Scheduler}. * * @param onError * the action to invoke if the source Observable calls {@code onError} * @return the source Observable with the side-effecting behavior applied * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#doonerror">RxJava Wiki: doOnError()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229804.aspx">MSDN: Observable.Do</a> */ public final Observable<T> doOnError(final Action1<Throwable> onError) { Observer<T> observer = new Observer<T>() { @Override public final void onCompleted() { } @Override public final void onError(Throwable e) { onError.call(e); } @Override public final void onNext(T args) { } }; return lift(new OperatorDoOnEach<T>(observer)); } /** * Modifies the source Observable so that it invokes an action when it calls {@code onNext}. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnNext.png"> * <p> * {@code doOnNext} does not operate by default on a particular {@link Scheduler}. * * @param onNext * the action to invoke when the source Observable calls {@code onNext} * @return the source Observable with the side-effecting behavior applied * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#dooneach">RxJava Wiki: doOnNext()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229804.aspx">MSDN: Observable.Do</a> */ public final Observable<T> doOnNext(final Action1<? super T> onNext) { Observer<T> observer = new Observer<T>() { @Override public final void onCompleted() { } @Override public final void onError(Throwable e) { } @Override public final void onNext(T args) { onNext.call(args); } }; return lift(new OperatorDoOnEach<T>(observer)); } /** * Modifies the source Observable so that it invokes an action when it calls {@code onCompleted} or * {@code onError}. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnTerminate.png"> * <p> * This differs from {@code finallyDo} in that this happens <em>before</em> the {@code onCompleted} or * {@code onError} notification. * <p> * {@code doOnTerminate} does not operate by default on a particular {@link Scheduler}. * * @param onTerminate * the action to invoke when the source Observable calls {@code onCompleted} or {@code onError} * @return the source Observable with the side-effecting behavior applied * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#doonterminate">RxJava Wiki: doOnTerminate()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229804.aspx">MSDN: Observable.Do</a> * @since 0.17 */ public final Observable<T> doOnTerminate(final Action0 onTerminate) { Observer<T> observer = new Observer<T>() { @Override public final void onCompleted() { onTerminate.call(); } @Override public final void onError(Throwable e) { onTerminate.call(); } @Override public final void onNext(T args) { } }; return lift(new OperatorDoOnEach<T>(observer)); } /** * Returns an Observable that emits the single item at a specified index in a sequence of emissions from a * source Observbable. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/elementAt.png"> * <p> * {@code elementAt} does not operate by default on a particular {@link Scheduler}. * * @param index * the zero-based index of the item to retrieve * @return an Observable that emits a single item: the item at the specified position in the sequence of * those emitted by the source Observable * @throws IndexOutOfBoundsException * if {@code index} is greater than or equal to the number of items emitted by the source * Observable, or * if {@code index} is less than 0 * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#elementat">RxJava Wiki: elementAt()</a> */ public final Observable<T> elementAt(int index) { return lift(new OperatorElementAt<T>(index)); } /** * Returns an Observable that emits the item found at a specified index in a sequence of emissions from a * source Observable, or a default item if that index is out of range. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/elementAtOrDefault.png"> * <p> * {@code elementAtOrDefault} does not operate by default on a particular {@link Scheduler}. * * @param index * the zero-based index of the item to retrieve * @param defaultValue * the default item * @return an Observable that emits the item at the specified position in the sequence emitted by the source * Observable, or the default item if that index is outside the bounds of the source sequence * @throws IndexOutOfBoundsException * if {@code index} is less than 0 * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#elementatordefault">RxJava Wiki: elementAtOrDefault()</a> */ public final Observable<T> elementAtOrDefault(int index, T defaultValue) { return lift(new OperatorElementAt<T>(index, defaultValue)); } /** * Returns an Observable that emits {@code true} if any item emitted by the source Observable satisfies a * specified condition, otherwise {@code false}. <em>Note:</em> this always emits {@code false} if the * source Observable is empty. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/exists.png"> * <p> * In Rx.Net this is the {@code any} Observer but we renamed it in RxJava to better match Java naming * idioms. * <p> * {@code exists} does not operate by default on a particular {@link Scheduler}. * * @param predicate * the condition to test items emitted by the source Observable * @return an Observable that emits a Boolean that indicates whether any item emitted by the source * Observable satisfies the {@code predicate} * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#exists-and-isempty">RxJava Wiki: exists()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211993.aspx">MSDN: Observable.Any (Note: the description in this page was wrong at the time of this writing)</a> */ public final Observable<Boolean> exists(Func1<? super T, Boolean> predicate) { return lift(new OperatorAny<T>(predicate, false)); } /** * Filters items emitted by an Observable by only emitting those that satisfy a specified predicate. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/filter.png"> * <p> * {@code filter} does not operate by default on a particular {@link Scheduler}. * * @param predicate * a function that evaluates each item emitted by the source Observable, returning {@code true} * if it passes the filter * @return an Observable that emits only those items emitted by the source Observable that the filter * evaluates as {@code true} * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#filter-or-where">RxJava Wiki: filter()</a> */ public final Observable<T> filter(Func1<? super T, Boolean> predicate) { return lift(new OperatorFilter<T>(predicate)); } /** * Registers an {@link Action0} to be called when this Observable invokes either * {@link Observer#onCompleted onCompleted} or {@link Observer#onError onError}. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/finallyDo.png"> * <p> * {@code finallyDo} does not operate by default on a particular {@link Scheduler}. * * @param action * an {@link Action0} to be invoked when the source Observable finishes * @return an Observable that emits the same items as the source Observable, then invokes the * {@link Action0} * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#finallydo">RxJava Wiki: finallyDo()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh212133.aspx">MSDN: Observable.Finally</a> */ public final Observable<T> finallyDo(Action0 action) { return lift(new OperatorFinally<T>(action)); } /** * Returns an Observable that emits only the very first item emitted by the source Observable, or notifies * of an {@code NoSuchElementException} if the source Observable is empty. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/first.png"> * <p> * {@code first} does not operate by default on a particular {@link Scheduler}. * * @return an Observable that emits only the very first item emitted by the source Observable, or raises an * {@code NoSuchElementException} if the source Observable is empty * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#first">RxJava Wiki: first()</a> * @see "MSDN: Observable.firstAsync()" */ public final Observable<T> first() { return take(1).single(); } /** * Returns an Observable that emits only the very first item emitted by the source Observable that satisfies * a specified condition, or notifies of an {@code NoSuchElementException} if no such items are emitted. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/firstN.png"> * <p> * {@code first} does not operate by default on a particular {@link Scheduler}. * * @param predicate * the condition that an item emitted by the source Observable has to satisfy * @return an Observable that emits only the very first item emitted by the source Observable that satisfies * the {@code predicate}, or raises an {@code NoSuchElementException} if no such items are emitted * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#first">RxJava Wiki: first()</a> * @see "MSDN: Observable.firstAsync()" */ public final Observable<T> first(Func1<? super T, Boolean> predicate) { return takeFirst(predicate).single(); } /** * Returns an Observable that emits only the very first item emitted by the source Observable, or a default * item if the source Observable completes without emitting anything. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/firstOrDefault.png"> * <p> * {@code firstOrDefault} does not operate by default on a particular {@link Scheduler}. * * @param defaultValue * the default item to emit if the source Observable doesn't emit anything * @return an Observable that emits only the very first item from the source, or a default item if the * source Observable completes without emitting any items * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#firstordefault">RxJava Wiki: firstOrDefault()</a> * @see "MSDN: Observable.firstOrDefaultAsync()" */ public final Observable<T> firstOrDefault(T defaultValue) { return take(1).singleOrDefault(defaultValue); } /** * Returns an Observable that emits only the very first item emitted by the source Observable that satisfies * a specified condition, or a default item if the source Observable emits no such items. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/firstOrDefaultN.png"> * <p> * {@code firstOrDefault} does not operate by default on a particular {@link Scheduler}. * * @param predicate * the condition any item emitted by the source Observable has to satisfy * @param defaultValue * the default item to emit if the source Observable doesn't emit anything that satisfies the * {@code predicate} * @return an Observable that emits only the very first item emitted by the source Observable that satisfies * the {@code predicate}, or a default item if the source Observable emits no such items * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#firstordefault">RxJava Wiki: firstOrDefault()</a> * @see "MSDN: Observable.firstOrDefaultAsync()" */ public final Observable<T> firstOrDefault(T defaultValue, Func1<? super T, Boolean> predicate) { return takeFirst(predicate).singleOrDefault(defaultValue); } /** * Returns an Observable that emits items based on applying a function that you supply to each item emitted * by the source Observable, where that function returns an Observable, and then merging those resulting * Observables and emitting the results of this merger. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/flatMap.png"> * <p> * {@code flatMap} does not operate by default on a particular {@link Scheduler}. * * @param func * a function that, when applied to an item emitted by the source Observable, returns an * Observable * @return an Observable that emits the result of applying the transformation function to each item emitted * by the source Observable and merging the results of the Observables obtained from this * transformation * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#mapmany-or-flatmap-and-mapmanydelayerror">RxJava Wiki: flatMap()</a> */ public final <R> Observable<R> flatMap(Func1<? super T, ? extends Observable<? extends R>> func) { return mergeMap(func); } /** * Subscribes to the {@link Observable} and receives notifications for each element. * <p> * Alias to {@link #subscribe(Action1)} * <p> * {@code forEach} does not operate by default on a particular {@link Scheduler}. * * @param onNext * {@link Action1} to execute for each item. * @throws IllegalArgumentException * if {@code onNext} is null, or * if {@code onError} is null, or * if {@code onComplete} is null * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a> * @since 0.19 */ public final void forEach(final Action1<? super T> onNext) { subscribe(onNext); } /** * Subscribes to the {@link Observable} and receives notifications for each element and error events. * <p> * Alias to {@link #subscribe(Action1, Action1)} * <p> * {@code forEach} does not operate by default on a particular {@link Scheduler}. * * @param onNext * {@link Action1} to execute for each item. * @param onError * {@link Action1} to execute when an error is emitted. * @throws IllegalArgumentException * if {@code onNext} is null, or * if {@code onError} is null, or * if {@code onComplete} is null * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a> * @since 0.19 */ public final void forEach(final Action1<? super T> onNext, final Action1<Throwable> onError) { subscribe(onNext, onError); } /** * Subscribes to the {@link Observable} and receives notifications for each element and the terminal events. * <p> * Alias to {@link #subscribe(Action1, Action1, Action0)} * <p> * {@code forEach} does not operate by default on a particular {@link Scheduler}. * * @param onNext * {@link Action1} to execute for each item. * @param onError * {@link Action1} to execute when an error is emitted. * @param onComplete * {@link Action0} to execute when completion is signalled. * @throws IllegalArgumentException * if {@code onNext} is null, or * if {@code onError} is null, or * if {@code onComplete} is null * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a> * @since 0.19 */ public final void forEach(final Action1<? super T> onNext, final Action1<Throwable> onError, final Action0 onComplete) { subscribe(onNext, onError, onComplete); } /** * Groups the items emitted by an {@code Observable} according to a specified criterion, and emits these * grouped items as {@link GroupedObservable}s, one {@code GroupedObservable} per group. * <p> * <img width="640" height="360" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/groupBy.png"> * <p> * <em>Note:</em> A {@link GroupedObservable} will cache the items it is to emit until such time as it * is subscribed to. For this reason, in order to avoid memory leaks, you should not simply ignore those * {@code GroupedObservable}s that do not concern you. Instead, you can signal to them that they may * discard their buffers by applying an operator like {@link #take}{@code (0)} to them. * <p> * {@code groupBy} does not operate by default on a particular {@link Scheduler}. * * @param keySelector * a function that extracts the key for each item * @param <K> * the key type * @return an {@code Observable} that emits {@link GroupedObservable}s, each of which corresponds to a * unique key value and each of which emits those items from the source Observable that share that * key value * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#groupby-and-groupbyuntil">RxJava Wiki: groupBy</a> */ public final <K> Observable<GroupedObservable<K, T>> groupBy(final Func1<? super T, ? extends K> keySelector) { return lift(new OperatorGroupBy<K, T>(keySelector)); } /** * Groups the items emitted by an {@code Observable} according to a specified key selector function until * the duration {@code Observable} expires for the key. * <p> * <img width="640" height="375" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/groupByUntil.png"> * <p> * <em>Note:</em> A {@link GroupedObservable} will cache the items it is to emit until such time as it * is subscribed to. For this reason, in order to avoid memory leaks, you should not simply ignore those * {@code GroupedObservable}s that do not concern you. Instead, you can signal to them that they may * discard their buffers by applying an operator like {@link #take}{@code (0)} to them. * <p> * {@code groupByUntil} does not operate by default on a particular {@link Scheduler}. * * @param keySelector * a function to extract the key for each item * @param durationSelector * a function to signal the expiration of a group * @return an {@code Observable} that emits {@link GroupedObservable}s, each of which corresponds to a key * value and each of which emits all items emitted by the source {@code Observable} during that * key's duration that share that same key value * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#groupby-and-groupbyuntil">RxJava Wiki: groupByUntil()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211932.aspx">MSDN: Observable.GroupByUntil</a> */ public final <TKey, TDuration> Observable<GroupedObservable<TKey, T>> groupByUntil(Func1<? super T, ? extends TKey> keySelector, Func1<? super GroupedObservable<TKey, T>, ? extends Observable<? extends TDuration>> durationSelector) { return groupByUntil(keySelector, Functions.<T> identity(), durationSelector); } /** * Groups the items emitted by an {@code Observable} (transformed by a selector) according to a specified * key selector function until the duration Observable expires for the key. * <p> * <img width="640" height="375" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/groupByUntil.png"> * <p> * <em>Note:</em> A {@link GroupedObservable} will cache the items it is to emit until such time as it * is subscribed to. For this reason, in order to avoid memory leaks, you should not simply ignore those * {@code GroupedObservable}s that do not concern you. Instead, you can signal to them that they may * discard their buffers by applying an operator like {@link #take}{@code (0)} to them. * <p> * {@code groupByUntil} does not operate by default on a particular {@link Scheduler}. * * @param keySelector * a function to extract the key for each item * @param valueSelector * a function to map each item emitted by the source {@code Observable} to an item emitted by one * of the resulting {@link GroupedObservable}s * @param durationSelector * a function to signal the expiration of a group * @return an {@code Observable} that emits {@link GroupedObservable}s, each of which corresponds to a key * value and each of which emits all items emitted by the source {@code Observable} during that * key's duration that share that same key value, transformed by the value selector * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#groupby-and-groupbyuntil">RxJava Wiki: groupByUntil()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229433.aspx">MSDN: Observable.GroupByUntil</a> */ public final <TKey, TValue, TDuration> Observable<GroupedObservable<TKey, TValue>> groupByUntil(Func1<? super T, ? extends TKey> keySelector, Func1<? super T, ? extends TValue> valueSelector, Func1<? super GroupedObservable<TKey, TValue>, ? extends Observable<? extends TDuration>> durationSelector) { return lift(new OperatorGroupByUntil<T, TKey, TValue, TDuration>(keySelector, valueSelector, durationSelector)); } /** * Returns an Observable that correlates two Observables when they overlap in time and groups the results. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/groupJoin.png"> * <p> * {@code groupJoin} does not operate by default on a particular {@link Scheduler}. * * @param right * the other Observable to correlate items from the source Observable with * @param leftDuration * a function that returns an Observable whose emissions indicate the duration of the values of * the source Observable * @param rightDuration * a function that returns an Observable whose emissions indicate the duration of the values of * the {@code right} Observable * @param resultSelector * a function that takes an item emitted by each Observable and returns the value to be emitted * by the resulting Observable * @return an Observable that emits items based on combining those items emitted by the source Observables * whose durations overlap * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#join-and-groupjoin">RxJava Wiiki: groupJoin</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh244235.aspx">MSDN: Observable.GroupJoin</a> */ public final <T2, D1, D2, R> Observable<R> groupJoin(Observable<T2> right, Func1<? super T, ? extends Observable<D1>> leftDuration, Func1<? super T2, ? extends Observable<D2>> rightDuration, Func2<? super T, ? super Observable<T2>, ? extends R> resultSelector) { return create(new OnSubscribeGroupJoin<T, T2, D1, D2, R>(this, right, leftDuration, rightDuration, resultSelector)); } /** * Ignores all items emitted by the source Observable and only calls {@code onCompleted} or {@code onError}. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/ignoreElements.png"> * <p> * {@code ignoreElements} does not operate by default on a particular {@link Scheduler}. * * @return an empty Observable that only calls {@code onCompleted} or {@code onError}, based on which one is * called by the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#ignoreelements">RxJava Wiki: ignoreElements()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229242.aspx">MSDN: Observable.IgnoreElements</a> */ public final Observable<T> ignoreElements() { return filter(alwaysFalse()); } /** * Returns an Observable that emits {@code true} if the source Observable is empty, otherwise {@code false}. * <p> * In Rx.Net this is negated as the {@code any} Observer but we renamed this in RxJava to better match Java * naming idioms. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/isEmpty.png"> * <p> * {@code isEmpty} does not operate by default on a particular {@link Scheduler}. * * @return an Observable that emits a Boolean * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#exists-and-isempty">RxJava Wiki: isEmpty()</a> * @see <a href= "http://msdn.microsoft.com/en-us/library/hh229905.aspx">MSDN: Observable.Any</a> */ public final Observable<Boolean> isEmpty() { return lift(new OperatorAny<T>(Functions.alwaysTrue(), true)); } /** * Correlates the items emitted by two Observables based on overlapping durations. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/join_.png"> * <p> * {@code join} does not operate by default on a particular {@link Scheduler}. * * @param right * the second Observable to join items from * @param leftDurationSelector * a function to select a duration for each item emitted by the source Observable, used to * determine overlap * @param rightDurationSelector * a function to select a duration for each item emitted by the {@code right} Observable, used to * determine overlap * @param resultSelector * a function that computes an item to be emitted by the resulting Observable for any two * overlapping items emitted by the two Observables * @return an Observable that emits items correlating to items emitted by the source Observables that have * overlapping durations * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#join">RxJava Wiki: join()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229750.aspx">MSDN: Observable.Join</a> */ public final <TRight, TLeftDuration, TRightDuration, R> Observable<R> join(Observable<TRight> right, Func1<T, Observable<TLeftDuration>> leftDurationSelector, Func1<TRight, Observable<TRightDuration>> rightDurationSelector, Func2<T, TRight, R> resultSelector) { return create(new OnSubscribeJoin<T, TRight, TLeftDuration, TRightDuration, R>(this, right, leftDurationSelector, rightDurationSelector, resultSelector)); } /** * Returns an Observable that emits the last item emitted by the source Observable or notifies observers of * a {@code NoSuchElementException} if the source Observable is empty. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/last.png"> * <p> * {@code last} does not operate by default on a particular {@link Scheduler}. * * @return an Observable that emits the last item from the source Observable or notifies observers of an * error * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observable-Operators#last">RxJava Wiki: last()</a> * @see "MSDN: Observable.lastAsync()" */ public final Observable<T> last() { return takeLast(1).single(); } /** * Returns an Observable that emits only the last item emitted by the source Observable that satisfies a * given condition, or notifies of a {@code NoSuchElementException} if no such items are emitted. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/last.p.png"> * <p> * {@code last} does not operate by default on a particular {@link Scheduler}. * * @param predicate * the condition any source emitted item has to satisfy * @return an Observable that emits only the last item satisfying the given condition from the source, or an * {@code NoSuchElementException} if no such items are emitted * @throws IllegalArgumentException * if no items that match the predicate are emitted by the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observable-Operators#last">RxJava Wiki: last()</a> * @see "MSDN: Observable.lastAsync()" */ public final Observable<T> last(Func1<? super T, Boolean> predicate) { return filter(predicate).takeLast(1).single(); } /** * Returns an Observable that emits only the last item emitted by the source Observable, or a default item * if the source Observable completes without emitting any items. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/lastOrDefault.png"> * <p> * {@code lastOrDefault} does not operate by default on a particular {@link Scheduler}. * * @param defaultValue * the default item to emit if the source Observable is empty * @return an Observable that emits only the last item emitted by the source Observable, or a default item * if the source Observable is empty * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#lastOrDefault">RxJava Wiki: lastOrDefault()</a> * @see "MSDN: Observable.lastOrDefaultAsync()" */ public final Observable<T> lastOrDefault(T defaultValue) { return takeLast(1).singleOrDefault(defaultValue); } /** * Returns an Observable that emits only the last item emitted by the source Observable that satisfies a * specified condition, or a default item if no such item is emitted by the source Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/lastOrDefault.p.png"> * <p> * {@code lastOrDefault} does not operate by default on a particular {@link Scheduler}. * * @param defaultValue * the default item to emit if the source Observable doesn't emit anything that satisfies the * specified {@code predicate} * @param predicate * the condition any item emitted by the source Observable has to satisfy * @return an Observable that emits only the last item emitted by the source Observable that satisfies the * given condition, or a default item if no such item is emitted by the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#lastOrDefault">RxJava Wiki: lastOrDefault()</a> * @see "MSDN: Observable.lastOrDefaultAsync()" */ public final Observable<T> lastOrDefault(T defaultValue, Func1<? super T, Boolean> predicate) { return filter(predicate).takeLast(1).singleOrDefault(defaultValue); } /** * Returns an Observable that emits only the first {@code num} items emitted by the source Observable. * <p> * Alias of {@link #take(int)} to match Java 8 Stream API naming convention. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/take.png"> * <p> * This method returns an Observable that will invoke a subscribing {@link Observer}'s * {@link Observer#onNext onNext} function a maximum of {@code num} times before invoking * {@link Observer#onCompleted onCompleted}. * <p> * {@code limit} does not operate by default on a particular {@link Scheduler}. * * @param num * the maximum number of items to emit * @return an Observable that emits only the first {@code num} items emitted by the source Observable, or * all of the items from the source Observable if that Observable emits fewer than {@code num} items * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#take">RxJava Wiki: take()</a> * @since 0.19 */ public final Observable<T> limit(int num) { return take(num); } /** * Returns an Observable that counts the total number of items emitted by the source Observable and emits * this count as a 64-bit Long. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/longCount.png"> * <p> * {@code longCount} does not operate by default on a particular {@link Scheduler}. * * @return an Observable that emits a single item: the number of items emitted by the source Observable as a * 64-bit Long item * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#count-and-longcount">RxJava Wiki: count()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229120.aspx">MSDN: Observable.LongCount</a> * @see #count() */ public final Observable<Long> longCount() { return reduce(0L, new Func2<Long, T, Long>() { @Override public final Long call(Long t1, T t2) { return t1 + 1; } }); } /** * Returns an Observable that applies a specified function to each item emitted by the source Observable and * emits the results of these function applications. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/map.png"> * <p> * {@code map} does not operate by default on a particular {@link Scheduler}. * * @param func * a function to apply to each item emitted by the Observable * @return an Observable that emits the items from the source Observable, transformed by the specified * function * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#map">RxJava Wiki: map()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh244306.aspx">MSDN: Observable.Select</a> */ public final <R> Observable<R> map(Func1<? super T, ? extends R> func) { return lift(new OperatorMap<T, R>(func)); } /** * Returns an Observable that represents all of the emissions <em>and</em> notifications from the source * Observable into emissions marked with their original types within {@link Notification} objects. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/materialize.png"> * <p> * {@code materialize} does not operate by default on a particular {@link Scheduler}. * * @return an Observable that emits items that are the result of materializing the items and notifications * of the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#materialize">RxJava Wiki: materialize()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229453.aspx">MSDN: Observable.materialize</a> */ public final Observable<Notification<T>> materialize() { return lift(new OperatorMaterialize<T>()); } /** * Returns an Observable that emits the results of applying a specified function to each item emitted by the * source Observable, where that function returns an Observable, and then merging those resulting * Observables and emitting the results of this merger. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeMap.png"> * <p> * {@code mergeMap} does not operate by default on a particular {@link Scheduler}. * * @param func * a function that, when applied to an item emitted by the source Observable, returns an * Observable * @return an Observable that emits the result of applying the transformation function to each item emitted * by the source Observable and merging the results of the Observables obtained from these * transformations * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#mapmany-or-flatmap-and-mapmanydelayerror">RxJava Wiki: flatMap()</a> * @see #flatMap(Func1) */ public final <R> Observable<R> mergeMap(Func1<? super T, ? extends Observable<? extends R>> func) { return merge(map(func)); } /** * Returns an Observable that applies a function to each item emitted or notification raised by the source * Observable and then flattens the Observables returned from these functions and emits the resulting items. * <p> * <img width="640" height="410" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeMap.nce.png"> * <p> * {@code mergeMap} does not operate by default on a particular {@link Scheduler}. * * @param <R> * the result type * @param onNext * a function that returns an Observable to merge for each item emitted by the source Observable * @param onError * a function that returns an Observable to merge for an onError notification from the source * Observable * @param onCompleted * a function that returns an Observable to merge for an onCompleted notification from the source * Observable * @return an Observable that emits the results of merging the Observables returned from applying the * specified functions to the emissions and notifications of the source Observable */ public final <R> Observable<R> mergeMap( Func1<? super T, ? extends Observable<? extends R>> onNext, Func1<? super Throwable, ? extends Observable<? extends R>> onError, Func0<? extends Observable<? extends R>> onCompleted) { return lift(new OperatorMergeMapTransform<T, R>(onNext, onError, onCompleted)); } /** * Returns an Observable that emits the results of a specified function to the pair of values emitted by the * source Observable and a specified collection Observable. * <p> * <img width="640" height="390" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeMap.r.png"> * <p> * {@code mergeMap} does not operate by default on a particular {@link Scheduler}. * * @param <U> * the type of items emitted by the collection Observable * @param <R> * the type of items emitted by the resulting Observable * @param collectionSelector * a function that returns an Observable for each item emitted by the source Observable * @param resultSelector * a function that combines one item emitted by each of the source and collection Observables and * returns an item to be emitted by the resulting Observable * @return an Observable that emits the results of applying a function to a pair of values emitted by the * source Observable and the collection Observable */ public final <U, R> Observable<R> mergeMap(Func1<? super T, ? extends Observable<? extends U>> collectionSelector, Func2<? super T, ? super U, ? extends R> resultSelector) { return lift(new OperatorMergeMapPair<T, U, R>(collectionSelector, resultSelector)); } /** * Returns an Observable that merges each item emitted by the source Observable with the values in an * Iterable corresponding to that item that is generated by a selector. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeMapIterable.png"> * <p> * {@code mergeMapIterable} does not operate by default on a particular {@link Scheduler}. * * @param <R> * the type of item emitted by the resulting Observable * @param collectionSelector * a function that returns an Iterable sequence of values for when given an item emitted by the * source Observable * @return an Observable that emits the results of merging the items emitted by the source Observable with * the values in the Iterables corresponding to those items, as generated by {@code collectionSelector} */ public final <R> Observable<R> mergeMapIterable(Func1<? super T, ? extends Iterable<? extends R>> collectionSelector) { return merge(map(OperatorMergeMapPair.convertSelector(collectionSelector))); } /** * Returns an Observable that emits the results of applying a function to the pair of values from the source * Observable and an Iterable corresponding to that item that is generated by a selector. * <p> * <img width="640" height="390" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/mergeMapIterable.r.png"> * <p> * {@code mergeMapIterable} does not operate by default on a particular {@link Scheduler}. * * @param <U> * the collection element type * @param <R> * the type of item emited by the resulting Observable * @param collectionSelector * a function that returns an Iterable sequence of values for each item emitted by the source * Observable * @param resultSelector * a function that returns an item based on the item emitted by the source Observable and the * Iterable returned for that item by the {@code collectionSelector} * @return an Observable that emits the items returned by {@code resultSelector} for each item in the source * Observable */ public final <U, R> Observable<R> mergeMapIterable(Func1<? super T, ? extends Iterable<? extends U>> collectionSelector, Func2<? super T, ? super U, ? extends R> resultSelector) { return mergeMap(OperatorMergeMapPair.convertSelector(collectionSelector), resultSelector); } /** * Flattens this and another Observable into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/merge.png"> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. * <p> * {@code merge} does not operate by default on a particular {@link Scheduler}. * * @param t1 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#merge">RxJava Wiki: merge()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a> * @since 0.20 */ public final Observable<T> mergeWith(Observable<? extends T> t1) { return merge(this, t1); } /** * Returns an Observable that emits items produced by multicasting the source Observable within a selector * function. * <p> * This is largely a helper function used by RxJava for other forms of multicasting, such as * {@link #publish} and {@link #publishLast}. * <p> * {@code multicast} does not operate by default on a particular {@link Scheduler}. * * @warn javadocs incomplete; description needs improvement * @param subjectFactory * the {@link Subject} factory * @warn javadocs incomplete; "subjectFactory" parameter described poorly * @param selector * the selector function, which can use the multicasted source Observable subject to the policies * enforced by the created {@code Subject} * @warn javadocs incomplete; "selector" parameter described poorly * @return an Observable that emits the items produced by multicasting the source Observable within a * selector function * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablepublish-and-observablemulticast">RxJava: Observable.publish() and Observable.multicast()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229708.aspx">MSDN: Observable.Multicast</a> */ public final <TIntermediate, TResult> Observable<TResult> multicast( final Func0<? extends Subject<? super T, ? extends TIntermediate>> subjectFactory, final Func1<? super Observable<TIntermediate>, ? extends Observable<TResult>> selector) { return create(new OnSubscribeMulticastSelector<T, TIntermediate, TResult>(this, subjectFactory, selector)); } /** * Returns a {@link ConnectableObservable} that upon connection causes the source Observable to push results * into the specified subject. A Connectable Observable resembles an ordinary Observable, except that it * does not begin emitting items when it is subscribed to, but only when its <code>connect()</code> method * is called. * <p> * {@code multicast} does not operate by default on a particular {@link Scheduler}. * * @param subject * the {@link Subject} for the {@link ConnectableObservable} to push source items into * @param <R> * the type of items emitted by the resulting {@code ConnectableObservable} * @return a {@link ConnectableObservable} that upon connection causes the source Observable to push results * into the specified {@link Subject} * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablepublish-and-observablemulticast">RxJava Wiki: Observable.publish() and Observable.multicast()</a> */ public final <R> ConnectableObservable<R> multicast(Subject<? super T, ? extends R> subject) { return new OperatorMulticast<T, R>(this, subject); } /** * Modifies an Observable to perform its emissions and notifications on a specified {@link Scheduler}, * asynchronously with an unbounded buffer. * <p> * <img width="640" height="308" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/observeOn.png"> * * @param scheduler * the {@link Scheduler} to notify {@link Observer}s on * @return the source Observable modified so that its {@link Observer}s are notified on the specified * {@link Scheduler} * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#observeon">RxJava Wiki: observeOn()</a> * @see <a href="http://www.grahamlea.com/2014/07/rxjava-threading-examples/">RxJava Threading Examples</a> * @see #subscribeOn */ public final Observable<T> observeOn(Scheduler scheduler) { return lift(new OperatorObserveOn<T>(scheduler)); } /** * Filters the items emitted by an Observable, only emitting those of the specified type. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/ofClass.png"> * <p> * {@code ofType} does not operate by default on a particular {@link Scheduler}. * * @param klass * the class type to filter the items emitted by the source Observable * @return an Observable that emits items from the source Observable of type {@code klass} * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#oftype">RxJava Wiki: ofType()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229380.aspx">MSDN: Observable.OfType</a> */ public final <R> Observable<R> ofType(final Class<R> klass) { return filter(new Func1<T, Boolean>() { public final Boolean call(T t) { return klass.isInstance(t); } }).cast(klass); } public final Observable<T> onBackpressureBuffer() { return lift(new OperatorOnBackpressureBuffer<T>()); } public final Observable<T> onBackpressureDrop() { return lift(new OperatorOnBackpressureDrop<T>()); } /** * Instructs an Observable to pass control to another Observable rather than invoking * {@link Observer#onError onError} if it encounters an error. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/onErrorResumeNext.png"> * <p> * By default, when an Observable encounters an error that prevents it from emitting the expected item to * its {@link Observer}, the Observable invokes its Observer's {@code onError} method, and then quits * without invoking any more of its Observer's methods. The {@code onErrorResumeNext} method changes this * behavior. If you pass a function that returns an Observable ({@code resumeFunction}) to * {@code onErrorResumeNext}, if the original Observable encounters an error, instead of invoking its * Observer's {@code onError} method, it will instead relinquish control to the Observable returned from * {@code resumeFunction}, which will invoke the Observer's {@link Observer#onNext onNext} method if it is * able to do so. In such a case, because no Observable necessarily invokes {@code onError}, the Observer * may never know that an error happened. * <p> * You can use this to prevent errors from propagating or to supply fallback data should errors be * encountered. * <p> * {@code onErrorResumeNext} does not operate by default on a particular {@link Scheduler}. * * @param resumeFunction * a function that returns an Observable that will take over if the source Observable encounters * an error * @return the original Observable, with appropriately modified behavior * @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#onerrorresumenext">RxJava Wiki: onErrorResumeNext()</a> */ public final Observable<T> onErrorResumeNext(final Func1<Throwable, ? extends Observable<? extends T>> resumeFunction) { return lift(new OperatorOnErrorResumeNextViaFunction<T>(resumeFunction)); } /** * Instructs an Observable to pass control to another Observable rather than invoking * {@link Observer#onError onError} if it encounters an error. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/onErrorResumeNext.png"> * <p> * By default, when an Observable encounters an error that prevents it from emitting the expected item to * its {@link Observer}, the Observable invokes its Observer's {@code onError} method, and then quits * without invoking any more of its Observer's methods. The {@code onErrorResumeNext} method changes this * behavior. If you pass another Observable ({@code resumeSequence}) to an Observable's * {@code onErrorResumeNext} method, if the original Observable encounters an error, instead of invoking its * Observer's {@code onError} method, it will instead relinquish control to {@code resumeSequence} which * will invoke the Observer's {@link Observer#onNext onNext} method if it is able to do so. In such a case, * because no Observable necessarily invokes {@code onError}, the Observer may never know that an error * happened. * <p> * You can use this to prevent errors from propagating or to supply fallback data should errors be * encountered. * <p> * {@code onErrorResumeNext} does not operate by default on a particular {@link Scheduler}. * * @param resumeSequence * a function that returns an Observable that will take over if the source Observable encounters * an error * @return the original Observable, with appropriately modified behavior * @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#onerrorresumenext">RxJava Wiki: onErrorResumeNext()</a> */ public final Observable<T> onErrorResumeNext(final Observable<? extends T> resumeSequence) { return lift(new OperatorOnErrorResumeNextViaObservable<T>(resumeSequence)); } /** * Instructs an Observable to emit an item (returned by a specified function) rather than invoking * {@link Observer#onError onError} if it encounters an error. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/onErrorReturn.png"> * <p> * By default, when an Observable encounters an error that prevents it from emitting the expected item to * its {@link Observer}, the Observable invokes its Observer's {@code onError} method, and then quits * without invoking any more of its Observer's methods. The {@code onErrorReturn} method changes this * behavior. If you pass a function ({@code resumeFunction}) to an Observable's {@code onErrorReturn} * method, if the original Observable encounters an error, instead of invoking its Observer's * {@code onError} method, it will instead emit the return value of {@code resumeFunction}. * <p> * You can use this to prevent errors from propagating or to supply fallback data should errors be * encountered. * <p> * {@code onErrorReturn} does not operate by default on a particular {@link Scheduler}. * * @param resumeFunction * a function that returns an item that the new Observable will emit if the source Observable * encounters an error * @return the original Observable with appropriately modified behavior * @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#onerrorreturn">RxJava Wiki: onErrorReturn()</a> */ public final Observable<T> onErrorReturn(Func1<Throwable, ? extends T> resumeFunction) { return lift(new OperatorOnErrorReturn<T>(resumeFunction)); } /** * Intercepts {@code onError} notifications from the source Observable and replaces them with the * {@code onNext} emissions of an Observable returned by a specified function. This allows the source * sequence to continue even if it issues multiple {@code onError} notifications. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/onErrorFlatMap.png"> * <p> * {@code onErrorFlatMap} does not operate by default on a particular {@link Scheduler}. * * @param resumeFunction * a function that accepts an {@link OnErrorThrowable} representing the Throwable issued by the * source Observable, and returns an Observable that emits items that will be emitted in place * of the error * @return the original Observable, with appropriately modified behavior * @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#onerrorflatmap">RxJava Wiki: onErrorFlatMap()</a> * @since 0.17 */ public final Observable<T> onErrorFlatMap(final Func1<OnErrorThrowable, ? extends Observable<? extends T>> resumeFunction) { return lift(new OperatorOnErrorFlatMap<T>(resumeFunction)); } /** * Instructs an Observable to pass control to another Observable rather than invoking * {@link Observer#onError onError} if it encounters an {@link java.lang.Exception}. * <p> * This differs from {@link #onErrorResumeNext} in that this one does not handle {@link java.lang.Throwable} * or {@link java.lang.Error} but lets those continue through. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/onExceptionResumeNextViaObservable.png"> * <p> * By default, when an Observable encounters an exception that prevents it from emitting the expected item * to its {@link Observer}, the Observable invokes its Observer's {@code onError} method, and then quits * without invoking any more of its Observer's methods. The {@code onExceptionResumeNext} method changes * this behavior. If you pass another Observable ({@code resumeSequence}) to an Observable's * {@code onExceptionResumeNext} method, if the original Observable encounters an exception, instead of * invoking its Observer's {@code onError} method, it will instead relinquish control to * {@code resumeSequence} which will invoke the Observer's {@link Observer#onNext onNext} method if it is * able to do so. In such a case, because no Observable necessarily invokes {@code onError}, the Observer * may never know that an exception happened. * <p> * You can use this to prevent exceptions from propagating or to supply fallback data should exceptions be * encountered. * <p> * {@code onErrorResumeNext} does not operate by default on a particular {@link Scheduler}. * * @param resumeSequence * a function that returns an Observable that will take over if the source Observable encounters * an exception * @return the original Observable, with appropriately modified behavior * @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#onexceptionresumenext">RxJava Wiki: onExceptionResumeNext()</a> */ public final Observable<T> onExceptionResumeNext(final Observable<? extends T> resumeSequence) { return lift(new OperatorOnExceptionResumeNextViaObservable<T>(resumeSequence)); } /** * Performs work on the source Observable in parallel by sharding it on a {@link Schedulers#computation()} * {@link Scheduler}, and returns the resulting Observable. * <p> * <img width="640" height="475" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/parallel.png"> * <p> * {@code parallel} operates by default on the {@code computation} {@link Scheduler}. * * @param f * a {@link Func1} that applies Observable Observers to {@code Observable<T>} in parallel and * returns an {@code Observable<R>} * @return an Observable that emits the results of applying {@code f} to the items emitted by the source * Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#parallel">RxJava Wiki: parallel()</a> */ public final <R> Observable<R> parallel(Func1<Observable<T>, Observable<R>> f) { return lift(new OperatorParallel<T, R>(f, Schedulers.computation())); } /** * Performs work on the source Observable<T> in parallel by sharding it on a {@link Scheduler}, and returns * the resulting Observable. * <p> * <img width="640" height="475" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/parallel.png"> * * @param f * a {@link Func1} that applies Observable Observers to {@code Observable<T>} in parallel and * returns an {@code Observable<R>} * @param s * a {@link Scheduler} to perform the work on * @return an Observable that emits the results of applying {@code f} to the items emitted by the source * Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#parallel">RxJava Wiki: parallel()</a> */ public final <R> Observable<R> parallel(final Func1<Observable<T>, Observable<R>> f, final Scheduler s) { return lift(new OperatorParallel<T, R>(f, s)); } /** * Returns a {@link ConnectableObservable}, which waits until its * {@link ConnectableObservable#connect connect} method is called before it begins emitting items to those * {@link Observer}s that have subscribed to it. * <p> * <img width="640" height="510" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishConnect.png"> * <p> * {@code publish} does not operate by default on a particular {@link Scheduler}. * * @return a {@link ConnectableObservable} that upon connection causes the source Observable to emit items * to its {@link Observer}s * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablepublish-and-observablemulticast">RxJava Wiki: publish()</a> */ public final ConnectableObservable<T> publish() { return new OperatorMulticast<T, T>(this, PublishSubject.<T> create()); } /** * Returns an Observable that emits the results of invoking a specified selector on items emitted by a * {@link ConnectableObservable} that shares a single subscription to the underlying sequence. * <p> * <img width="640" height="510" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishConnect.f.png"> * <p> * {@code publish} does not operate by default on a particular {@link Scheduler}. * * @param <R> * the type of items emitted by the resulting Observable * @param selector * a function that can use the multicasted source sequence as many times as needed, without * causing multiple subscriptions to the source sequence. Subscribers to the given source will * receive all notifications of the source from the time of the subscription forward. * @return an Observable that emits the results of invoking the selector on the items emitted by a {@link ConnectableObservable} that shares a single subscription to the underlying sequence */ public final <R> Observable<R> publish(Func1<? super Observable<T>, ? extends Observable<R>> selector) { return multicast(new Func0<Subject<T, T>>() { @Override public final Subject<T, T> call() { return PublishSubject.create(); } }, selector); } /** * Returns an Observable that emits {@code initialValue} followed by the results of invoking a specified * selector on items emitted by a {@link ConnectableObservable} that shares a single subscription to the * source Observable. * <p> * <img width="640" height="510" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishConnect.if.png"> * <p> * {@code publish} does not operate by default on a particular {@link Scheduler}. * * @param <R> * the type of items emitted by the resulting Observable * @param selector * a function that can use the multicasted source sequence as many times as needed, without * causing multiple subscriptions to the source Observable. Subscribers to the source will * receive all notifications of the source from the time of the subscription forward * @param initialValue * the initial value of the underlying {@link BehaviorSubject} * @return an Observable that emits {@code initialValue} followed by the results of invoking the selector * on a {@link ConnectableObservable} that shares a single subscription to the underlying Observable */ public final <R> Observable<R> publish(Func1<? super Observable<T>, ? extends Observable<R>> selector, final T initialValue) { return multicast(new Func0<Subject<T, T>>() { @Override public final Subject<T, T> call() { return BehaviorSubject.create(initialValue); } }, selector); } /** * Returns a {@link ConnectableObservable} that emits {@code initialValue} followed by the items emitted by * the source Observable. A Connectable Observable resembles an ordinary Observable, except that it does not * begin emitting items when it is subscribed to, but only when its <code>connect()</code> method is called. * <p> * <img width="640" height="510" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishConnect.i.png"> * <p> * {@code publish} does not operate by default on a particular {@link Scheduler}. * * @param initialValue * the initial value to be emitted by the resulting Observable * @return a {@link ConnectableObservable} that shares a single subscription to the underlying Observable * and starts with {@code initialValue} */ public final ConnectableObservable<T> publish(T initialValue) { return new OperatorMulticast<T, T>(this, BehaviorSubject.<T> create(initialValue)); } /** * Returns a {@link ConnectableObservable} that emits only the last item emitted by the source Observable. * A Connectable Observable resembles an ordinary Observable, except that it does not begin emitting items * when it is subscribed to, but only when its <code>connect()</code> method is called. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishLast.png"> * <p> * {@code publishLast} does not operate by default on a particular {@link Scheduler}. * * @return a {@link ConnectableObservable} that emits only the last item emitted by the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablepublishlast">RxJava Wiki: publishLast()</a> */ public final ConnectableObservable<T> publishLast() { return new OperatorMulticast<T, T>(this, AsyncSubject.<T> create()); } /** * Returns an Observable that emits an item that results from invoking a specified selector on the last item * emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishLast.f.png"> * <p> * {@code publishLast} does not operate by default on a particular {@link Scheduler}. * * @param <R> * the type of items emitted by the resulting Observable * @param selector * a function that can use the multicasted source sequence as many times as needed, without * causing multiple subscriptions to the source Observable. Subscribers to the source will only * receive the last item emitted by the source. * @return an Observable that emits an item that is the result of invoking the selector on a {@link ConnectableObservable} that shares a single subscription to the source Observable */ public final <R> Observable<R> publishLast(Func1<? super Observable<T>, ? extends Observable<R>> selector) { return multicast(new Func0<Subject<T, T>>() { @Override public final Subject<T, T> call() { return AsyncSubject.create(); } }, selector); } /** * Returns an Observable that applies a function of your choosing to the first item emitted by a source * Observable, then feeds the result of that function along with the second item emitted by the source * Observable into the same function, and so on until all items have been emitted by the source Observable, * and emits the final result from the final call to your function as its sole item. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/reduce.png"> * <p> * This technique, which is called "reduce" here, is sometimes called "aggregate," "fold," "accumulate," * "compress," or "inject" in other programming contexts. Groovy, for instance, has an {@code inject} method * that does a similar operation on lists. * <p> * {@code reduce} does not operate by default on a particular {@link Scheduler}. * * @param accumulator * an accumulator function to be invoked on each item emitted by the source Observable, whose * result will be used in the next accumulator call * @return an Observable that emits a single item that is the result of accumulating the items emitted by * the source Observable * @throws IllegalArgumentException * if the source Observable emits no items * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#reduce">RxJava Wiki: reduce()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229154.aspx">MSDN: Observable.Aggregate</a> * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> */ public final Observable<T> reduce(Func2<T, T, T> accumulator) { /* * Discussion and confirmation of implementation at * https://github.com/Netflix/RxJava/issues/423#issuecomment-27642532 * * It should use last() not takeLast(1) since it needs to emit an error if the sequence is empty. */ return scan(accumulator).last(); } /** * Returns an Observable that applies a function of your choosing to the first item emitted by a source * Observable and a specified seed value, then feeds the result of that function along with the second item * emitted by an Observable into the same function, and so on until all items have been emitted by the * source Observable, emitting the final result from the final call to your function as its sole item. * <p> * <img width="640" height="325" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/reduceSeed.png"> * <p> * This technique, which is called "reduce" here, is sometimec called "aggregate," "fold," "accumulate," * "compress," or "inject" in other programming contexts. Groovy, for instance, has an {@code inject} method * that does a similar operation on lists. * <p> * {@code reduce} does not operate by default on a particular {@link Scheduler}. * * @param initialValue * the initial (seed) accumulator value * @param accumulator * an accumulator function to be invoked on each item emitted by the source Observable, the * result of which will be used in the next accumulator call * @return an Observable that emits a single item that is the result of accumulating the output from the * items emitted by the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#reduce">RxJava Wiki: reduce()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229154.aspx">MSDN: Observable.Aggregate</a> * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> */ public final <R> Observable<R> reduce(R initialValue, Func2<R, ? super T, R> accumulator) { return scan(initialValue, accumulator).takeLast(1); } /** * Returns an Observable that repeats the sequence of items emitted by the source Observable indefinitely. * <p> * <img width="640" height="309" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/repeat.o.png"> * <p> * {@code repeat} operates by default on the {@code trampoline} {@link Scheduler}. * * @return an Observable that emits the items emitted by the source Observable repeatedly and in sequence * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#repeat">RxJava Wiki: repeat()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229428.aspx">MSDN: Observable.Repeat</a> */ public final Observable<T> repeat() { return nest().lift(new OperatorRepeat<T>()); } /** * Returns an Observable that repeats the sequence of items emitted by the source Observable indefinitely, * on a particular Scheduler. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/repeat.os.png"> * * @param scheduler * the Scheduler to emit the items on * @return an Observable that emits the items emitted by the source Observable repeatedly and in sequence * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#repeat">RxJava Wiki: repeat()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229428.aspx">MSDN: Observable.Repeat</a> */ public final Observable<T> repeat(Scheduler scheduler) { return nest().lift(new OperatorRepeat<T>(scheduler)); } /** * Returns an Observable that repeats the sequence of items emitted by the source Observable at most * {@code count} times. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/repeat.on.png"> * <p> * {@code repeat} operates by default on the {@code trampoline} {@link Scheduler}. * * @param count * the number of times the source Observable items are repeated, a count of 0 will yield an empty * sequence * @return an Observable that repeats the sequence of items emitted by the source Observable at most * {@code count} times * @throws IllegalArgumentException * if {@code count} is less than zero * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#repeat">RxJava Wiki: repeat()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229428.aspx">MSDN: Observable.Repeat</a> * @since 0.17 */ public final Observable<T> repeat(long count) { if (count < 0) { throw new IllegalArgumentException("count >= 0 expected"); } return nest().lift(new OperatorRepeat<T>(count)); } /** * Returns an Observable that repeats the sequence of items emitted by the source Observable at most * {@code count} times, on a particular Scheduler. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/repeat.ons.png"> * * @param count * the number of times the source Observable items are repeated, a count of 0 will yield an empty * sequence * @param scheduler * the {@link Scheduler} to emit the items on * @return an Observable that repeats the sequence of items emitted by the source Observable at most * {@code count} times on a particular Scheduler * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#repeat">RxJava Wiki: repeat()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229428.aspx">MSDN: Observable.Repeat</a> * @since 0.17 */ public final Observable<T> repeat(long count, Scheduler scheduler) { return nest().lift(new OperatorRepeat<T>(count, scheduler)); } /** * Returns a {@link ConnectableObservable} that shares a single subscription to the underlying Observable * that will replay all of its items and notifications to any future {@link Observer}. A Connectable * Observable resembles an ordinary Observable, except that it does not begin emitting items when it is * subscribed to, but only when its <code>connect()</code> method is called. * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.png"> * <p> * This version of {@code replay} does not operate by default on a particular {@link Scheduler}. * * @return a {@link ConnectableObservable} that upon connection causes the source Observable to emit its * items to its {@link Observer}s * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablereplay">RxJava Wiki: replay()</a> */ public final ConnectableObservable<T> replay() { return new OperatorMulticast<T, T>(this, ReplaySubject.<T> create()); } /** * Returns an Observable that emits items that are the results of invoking a specified selector on the items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable. * <p> * <img width="640" height="450" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.f.png"> * <p> * This version of {@code replay} does not operate by default on a particular {@link Scheduler}. * * @param <R> * the type of items emitted by the resulting Observable * @param selector * the selector function, which can use the multicasted sequence as many times as needed, without * causing multiple subscriptions to the Observable * @return an Observable that emits items that are the results of invoking the selector on a * {@link ConnectableObservable} that shares a single subscription to the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablereplay">RxJava Wiki: replay()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229653.aspx">MSDN: Observable.Replay</a> */ public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector) { return create(new OnSubscribeMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() { @Override public final Subject<T, T> call() { return ReplaySubject.create(); } }, selector)); } /** * Returns an Observable that emits items that are the results of invoking a specified selector on items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying {@code bufferSize} notifications. * <p> * <img width="640" height="440" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fn.png"> * <p> * This version of {@code replay} does not operate by default on a particular {@link Scheduler}. * * @param <R> * the type of items emitted by the resulting Observable * @param selector * the selector function, which can use the multicasted sequence as many times as needed, without * causing multiple subscriptions to the Observable * @param bufferSize * the buffer size that limits the number of items the connectable observable can replay * @return an Observable that emits items that are the results of invoking the selector on items emitted by * a {@link ConnectableObservable} that shares a single subscription to the source Observable * replaying no more than {@code bufferSize} items * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablereplay">RxJava Wiki: replay()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211675.aspx">MSDN: Observable.Replay</a> */ public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final int bufferSize) { return create(new OnSubscribeMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() { @Override public final Subject<T, T> call() { return ReplaySubject.<T>createWithSize(bufferSize); } }, selector)); } /** * Returns an Observable that emits items that are the results of invoking a specified selector on items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying no more than {@code bufferSize} items that were emitted within a specified time window. * <p> * <img width="640" height="445" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fnt.png"> * <p> * This version of {@code replay} operates by default on the {@code computation} {@link Scheduler}. * * @param <R> * the type of items emitted by the resulting Observable * @param selector * a selector function, which can use the multicasted sequence as many times as needed, without * causing multiple subscriptions to the Observable * @param bufferSize * the buffer size that limits the number of items the connectable observable can replay * @param time * the duration of the window in which the replayed items must have been emitted * @param unit * the time unit of {@code time} * @return an Observable that emits items that are the results of invoking the selector on items emitted by * a {@link ConnectableObservable} that shares a single subscription to the source Observable, and * replays no more than {@code bufferSize} items that were emitted within the window defined by * {@code time} * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablereplay">RxJava Wiki: replay()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh228952.aspx">MSDN: Observable.Replay</a> */ public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, int bufferSize, long time, TimeUnit unit) { return replay(selector, bufferSize, time, unit, Schedulers.computation()); } /** * Returns an Observable that emits items that are the results of invoking a specified selector on items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying no more than {@code bufferSize} items that were emitted within a specified time window. * <p> * <img width="640" height="445" height="440" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fnts.png"> * * @param <R> * the type of items emitted by the resulting Observable * @param selector * a selector function, which can use the multicasted sequence as many times as needed, without * causing multiple subscriptions to the Observable * @param bufferSize * the buffer size that limits the number of items the connectable observable can replay * @param time * the duration of the window in which the replayed items must have been emitted * @param unit * the time unit of {@code time} * @param scheduler * the Scheduler that is the time source for the window * @return an Observable that emits items that are the results of invoking the selector on items emitted by * a {@link ConnectableObservable} that shares a single subscription to the source Observable, and * replays no more than {@code bufferSize} items that were emitted within the window defined by * {@code time} * @throws IllegalArgumentException * if {@code bufferSize} is less than zero * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablereplay">RxJava Wiki: replay()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229404.aspx">MSDN: Observable.Replay</a> */ public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final int bufferSize, final long time, final TimeUnit unit, final Scheduler scheduler) { if (bufferSize < 0) { throw new IllegalArgumentException("bufferSize < 0"); } return create(new OnSubscribeMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() { @Override public final Subject<T, T> call() { return ReplaySubject.<T>createWithTimeAndSize(time, unit, bufferSize, scheduler); } }, selector)); } /** * Returns an Observable that emits items that are the results of invoking a specified selector on items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying a maximum of {@code bufferSize} items. * <p> * <img width="640" height="440" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fns.png"> * * @param <R> * the type of items emitted by the resulting Observable * @param selector * a selector function, which can use the multicasted sequence as many times as needed, without * causing multiple subscriptions to the Observable * @param bufferSize * the buffer size that limits the number of items the connectable observable can replay * @param scheduler * the Scheduler on which the replay is observed * @return an Observable that emits items that are the results of invoking the selector on items emitted by * a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying no more than {@code bufferSize} notifications * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablereplay">RxJava Wiki: replay()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229928.aspx">MSDN: Observable.Replay</a> */ public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final int bufferSize, final Scheduler scheduler) { return create(new OnSubscribeMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() { @Override public final Subject<T, T> call() { return OperatorReplay.<T> createScheduledSubject(ReplaySubject.<T>createWithSize(bufferSize), scheduler); } }, selector)); } /** * Returns an Observable that emits items that are the results of invoking a specified selector on items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying all items that were emitted within a specified time window. * <p> * <img width="640" height="435" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.ft.png"> * <p> * This version of {@code replay} does operates by default on the {@code computation} {@link Scheduler}. * * @param <R> * the type of items emitted by the resulting Observable * @param selector * a selector function, which can use the multicasted sequence as many times as needed, without * causing multiple subscriptions to the Observable * @param time * the duration of the window in which the replayed items must have been emitted * @param unit * the time unit of {@code time} * @return an Observable that emits items that are the results of invoking the selector on items emitted by * a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying all items that were emitted within the window defined by {@code time} * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablereplay">RxJava Wiki: replay()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229526.aspx">MSDN: Observable.Replay</a> */ public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, long time, TimeUnit unit) { return replay(selector, time, unit, Schedulers.computation()); } /** * Returns an Observable that emits items that are the results of invoking a specified selector on items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying all items that were emitted within a specified time window. * <p> * <img width="640" height="440" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fts.png"> * * @param <R> * the type of items emitted by the resulting Observable * @param selector * a selector function, which can use the multicasted sequence as many times as needed, without * causing multiple subscriptions to the Observable * @param time * the duration of the window in which the replayed items must have been emitted * @param unit * the time unit of {@code time} * @param scheduler * the scheduler that is the time source for the window * @return an Observable that emits items that are the results of invoking the selector on items emitted by * a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying all items that were emitted within the window defined by {@code time} * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablereplay">RxJava Wiki: replay()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh244327.aspx">MSDN: Observable.Replay</a> */ public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final long time, final TimeUnit unit, final Scheduler scheduler) { return create(new OnSubscribeMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() { @Override public final Subject<T, T> call() { return ReplaySubject.<T>createWithTime(time, unit, scheduler); } }, selector)); } /** * Returns an Observable that emits items that are the results of invoking a specified selector on items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable. * <p> * <img width="640" height="445" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.fs.png"> * * @param <R> * the type of items emitted by the resulting Observable * @param selector * a selector function, which can use the multicasted sequence as many times as needed, without * causing multiple subscriptions to the Observable * @param scheduler * the Scheduler where the replay is observed * @return an Observable that emits items that are the results of invoking the selector on items emitted by * a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying all items * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablereplay">RxJava Wiki: replay()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211644.aspx">MSDN: Observable.Replay</a> */ public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final Scheduler scheduler) { return create(new OnSubscribeMulticastSelector<T, T, R>(this, new Func0<Subject<T, T>>() { @Override public final Subject<T, T> call() { return OperatorReplay.createScheduledSubject(ReplaySubject.<T> create(), scheduler); } }, selector)); } /** * Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable that * replays at most {@code bufferSize} items emitted by that Observable. A Connectable Observable resembles * an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only * when its <code>connect()</code> method is called. * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.n.png"> * <p> * This version of {@code replay} does not operate by default on a particular {@link Scheduler}. * * @param bufferSize * the buffer size that limits the number of items that can be replayed * @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays at most {@code bufferSize} items emitted by that Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablereplay">RxJava Wiki: replay()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211976.aspx">MSDN: Observable.Replay</a> */ public final ConnectableObservable<T> replay(int bufferSize) { return new OperatorMulticast<T, T>(this, ReplaySubject.<T>createWithSize(bufferSize)); } /** * Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays at most {@code bufferSize} items that were emitted during a specified time window. A Connectable * Observable resembles an ordinary Observable, except that it does not begin emitting items when it is * subscribed to, but only when its <code>connect()</code> method is called. * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.nt.png"> * <p> * This version of {@code replay} operates by default on the {@code computation} {@link Scheduler}. * * @param bufferSize * the buffer size that limits the number of items that can be replayed * @param time * the duration of the window in which the replayed items must have been emitted * @param unit * the time unit of {@code time} * @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays at most {@code bufferSize} items that were emitted during the window defined by * {@code time} * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablereplay">RxJava Wiki: replay()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229874.aspx">MSDN: Observable.Replay</a> */ public final ConnectableObservable<T> replay(int bufferSize, long time, TimeUnit unit) { return replay(bufferSize, time, unit, Schedulers.computation()); } /** * Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and * that replays a maximum of {@code bufferSize} items that are emitted within a specified time window. A * Connectable Observable resembles an ordinary Observable, except that it does not begin emitting items * when it is subscribed to, but only when its <code>connect()</code> method is called. * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.nts.png"> * * @param bufferSize * the buffer size that limits the number of items that can be replayed * @param time * the duration of the window in which the replayed items must have been emitted * @param unit * the time unit of {@code time} * @param scheduler * the scheduler that is used as a time source for the window * @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays at most {@code bufferSize} items that were emitted during the window defined by * {@code time} * @throws IllegalArgumentException * if {@code bufferSize} is less than zero * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablereplay">RxJava Wiki: replay()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211759.aspx">MSDN: Observable.Replay</a> */ public final ConnectableObservable<T> replay(int bufferSize, long time, TimeUnit unit, Scheduler scheduler) { if (bufferSize < 0) { throw new IllegalArgumentException("bufferSize < 0"); } return new OperatorMulticast<T, T>(this, ReplaySubject.<T>createWithTimeAndSize(time, unit, bufferSize, scheduler)); } /** * Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays at most {@code bufferSize} items emitted by that Observable. A Connectable Observable resembles * an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only * when its <code>connect()</code> method is called. * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.ns.png"> * * @param bufferSize * the buffer size that limits the number of items that can be replayed * @param scheduler * the scheduler on which the Observers will observe the emitted items * @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays at most {@code bufferSize} items that were emitted by the Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablereplay">RxJava Wiki: replay()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229814.aspx">MSDN: Observable.Replay</a> */ public final ConnectableObservable<T> replay(int bufferSize, Scheduler scheduler) { return new OperatorMulticast<T, T>(this, OperatorReplay.createScheduledSubject( ReplaySubject.<T>createWithSize(bufferSize), scheduler)); } /** * Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays all items emitted by that Observable within a specified time window. A Connectable Observable * resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to, * but only when its <code>connect()</code> method is called. * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.t.png"> * <p> * This version of {@code replay} operates by default on the {@code computation} {@link Scheduler}. * * @param time * the duration of the window in which the replayed items must have been emitted * @param unit * the time unit of {@code time} * @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays the items that were emitted during the window defined by {@code time} * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablereplay">RxJava Wiki: replay()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229232.aspx">MSDN: Observable.Replay</a> */ public final ConnectableObservable<T> replay(long time, TimeUnit unit) { return replay(time, unit, Schedulers.computation()); } /** * Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays all items emitted by that Observable within a specified time window. A Connectable Observable * resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to, * but only when its <code>connect()</code> method is called. * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.ts.png"> * * @param time * the duration of the window in which the replayed items must have been emitted * @param unit * the time unit of {@code time} * @param scheduler * the Scheduler that is the time source for the window * @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays the items that were emitted during the window defined by {@code time} * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablereplay">RxJava Wiki: replay()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211811.aspx">MSDN: Observable.Replay</a> */ public final ConnectableObservable<T> replay(long time, TimeUnit unit, Scheduler scheduler) { return new OperatorMulticast<T, T>(this, ReplaySubject.<T>createWithTime(time, unit, scheduler)); } /** * Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable that * will replay all of its items and notifications to any future {@link Observer} on the given * {@link Scheduler}. A Connectable Observable resembles an ordinary Observable, except that it does not * begin emitting items when it is subscribed to, but only when its <code>connect()</code> method is called. * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/replay.s.png"> * * @param scheduler * the Scheduler on which the Observers will observe the emitted items * @return a {@link ConnectableObservable} that shares a single subscription to the source Observable that * will replay all of its items and notifications to any future {@link Observer} on the given * {@link Scheduler} * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#observablereplay">RxJava Wiki: replay()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211699.aspx">MSDN: Observable.Replay</a> */ public final ConnectableObservable<T> replay(Scheduler scheduler) { return new OperatorMulticast<T, T>(this, OperatorReplay.createScheduledSubject(ReplaySubject.<T> create(), scheduler)); } /** * Returns an Observable that mirrors the source Observable, resubscribing to it if it calls {@code onError} * (infinite retry count). * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/retry.png"> * <p> * If the source Observable calls {@link Observer#onError}, this method will resubscribe to the source * Observable rather than propagating the {@code onError} call. * <p> * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even * those emitted during failed subscriptions. For example, if an Observable fails at first but emits * {@code [1, 2]} then succeeds the second time and emits {@code [1, 2, 3, 4, 5]} then the complete sequence * of emissions and notifications would be {@code [1, 2, 1, 2, 3, 4, 5, onCompleted]}. * <p> * {@code retry} operates by default on the {@code trampoline} {@link Scheduler}. * * @return the source Observable modified with retry logic * @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#retry">RxJava Wiki: retry()</a> */ public final Observable<T> retry() { return nest().lift(new OperatorRetry<T>()); } /** * Returns an Observable that mirrors the source Observable, resubscribing to it if it calls {@code onError} * up to a specified number of retries. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/retry.png"> * <p> * If the source Observable calls {@link Observer#onError}, this method will resubscribe to the source * Observable for a maximum of {@code retryCount} resubscriptions rather than propagating the * {@code onError} call. * <p> * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even * those emitted during failed subscriptions. For example, if an Observable fails at first but emits * {@code [1, 2]} then succeeds the second time and emits {@code [1, 2, 3, 4, 5]} then the complete sequence * of emissions and notifications would be {@code [1, 2, 1, 2, 3, 4, 5, onCompleted]}. * * @param retryCount * number of retry attempts before failing * @return the source Observable modified with retry logic * @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#retry">RxJava Wiki: retry()</a> */ public final Observable<T> retry(int retryCount) { return nest().lift(new OperatorRetry<T>(retryCount)); } /** * Returns an Observable that mirrors the source Observable, resubscribing to it if it calls {@code onError} * and the predicate returns true for that specific exception and retry count. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/retry.png"> * <p> * {@code retry} operates by default on the {@code trampoline} {@link Scheduler}. * * @param predicate * the predicate that determines if a resubscription may happen in case of a specific exception * and retry count * @return the source Observable modified with retry logic * @see #retry() * @see <a href="https://github.com/Netflix/RxJava/wiki/Error-Handling-Operators#retry">RxJava Wiki: retry()</a> */ public final Observable<T> retry(Func2<Integer, Throwable, Boolean> predicate) { return nest().lift(new OperatorRetryWithPredicate<T>(predicate)); } /** * Returns an Observable that emits the most recently emitted item (if any) emitted by the source Observable * within periodic time intervals. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/sample.png"> * <p> * {@code sample} operates by default on the {@code computation} {@link Scheduler}. * * @param period * the sampling rate * @param unit * the {@link TimeUnit} in which {@code period} is defined * @return an Observable that emits the results of sampling the items emitted by the source Observable at * the specified time interval * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#sample-or-throttlelast">RxJava Wiki: sample()</a> */ public final Observable<T> sample(long period, TimeUnit unit) { return lift(new OperatorSampleWithTime<T>(period, unit, Schedulers.computation())); } /** * Returns an Observable that emits the most recently emitted item (if any) emitted by the source Observable * within periodic time intervals, where the intervals are defined on a particular Scheduler. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/sample.s.png"> * * @param period * the sampling rate * @param unit * the {@link TimeUnit} in which {@code period} is defined * @param scheduler * the {@link Scheduler} to use when sampling * @return an Observable that emits the results of sampling the items emitted by the source Observable at * the specified time interval * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#sample-or-throttlelast">RxJava Wiki: sample()</a> */ public final Observable<T> sample(long period, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorSampleWithTime<T>(period, unit, scheduler)); } /** * Returns an Observable that, when the specified {@code sampler} Observable emits an item or completes, * emits the most recently emitted item (if any) emitted by the source Observable since the previous * emission from the {@code sampler} Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/sample.o.png"> * <p> * This version of {@code sample} does not operate by default on a particular {@link Scheduler}. * * @param sampler * the Observable to use for sampling the source Observable * @return an Observable that emits the results of sampling the items emitted by this Observable whenever * the {@code sampler} Observable emits an item or completes * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#sample-or-throttlelast">RxJava Wiki: sample()</a> */ public final <U> Observable<T> sample(Observable<U> sampler) { return lift(new OperatorSampleWithObservable<T, U>(sampler)); } /** * Returns an Observable that applies a function of your choosing to the first item emitted by a source * Observable, then feeds the result of that function along with the second item emitted by the source * Observable into the same function, and so on until all items have been emitted by the source Observable, * emitting the result of each of these iterations. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/scan.png"> * <p> * This sort of function is sometimes called an accumulator. * <p> * {@code scan} does not operate by default on a particular {@link Scheduler}. * * @param accumulator * an accumulator function to be invoked on each item emitted by the source Observable, whose * result will be emitted to {@link Observer}s via {@link Observer#onNext onNext} and used in the * next accumulator call * @return an Observable that emits the results of each call to the accumulator function * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#scan">RxJava Wiki: scan()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211665.aspx">MSDN: Observable.Scan</a> */ public final Observable<T> scan(Func2<T, T, T> accumulator) { return lift(new OperatorScan<T, T>(accumulator)); } /** * Returns an Observable that applies a function of your choosing to the first item emitted by a source * Observable and a seed value, then feeds the result of that function along with the second item emitted by * the source Observable into the same function, and so on until all items have been emitted by the source * Observable, emitting the result of each of these iterations. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/scanSeed.png"> * <p> * This sort of function is sometimes called an accumulator. * <p> * Note that the Observable that results from this method will emit {@code initialValue} as its first * emitted item. * <p> * {@code scan} does not operate by default on a particular {@link Scheduler}. * * @param initialValue * the initial (seed) accumulator item * @param accumulator * an accumulator function to be invoked on each item emitted by the source Observable, whose * result will be emitted to {@link Observer}s via {@link Observer#onNext onNext} and used in the * next accumulator call * @return an Observable that emits {@code initialValue} followed by the results of each call to the * accumulator function * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#scan">RxJava Wiki: scan()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211665.aspx">MSDN: Observable.Scan</a> */ public final <R> Observable<R> scan(R initialValue, Func2<R, ? super T, R> accumulator) { return lift(new OperatorScan<R, T>(initialValue, accumulator)); } /** * Forces an Observable's emissions and notifications to be serialized and for it to obey the Rx contract * in other ways. * <p> * It is possible for an Observable to invoke its Subscribers' methods asynchronously, perhaps from * different threads. This could make such an Observable poorly-behaved, in that it might try to invoke * {@code onCompleted} or {@code onError} before one of its {@code onNext} invocations, or it might call * {@code onNext} from two different threads concurrently. You can force such an Observable to be * well-behaved and sequential by applying the {@code serialize} method to it. * <p> * <img width="640" height="400" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/synchronize.png"> * <p> * {@code serialize} does not operate by default on a particular {@link Scheduler}. * * @return an {@link Observable} that is guaranteed to be well-behaved and to make only serialized calls to * its observers * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#serialize">RxJava Wiki: serialize()</a> * @since 0.17 */ public final Observable<T> serialize() { return lift(new OperatorSerialize<T>()); } /** * Returns a new {@link Observable} that multicasts (shares) the original {@link Observable}. As long as * there is more than 1 {@link Subscriber} this {@link Observable} will be subscribed and emitting data. * When all subscribers have unsubscribed it will unsubscribe from the source {@link Observable}. * <p> * This is an alias for {@link #publish()}.{@link ConnectableObservable#refCount()}. * <p> * <img width="640" height="510" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/publishRefCount.png"> * <p> * {@code share} does not operate by default on a particular {@link Scheduler}. * * @return a {@link Observable} that upon connection causes the source Observable to emit items * to its {@link Observer}s * @see <a href="https://github.com/Netflix/RxJava/wiki/Connectable-Observable-Operators#connectableobservablerefcount">RxJava Wiki: refCount()</a> * @since 0.19 */ public final Observable<T> share() { return publish().refCount(); } /** * Returns an Observable that emits the single item emitted by the source Observable, if that Observable * emits only a single item. If the source Observable emits more than one item or no items, notify of an * {@code IllegalArgumentException} or {@code NoSuchElementException} respectively. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/single.png"> * <p> * {@code single} does not operate by default on a particular {@link Scheduler}. * * @return an Observable that emits the single item emitted by the source Observable * @throws IllegalArgumentException * if the source emits more than one item * @throws NoSuchElementException * if the source emits no items * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#single-and-singleordefault">RxJava Wiki: single()</a> * @see "MSDN: Observable.singleAsync()" */ public final Observable<T> single() { return lift(new OperatorSingle<T>()); } /** * Returns an Observable that emits the single item emitted by the source Observable that matches a * specified predicate, if that Observable emits one such item. If the source Observable emits more than one * such item or no such items, notify of an {@code IllegalArgumentException} or * {@code NoSuchElementException} respectively. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/single.p.png"> * <p> * {@code single} does not operate by default on a particular {@link Scheduler}. * * @param predicate * a predicate function to evaluate items emitted by the source Observable * @return an Observable that emits the single item emitted by the source Observable that matches the * predicate * @throws IllegalArgumentException * if the source Observable emits more than one item that matches the predicate * @throws NoSuchElementException * if the source Observable emits no item that matches the predicate * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#single-and-singleordefault">RxJava Wiki: single()</a> * @see "MSDN: Observable.singleAsync()" */ public final Observable<T> single(Func1<? super T, Boolean> predicate) { return filter(predicate).single(); } /** * Returns an Observable that emits the single item emitted by the source Observable, if that Observable * emits only a single item, or a default item if the source Observable emits no items. If the source * Observable emits more than one item, throw an {@code IllegalArgumentException}. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/singleOrDefault.png"> * <p> * {@code singleOrDefault} does not operate by default on a particular {@link Scheduler}. * * @param defaultValue * a default value to emit if the source Observable emits no item * @return an Observable that emits the single item emitted by the source Observable, or a default item if * the source Observable is empty * @throws IllegalArgumentException * if the source Observable emits more than one item * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#single-and-singleordefault">RxJava Wiki: single()</a> * @see "MSDN: Observable.singleOrDefaultAsync()" */ public final Observable<T> singleOrDefault(T defaultValue) { return lift(new OperatorSingle<T>(defaultValue)); } /** * Returns an Observable that emits the single item emitted by the source Observable that matches a * predicate, if that Observable emits only one such item, or a default item if the source Observable emits * no such items. If the source Observable emits more than one such item, throw an * {@code IllegalArgumentException}. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/singleOrDefault.p.png"> * <p> * {@code singleOrDefault} does not operate by default on a particular {@link Scheduler}. * * @param defaultValue * a default item to emit if the source Observable emits no matching items * @param predicate * a predicate function to evaluate items emitted by the source Observable * @return an Observable that emits the single item emitted by the source Observable that matches the * predicate, or the default item if no emitted item matches the predicate * @throws IllegalArgumentException * if the source Observable emits more than one item that matches the predicate * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#single-and-singleordefault">RxJava Wiki: single()</a> * @see "MSDN: Observable.singleOrDefaultAsync()" */ public final Observable<T> singleOrDefault(T defaultValue, Func1<? super T, Boolean> predicate) { return filter(predicate).singleOrDefault(defaultValue); } /** * Returns an Observable that skips the first {@code num} items emitted by the source Observable and emits * the remainder. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skip.png"> * <p> * This version of {@code skip} does not operate by default on a particular {@link Scheduler}. * * @param num * the number of items to skip * @return an Observable that is identical to the source Observable except that it does not emit the first * {@code num} items that the source Observable emits * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#skip">RxJava Wiki: skip()</a> */ public final Observable<T> skip(int num) { return lift(new OperatorSkip<T>(num)); } /** * Returns an Observable that skips values emitted by the source Observable before a specified time window * elapses. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skip.t.png"> * <p> * This version of {@code skip} operates by default on the {@code computation} {@link Scheduler}. * * @param time * the length of the time window to skip * @param unit * the time unit of {@code time} * @return an Observable that skips values emitted by the source Observable before the time window defined * by {@code time} elapses and the emits the remainder * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#skip">RxJava Wiki: skip()</a> */ public final Observable<T> skip(long time, TimeUnit unit) { return skip(time, unit, Schedulers.computation()); } /** * Returns an Observable that skips values emitted by the source Observable before a specified time window * on a specified {@link Scheduler} elapses. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skip.ts.png"> * * @param time * the length of the time window to skip * @param unit * the time unit of {@code time} * @param scheduler * the {@link Scheduler} on which the timed wait happens * @return an Observable that skips values emitted by the source Observable before the time window defined * by {@code time} and {@code scheduler} elapses, and then emits the remainder * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#skip">RxJava Wiki: skip()</a> */ public final Observable<T> skip(long time, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorSkipTimed<T>(time, unit, scheduler)); } /** * Returns an Observable that drops a specified number of items from the end of the sequence emitted by the * source Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipLast.png"> * <p> * This Observer accumulates a queue long enough to store the first {@code count} items. As more items are * received, items are taken from the front of the queue and emitted by the returned Observable. This causes * such items to be delayed. * <p> * This version of {@code skipLast} does not operate by default on a particular {@link Scheduler}. * * @param count * number of items to drop from the end of the source sequence * @return an Observable that emits the items emitted by the source Observable except for the dropped ones * at the end * @throws IndexOutOfBoundsException * if {@code count} is less than zero * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#skiplast">RxJava Wiki: skipLast()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211750.aspx">MSDN: Observable.SkipLast</a> */ public final Observable<T> skipLast(int count) { return lift(new OperatorSkipLast<T>(count)); } /** * Returns an Observable that drops items emitted by the source Observable during a specified time window * before the source completes. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipLast.t.png"> * <p> * Note: this action will cache the latest items arriving in the specified time window. * <p> * This version of {@code skipLast} operates by default on the {@code computation} {@link Scheduler}. * * @param time * the length of the time window * @param unit * the time unit of {@code time} * @return an Observable that drops those items emitted by the source Observable in a time window before the * source completes defined by {@code time} * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#skiplast">RxJava Wiki: skipLast()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211750.aspx">MSDN: Observable.SkipLast</a> */ public final Observable<T> skipLast(long time, TimeUnit unit) { return skipLast(time, unit, Schedulers.computation()); } /** * Returns an Observable that drops items emitted by the source Observable during a specified time window * (defined on a specified scheduler) before the source completes. * <p> * <img width="640" height="340" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipLast.ts.png"> * <p> * Note: this action will cache the latest items arriving in the specified time window. * * @param time * the length of the time window * @param unit * the time unit of {@code time} * @param scheduler * the scheduler used as the time source * @return an Observable that drops those items emitted by the source Observable in a time window before the * source completes defined by {@code time} and {@code scheduler} * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#skiplast">RxJava Wiki: skipLast()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211750.aspx">MSDN: Observable.SkipLast</a> */ public final Observable<T> skipLast(long time, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorSkipLastTimed<T>(time, unit, scheduler)); } /** * Returns an Observable that skips items emitted by the source Observable until a second Observable emits * an item. * <p> * <img width="640" height="375" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipUntil.png"> * <p> * {@code skipUntil} does not operate by default on a particular {@link Scheduler}. * * @param other * the second Observable that has to emit an item before the source Observable's elements begin * to be mirrored by the resulting Observable * @return an Observable that skips items from the source Observable until the second Observable emits an * item, then emits the remaining items * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#skipuntil">RxJava Wiki: skipUntil()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229358.aspx">MSDN: Observable.SkipUntil</a> */ public final <U> Observable<T> skipUntil(Observable<U> other) { return lift(new OperatorSkipUntil<T, U>(other)); } /** * Returns an Observable that skips all items emitted by the source Observable as long as a specified * condition holds true, but emits all further source items as soon as the condition becomes false. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipWhile.png"> * <p> * {@code skipWhile} does not operate by default on a particular {@link Scheduler}. * * @param predicate * a function to test each item emitted from the source Observable * @return an Observable that begins emitting items emitted by the source Observable when the specified * predicate becomes false * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#skipwhile-and-skipwhilewithindex">RxJava Wiki: skipWhile()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229685.aspx">MSDN: Observable.SkipWhile</a> */ public final Observable<T> skipWhile(Func1<? super T, Boolean> predicate) { return lift(new OperatorSkipWhile<T>(OperatorSkipWhile.toPredicate2(predicate))); } /** * Returns an Observable that skips all items emitted by the source Observable as long as a specified * condition holds true, but emits all further source items as soon as the condition becomes false. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/skipWhileWithIndex.png"> * <p> * {@code skipWhileWithIndex} does not operate by default on a particular {@link Scheduler}. * * @param predicate * a function to test each item emitted from the source Observable. It takes the emitted item as * the first parameter and the sequential index of the emitted item as a second parameter. * @return an Observable that begins emitting items emitted by the source Observable when the specified * predicate becomes false * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#skipwhile-and-skipwhilewithindex">RxJava Wiki: skipWhileWithIndex()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211631.aspx">MSDN: Observable.SkipWhile</a> */ public final Observable<T> skipWhileWithIndex(Func2<? super T, Integer, Boolean> predicate) { return lift(new OperatorSkipWhile<T>(predicate)); } /** * Returns an Observable that emits the items in a specified {@link Observable} before it begins to emit * items emitted by the source Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.o.png"> * <p> * {@code startWith} does not operate by default on a particular {@link Scheduler}. * * @param values * an Observable that contains the items you want the modified Observable to emit first * @return an Observable that emits the items in the specified {@link Observable} and then emits the items * emitted by the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#startwith">RxJava Wiki: startWith()</a> */ public final Observable<T> startWith(Observable<T> values) { return concat(values, this); } /** * Returns an Observable that emits the items in a specified {@link Iterable} before it begins to emit items * emitted by the source Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png"> * <p> * {@code startWith} does not operate by default on a particular {@link Scheduler}. * * @param values * an Iterable that contains the items you want the modified Observable to emit first * @return an Observable that emits the items in the specified {@link Iterable} and then emits the items * emitted by the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#startwith">RxJava Wiki: startWith()</a> */ public final Observable<T> startWith(Iterable<T> values) { return concat(Observable.<T> from(values), this); } /** * Returns an Observable that emits the items in a specified {@link Iterable}, on a specified * {@link Scheduler}, before it begins to emit items emitted by the source Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.s.png"> * * @param values * an Iterable that contains the items you want the modified Observable to emit first * @param scheduler * the Scheduler to emit the prepended values on * @return an Observable that emits the items in the specified {@link Iterable} and then emits the items * emitted by the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#startwith">RxJava Wiki: startWith()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229372.aspx">MSDN: Observable.StartWith</a> */ public final Observable<T> startWith(Iterable<T> values, Scheduler scheduler) { return concat(from(values, scheduler), this); } /** * Returns an Observable that emits a specified item before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png"> * <p> * {@code startWith} does not operate by default on a particular {@link Scheduler}. * * @param t1 * the item to emit * @return an Observable that emits the specified item before it begins to emit items emitted by the source * Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#startwith">RxJava Wiki: startWith()</a> */ public final Observable<T> startWith(T t1) { return concat(Observable.<T> from(t1), this); } /** * Returns an Observable that emits the specified items before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png"> * <p> * {@code startWith} does not operate by default on a particular {@link Scheduler}. * * @param t1 * the first item to emit * @param t2 * the second item to emit * @return an Observable that emits the specified items before it begins to emit items emitted by the source * Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#startwith">RxJava Wiki: startWith()</a> */ public final Observable<T> startWith(T t1, T t2) { return concat(Observable.<T> from(t1, t2), this); } /** * Returns an Observable that emits the specified items before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png"> * <p> * {@code startWith} does not operate by default on a particular {@link Scheduler}. * * @param t1 * the first item to emit * @param t2 * the second item to emit * @param t3 * the third item to emit * @return an Observable that emits the specified items before it begins to emit items emitted by the source * Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#startwith">RxJava Wiki: startWith()</a> */ public final Observable<T> startWith(T t1, T t2, T t3) { return concat(Observable.<T> from(t1, t2, t3), this); } /** * Returns an Observable that emits the specified items before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png"> * <p> * {@code startWith} does not operate by default on a particular {@link Scheduler}. * * @param t1 * the first item to emit * @param t2 * the second item to emit * @param t3 * the third item to emit * @param t4 * the fourth item to emit * @return an Observable that emits the specified items before it begins to emit items emitted by the source * Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#startwith">RxJava Wiki: startWith()</a> */ public final Observable<T> startWith(T t1, T t2, T t3, T t4) { return concat(Observable.<T> from(t1, t2, t3, t4), this); } /** * Returns an Observable that emits the specified items before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png"> * <p> * {@code startWith} does not operate by default on a particular {@link Scheduler}. * * @param t1 * the first item to emit * @param t2 * the second item to emit * @param t3 * the third item to emit * @param t4 * the fourth item to emit * @param t5 * the fifth item to emit * @return an Observable that emits the specified items before it begins to emit items emitted by the source * Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#startwith">RxJava Wiki: startWith()</a> */ public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5) { return concat(Observable.<T> from(t1, t2, t3, t4, t5), this); } /** * Returns an Observable that emits the specified items before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png"> * <p> * {@code startWith} does not operate by default on a particular {@link Scheduler}. * * @param t1 * the first item to emit * @param t2 * the second item to emit * @param t3 * the third item to emit * @param t4 * the fourth item to emit * @param t5 * the fifth item to emit * @param t6 * the sixth item to emit * @return an Observable that emits the specified items before it begins to emit items emitted * by the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#startwith">RxJava Wiki: startWith()</a> */ public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5, T t6) { return concat(Observable.<T> from(t1, t2, t3, t4, t5, t6), this); } /** * Returns an Observable that emits the specified items before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png"> * <p> * {@code startWith} does not operate by default on a particular {@link Scheduler}. * * @param t1 * the first item to emit * @param t2 * the second item to emit * @param t3 * the third item to emit * @param t4 * the fourth item to emit * @param t5 * the fifth item to emit * @param t6 * the sixth item to emit * @param t7 * the seventh item to emit * @return an Observable that emits the specified items before it begins to emit items emitted by the source * Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#startwith">RxJava Wiki: startWith()</a> */ public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5, T t6, T t7) { return concat(Observable.<T> from(t1, t2, t3, t4, t5, t6, t7), this); } /** * Returns an Observable that emits the specified items before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png"> * <p> * {@code startWith} does not operate by default on a particular {@link Scheduler}. * * @param t1 * the first item to emit * @param t2 * the second item to emit * @param t3 * the third item to emit * @param t4 * the fourth item to emit * @param t5 * the fifth item to emit * @param t6 * the sixth item to emit * @param t7 * the seventh item to emit * @param t8 * the eighth item to emit * @return an Observable that emits the specified items before it begins to emit items emitted by the source * Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#startwith">RxJava Wiki: startWith()</a> */ public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8) { return concat(Observable.<T> from(t1, t2, t3, t4, t5, t6, t7, t8), this); } /** * Returns an Observable that emits the specified items before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.png"> * <p> * {@code startWith} does not operate by default on a particular {@link Scheduler}. * * @param t1 * the first item to emit * @param t2 * the second item to emit * @param t3 * the third item to emit * @param t4 * the fourth item to emit * @param t5 * the fifth item to emit * @param t6 * the sixth item to emit * @param t7 * the seventh item to emit * @param t8 * the eighth item to emit * @param t9 * the ninth item to emit * @return an Observable that emits the specified items before it begins to emit items emitted by the source * Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#startwith">RxJava Wiki: startWith()</a> */ public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8, T t9) { return concat(Observable.<T> from(t1, t2, t3, t4, t5, t6, t7, t8, t9), this); } /** * Returns an Observable that emits the items from a specified array, on a specified Scheduler, before it * begins to emit items emitted by the source Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/startWith.s.png"> * * @param values * the items you want the modified Observable to emit first * @param scheduler * the Scheduler to emit the prepended values on * @return an Observable that emits the items from {@code values}, on {@code scheduler}, before it begins to * emit items emitted by the source Observable. * @see <a href="https://github.com/Netflix/RxJava/wiki/Combining-Observables#startwith">RxJava Wiki: startWith()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229372.aspx">MSDN: Observable.StartWith</a> */ public final Observable<T> startWith(T[] values, Scheduler scheduler) { return startWith(Arrays.asList(values), scheduler); } /** * Subscribes to an Observable but ignore its emissions and notifications. * <p> * {@code subscribe} does not operate by default on a particular {@link Scheduler}. * * @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before * the Observable has finished sending them * @throws OnErrorNotImplementedException * if the Observable tries to call {@code onError} */ public final Subscription subscribe() { return subscribe(new Subscriber<T>() { @Override public final void onCompleted() { // do nothing } @Override public final void onError(Throwable e) { throw new OnErrorNotImplementedException(e); } @Override public final void onNext(T args) { // do nothing } }); } /** * Subscribes to an Observable and provides a callback to handle the items it emits. * <p> * {@code subscribe} does not operate by default on a particular {@link Scheduler}. * * @param onNext * the {@code Action1<T>} you have designed to accept emissions from the Observable * @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before * the Observable has finished sending them * @throws IllegalArgumentException * if {@code onNext} is null * @throws OnErrorNotImplementedException * if the Observable tries to call {@code onError} * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a> */ public final Subscription subscribe(final Action1<? super T> onNext) { if (onNext == null) { throw new IllegalArgumentException("onNext can not be null"); } return subscribe(new Subscriber<T>() { @Override public final void onCompleted() { // do nothing } @Override public final void onError(Throwable e) { throw new OnErrorNotImplementedException(e); } @Override public final void onNext(T args) { onNext.call(args); } }); } /** * Subscribes to an Observable and provides callbacks to handle the items it emits and any error * notification it issues. * <p> * {@code subscribe} does not operate by default on a particular {@link Scheduler}. * * @param onNext * the {@code Action1<T>} you have designed to accept emissions from the Observable * @param onError * the {@code Action1<Throwable>} you have designed to accept any error notification from the * Observable * @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before * the Observable has finished sending them * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a> * @throws IllegalArgumentException * if {@code onNext} is null, or * if {@code onError} is null */ public final Subscription subscribe(final Action1<? super T> onNext, final Action1<Throwable> onError) { if (onNext == null) { throw new IllegalArgumentException("onNext can not be null"); } if (onError == null) { throw new IllegalArgumentException("onError can not be null"); } return subscribe(new Subscriber<T>() { @Override public final void onCompleted() { // do nothing } @Override public final void onError(Throwable e) { onError.call(e); } @Override public final void onNext(T args) { onNext.call(args); } }); } /** * Subscribes to an Observable and provides callbacks to handle the items it emits and any error or * completion notification it issues. * <p> * {@code subscribe} does not operate by default on a particular {@link Scheduler}. * * @param onNext * the {@code Action1<T>} you have designed to accept emissions from the Observable * @param onError * the {@code Action1<Throwable>} you have designed to accept any error notification from the * Observable * @param onComplete * the {@code Action0} you have designed to accept a completion notification from the * Observable * @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before * the Observable has finished sending them * @throws IllegalArgumentException * if {@code onNext} is null, or * if {@code onError} is null, or * if {@code onComplete} is null * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a> */ public final Subscription subscribe(final Action1<? super T> onNext, final Action1<Throwable> onError, final Action0 onComplete) { if (onNext == null) { throw new IllegalArgumentException("onNext can not be null"); } if (onError == null) { throw new IllegalArgumentException("onError can not be null"); } if (onComplete == null) { throw new IllegalArgumentException("onComplete can not be null"); } return subscribe(new Subscriber<T>() { @Override public final void onCompleted() { onComplete.call(); } @Override public final void onError(Throwable e) { onError.call(e); } @Override public final void onNext(T args) { onNext.call(args); } }); } /** * Subscribes to an Observable and provides an Observer that implements functions to handle the items the * Observable emits and any error or completion notification it issues. * <p> * {@code subscribe} does not operate by default on a particular {@link Scheduler}. * * @param observer * the Observer that will handle emissions and notifications from the Observable * @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before * the Observable has completed * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable#onnext-oncompleted-and-onerror">RxJava Wiki: onNext, onCompleted, and onError</a> */ public final Subscription subscribe(final Observer<? super T> observer) { return subscribe(new Subscriber<T>() { @Override public void onCompleted() { observer.onCompleted(); } @Override public void onError(Throwable e) { observer.onError(e); } @Override public void onNext(T t) { observer.onNext(t); } }); } /** * Subscribes to an Observable and invokes {@link OnSubscribe} function without any contract protection, * error handling, unsubscribe, or execution hooks. * <p> * Use this only for implementing an {@link Operator} that requires nested subscriptions. For other * purposes, use {@link #subscribe(Subscriber)} which ensures the Rx contract and other functionality. * <p> * {@code unsafeSubscribe} does not operate by default on a particular {@link Scheduler}. * * @param subscriber * the Subscriber that will handle emissions and notifications from the Observable * @return a {@link Subscription} reference with which the {@link Subscriber} can stop receiving items * before the Observable has completed * @since 0.17 */ public final Subscription unsafeSubscribe(Subscriber<? super T> subscriber) { try { // new Subscriber so onStart it subscriber.onStart(); // allow the hook to intercept and/or decorate hook.onSubscribeStart(this, onSubscribe).call(subscriber); return hook.onSubscribeReturn(subscriber); } catch (Throwable e) { // special handling for certain Throwable/Error/Exception types Exceptions.throwIfFatal(e); // if an unhandled error occurs executing the onSubscribe we will propagate it try { subscriber.onError(hook.onSubscribeError(e)); } catch (OnErrorNotImplementedException e2) { // special handling when onError is not implemented ... we just rethrow throw e2; } catch (Throwable e2) { // if this happens it means the onError itself failed (perhaps an invalid function implementation) // so we are unable to propagate the error correctly and will just throw RuntimeException r = new RuntimeException("Error occurred attempting to subscribe [" + e.getMessage() + "] and then again while trying to pass to onError.", e2); // TODO could the hook be the cause of the error in the on error handling. hook.onSubscribeError(r); // TODO why aren't we throwing the hook's return value. throw r; } return Subscriptions.empty(); } } /** * Subscribes to an Observable and provides a Subscriber that implements functions to handle the items the * Observable emits and any error or completion notification it issues. * <p> * A typical implementation of {@code subscribe} does the following: * <ol> * <li>It stores a reference to the Subscriber in a collection object, such as a {@code List<T>} object.</li> * <li>It returns a reference to the {@link Subscription} interface. This enables Subscribers to * unsubscribe, that is, to stop receiving items and notifications before the Observable completes, which * also invokes the Subscriber's {@link Subscriber#onCompleted onCompleted} method.</li> * </ol><p> * An {@code Observable<T>} instance is responsible for accepting all subscriptions and notifying all * Subscribers. Unless the documentation for a particular {@code Observable<T>} implementation indicates * otherwise, Subscriber should make no assumptions about the order in which multiple Subscribers will * receive their notifications. * <p> * For more information see the * <a href="https://github.com/Netflix/RxJava/wiki/Observable">RxJava Wiki</a> * <p> * {@code subscribe} does not operate by default on a particular {@link Scheduler}. * * @param subscriber * the {@link Subscriber} that will handle emissions and notifications from the Observable * @return a {@link Subscription} reference with which Subscribers that are {@link Observer}s can * unsubscribe from the Observable * @throws IllegalStateException * if {@code subscribe} is unable to obtain an {@code OnSubscribe<>} function * @throws IllegalArgumentException * if the {@link Subscriber} provided as the argument to {@code subscribe} is {@code null} * @throws OnErrorNotImplementedException * if the {@link Subscriber}'s {@code onError} method is null * @throws RuntimeException * if the {@link Subscriber}'s {@code onError} method itself threw a {@code Throwable} */ public final Subscription subscribe(Subscriber<? super T> subscriber) { // validate and proceed if (subscriber == null) { throw new IllegalArgumentException("observer can not be null"); } if (onSubscribe == null) { throw new IllegalStateException("onSubscribe function can not be null."); /* * the subscribe function can also be overridden but generally that's not the appropriate approach * so I won't mention that in the exception */ } // new Subscriber so onStart it subscriber.onStart(); /* * See https://github.com/Netflix/RxJava/issues/216 for discussion on "Guideline 6.4: Protect calls * to user code from within an Observer" */ // if not already wrapped if (!(subscriber instanceof SafeSubscriber)) { // assign to `observer` so we return the protected version subscriber = new SafeSubscriber<T>(subscriber); } // The code below is exactly the same an unsafeSubscribe but not used because it would add a sigificent depth to alreay huge call stacks. try { // allow the hook to intercept and/or decorate hook.onSubscribeStart(this, onSubscribe).call(subscriber); return hook.onSubscribeReturn(subscriber); } catch (Throwable e) { // special handling for certain Throwable/Error/Exception types Exceptions.throwIfFatal(e); // if an unhandled error occurs executing the onSubscribe we will propagate it try { subscriber.onError(hook.onSubscribeError(e)); } catch (OnErrorNotImplementedException e2) { // special handling when onError is not implemented ... we just rethrow throw e2; } catch (Throwable e2) { // if this happens it means the onError itself failed (perhaps an invalid function implementation) // so we are unable to propagate the error correctly and will just throw RuntimeException r = new RuntimeException("Error occurred attempting to subscribe [" + e.getMessage() + "] and then again while trying to pass to onError.", e2); // TODO could the hook be the cause of the error in the on error handling. hook.onSubscribeError(r); // TODO why aren't we throwing the hook's return value. throw r; } return Subscriptions.empty(); } } /** * Asynchronously subscribes Observers to this Observable on the specified {@link Scheduler}. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/subscribeOn.png"> * * @param scheduler * the {@link Scheduler} to perform subscription actions on * @return the source Observable modified so that its subscriptions happen on the * specified {@link Scheduler} * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#subscribeon">RxJava Wiki: subscribeOn()</a> * @see <a href="http://www.grahamlea.com/2014/07/rxjava-threading-examples/">RxJava Threading Examples</a> * @see #observeOn */ public final Observable<T> subscribeOn(Scheduler scheduler) { return nest().lift(new OperatorSubscribeOn<T>(scheduler)); } /** * Returns a new Observable by applying a function that you supply to each item emitted by the source * Observable that returns an Observable, and then emitting the items emitted by the most recently emitted * of these Observables. * <p> * <img width="640" height="350" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/switchMap.png"> * <p> * {@code switchMap} does not operate by default on a particular {@link Scheduler}. * * @param func * a function that, when applied to an item emitted by the source Observable, returns an * Observable * @return an Observable that emits the items emitted by the Observable returned from applying {@code func} to the most recently emitted item emitted by the source Observable */ public final <R> Observable<R> switchMap(Func1<? super T, ? extends Observable<? extends R>> func) { return switchOnNext(map(func)); } /** * Returns an Observable that emits only the first {@code num} items emitted by the source Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/take.png"> * <p> * This method returns an Observable that will invoke a subscribing {@link Observer}'s * {@link Observer#onNext onNext} function a maximum of {@code num} times before invoking * {@link Observer#onCompleted onCompleted}. * <p> * This version of {@code take} does not operate by default on a particular {@link Scheduler}. * * @param num * the maximum number of items to emit * @return an Observable that emits only the first {@code num} items emitted by the source Observable, or * all of the items from the source Observable if that Observable emits fewer than {@code num} items * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#take">RxJava Wiki: take()</a> */ public final Observable<T> take(final int num) { return lift(new OperatorTake<T>(num)); } /** * Returns an Observable that emits those items emitted by source Observable before a specified time runs * out. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/take.t.png"> * <p> * This version of {@code take} operates by default on the {@code computation} {@link Scheduler}. * * @param time * the length of the time window * @param unit * the time unit of {@code time} * @return an Observable that emits those items emitted by the source Observable before the time runs out * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#take">RxJava Wiki: take()</a> */ public final Observable<T> take(long time, TimeUnit unit) { return take(time, unit, Schedulers.computation()); } /** * Returns an Observable that emits those items emitted by source Observable before a specified time (on a * specified Scheduler) runs out. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/take.ts.png"> * * @param time * the length of the time window * @param unit * the time unit of {@code time} * @param scheduler * the Scheduler used for time source * @return an Observable that emits those items emitted by the source Observable before the time runs out, * according to the specified Scheduler * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#take">RxJava Wiki: take()</a> */ public final Observable<T> take(long time, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorTakeTimed<T>(time, unit, scheduler)); } /** * Returns an Observable that emits only the very first item emitted by the source Observable that satisfies * a specified condition. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeFirstN.png"> * <p> * {@code takeFirst} does not operate by default on a particular {@link Scheduler}. * * @param predicate * the condition any item emitted by the source Observable has to satisfy * @return an Observable that emits only the very first item emitted by the source Observable that satisfies * the given condition, or that completes without emitting anything if the source Observable * completes without emitting a single condition-satisfying item * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#first">RxJava Wiki: first()</a> * @see "MSDN: Observable.firstAsync()" */ public final Observable<T> takeFirst(Func1<? super T, Boolean> predicate) { return filter(predicate).take(1); } /** * Returns an Observable that emits only the last {@code count} items emitted by the source Observable. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLast.n.png"> * <p> * This version of {@code takeLast} does not operate by default on a particular {@link Scheduler}. * * @param count * the number of items to emit from the end of the sequence of items emitted by the source * Observable * @return an Observable that emits only the last {@code count} items emitted by the source Observable * @throws IndexOutOfBoundsException * if {@code count} is less than zero * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#takelast">RxJava Wiki: takeLast()</a> */ public final Observable<T> takeLast(final int count) { return lift(new OperatorTakeLast<T>(count)); } /** * Returns an Observable that emits at most a specified number of items from the source Observable that were * emitted in a specified window of time before the Observable completed. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLast.tn.png"> * <p> * This version of {@code takeLast} operates by default on the {@code computation} {@link Scheduler}. * * @param count * the maximum number of items to emit * @param time * the length of the time window * @param unit * the time unit of {@code time} * @return an Observable that emits at most {@code count} items from the source Observable that were emitted * in a specified window of time before the Observable completed */ public final Observable<T> takeLast(int count, long time, TimeUnit unit) { return takeLast(count, time, unit, Schedulers.computation()); } /** * Returns an Observable that emits at most a specified number of items from the source Observable that were * emitted in a specified window of time before the Observable completed, where the timing information is * provided by a given Scheduler. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLast.tns.png"> * * @param count * the maximum number of items to emit * @param time * the length of the time window * @param unit * the time unit of {@code time} * @param scheduler * the {@link Scheduler} that provides the timestamps for the observed items * @return an Observable that emits at most {@code count} items from the source Observable that were emitted * in a specified window of time before the Observable completed, where the timing information is * provided by the given {@code scheduler} * @throws IndexOutOfBoundsException * if {@code count} is less than zero */ public final Observable<T> takeLast(int count, long time, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorTakeLastTimed<T>(count, time, unit, scheduler)); } /** * Returns an Observable that emits the items from the source Observable that were emitted in a specified * window of time before the Observable completed. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLast.t.png"> * <p> * This version of {@code takeLast} operates by default on the {@code computation} {@link Scheduler}. * * @param time * the length of the time window * @param unit * the time unit of {@code time} * @return an Observable that emits the items from the source Observable that were emitted in the window of * time before the Observable completed specified by {@code time} */ public final Observable<T> takeLast(long time, TimeUnit unit) { return takeLast(time, unit, Schedulers.computation()); } /** * Returns an Observable that emits the items from the source Observable that were emitted in a specified * window of time before the Observable completed, where the timing information is provided by a specified * Scheduler. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLast.ts.png"> * * @param time * the length of the time window * @param unit * the time unit of {@code time} * @param scheduler * the Scheduler that provides the timestamps for the Observed items * @return an Observable that emits the items from the source Observable that were emitted in the window of * time before the Observable completed specified by {@code time}, where the timing information is * provided by {@code scheduler} */ public final Observable<T> takeLast(long time, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorTakeLastTimed<T>(time, unit, scheduler)); } /** * Returns an Observable that emits a single List containing the last {@code count} elements emitted by the * source Observable. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLastBuffer.png"> * * @param count * the number of items to emit in the list * @return an Observable that emits a single list containing the last {@code count} elements emitted by the * source Observable */ public final Observable<List<T>> takeLastBuffer(int count) { return takeLast(count).toList(); } /** * Returns an Observable that emits a single List containing at most {@code count} items from the source * Observable that were emitted during a specified window of time before the source Observable completed. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLastBuffer.tn.png"> * <p> * This version of {@code takeLastBuffer} operates by default on the {@code computation} {@link Scheduler}. * * @param count * the maximum number of items to emit * @param time * the length of the time window * @param unit * the time unit of {@code time} * @return an Observable that emits a single List containing at most {@code count} items emitted by the * source Observable during the time window defined by {@code time} before the source Observable * completed */ public final Observable<List<T>> takeLastBuffer(int count, long time, TimeUnit unit) { return takeLast(count, time, unit).toList(); } /** * Returns an Observable that emits a single List containing at most {@code count} items from the source * Observable that were emitted during a specified window of time (on a specified Scheduler) before the * source Observable completed. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLastBuffer.tns.png"> * * @param count * the maximum number of items to emit * @param time * the length of the time window * @param unit * the time unit of {@code time} * @param scheduler * the Scheduler that provides the timestamps for the observed items * @return an Observable that emits a single List containing at most {@code count} items emitted by the * source Observable during the time window defined by {@code time} before the source Observable * completed */ public final Observable<List<T>> takeLastBuffer(int count, long time, TimeUnit unit, Scheduler scheduler) { return takeLast(count, time, unit, scheduler).toList(); } /** * Returns an Observable that emits a single List containing those items from the source Observable that * were emitted during a specified window of time before the source Observable completed. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLastBuffer.t.png"> * <p> * This version of {@code takeLastBuffer} operates by default on the {@code computation} {@link Scheduler}. * * @param time * the length of the time window * @param unit * the time unit of {@code time} * @return an Observable that emits a single List containing the items emitted by the source Observable * during the time window defined by {@code time} before the source Observable completed */ public final Observable<List<T>> takeLastBuffer(long time, TimeUnit unit) { return takeLast(time, unit).toList(); } /** * Returns an Observable that emits a single List containing those items from the source Observable that * were emitted during a specified window of time before the source Observable completed, where the timing * information is provided by the given Scheduler. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeLastBuffer.ts.png"> * * @param time * the length of the time window * @param unit * the time unit of {@code time} * @param scheduler * the Scheduler that provides the timestamps for the observed items * @return an Observable that emits a single List containing the items emitted by the source Observable * during the time window defined by {@code time} before the source Observable completed, where the * timing information is provided by {@code scheduler} */ public final Observable<List<T>> takeLastBuffer(long time, TimeUnit unit, Scheduler scheduler) { return takeLast(time, unit, scheduler).toList(); } /** * Returns an Observable that emits the items emitted by the source Observable until a second Observable * emits an item. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeUntil.png"> * <p> * {@code takeUntil} does not operate by default on a particular {@link Scheduler}. * * @param other * the Observable whose first emitted item will cause {@code takeUntil} to stop emitting items * from the source Observable * @param <E> * the type of items emitted by {@code other} * @return an Observable that emits the items emitted by the source Observable until such time as {@code other} emits its first item * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#takeuntil">RxJava Wiki: takeUntil()</a> */ public final <E> Observable<T> takeUntil(Observable<? extends E> other) { return lift(new OperatorTakeUntil<T, E>(other)); } /** * Returns an Observable that emits items emitted by the source Observable so long as each item satisfied a * specified condition, and then completes as soon as this condition is not satisfied. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeWhile.png"> * <p> * {@code takeWhile} does not operate by default on a particular {@link Scheduler}. * * @param predicate * a function that evaluates an item emitted by the source Observable and returns a Boolean * @return an Observable that emits the items from the source Observable so long as each item satisfies the * condition defined by {@code predicate}, then completes * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#takewhile-and-takewhilewithindex">RxJava Wiki: takeWhile()</a> */ public final Observable<T> takeWhile(final Func1<? super T, Boolean> predicate) { return lift(new OperatorTakeWhile<T>(predicate)); } /** * Returns an Observable that emits the items emitted by a source Observable so long as a given predicate * remains true, where the predicate operates on both the item and its index relative to the complete * sequence of emitted items. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/takeWhileWithIndex.png"> * <p> * {@code takeWhile} does not operate by default on a particular {@link Scheduler}. * * @param predicate * a function to test each item emitted by the source Observable for a condition; the second * parameter of the function represents the sequential index of the source item; it returns a * Boolean * @return an Observable that emits items from the source Observable so long as the predicate continues to * return {@code true} for each item, then completes * @see <a href="https://github.com/Netflix/RxJava/wiki/Conditional-and-Boolean-Operators#takewhile-and-takewhilewithindex">RxJava Wiki: takeWhileWithIndex()</a> */ public final Observable<T> takeWhileWithIndex(final Func2<? super T, ? super Integer, Boolean> predicate) { return lift(new OperatorTakeWhile<T>(predicate)); } /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential * time windows of a specified duration. * <p> * This differs from {@link #throttleLast} in that this only tracks passage of time whereas * {@link #throttleLast} ticks at scheduled intervals. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleFirst.png"> * <p> * {@code throttleFirst} operates by default on the {@code computation} {@link Scheduler}. * * @param windowDuration * time to wait before emitting another item after emitting the last item * @param unit * the unit of time of {@code windowDuration} * @return an Observable that performs the throttle operation * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#throttlefirst">RxJava Wiki: throttleFirst()</a> */ public final Observable<T> throttleFirst(long windowDuration, TimeUnit unit) { return lift(new OperatorThrottleFirst<T>(windowDuration, unit, Schedulers.computation())); } /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential * time windows of a specified duration, where the windows are managed by a specified Scheduler. * <p> * This differs from {@link #throttleLast} in that this only tracks passage of time whereas * {@link #throttleLast} ticks at scheduled intervals. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleFirst.s.png"> * * @param skipDuration * time to wait before emitting another item after emitting the last item * @param unit * the unit of time of {@code skipDuration} * @param scheduler * the {@link Scheduler} to use internally to manage the timers that handle timeout for each * event * @return an Observable that performs the throttle operation * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#throttlefirst">RxJava Wiki: throttleFirst()</a> */ public final Observable<T> throttleFirst(long skipDuration, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorThrottleFirst<T>(skipDuration, unit, scheduler)); } /** * Returns an Observable that emits only the last item emitted by the source Observable during sequential * time windows of a specified duration. * <p> * This differs from {@link #throttleFirst} in that this ticks along at a scheduled interval whereas * {@link #throttleFirst} does not tick, it just tracks passage of time. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleLast.png"> * <p> * {@code throttleLast} operates by default on the {@code computation} {@link Scheduler}. * * @param intervalDuration * duration of windows within which the last item emitted by the source Observable will be * emitted * @param unit * the unit of time of {@code intervalDuration} * @return an Observable that performs the throttle operation * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#takelast">RxJava Wiki: throttleLast()</a> * @see #sample(long, TimeUnit) */ public final Observable<T> throttleLast(long intervalDuration, TimeUnit unit) { return sample(intervalDuration, unit); } /** * Returns an Observable that emits only the last item emitted by the source Observable during sequential * time windows of a specified duration, where the duration is governed by a specified Scheduler. * <p> * This differs from {@link #throttleFirst} in that this ticks along at a scheduled interval whereas * {@link #throttleFirst} does not tick, it just tracks passage of time. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleLast.s.png"> * * @param intervalDuration * duration of windows within which the last item emitted by the source Observable will be * emitted * @param unit * the unit of time of {@code intervalDuration} * @param scheduler * the {@link Scheduler} to use internally to manage the timers that handle timeout for each * event * @return an Observable that performs the throttle operation * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#takelast">RxJava Wiki: throttleLast()</a> * @see #sample(long, TimeUnit, Scheduler) */ public final Observable<T> throttleLast(long intervalDuration, TimeUnit unit, Scheduler scheduler) { return sample(intervalDuration, unit, scheduler); } /** * Returns an Observable that only emits those items emitted by the source Observable that are not followed * by another emitted item within a specified time window. * <p> * <em>Note:</em> If the source Observable keeps emitting items more frequently than the length of the time * window then no items will be emitted by the resulting Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleWithTimeout.png"> * <p> * Information on debounce vs throttle: * <p> * <ul> * <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li> * <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li> * <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li> * </ul> * <p> * {@code throttleWithTimeout} operates by default on the {@code computation} {@link Scheduler}. * * @param timeout * the length of the window of time that must pass after the emission of an item from the source * Observable in which that Observable emits no items in order for the item to be emitted by the * resulting Observable * @param unit * the {@link TimeUnit} of {@code timeout} * @return an Observable that filters out items that are too quickly followed by newer items * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#throttlewithtimeout-or-debounce">RxJava Wiki: throttleWithTimeout()</a> * @see #debounce(long, TimeUnit) */ public final Observable<T> throttleWithTimeout(long timeout, TimeUnit unit) { return debounce(timeout, unit); } /** * Returns an Observable that only emits those items emitted by the source Observable that are not followed * by another emitted item within a specified time window, where the time window is governed by a specified * Scheduler. * <p> * <em>Note:</em> If the source Observable keeps emitting items more frequently than the length of the time * window then no items will be emitted by the resulting Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/throttleWithTimeout.s.png"> * <p> * Information on debounce vs throttle: * <p> * <ul> * <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li> * <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li> * <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li> * </ul> * * @param timeout * the length of the window of time that must pass after the emission of an item from the source * Observable in which that Observable emits no items in order for the item to be emitted by the * resulting Observable * @param unit * the {@link TimeUnit} of {@code timeout} * @param scheduler * the {@link Scheduler} to use internally to manage the timers that handle the timeout for each * item * @return an Observable that filters out items that are too quickly followed by newer items * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#throttlewithtimeout-or-debounce">RxJava Wiki: throttleWithTimeout()</a> * @see #debounce(long, TimeUnit, Scheduler) */ public final Observable<T> throttleWithTimeout(long timeout, TimeUnit unit, Scheduler scheduler) { return debounce(timeout, unit, scheduler); } /** * Returns an Observable that emits records of the time interval between consecutive items emitted by the * source Observable. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeInterval.png"> * <p> * {@code timeInterval} operates by default on the {@code immediate} {@link Scheduler}. * * @return an Observable that emits time interval information items * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#timeinterval">RxJava Wiki: timeInterval()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh212107.aspx">MSDN: Observable.TimeInterval</a> */ public final Observable<TimeInterval<T>> timeInterval() { return lift(new OperatorTimeInterval<T>(Schedulers.immediate())); } /** * Returns an Observable that emits records of the time interval between consecutive items emitted by the * source Observable, where this interval is computed on a specified Scheduler. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeInterval.s.png"> * * @param scheduler * the {@link Scheduler} used to compute time intervals * @return an Observable that emits time interval information items * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#timeinterval">RxJava Wiki: timeInterval()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh212107.aspx">MSDN: Observable.TimeInterval</a> */ public final Observable<TimeInterval<T>> timeInterval(Scheduler scheduler) { return lift(new OperatorTimeInterval<T>(scheduler)); } /** * Returns an Observable that mirrors the source Observable, but notifies observers of a TimeoutException if * either the first item emitted by the source Observable or any subsequent item don't arrive within time * windows defined by other Observables. * <p> * <img width="640" height="400" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout5.png"> * <p> * This version of {@code timeout} operates by default on the {@code immediate} {@link Scheduler}. * * @param <U> * the first timeout value type (ignored) * @param <V> * the subsequent timeout value type (ignored) * @param firstTimeoutSelector * a function that returns an Observable that determines the timeout window for the first source * item * @param timeoutSelector * a function that returns an Observable for each item emitted by the source Observable and that * determines the timeout window in which the subsequent source item must arrive in order to * continue the sequence * @return an Observable that mirrors the source Observable, but notifies observers of a TimeoutException if * either the first item or any subsequent item doesn't arrive within the time windows specified by * the timeout selectors */ public final <U, V> Observable<T> timeout(Func0<? extends Observable<U>> firstTimeoutSelector, Func1<? super T, ? extends Observable<V>> timeoutSelector) { return timeout(firstTimeoutSelector, timeoutSelector, null); } /** * Returns an Observable that mirrors the source Observable, but switches to a fallback Observable if either * the first item emitted by the source Observable or any subsequent item don't arrive within time windows * defined by other Observables. * <p> * <img width="640" height="400" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout6.png"> * <p> * This version of {@code timeout} operates by default on the {@code immediate} {@link Scheduler}. * * @param <U> * the first timeout value type (ignored) * @param <V> * the subsequent timeout value type (ignored) * @param firstTimeoutSelector * a function that returns an Observable which determines the timeout window for the first source * item * @param timeoutSelector * a function that returns an Observable for each item emitted by the source Observable and that * determines the timeout window in which the subsequent source item must arrive in order to * continue the sequence * @param other * the fallback Observable to switch to if the source Observable times out * @return an Observable that mirrors the source Observable, but switches to the {@code other} Observable if * either the first item emitted by the source Observable or any subsequent item don't arrive within * time windows defined by the timeout selectors * @throws NullPointerException * if {@code timeoutSelector} is null */ public final <U, V> Observable<T> timeout(Func0<? extends Observable<U>> firstTimeoutSelector, Func1<? super T, ? extends Observable<V>> timeoutSelector, Observable<? extends T> other) { if (timeoutSelector == null) { throw new NullPointerException("timeoutSelector is null"); } return lift(new OperatorTimeoutWithSelector<T, U, V>(firstTimeoutSelector, timeoutSelector, other)); } /** * Returns an Observable that mirrors the source Observable, but notifies observers of a TimeoutException if * an item emitted by the source Observable doesn't arrive within a window of time after the emission of the * previous item, where that period of time is measured by an Observable that is a function of the previous * item. * <p> * <img width="640" height="400" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout3.png"> * <p> * Note: The arrival of the first source item is never timed out. * <p> * This version of {@code timeout} operates by default on the {@code immediate} {@link Scheduler}. * * @param <V> * the timeout value type (ignored) * @param timeoutSelector * a function that returns an observable for each item emitted by the source * Observable and that determines the timeout window for the subsequent item * @return an Observable that mirrors the source Observable, but notifies observers of a TimeoutException if * an item emitted by the source Observable takes longer to arrive than the time window defined by * the selector for the previously emitted item */ public final <V> Observable<T> timeout(Func1<? super T, ? extends Observable<V>> timeoutSelector) { return timeout(null, timeoutSelector, null); } /** * Returns an Observable that mirrors the source Observable, but that switches to a fallback Observable if * an item emitted by the source Observable doesn't arrive within a window of time after the emission of the * previous item, where that period of time is measured by an Observable that is a function of the previous * item. * <p> * <img width="640" height="400" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout4.png"> * <p> * Note: The arrival of the first source item is never timed out. * <p> * This version of {@code timeout} operates by default on the {@code immediate} {@link Scheduler}. * * @param <V> * the timeout value type (ignored) * @param timeoutSelector * a function that returns an Observable, for each item emitted by the source Observable, that * determines the timeout window for the subsequent item * @param other * the fallback Observable to switch to if the source Observable times out * @return an Observable that mirrors the source Observable, but switches to mirroring a fallback Observable * if an item emitted by the source Observable takes longer to arrive than the time window defined * by the selector for the previously emitted item */ public final <V> Observable<T> timeout(Func1<? super T, ? extends Observable<V>> timeoutSelector, Observable<? extends T> other) { return timeout(null, timeoutSelector, other); } /** * Returns an Observable that mirrors the source Observable but applies a timeout policy for each emitted * item. If the next item isn't emitted within the specified timeout duration starting from its predecessor, * the resulting Observable terminates and notifies observers of a {@code TimeoutException}. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout.1.png"> * <p> * This version of {@code timeout} operates by default on the {@code computation} {@link Scheduler}. * * @param timeout * maximum duration between emitted items before a timeout occurs * @param timeUnit * the unit of time that applies to the {@code timeout} argument. * @return the source Observable modified to notify observers of a {@code TimeoutException} in case of a * timeout * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#timeout">RxJava Wiki: timeout()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh244283.aspx">MSDN: Observable.Timeout</a> */ public final Observable<T> timeout(long timeout, TimeUnit timeUnit) { return timeout(timeout, timeUnit, null, Schedulers.computation()); } /** * Returns an Observable that mirrors the source Observable but applies a timeout policy for each emitted * item. If the next item isn't emitted within the specified timeout duration starting from its predecessor, * the resulting Observable begins instead to mirror a fallback Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout.2.png"> * <p> * This version of {@code timeout} operates by default on the {@code computation} {@link Scheduler}. * * @param timeout * maximum duration between items before a timeout occurs * @param timeUnit * the unit of time that applies to the {@code timeout} argument * @param other * the fallback Observable to use in case of a timeout * @return the source Observable modified to switch to the fallback Observable in case of a timeout * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#timeout">RxJava Wiki: timeout()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229512.aspx">MSDN: Observable.Timeout</a> */ public final Observable<T> timeout(long timeout, TimeUnit timeUnit, Observable<? extends T> other) { return timeout(timeout, timeUnit, other, Schedulers.computation()); } /** * Returns an Observable that mirrors the source Observable but applies a timeout policy for each emitted * item using a specified Scheduler. If the next item isn't emitted within the specified timeout duration * starting from its predecessor, the resulting Observable begins instead to mirror a fallback Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout.2s.png"> * * @param timeout * maximum duration between items before a timeout occurs * @param timeUnit * the unit of time that applies to the {@code timeout} argument * @param other * the Observable to use as the fallback in case of a timeout * @param scheduler * the {@link Scheduler} to run the timeout timers on * @return the source Observable modified so that it will switch to the fallback Observable in case of a * timeout * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#timeout">RxJava Wiki: timeout()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211676.aspx">MSDN: Observable.Timeout</a> */ public final Observable<T> timeout(long timeout, TimeUnit timeUnit, Observable<? extends T> other, Scheduler scheduler) { return lift(new OperatorTimeout<T>(timeout, timeUnit, other, scheduler)); } /** * Returns an Observable that mirrors the source Observable but applies a timeout policy for each emitted * item, where this policy is governed on a specified Scheduler. If the next item isn't emitted within the * specified timeout duration starting from its predecessor, the resulting Observable terminates and * notifies observers of a {@code TimeoutException}. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout.1s.png"> * * @param timeout * maximum duration between items before a timeout occurs * @param timeUnit * the unit of time that applies to the {@code timeout} argument * @param scheduler * the Scheduler to run the timeout timers on * @return the source Observable modified to notify observers of a {@code TimeoutException} in case of a * timeout * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#timeout">RxJava Wiki: timeout()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh228946.aspx">MSDN: Observable.Timeout</a> */ public final Observable<T> timeout(long timeout, TimeUnit timeUnit, Scheduler scheduler) { return timeout(timeout, timeUnit, null, scheduler); } /** * Returns an Observable that emits each item emitted by the source Observable, wrapped in a * {@link Timestamped} object. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timestamp.png"> * <p> * {@code timestamp} operates by default on the {@code immediate} {@link Scheduler}. * * @return an Observable that emits timestamped items from the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#timestamp">RxJava Wiki: timestamp()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229003.aspx">MSDN: Observable.Timestamp</a> */ public final Observable<Timestamped<T>> timestamp() { return timestamp(Schedulers.immediate()); } /** * Returns an Observable that emits each item emitted by the source Observable, wrapped in a * {@link Timestamped} object whose timestamps are provided by a specified Scheduler. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timestamp.s.png"> * * @param scheduler * the {@link Scheduler} to use as a time source * @return an Observable that emits timestamped items from the source Observable with timestamps provided by * the {@code scheduler} * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#timestamp">RxJava Wiki: timestamp()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229003.aspx">MSDN: Observable.Timestamp</a> */ public final Observable<Timestamped<T>> timestamp(Scheduler scheduler) { return lift(new OperatorTimestamp<T>(scheduler)); } /** * Converts an Observable into a {@link BlockingObservable} (an Observable with blocking operators). * * @return a {@code BlockingObservable} version of this Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Blocking-Observable-Operators">RxJava Wiki: Blocking Observable Observers</a> * @deprecated Use {@link #toBlocking()} instead. */ @Deprecated public final BlockingObservable<T> toBlockingObservable() { return BlockingObservable.from(this); } /** * Converts an Observable into a {@link BlockingObservable} (an Observable with blocking operators). * <p> * {@code toBlocking} does not operate by default on a particular {@link Scheduler}. * * @return a {@code BlockingObservable} version of this Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Blocking-Observable-Operators">RxJava Wiki: Blocking Observable Observers</a> * @since 0.19 */ public final BlockingObservable<T> toBlocking() { return BlockingObservable.from(this); } /** * Returns an Observable that emits a single item, a list composed of all the items emitted by the source * Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toList.png"> * <p> * Normally, an Observable that returns multiple items will do so by invoking its {@link Observer}'s * {@link Observer#onNext onNext} method for each such item. You can change this behavior, instructing the * Observable to compose a list of all of these items and then to invoke the Observer's {@code onNext} * function once, passing it the entire list, by calling the Observable's {@code toList} method prior to * calling its {@link #subscribe} method. * <p> * Be careful not to use this operator on Observables that emit infinite or very large numbers of items, as * you do not have the option to unsubscribe. * <p> * {@code toList} does not operate by default on a particular {@link Scheduler}. * * @return an Observable that emits a single item: a List containing all of the items emitted by the source * Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#tolist">RxJava Wiki: toList()</a> */ public final Observable<List<T>> toList() { return lift(new OperatorToObservableList<T>()); } /** * Returns an Observable that emits a single HashMap containing all items emitted by the source Observable, * mapped by the keys returned by a specified {@code keySelector} function. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMap.png"> * <p> * If more than one source item maps to the same key, the HashMap will contain the latest of those items. * <p> * {@code toMap} does not operate by default on a particular {@link Scheduler}. * * @param keySelector * the function that extracts the key from a source item to be used in the HashMap * @return an Observable that emits a single item: a HashMap containing the mapped items from the source * Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#tomap-and-tomultimap">RxJava Wiki: toMap()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229137.aspx">MSDN: Observable.ToDictionary</a> */ public final <K> Observable<Map<K, T>> toMap(Func1<? super T, ? extends K> keySelector) { return lift(new OperatorToMap<T, K, T>(keySelector, Functions.<T>identity())); } /** * Returns an Observable that emits a single HashMap containing values corresponding to items emitted by the * source Observable, mapped by the keys returned by a specified {@code keySelector} function. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMap.png"> * <p> * If more than one source item maps to the same key, the HashMap will contain a single entry that * corresponds to the latest of those items. * <p> * {@code toMap} does not operate by default on a particular {@link Scheduler}. * * @param keySelector * the function that extracts the key from a source item to be used in the HashMap * @param valueSelector * the function that extracts the value from a source item to be used in the HashMap * @return an Observable that emits a single item: a HashMap containing the mapped items from the source * Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#tomap-and-tomultimap">RxJava Wiki: toMap()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh212075.aspx">MSDN: Observable.ToDictionary</a> */ public final <K, V> Observable<Map<K, V>> toMap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector) { return lift(new OperatorToMap<T, K, V>(keySelector, valueSelector)); } /** * Returns an Observable that emits a single Map, returned by a specified {@code mapFactory} function, that * contains keys and values extracted from the items emitted by the source Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMap.png"> * <p> * {@code toMap} does not operate by default on a particular {@link Scheduler}. * * @param keySelector * the function that extracts the key from a source item to be used in the Map * @param valueSelector * the function that extracts the value from the source items to be used as value in the Map * @param mapFactory * the function that returns a Map instance to be used * @return an Observable that emits a single item: a Map that contains the mapped items emitted by the * source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#tomap-and-tomultimap">RxJava Wiki: toMap()</a> */ public final <K, V> Observable<Map<K, V>> toMap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector, Func0<? extends Map<K, V>> mapFactory) { return lift(new OperatorToMap<T, K, V>(keySelector, valueSelector, mapFactory)); } /** * Returns an Observable that emits a single HashMap that contains an ArrayList of items emitted by the * source Observable keyed by a specified {@code keySelector} function. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMultiMap.png"> * <p> * {@code toMultiMap} does not operate by default on a particular {@link Scheduler}. * * @param keySelector * the function that extracts the key from the source items to be used as key in the HashMap * @return an Observable that emits a single item: a HashMap that contains an ArrayList of items mapped from * the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#tomap-and-tomultimap">RxJava Wiki: toMap()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh212098.aspx">MSDN: Observable.ToLookup</a> */ public final <K> Observable<Map<K, Collection<T>>> toMultimap(Func1<? super T, ? extends K> keySelector) { return lift(new OperatorToMultimap<T, K, T>(keySelector, Functions.<T>identity())); } /** * Returns an Observable that emits a single HashMap that contains an ArrayList of values extracted by a * specified {@code valueSelector} function from items emitted by the source Observable, keyed by a * specified {@code keySelector} function. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMultiMap.png"> * <p> * {@code toMultiMap} does not operate by default on a particular {@link Scheduler}. * * @param keySelector * the function that extracts a key from the source items to be used as key in the HashMap * @param valueSelector * the function that extracts a value from the source items to be used as value in the HashMap * @return an Observable that emits a single item: a HashMap that contains an ArrayList of items mapped from * the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#tomap-and-tomultimap">RxJava Wiki: toMap()</a> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229101.aspx">MSDN: Observable.ToLookup</a> */ public final <K, V> Observable<Map<K, Collection<V>>> toMultimap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector) { return lift(new OperatorToMultimap<T, K, V>(keySelector, valueSelector)); } /** * Returns an Observable that emits a single Map, returned by a specified {@code mapFactory} function, that * contains an ArrayList of values, extracted by a specified {@code valueSelector} function from items * emitted by the source Observable and keyed by the {@code keySelector} function. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMultiMap.png"> * <p> * {@code toMultiMap} does not operate by default on a particular {@link Scheduler}. * * @param keySelector * the function that extracts a key from the source items to be used as the key in the Map * @param valueSelector * the function that extracts a value from the source items to be used as the value in the Map * @param mapFactory * the function that returns a Map instance to be used * @return an Observable that emits a single item: a Map that contains a list items mapped from the source * Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#tomap-and-tomultimap">RxJava Wiki: toMap()</a> */ public final <K, V> Observable<Map<K, Collection<V>>> toMultimap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector, Func0<? extends Map<K, Collection<V>>> mapFactory) { return lift(new OperatorToMultimap<T, K, V>(keySelector, valueSelector, mapFactory)); } /** * Returns an Observable that emits a single Map, returned by a specified {@code mapFactory} function, that * contains a custom collection of values, extracted by a specified {@code valueSelector} function from * items emitted by the source Observable, and keyed by the {@code keySelector} function. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toMultiMap.png"> * <p> * {@code toMultiMap} does not operate by default on a particular {@link Scheduler}. * * @param keySelector * the function that extracts a key from the source items to be used as the key in the Map * @param valueSelector * the function that extracts a value from the source items to be used as the value in the Map * @param mapFactory * the function that returns a Map instance to be used * @param collectionFactory * the function that returns a Collection instance for a particular key to be used in the Map * @return an Observable that emits a single item: a Map that contains the collection of mapped items from * the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#tomap-and-tomultimap">RxJava Wiki: toMap()</a> */ public final <K, V> Observable<Map<K, Collection<V>>> toMultimap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector, Func0<? extends Map<K, Collection<V>>> mapFactory, Func1<? super K, ? extends Collection<V>> collectionFactory) { return lift(new OperatorToMultimap<T, K, V>(keySelector, valueSelector, mapFactory, collectionFactory)); } /** * Returns an Observable that emits a list that contains the items emitted by the source Observable, in a * sorted order. Each item emitted by the Observable must implement {@link Comparable} with respect to all * other items in the sequence. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toSortedList.png"> * <p> * {@code toSortedList} does not operate by default on a particular {@link Scheduler}. * * @throws ClassCastException * if any item emitted by the Observable does not implement {@link Comparable} with respect to * all other items emitted by the Observable * @return an Observable that emits a list that contains the items emitted by the source Observable in * sorted order * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#tosortedlist">RxJava Wiki: toSortedList()</a> */ public final Observable<List<T>> toSortedList() { return lift(new OperatorToObservableSortedList<T>()); } /** * Returns an Observable that emits a list that contains the items emitted by the source Observable, in a * sorted order based on a specified comparison function. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toSortedList.f.png"> * <p> * {@code toSortedList} does not operate by default on a particular {@link Scheduler}. * * @param sortFunction * a function that compares two items emitted by the source Observable and returns an Integer * that indicates their sort order * @return an Observable that emits a list that contains the items emitted by the source Observable in * sorted order * @see <a href="https://github.com/Netflix/RxJava/wiki/Mathematical-and-Aggregate-Operators#tosortedlist">RxJava Wiki: toSortedList()</a> */ public final Observable<List<T>> toSortedList(Func2<? super T, ? super T, Integer> sortFunction) { return lift(new OperatorToObservableSortedList<T>(sortFunction)); } /** * Modifies the source Observable so that subscribers will unsubscribe from it on a specified * {@link Scheduler}. * * @param scheduler * the {@link Scheduler} to perform unsubscription actions on * @return the source Observable modified so that its unsubscriptions happen on the specified * {@link Scheduler} * @since 0.17 */ public final Observable<T> unsubscribeOn(Scheduler scheduler) { return lift(new OperatorUnsubscribeOn<T>(scheduler)); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping windows. It emits the current window and opens a new one * whenever the Observable produced by the specified {@code closingSelector} emits an item. * <p> * <img width="640" height="485" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window1.png"> * <p> * This version of {@code window} does not operate by default on a particular {@link Scheduler}. * * @param closingSelector * a {@link Func0} that returns an {@code Observable} that governs the boundary between windows. * When this {@code Observable} emits an item, {@code window} emits the current window and begins * a new one. * @return an Observable that emits connected, non-overlapping windows of items from the source Observable * whenever {@code closingSelector} emits an item * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#window">RxJava Wiki: window()</a> */ public final <TClosing> Observable<Observable<T>> window(Func0<? extends Observable<? extends TClosing>> closingSelector) { return lift(new OperatorWindowWithObservable<T, TClosing>(closingSelector)); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping windows, each containing {@code count} items. When the source * Observable completes or encounters an error, the resulting Observable emits the current window and * propagates the notification from the source Observable. * <p> * <img width="640" height="400" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window3.png"> * <p> * This version of {@code window} does not operate by default on a particular {@link Scheduler}. * * @param count * the maximum size of each window before it should be emitted * @return an Observable that emits connected, non-overlapping windows, each containing at most * {@code count} items from the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#window">RxJava Wiki: window()</a> */ public final Observable<Observable<T>> window(int count) { return lift(new OperatorWindowWithSize<T>(count, count)); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable emits windows every {@code skip} items, each containing no more than {@code count} items. When * the source Observable completes or encounters an error, the resulting Observable emits the current window * and propagates the notification from the source Observable. * <p> * <img width="640" height="365" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window4.png"> * <p> * This version of {@code window} does not operate by default on a particular {@link Scheduler}. * * @param count * the maximum size of each window before it should be emitted * @param skip * how many items need to be skipped before starting a new window. Note that if {@code skip} and * {@code count} are equal this is the same operation as {@link #window(int)}. * @return an Observable that emits windows every {@code skip} items containing at most {@code count} items * from the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#window">RxJava Wiki: window()</a> */ public final Observable<Observable<T>> window(int count, int skip) { return lift(new OperatorWindowWithSize<T>(count, skip)); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable starts a new window periodically, as determined by the {@code timeshift} argument. It emits * each window after a fixed timespan, specified by the {@code timespan} argument. When the source * Observable completes or Observable completes or encounters an error, the resulting Observable emits the * current window and propagates the notification from the source Observable. * <p> * <img width="640" height="335" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window7.png"> * <p> * This version of {@code window} operates by default on the {@code computation} {@link Scheduler}. * * @param timespan * the period of time each window collects items before it should be emitted * @param timeshift * the period of time after which a new window will be created * @param unit * the unit of time that applies to the {@code timespan} and {@code timeshift} arguments * @return an Observable that emits new windows periodically as a fixed timespan elapses * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#window">RxJava Wiki: window()</a> */ public final Observable<Observable<T>> window(long timespan, long timeshift, TimeUnit unit) { return lift(new OperatorWindowWithTime<T>(timespan, timeshift, unit, Integer.MAX_VALUE, Schedulers.computation())); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable starts a new window periodically, as determined by the {@code timeshift} argument. It emits * each window after a fixed timespan, specified by the {@code timespan} argument. When the source * Observable completes or Observable completes or encounters an error, the resulting Observable emits the * current window and propagates the notification from the source Observable. * <p> * <img width="640" height="335" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window7.s.png"> * * @param timespan * the period of time each window collects items before it should be emitted * @param timeshift * the period of time after which a new window will be created * @param unit * the unit of time that applies to the {@code timespan} and {@code timeshift} arguments * @param scheduler * the {@link Scheduler} to use when determining the end and start of a window * @return an Observable that emits new windows periodically as a fixed timespan elapses * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#window">RxJava Wiki: window()</a> */ public final Observable<Observable<T>> window(long timespan, long timeshift, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorWindowWithTime<T>(timespan, timeshift, unit, Integer.MAX_VALUE, scheduler)); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping windows, each of a fixed duration specified by the * {@code timespan} argument. When the source Observable completes or encounters an error, the resulting * Observable emits the current window and propagates the notification from the source Observable. * <p> * <img width="640" height="375" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window5.png"> * <p> * This version of {@code window} operates by default on the {@code computation} {@link Scheduler}. * * @param timespan * the period of time each window collects items before it should be emitted and replaced with a * new window * @param unit * the unit of time that applies to the {@code timespan} argument * @return an Observable that emits connected, non-overlapping windows represending items emitted by the * source Observable during fixed, consecutive durations * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#window">RxJava Wiki: window()</a> */ public final Observable<Observable<T>> window(long timespan, TimeUnit unit) { return lift(new OperatorWindowWithTime<T>(timespan, timespan, unit, Integer.MAX_VALUE, Schedulers.computation())); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping windows, each of a fixed duration as specified by the * {@code timespan} argument or a maximum size as specified by the {@code count} argument (whichever is * reached first). When the source Observable completes or encounters an error, the resulting Observable * emits the current window and propagates the notification from the source Observable. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window6.png"> * <p> * This version of {@code window} operates by default on the {@code computation} {@link Scheduler}. * * @param timespan * the period of time each window collects items before it should be emitted and replaced with a * new window * @param unit * the unit of time that applies to the {@code timespan} argument * @param count * the maximum size of each window before it should be emitted * @return an Observable that emits connected, non-overlapping windows of items from the source Observable * that were emitted during a fixed duration of time or when the window has reached maximum capacity * (whichever occurs first) * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#window">RxJava Wiki: window()</a> */ public final Observable<Observable<T>> window(long timespan, TimeUnit unit, int count) { return lift(new OperatorWindowWithTime<T>(timespan, timespan, unit, count, Schedulers.computation())); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping windows, each of a fixed duration specified by the * {@code timespan} argument or a maximum size specified by the {@code count} argument (whichever is reached * first). When the source Observable completes or encounters an error, the resulting Observable emits the * current window and propagates the notification from the source Observable. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window6.s.png"> * * @param timespan * the period of time each window collects items before it should be emitted and replaced with a * new window * @param unit * the unit of time which applies to the {@code timespan} argument * @param count * the maximum size of each window before it should be emitted * @param scheduler * the {@link Scheduler} to use when determining the end and start of a window * @return an Observable that emits connected, non-overlapping windows of items from the source Observable * that were emitted during a fixed duration of time or when the window has reached maximum capacity * (whichever occurs first) * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#window">RxJava Wiki: window()</a> */ public final Observable<Observable<T>> window(long timespan, TimeUnit unit, int count, Scheduler scheduler) { return lift(new OperatorWindowWithTime<T>(timespan, timespan, unit, count, scheduler)); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping windows, each of a fixed duration as specified by the * {@code timespan} argument. When the source Observable completes or encounters an error, the resulting * Observable emits the current window and propagates the notification from the source Observable. * <p> * <img width="640" height="375" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window5.s.png"> * * @param timespan * the period of time each window collects items before it should be emitted and replaced with a * new window * @param unit * the unit of time which applies to the {@code timespan} argument * @param scheduler * the {@link Scheduler} to use when determining the end and start of a window * @return an Observable that emits connected, non-overlapping windows containing items emitted by the * source Observable within a fixed duration * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#window">RxJava Wiki: window()</a> */ public final Observable<Observable<T>> window(long timespan, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorWindowWithTime<T>(timespan, timespan, unit, Integer.MAX_VALUE, scheduler)); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable emits windows that contain those items emitted by the source Observable between the time when * the {@code windowOpenings} Observable emits an item and when the Observable returned by * {@code closingSelector} emits an item. * <p> * <img width="640" height="550" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window2.png"> * <p> * This version of {@code window} does not operate by default on a particular {@link Scheduler}. * * @param windowOpenings * an Observable that, when it emits an item, causes another window to be created * @param closingSelector * a {@link Func1} that produces an Observable for every window created. When this Observable * emits an item, the associated window is closed and emitted * @return an Observable that emits windows of items emitted by the source Observable that are governed by * the specified window-governing Observables * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#window">RxJava Wiki: window()</a> */ public final <TOpening, TClosing> Observable<Observable<T>> window(Observable<? extends TOpening> windowOpenings, Func1<? super TOpening, ? extends Observable<? extends TClosing>> closingSelector) { return lift(new OperatorWindowWithStartEndObservable<T, TOpening, TClosing>(windowOpenings, closingSelector)); } /** * Returns an Observable that emits non-overlapping windows of items it collects from the source Observable * where the boundary of each window is determined by the items emitted from a specified boundary-governing * Observable. * <p> * <img width="640" height="475" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/window8.png"> * <p> * This version of {@code window} does not operate by default on a particular {@link Scheduler}. * * @param <U> * the window element type (ignored) * @param boundary * an Observable whose emitted items close and open windows * @return an Observable that emits non-overlapping windows of items it collects from the source Observable * where the boundary of each window is determined by the items emitted from the {@code boundary} * Observable */ public final <U> Observable<Observable<T>> window(Observable<U> boundary) { return lift(new OperatorWindowWithObservable<T, U>(boundary)); } /** * Returns an Observable that emits items that are the result of applying a specified function to pairs of * values, one each from the source Observable and a specified Iterable sequence. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.i.png"> * <p> * Note that the {@code other} Iterable is evaluated as items are observed from the source Observable; it is * not pre-consumed. This allows you to zip infinite streams on either side. * <p> * {@code zip} does not operate by default on a particular {@link Scheduler}. * * @param <T2> * the type of items in the {@code other} Iterable * @param <R> * the type of items emitted by the resulting Observable * @param other * the Iterable sequence * @param zipFunction * a function that combines the pairs of items from the Observable and the Iterable to generate * the items to be emitted by the resulting Observable * @return an Observable that pairs up values from the source Observable and the {@code other} Iterable * sequence and emits the results of {@code zipFunction} applied to these pairs */ public final <T2, R> Observable<R> zip(Iterable<? extends T2> other, Func2<? super T, ? super T2, ? extends R> zipFunction) { return lift(new OperatorZipIterable<T, T2, R>(other, zipFunction)); } /** * Returns an Observable that emits items that are the result of applying a specified function to pairs of * values, one each from the source Observable and another specified Observable. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/zip.png"> * <p> * {@code zip} does not operate by default on a particular {@link Scheduler}. * * @param <T2> * the type of items emitted by the {@code other} Observable * @param <R> * the type of items emitted by the resulting Observable * @param other * the other Observable * @param zipFunction * a function that combines the pairs of items from the two Observables to generate the items to * be emitted by the resulting Observable * @return an Observable that pairs up values from the source Observable and the {@code other} Observable * and emits the results of {@code zipFunction} applied to these pairs */ public final <T2, R> Observable<R> zip(Observable<? extends T2> other, Func2<? super T, ? super T2, ? extends R> zipFunction) { return zip(this, other, zipFunction); } /** * An Observable that never sends any information to an {@link Observer}. * This Observable is useful primarily for testing purposes. * * @param <T> * the type of item (not) emitted by the Observable */ private static class NeverObservable<T> extends Observable<T> { public NeverObservable() { super(new OnSubscribe<T>() { @Override public void call(Subscriber<? super T> observer) { // do nothing } }); } } /** * An Observable that invokes {@link Observer#onError onError} when the {@link Observer} subscribes to it. * * @param <T> * the type of item (ostensibly) emitted by the Observable */ private static class ThrowObservable<T> extends Observable<T> { public ThrowObservable(final Throwable exception) { super(new OnSubscribe<T>() { /** * Accepts an {@link Observer} and calls its {@link Observer#onError onError} method. * * @param observer * an {@link Observer} of this Observable */ @Override public void call(Subscriber<? super T> observer) { observer.onError(exception); } }); } } }
apache-2.0
cvandeplas/plaso
plaso/parsers/winevtx.py
4809
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2013 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Parser for Windows XML EventLog (EVTX) files.""" import logging import pyevtx from plaso.events import time_events from plaso.lib import errors from plaso.lib import eventdata from plaso.parsers import interface from plaso.parsers import manager class WinEvtxRecordEvent(time_events.FiletimeEvent): """Convenience class for a Windows XML EventLog (EVTX) record event.""" DATA_TYPE = 'windows:evtx:record' def __init__(self, evtx_record, recovered=False): """Initializes the event. Args: evtx_record: The EVTX record (pyevtx.record). recovered: Boolean value to indicate the record was recovered, False by default. """ try: timestamp = evtx_record.get_written_time_as_integer() except OverflowError as exception: logging.warning( u'Unable to read the timestamp from record with error: {0:s}'.format( exception)) timestamp = 0 super(WinEvtxRecordEvent, self).__init__( timestamp, eventdata.EventTimestamp.WRITTEN_TIME) self.recovered = recovered self.offset = evtx_record.offset try: self.record_number = evtx_record.identifier except OverflowError as exception: logging.warning( u'Unable to assign the record number with error: {0:s}.'.format( exception)) try: self.event_identifier = evtx_record.event_identifier except OverflowError as exception: logging.warning( u'Unable to assign the event identifier with error: {0:s}.'.format( exception)) self.event_level = evtx_record.event_level self.source_name = evtx_record.source_name # Computer name is the value stored in the event record and does not # necessarily corresponds with the actual hostname. self.computer_name = evtx_record.computer_name self.user_sid = evtx_record.user_security_identifier self.strings = list(evtx_record.strings) self.xml_string = evtx_record.xml_string class WinEvtxParser(interface.BaseParser): """Parses Windows XML EventLog (EVTX) files.""" NAME = 'winevtx' DESCRIPTION = u'Parser for Windows XML EventLog (EVTX) files.' def Parse(self, parser_context, file_entry): """Extract data from a Windows XML EventLog (EVTX) file. Args: parser_context: A parser context object (instance of ParserContext). file_entry: A file entry object (instance of dfvfs.FileEntry). """ file_object = file_entry.GetFileObject() evtx_file = pyevtx.file() evtx_file.set_ascii_codepage(parser_context.codepage) try: evtx_file.open_file_object(file_object) except IOError as exception: evtx_file.close() file_object.close() raise errors.UnableToParseFile( u'[{0:s}] unable to parse file {1:s} with error: {2:s}'.format( self.NAME, file_entry.name, exception)) for record_index in range(0, evtx_file.number_of_records): try: evtx_record = evtx_file.get_record(record_index) event_object = WinEvtxRecordEvent(evtx_record) parser_context.ProduceEvent( event_object, parser_name=self.NAME, file_entry=file_entry) except IOError as exception: logging.warning(( u'[{0:s}] unable to parse event record: {1:d} in file: {2:s} ' u'with error: {3:s}').format( self.NAME, record_index, file_entry.name, exception)) for record_index in range(0, evtx_file.number_of_recovered_records): try: evtx_record = evtx_file.get_recovered_record(record_index) event_object = WinEvtxRecordEvent(evtx_record, recovered=True) parser_context.ProduceEvent( event_object, parser_name=self.NAME, file_entry=file_entry) except IOError as exception: logging.debug(( u'[{0:s}] unable to parse recovered event record: {1:d} in file: ' u'{2:s} with error: {3:s}').format( self.NAME, record_index, file_entry.name, exception)) evtx_file.close() file_object.close() manager.ParsersManager.RegisterParser(WinEvtxParser)
apache-2.0
HewlettPackard/oneview-sdk-ruby
spec/integration/resource/api200/event/create_spec.rb
830
# (C) Copyright 2017 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # You may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. require 'spec_helper' klass = OneviewSDK::Event RSpec.describe klass, integration: true, type: CREATE, sequence: seq(klass) do let(:current_client) { $client } include_examples 'EventCreateExample', 'integration context' end
apache-2.0
whisher/angular-expresso-chat
server/config/env/development.js
248
'use strict'; module.exports = { db: 'mongodb://' + (process.env.DB_PORT_27017_TCP_ADDR || 'localhost') + '/angular-expresso-chat-dev', debug: true, mongoose: { debug: false }, app: { name: 'Angular Express - Mean stack' } };
apache-2.0
vespa-engine/vespa
searchcore/src/tests/proton/documentdb/documentbucketmover/documentbucketmover_test.cpp
23578
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "bucketmover_common.h" #include <vespa/searchcore/proton/server/bucketmovejob.h> #include <vespa/searchcore/proton/server/executor_thread_service.h> #include <vespa/searchcore/proton/server/document_db_maintenance_config.h> #include <vespa/persistence/dummyimpl/dummy_bucket_executor.h> #include <vespa/vespalib/util/threadstackexecutor.h> #include <vespa/vespalib/util/lambdatask.h> #include <vespa/vespalib/gtest/gtest.h> #include <vespa/log/log.h> #include <vespa/searchcore/proton/metrics/documentdb_tagged_metrics.h> LOG_SETUP("document_bucket_mover_test"); using namespace proton; using namespace proton::move::test; using document::BucketId; using document::test::makeBucketSpace; using proton::bucketdb::BucketCreateNotifier; using storage::spi::BucketInfo; using BlockedReason = IBlockableMaintenanceJob::BlockedReason; using MoveOperationVector = std::vector<MoveOperation>; using storage::spi::dummy::DummyBucketExecutor; using vespalib::MonitoredRefCount; using vespalib::RetainGuard; using vespalib::ThreadStackExecutor; struct ControllerFixtureBase : public ::testing::Test { test::UserDocumentsBuilder _builder; test::BucketStateCalculator::SP _calc; test::ClusterStateHandler _clusterStateHandler; test::BucketHandler _bucketHandler; MyBucketModifiedHandler _modifiedHandler; std::shared_ptr<bucketdb::BucketDBOwner> _bucketDB; MySubDb _ready; MySubDb _notReady; BucketCreateNotifier _bucketCreateNotifier; test::DiskMemUsageNotifier _diskMemUsageNotifier; MonitoredRefCount _refCount; ThreadStackExecutor _singleExecutor; SyncableExecutorThreadService _master; DummyBucketExecutor _bucketExecutor; MyMoveHandler _moveHandler; DocumentDBTaggedMetrics _metrics; std::shared_ptr<BucketMoveJob> _bmj; MyCountJobRunner _runner; ControllerFixtureBase(const BlockableMaintenanceJobConfig &blockableConfig, bool storeMoveDoneContexts); ~ControllerFixtureBase(); ControllerFixtureBase &addReady(const BucketId &bucket) { _calc->addReady(bucket); return *this; } ControllerFixtureBase &remReady(const BucketId &bucket) { _calc->remReady(bucket); return *this; } ControllerFixtureBase &changeCalc() { _calc->resetAsked(); _moveHandler.reset(); _modifiedHandler.reset(); _clusterStateHandler.notifyClusterStateChanged(_calc); return *this; } ControllerFixtureBase &activateBucket(const BucketId &bucket) { _ready.setBucketState(bucket, true); _bucketHandler.notifyBucketStateChanged(bucket, BucketInfo::ActiveState::ACTIVE); return *this; } ControllerFixtureBase &deactivateBucket(const BucketId &bucket) { _ready.setBucketState(bucket, false); _bucketHandler.notifyBucketStateChanged(bucket, BucketInfo::ActiveState::NOT_ACTIVE); return *this; } void failRetrieveForLid(uint32_t lid) { _ready.failRetrieveForLid(lid); _notReady.failRetrieveForLid(lid); } void fixRetriever() { _ready.failRetrieveForLid(0); _notReady.failRetrieveForLid(0); } const MoveOperationVector &docsMoved() const { return _moveHandler._moves; } const std::vector<BucketId> &bucketsModified() const { return _modifiedHandler._modified; } const BucketId::List &calcAsked() const { return _calc->asked(); } size_t numPending() { _bmj->updateMetrics(_metrics); return _metrics.bucketMove.bucketsPending.getLast(); } void runLoop() { while (!_bmj->isBlocked() && !_bmj->run()) { } } void sync() { _bucketExecutor.sync(); _master.sync(); _master.sync(); // Handle that master schedules onto master again } template <typename FunctionType> void masterExecute(FunctionType &&function) { _master.execute(vespalib::makeLambdaTask(std::forward<FunctionType>(function))); _master.sync(); } }; ControllerFixtureBase::ControllerFixtureBase(const BlockableMaintenanceJobConfig &blockableConfig, bool storeMoveDoneContexts) : _builder(), _calc(std::make_shared<test::BucketStateCalculator>()), _bucketHandler(), _modifiedHandler(), _bucketDB(std::make_shared<bucketdb::BucketDBOwner>()), _ready(_builder.getRepo(), _bucketDB, 1, SubDbType::READY), _notReady(_builder.getRepo(), _bucketDB, 2, SubDbType::NOTREADY), _bucketCreateNotifier(), _diskMemUsageNotifier(), _refCount(), _singleExecutor(1, 0x10000), _master(_singleExecutor), _bucketExecutor(4), _moveHandler(*_bucketDB, storeMoveDoneContexts), _metrics("test", 1), _bmj(BucketMoveJob::create(_calc, RetainGuard(_refCount), _moveHandler, _modifiedHandler, _master, _bucketExecutor, _ready._subDb, _notReady._subDb, _bucketCreateNotifier, _clusterStateHandler, _bucketHandler, _diskMemUsageNotifier, blockableConfig, "test", makeBucketSpace())), _runner(*_bmj) { } ControllerFixtureBase::~ControllerFixtureBase() = default; constexpr double RESOURCE_LIMIT_FACTOR = 1.0; constexpr uint32_t MAX_OUTSTANDING_OPS = 10; const BlockableMaintenanceJobConfig BLOCKABLE_CONFIG(RESOURCE_LIMIT_FACTOR, MAX_OUTSTANDING_OPS); struct ControllerFixture : public ControllerFixtureBase { ControllerFixture(const BlockableMaintenanceJobConfig &blockableConfig = BLOCKABLE_CONFIG) : ControllerFixtureBase(blockableConfig, blockableConfig.getMaxOutstandingMoveOps() != MAX_OUTSTANDING_OPS) { _builder.createDocs(1, 1, 4); // 3 docs _builder.createDocs(2, 4, 6); // 2 docs _ready.insertDocs(_builder.getDocs()); _builder.clearDocs(); _builder.createDocs(3, 1, 3); // 2 docs _builder.createDocs(4, 3, 6); // 3 docs _notReady.insertDocs(_builder.getDocs()); } }; struct OnlyReadyControllerFixture : public ControllerFixtureBase { OnlyReadyControllerFixture() : ControllerFixtureBase(BLOCKABLE_CONFIG, false) { _builder.createDocs(1, 1, 2); // 1 docs _builder.createDocs(2, 2, 4); // 2 docs _builder.createDocs(3, 4, 7); // 3 docs _builder.createDocs(4, 7, 11); // 4 docs _ready.insertDocs(_builder.getDocs()); } }; TEST_F(ControllerFixture, require_that_nothing_is_moved_if_bucket_state_says_so) { EXPECT_TRUE(_bmj->done()); addReady(_ready.bucket(1)); addReady(_ready.bucket(2)); _bmj->recompute(); masterExecute([this]() { EXPECT_TRUE(_bmj->scanAndMove(4, 3)); EXPECT_TRUE(_bmj->done()); }); EXPECT_TRUE(docsMoved().empty()); EXPECT_TRUE(bucketsModified().empty()); } TEST_F(ControllerFixture, require_that_not_ready_bucket_is_moved_to_ready_if_bucket_state_says_so) { // bucket 4 should be moved addReady(_ready.bucket(1)); addReady(_ready.bucket(2)); addReady(_notReady.bucket(4)); EXPECT_EQ(0, numPending()); _bmj->recompute(); EXPECT_EQ(1, numPending()); masterExecute([this]() { EXPECT_FALSE(_bmj->done()); EXPECT_TRUE(_bmj->scanAndMove(4, 3)); EXPECT_TRUE(_bmj->done()); }); sync(); EXPECT_EQ(0, numPending()); EXPECT_EQ(3u, docsMoved().size()); assertEqual(_notReady.bucket(4), _notReady.docs(4)[0], 2, 1, docsMoved()[0]); assertEqual(_notReady.bucket(4), _notReady.docs(4)[1], 2, 1, docsMoved()[1]); assertEqual(_notReady.bucket(4), _notReady.docs(4)[2], 2, 1, docsMoved()[2]); ASSERT_EQ(1u, bucketsModified().size()); EXPECT_EQ(_notReady.bucket(4), bucketsModified()[0]); } TEST_F(ControllerFixture, require_that_ready_bucket_is_moved_to_not_ready_if_bucket_state_says_so) { // bucket 2 should be moved addReady(_ready.bucket(1)); _bmj->recompute(); masterExecute([this]() { EXPECT_FALSE(_bmj->done()); EXPECT_TRUE(_bmj->scanAndMove(4, 3)); EXPECT_TRUE(_bmj->done()); }); sync(); EXPECT_EQ(2u, docsMoved().size()); assertEqual(_ready.bucket(2), _ready.docs(2)[0], 1, 2, docsMoved()[0]); assertEqual(_ready.bucket(2), _ready.docs(2)[1], 1, 2, docsMoved()[1]); EXPECT_EQ(1u, bucketsModified().size()); EXPECT_EQ(_ready.bucket(2), bucketsModified()[0]); } TEST_F(ControllerFixture, require_that_bucket_is_moved_even_with_error) { // bucket 2 should be moved addReady(_ready.bucket(1)); _bmj->recompute(); failRetrieveForLid(5); masterExecute([this]() { EXPECT_FALSE(_bmj->done()); EXPECT_TRUE(_bmj->scanAndMove(4, 3)); EXPECT_TRUE(_bmj->done()); }); sync(); EXPECT_FALSE(_bmj->done()); fixRetriever(); masterExecute([this]() { EXPECT_TRUE(_bmj->scanAndMove(4, 3)); EXPECT_TRUE(_bmj->done()); }); sync(); EXPECT_EQ(2u, docsMoved().size()); assertEqual(_ready.bucket(2), _ready.docs(2)[0], 1, 2, docsMoved()[0]); assertEqual(_ready.bucket(2), _ready.docs(2)[1], 1, 2, docsMoved()[1]); EXPECT_EQ(1u, bucketsModified().size()); EXPECT_EQ(_ready.bucket(2), bucketsModified()[0]); } TEST_F(ControllerFixture, require_that_we_move_buckets_in_several_steps) { // bucket 2, 3, and 4 should be moved addReady(_ready.bucket(1)); addReady(_notReady.bucket(3)); addReady(_notReady.bucket(4)); _bmj->recompute(); EXPECT_EQ(3, numPending()); masterExecute([this]() { EXPECT_FALSE(_bmj->done()); EXPECT_FALSE(_bmj->scanAndMove(1, 2)); EXPECT_FALSE(_bmj->done()); }); sync(); EXPECT_EQ(2, numPending()); EXPECT_EQ(2u, docsMoved().size()); masterExecute([this]() { EXPECT_FALSE(_bmj->scanAndMove(1, 2)); EXPECT_FALSE(_bmj->done()); }); sync(); EXPECT_EQ(2, numPending()); EXPECT_EQ(4u, docsMoved().size()); masterExecute([this]() { EXPECT_FALSE(_bmj->scanAndMove(1, 2)); EXPECT_FALSE(_bmj->done()); }); sync(); EXPECT_EQ(1, numPending()); EXPECT_EQ(6u, docsMoved().size()); // move bucket 4, docs 3 masterExecute([this]() { EXPECT_TRUE(_bmj->scanAndMove(1, 2)); EXPECT_TRUE(_bmj->done()); }); sync(); EXPECT_EQ(0, numPending()); EXPECT_EQ(7u, docsMoved().size()); EXPECT_EQ(3u, bucketsModified().size()); EXPECT_EQ(_ready.bucket(2), bucketsModified()[0]); EXPECT_EQ(_notReady.bucket(3), bucketsModified()[1]); EXPECT_EQ(_notReady.bucket(4), bucketsModified()[2]); } TEST_F(ControllerFixture, require_that_last_bucket_is_moved_before_reporting_done) { // bucket 4 should be moved addReady(_ready.bucket(1)); addReady(_ready.bucket(2)); addReady(_notReady.bucket(4)); _bmj->recompute(); masterExecute([this]() { EXPECT_FALSE(_bmj->done()); EXPECT_FALSE(_bmj->scanAndMove(1, 1)); EXPECT_FALSE(_bmj->done()); }); sync(); EXPECT_EQ(1u, docsMoved().size()); EXPECT_EQ(4u, calcAsked().size()); masterExecute([this]() { EXPECT_TRUE(_bmj->scanAndMove(1, 2)); EXPECT_TRUE(_bmj->done()); }); sync(); EXPECT_EQ(3u, docsMoved().size()); EXPECT_EQ(4u, calcAsked().size()); } TEST_F(ControllerFixture, require_that_active_bucket_is_not_moved_from_ready_to_not_ready_until_being_not_active) { // bucket 1 should be moved but is active addReady(_ready.bucket(2)); _bmj->recompute(); EXPECT_FALSE(_bmj->done()); activateBucket(_ready.bucket(1)); masterExecute([this]() { EXPECT_TRUE(_bmj->scanAndMove(4, 3)); // scan all, delay active bucket 1 EXPECT_TRUE(_bmj->done()); }); sync(); EXPECT_EQ(0u, docsMoved().size()); EXPECT_EQ(0u, bucketsModified().size()); deactivateBucket(_ready.bucket(1)); masterExecute([this]() { EXPECT_FALSE(_bmj->done()); EXPECT_TRUE(_bmj->scanAndMove(4, 3)); // move delayed and de-activated bucket 1 EXPECT_TRUE(_bmj->done()); }); sync(); EXPECT_EQ(3u, docsMoved().size()); EXPECT_EQ(1u, bucketsModified().size()); EXPECT_EQ(_ready.bucket(1), bucketsModified()[0]); } TEST_F(ControllerFixture, require_that_current_bucket_moving_is_cancelled_when_we_change_calculator) { // bucket 1 should be moved addReady(_ready.bucket(2)); masterExecute([this]() { _bmj->recompute(); _bmj->scanAndMove(1, 1); EXPECT_FALSE(_bmj->done()); }); sync(); EXPECT_EQ(1u, docsMoved().size()); EXPECT_EQ(4u, calcAsked().size()); masterExecute([this]() { changeCalc(); // Not cancelled, bucket 1 still moving to notReady EXPECT_EQ(4u, calcAsked().size()); EXPECT_EQ(_ready.bucket(1), calcAsked()[0]); _calc->resetAsked(); _bmj->scanAndMove(1, 1); EXPECT_FALSE(_bmj->done()); }); sync(); EXPECT_EQ(1u, docsMoved().size()); EXPECT_EQ(0u, calcAsked().size()); addReady(_ready.bucket(1)); masterExecute([this]() { changeCalc(); // cancelled, bucket 1 no longer moving to notReady EXPECT_EQ(4u, calcAsked().size()); EXPECT_EQ(_ready.bucket(1), calcAsked()[0]); _calc->resetAsked(); remReady(_ready.bucket(1)); _calc->resetAsked(); changeCalc(); // not cancelled. No active bucket move EXPECT_EQ(4u, calcAsked().size()); _bmj->scanAndMove(1, 1); }); sync(); EXPECT_EQ(1u, docsMoved().size()); EXPECT_EQ(4u, calcAsked().size()); EXPECT_EQ(_ready.bucket(2), calcAsked()[1]); EXPECT_EQ(_notReady.bucket(3), calcAsked()[2]); masterExecute([this]() { _bmj->scanAndMove(2, 3); }); EXPECT_TRUE(_bmj->done()); sync(); EXPECT_EQ(3u, docsMoved().size()); EXPECT_EQ(4u, calcAsked().size()); EXPECT_EQ(_notReady.bucket(4), calcAsked()[3]); EXPECT_EQ(_ready.bucket(1), calcAsked()[0]); } TEST_F(ControllerFixture, require_that_de_activated_bucket_is_not_moved_if_new_calculator_does_not_say_so) { // bucket 1 should be moved addReady(_ready.bucket(2)); _bmj->recompute(); masterExecute([this]() { activateBucket(_ready.bucket(1)); _bmj->scanAndMove(4, 3); // scan all, delay active bucket 1 }); sync(); EXPECT_EQ(0u, docsMoved().size()); EXPECT_EQ(0u, bucketsModified().size()); masterExecute([this]() { deactivateBucket(_ready.bucket(1)); addReady(_ready.bucket(1)); changeCalc(); _bmj->scanAndMove(4, 3); // consider delayed bucket 3 }); sync(); EXPECT_EQ(0u, docsMoved().size()); EXPECT_EQ(0u, bucketsModified().size()); EXPECT_EQ(4u, calcAsked().size()); EXPECT_EQ(_ready.bucket(1), calcAsked()[0]); } TEST_F(ControllerFixture, ready_bucket_not_moved_to_not_ready_if_node_is_marked_as_retired) { _calc->setNodeRetired(true); // Bucket 2 would be moved from ready to not ready in a non-retired case, but not when retired. addReady(_ready.bucket(1)); masterExecute([this]() { _bmj->recompute(); _bmj->scanAndMove(4, 3); EXPECT_TRUE(_bmj->done()); }); sync(); EXPECT_EQ(0u, docsMoved().size()); } // Technically this should never happen since a retired node is never in the ideal state, // but test this case for the sake of completion. TEST_F(ControllerFixture, inactive_not_ready_bucket_not_moved_to_ready_if_node_is_marked_as_retired) { _calc->setNodeRetired(true); addReady(_ready.bucket(1)); addReady(_ready.bucket(2)); addReady(_notReady.bucket(3)); masterExecute([this]() { _bmj->recompute(); _bmj->scanAndMove(4, 3); EXPECT_TRUE(_bmj->done()); }); sync(); EXPECT_EQ(0u, docsMoved().size()); } TEST_F(ControllerFixture, explicitly_active_not_ready_bucket_can_be_moved_to_ready_even_if_node_is_marked_as_retired) { _calc->setNodeRetired(true); addReady(_ready.bucket(1)); addReady(_ready.bucket(2)); addReady(_notReady.bucket(3)); _bmj->recompute(); masterExecute([this]() { activateBucket(_notReady.bucket(3)); _bmj->scanAndMove(4, 3); EXPECT_TRUE(_bmj->done()); }); sync(); ASSERT_EQ(2u, docsMoved().size()); assertEqual(_notReady.bucket(3), _notReady.docs(3)[0], 2, 1, docsMoved()[0]); assertEqual(_notReady.bucket(3), _notReady.docs(3)[1], 2, 1, docsMoved()[1]); ASSERT_EQ(1u, bucketsModified().size()); EXPECT_EQ(_notReady.bucket(3), bucketsModified()[0]); } TEST_F(ControllerFixture, require_that_notifyCreateBucket_causes_bucket_to_be_reconsidered_by_job) { EXPECT_TRUE(_bmj->done()); addReady(_ready.bucket(1)); addReady(_ready.bucket(2)); runLoop(); EXPECT_TRUE(_bmj->done()); sync(); EXPECT_TRUE(docsMoved().empty()); EXPECT_TRUE(bucketsModified().empty()); addReady(_notReady.bucket(3)); // bucket 3 now ready, no notify EXPECT_TRUE(_bmj->done()); // move job still believes work done sync(); EXPECT_TRUE(bucketsModified().empty()); masterExecute([this]() { _bmj->notifyCreateBucket(_bucketDB->takeGuard(), _notReady.bucket(3)); // reconsider bucket 3 EXPECT_FALSE(_bmj->done()); EXPECT_TRUE(bucketsModified().empty()); }); sync(); EXPECT_TRUE(bucketsModified().empty()); runLoop(); EXPECT_TRUE(_bmj->done()); sync(); EXPECT_EQ(1u, bucketsModified().size()); EXPECT_EQ(2u, docsMoved().size()); } struct ResourceLimitControllerFixture : public ControllerFixture { ResourceLimitControllerFixture(double resourceLimitFactor = RESOURCE_LIMIT_FACTOR) : ControllerFixture(BlockableMaintenanceJobConfig(resourceLimitFactor, MAX_OUTSTANDING_OPS)) {} void testJobStopping(DiskMemUsageState blockingUsageState) { // Bucket 1 should be moved addReady(_ready.bucket(2)); _bmj->recompute(); EXPECT_FALSE(_bmj->done()); // Note: This depends on _bmj->run() moving max 1 documents EXPECT_FALSE(_bmj->run()); sync(); EXPECT_EQ(1u, docsMoved().size()); EXPECT_EQ(0u, bucketsModified().size()); // Notify that we've over limit _diskMemUsageNotifier.notify(blockingUsageState); EXPECT_TRUE(_bmj->run()); sync(); EXPECT_EQ(1u, docsMoved().size()); EXPECT_EQ(0u, bucketsModified().size()); // Notify that we've under limit _diskMemUsageNotifier.notify(DiskMemUsageState()); EXPECT_FALSE(_bmj->run()); sync(); EXPECT_EQ(2u, docsMoved().size()); EXPECT_EQ(0u, bucketsModified().size()); } void testJobNotStopping(DiskMemUsageState blockingUsageState) { // Bucket 1 should be moved addReady(_ready.bucket(2)); _bmj->recompute(); EXPECT_FALSE(_bmj->done()); // Note: This depends on _bmj->run() moving max 1 documents EXPECT_FALSE(_bmj->run()); sync(); EXPECT_EQ(1u, docsMoved().size()); EXPECT_EQ(0u, bucketsModified().size()); // Notify that we've over limit, but not over adjusted limit _diskMemUsageNotifier.notify(blockingUsageState); EXPECT_FALSE(_bmj->run()); sync(); EXPECT_EQ(2u, docsMoved().size()); EXPECT_EQ(0u, bucketsModified().size()); } }; struct ResourceLimitControllerFixture_1_2 : public ResourceLimitControllerFixture { ResourceLimitControllerFixture_1_2() : ResourceLimitControllerFixture(1.2) {} }; TEST_F(ResourceLimitControllerFixture, require_that_bucket_move_stops_when_disk_limit_is_reached) { testJobStopping(DiskMemUsageState(ResourceUsageState(0.7, 0.8), ResourceUsageState())); } TEST_F(ResourceLimitControllerFixture, require_that_bucket_move_stops_when_memory_limit_is_reached) { testJobStopping(DiskMemUsageState(ResourceUsageState(), ResourceUsageState(0.7, 0.8))); } TEST_F(ResourceLimitControllerFixture_1_2, require_that_bucket_move_uses_resource_limit_factor_for_disk_resource_limit) { testJobNotStopping(DiskMemUsageState(ResourceUsageState(0.7, 0.8), ResourceUsageState())); } TEST_F(ResourceLimitControllerFixture_1_2, require_that_bucket_move_uses_resource_limit_factor_for_memory_resource_limit) { testJobNotStopping(DiskMemUsageState(ResourceUsageState(), ResourceUsageState(0.7, 0.8))); } struct MaxOutstandingMoveOpsFixture : public ControllerFixtureBase { MaxOutstandingMoveOpsFixture(uint32_t maxOutstandingOps) : ControllerFixtureBase(BlockableMaintenanceJobConfig(RESOURCE_LIMIT_FACTOR, maxOutstandingOps), true) { _builder.createDocs(1, 1, 2); _builder.createDocs(2, 2, 3); _builder.createDocs(3, 3, 4); _builder.createDocs(4, 4, 5); _ready.insertDocs(_builder.getDocs()); _builder.clearDocs(); _builder.createDocs(11, 1, 2); _builder.createDocs(12, 2, 3); _builder.createDocs(13, 3, 4); _builder.createDocs(14, 4, 5); _notReady.insertDocs(_builder.getDocs()); addReady(_ready.bucket(3)); _bmj->recompute(); } void assertRunToBlocked() { EXPECT_TRUE(_bmj->run()); // job becomes blocked as max outstanding limit is reached EXPECT_FALSE(_bmj->done()); EXPECT_TRUE(_bmj->isBlocked()); EXPECT_TRUE(_bmj->isBlocked(BlockedReason::OUTSTANDING_OPS)); } void assertRunToNotBlocked() { EXPECT_FALSE(_bmj->run()); EXPECT_FALSE(_bmj->done()); EXPECT_FALSE(_bmj->isBlocked()); } void assertRunToFinished() { EXPECT_TRUE(_bmj->run()); EXPECT_TRUE(_bmj->done()); EXPECT_FALSE(_bmj->isBlocked()); } void assertDocsMoved(uint32_t expDocsMovedCnt, uint32_t expMoveContextsCnt) { EXPECT_EQ(expDocsMovedCnt, docsMoved().size()); EXPECT_EQ(expMoveContextsCnt, _moveHandler._moveDoneContexts.size()); } void unblockJob(uint32_t expRunnerCnt) { _moveHandler.clearMoveDoneContexts(); // unblocks job and try to execute it via runner EXPECT_EQ(expRunnerCnt, _runner.runCount); EXPECT_FALSE(_bmj->isBlocked()); } }; struct MaxOutstandingMoveOpsFixture_1 : public MaxOutstandingMoveOpsFixture { MaxOutstandingMoveOpsFixture_1() : MaxOutstandingMoveOpsFixture(1) {} }; struct MaxOutstandingMoveOpsFixture_2 : public MaxOutstandingMoveOpsFixture { MaxOutstandingMoveOpsFixture_2() : MaxOutstandingMoveOpsFixture(2) {} }; TEST_F(MaxOutstandingMoveOpsFixture_1, require_that_bucket_move_job_is_blocked_if_it_has_too_many_outstanding_move_operations_max_1) { assertRunToBlocked(); sync(); assertDocsMoved(1, 1); assertRunToBlocked(); assertDocsMoved(1, 1); unblockJob(1); assertRunToBlocked(); sync(); assertDocsMoved(2, 1); unblockJob(2); assertRunToBlocked(); sync(); assertDocsMoved(3, 1); unblockJob(3); assertRunToFinished(); sync(); assertDocsMoved(3, 0); } TEST_F(MaxOutstandingMoveOpsFixture_2, require_that_bucket_move_job_is_blocked_if_it_has_too_many_outstanding_move_operations_max_2) { assertRunToNotBlocked(); sync(); assertDocsMoved(1, 1); assertRunToBlocked(); sync(); assertDocsMoved(2, 2); unblockJob(1); assertRunToFinished(); sync(); assertDocsMoved(3, 1); } GTEST_MAIN_RUN_ALL_TESTS()
apache-2.0
mathews/orchastack-core
orchastack.core.security/orchastack.core.security.shiro.ext/src/main/java/orchastack/core/security/shiro/ext/Serializer.java
817
package orchastack.core.security.shiro.ext; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Serializer { public static byte[] serialize(Object msg) throws Exception { if (msg == null) return null; ByteArrayOutputStream bytmesg = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bytmesg); out.writeObject(msg); out.close(); return bytmesg.toByteArray(); } public static Object deserialize(byte[] msgByte) throws Exception { if (msgByte == null) return null; ByteArrayInputStream bytmesg = new ByteArrayInputStream(msgByte); ObjectInputStream in = new ObjectInputStream(bytmesg); Object msg = in.readObject(); in.close(); return msg; } }
apache-2.0
lianying/asdf
src/main/java/com/taobao/api/response/TmallProductSpecPicUploadResponse.java
665
package com.taobao.api.response; import com.taobao.api.internal.mapping.ApiField; import com.taobao.api.TaobaoResponse; /** * TOP API: tmall.product.spec.pic.upload response. * * @author auto create * @since 1.0, null */ public class TmallProductSpecPicUploadResponse extends TaobaoResponse { private static final long serialVersionUID = 4182722346614787972L; /** * 上传成功的产品规格认证图片url */ @ApiField("spec_pic_url") private String specPicUrl; public void setSpecPicUrl(String specPicUrl) { this.specPicUrl = specPicUrl; } public String getSpecPicUrl( ) { return this.specPicUrl; } }
apache-2.0
matsprea/omim
indexer/indexer_tests/postcodes_tests.cpp
1076
#include "testing/testing.hpp" #include "indexer/postcodes.hpp" #include "coding/reader.hpp" #include "coding/writer.hpp" #include <cstdint> #include <map> #include <string> using namespace indexer; using namespace std; using Buffer = vector<uint8_t>; UNIT_TEST(Postcodes_Smoke) { map<uint32_t, string> const features = { {1, "127001"}, {5, "aa1 1aa"}, {10, "123"}, {20, "aaa 1111"}}; Buffer buffer; { PostcodesBuilder builder; for (auto const & feature : features) builder.Put(feature.first, feature.second); MemWriter<Buffer> writer(buffer); builder.Freeze(writer); } { MemReader reader(buffer.data(), buffer.size()); auto postcodes = Postcodes::Load(reader); TEST(postcodes.get(), ()); string actual; for (uint32_t i = 0; i < 100; ++i) { auto const it = features.find(i); if (it != features.end()) { TEST(postcodes->Get(i, actual), ()); TEST_EQUAL(actual, it->second, ()); } else { TEST(!postcodes->Get(i, actual), ()); } } } }
apache-2.0
CloudCredo/cloudrocker
Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive.go
30119
package archive import ( "archive/tar" "bufio" "bytes" "compress/bzip2" "compress/gzip" "errors" "fmt" "io" "io/ioutil" "os" "os/exec" "path/filepath" "runtime" "strings" "syscall" "github.com/cloudcredo/cloudrocker/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus" "github.com/cloudcredo/cloudrocker/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils" "github.com/cloudcredo/cloudrocker/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools" "github.com/cloudcredo/cloudrocker/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils" "github.com/cloudcredo/cloudrocker/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools" "github.com/cloudcredo/cloudrocker/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/promise" "github.com/cloudcredo/cloudrocker/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" ) type ( // Archive is a type of io.ReadCloser which has two interfaces Read and Closer. Archive io.ReadCloser // Reader is a type of io.Reader. Reader io.Reader // Compression is the state represtents if compressed or not. Compression int // TarChownOptions wraps the chown options UID and GID. TarChownOptions struct { UID, GID int } // TarOptions wraps the tar options. TarOptions struct { IncludeFiles []string ExcludePatterns []string Compression Compression NoLchown bool UIDMaps []idtools.IDMap GIDMaps []idtools.IDMap ChownOpts *TarChownOptions IncludeSourceDir bool // When unpacking, specifies whether overwriting a directory with a // non-directory is allowed and vice versa. NoOverwriteDirNonDir bool // For each include when creating an archive, the included name will be // replaced with the matching name from this map. RebaseNames map[string]string } // Archiver allows the reuse of most utility functions of this package // with a pluggable Untar function. Also, to facilitate the passing of // specific id mappings for untar, an archiver can be created with maps // which will then be passed to Untar operations Archiver struct { Untar func(io.Reader, string, *TarOptions) error UIDMaps []idtools.IDMap GIDMaps []idtools.IDMap } // breakoutError is used to differentiate errors related to breaking out // When testing archive breakout in the unit tests, this error is expected // in order for the test to pass. breakoutError error ) var ( // ErrNotImplemented is the error message of function not implemented. ErrNotImplemented = errors.New("Function not implemented") defaultArchiver = &Archiver{Untar: Untar, UIDMaps: nil, GIDMaps: nil} ) const ( // Uncompressed represents the uncompressed. Uncompressed Compression = iota // Bzip2 is bzip2 compression algorithm. Bzip2 // Gzip is gzip compression algorithm. Gzip // Xz is xz compression algorithm. Xz ) // IsArchive checks if it is a archive by the header. func IsArchive(header []byte) bool { compression := DetectCompression(header) if compression != Uncompressed { return true } r := tar.NewReader(bytes.NewBuffer(header)) _, err := r.Next() return err == nil } // DetectCompression detects the compression algorithm of the source. func DetectCompression(source []byte) Compression { for compression, m := range map[Compression][]byte{ Bzip2: {0x42, 0x5A, 0x68}, Gzip: {0x1F, 0x8B, 0x08}, Xz: {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00}, } { if len(source) < len(m) { logrus.Debugf("Len too short") continue } if bytes.Compare(m, source[:len(m)]) == 0 { return compression } } return Uncompressed } func xzDecompress(archive io.Reader) (io.ReadCloser, <-chan struct{}, error) { args := []string{"xz", "-d", "-c", "-q"} return cmdStream(exec.Command(args[0], args[1:]...), archive) } // DecompressStream decompress the archive and returns a ReaderCloser with the decompressed archive. func DecompressStream(archive io.Reader) (io.ReadCloser, error) { p := pools.BufioReader32KPool buf := p.Get(archive) bs, err := buf.Peek(10) if err != nil { return nil, err } compression := DetectCompression(bs) switch compression { case Uncompressed: readBufWrapper := p.NewReadCloserWrapper(buf, buf) return readBufWrapper, nil case Gzip: gzReader, err := gzip.NewReader(buf) if err != nil { return nil, err } readBufWrapper := p.NewReadCloserWrapper(buf, gzReader) return readBufWrapper, nil case Bzip2: bz2Reader := bzip2.NewReader(buf) readBufWrapper := p.NewReadCloserWrapper(buf, bz2Reader) return readBufWrapper, nil case Xz: xzReader, chdone, err := xzDecompress(buf) if err != nil { return nil, err } readBufWrapper := p.NewReadCloserWrapper(buf, xzReader) return ioutils.NewReadCloserWrapper(readBufWrapper, func() error { <-chdone return readBufWrapper.Close() }), nil default: return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) } } // CompressStream compresses the dest with specified compression algorithm. func CompressStream(dest io.WriteCloser, compression Compression) (io.WriteCloser, error) { p := pools.BufioWriter32KPool buf := p.Get(dest) switch compression { case Uncompressed: writeBufWrapper := p.NewWriteCloserWrapper(buf, buf) return writeBufWrapper, nil case Gzip: gzWriter := gzip.NewWriter(dest) writeBufWrapper := p.NewWriteCloserWrapper(buf, gzWriter) return writeBufWrapper, nil case Bzip2, Xz: // archive/bzip2 does not support writing, and there is no xz support at all // However, this is not a problem as docker only currently generates gzipped tars return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) default: return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) } } // Extension returns the extension of a file that uses the specified compression algorithm. func (compression *Compression) Extension() string { switch *compression { case Uncompressed: return "tar" case Bzip2: return "tar.bz2" case Gzip: return "tar.gz" case Xz: return "tar.xz" } return "" } type tarAppender struct { TarWriter *tar.Writer Buffer *bufio.Writer // for hardlink mapping SeenFiles map[uint64]string UIDMaps []idtools.IDMap GIDMaps []idtools.IDMap } // canonicalTarName provides a platform-independent and consistent posix-style //path for files and directories to be archived regardless of the platform. func canonicalTarName(name string, isDir bool) (string, error) { name, err := CanonicalTarNameForPath(name) if err != nil { return "", err } // suffix with '/' for directories if isDir && !strings.HasSuffix(name, "/") { name += "/" } return name, nil } func (ta *tarAppender) addTarFile(path, name string) error { fi, err := os.Lstat(path) if err != nil { return err } link := "" if fi.Mode()&os.ModeSymlink != 0 { if link, err = os.Readlink(path); err != nil { return err } } hdr, err := tar.FileInfoHeader(fi, link) if err != nil { return err } hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) name, err = canonicalTarName(name, fi.IsDir()) if err != nil { return fmt.Errorf("tar: cannot canonicalize path: %v", err) } hdr.Name = name inode, err := setHeaderForSpecialDevice(hdr, ta, name, fi.Sys()) if err != nil { return err } // if it's not a directory and has more than 1 link, // it's hardlinked, so set the type flag accordingly if !fi.IsDir() && hasHardlinks(fi) { // a link should have a name that it links too // and that linked name should be first in the tar archive if oldpath, ok := ta.SeenFiles[inode]; ok { hdr.Typeflag = tar.TypeLink hdr.Linkname = oldpath hdr.Size = 0 // This Must be here for the writer math to add up! } else { ta.SeenFiles[inode] = name } } capability, _ := system.Lgetxattr(path, "security.capability") if capability != nil { hdr.Xattrs = make(map[string]string) hdr.Xattrs["security.capability"] = string(capability) } //handle re-mapping container ID mappings back to host ID mappings before //writing tar headers/files if ta.UIDMaps != nil || ta.GIDMaps != nil { uid, gid, err := getFileUIDGID(fi.Sys()) if err != nil { return err } xUID, err := idtools.ToContainer(uid, ta.UIDMaps) if err != nil { return err } xGID, err := idtools.ToContainer(gid, ta.GIDMaps) if err != nil { return err } hdr.Uid = xUID hdr.Gid = xGID } if err := ta.TarWriter.WriteHeader(hdr); err != nil { return err } if hdr.Typeflag == tar.TypeReg { file, err := os.Open(path) if err != nil { return err } ta.Buffer.Reset(ta.TarWriter) defer ta.Buffer.Reset(nil) _, err = io.Copy(ta.Buffer, file) file.Close() if err != nil { return err } err = ta.Buffer.Flush() if err != nil { return err } } return nil } func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, Lchown bool, chownOpts *TarChownOptions) error { // hdr.Mode is in linux format, which we can use for sycalls, // but for os.Foo() calls we need the mode converted to os.FileMode, // so use hdrInfo.Mode() (they differ for e.g. setuid bits) hdrInfo := hdr.FileInfo() switch hdr.Typeflag { case tar.TypeDir: // Create directory unless it exists as a directory already. // In that case we just want to merge the two if fi, err := os.Lstat(path); !(err == nil && fi.IsDir()) { if err := os.Mkdir(path, hdrInfo.Mode()); err != nil { return err } } case tar.TypeReg, tar.TypeRegA: // Source is regular file file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, hdrInfo.Mode()) if err != nil { return err } if _, err := io.Copy(file, reader); err != nil { file.Close() return err } file.Close() case tar.TypeBlock, tar.TypeChar, tar.TypeFifo: // Handle this is an OS-specific way if err := handleTarTypeBlockCharFifo(hdr, path); err != nil { return err } case tar.TypeLink: targetPath := filepath.Join(extractDir, hdr.Linkname) // check for hardlink breakout if !strings.HasPrefix(targetPath, extractDir) { return breakoutError(fmt.Errorf("invalid hardlink %q -> %q", targetPath, hdr.Linkname)) } if err := os.Link(targetPath, path); err != nil { return err } case tar.TypeSymlink: // path -> hdr.Linkname = targetPath // e.g. /extractDir/path/to/symlink -> ../2/file = /extractDir/path/2/file targetPath := filepath.Join(filepath.Dir(path), hdr.Linkname) // the reason we don't need to check symlinks in the path (with FollowSymlinkInScope) is because // that symlink would first have to be created, which would be caught earlier, at this very check: if !strings.HasPrefix(targetPath, extractDir) { return breakoutError(fmt.Errorf("invalid symlink %q -> %q", path, hdr.Linkname)) } if err := os.Symlink(hdr.Linkname, path); err != nil { return err } case tar.TypeXGlobalHeader: logrus.Debugf("PAX Global Extended Headers found and ignored") return nil default: return fmt.Errorf("Unhandled tar header type %d\n", hdr.Typeflag) } // Lchown is not supported on Windows. if Lchown && runtime.GOOS != "windows" { if chownOpts == nil { chownOpts = &TarChownOptions{UID: hdr.Uid, GID: hdr.Gid} } if err := os.Lchown(path, chownOpts.UID, chownOpts.GID); err != nil { return err } } for key, value := range hdr.Xattrs { if err := system.Lsetxattr(path, key, []byte(value), 0); err != nil { return err } } // There is no LChmod, so ignore mode for symlink. Also, this // must happen after chown, as that can modify the file mode if err := handleLChmod(hdr, path, hdrInfo); err != nil { return err } // system.Chtimes doesn't support a NOFOLLOW flag atm if hdr.Typeflag == tar.TypeLink { if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) { if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil { return err } } } else if hdr.Typeflag != tar.TypeSymlink { if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil { return err } } else { ts := []syscall.Timespec{timeToTimespec(hdr.AccessTime), timeToTimespec(hdr.ModTime)} if err := system.LUtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform { return err } } return nil } // Tar creates an archive from the directory at `path`, and returns it as a // stream of bytes. func Tar(path string, compression Compression) (io.ReadCloser, error) { return TarWithOptions(path, &TarOptions{Compression: compression}) } // TarWithOptions creates an archive from the directory at `path`, only including files whose relative // paths are included in `options.IncludeFiles` (if non-nil) or not in `options.ExcludePatterns`. func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) { // Fix the source path to work with long path names. This is a no-op // on platforms other than Windows. srcPath = fixVolumePathPrefix(srcPath) patterns, patDirs, exceptions, err := fileutils.CleanPatterns(options.ExcludePatterns) if err != nil { return nil, err } pipeReader, pipeWriter := io.Pipe() compressWriter, err := CompressStream(pipeWriter, options.Compression) if err != nil { return nil, err } go func() { ta := &tarAppender{ TarWriter: tar.NewWriter(compressWriter), Buffer: pools.BufioWriter32KPool.Get(nil), SeenFiles: make(map[uint64]string), UIDMaps: options.UIDMaps, GIDMaps: options.GIDMaps, } defer func() { // Make sure to check the error on Close. if err := ta.TarWriter.Close(); err != nil { logrus.Debugf("Can't close tar writer: %s", err) } if err := compressWriter.Close(); err != nil { logrus.Debugf("Can't close compress writer: %s", err) } if err := pipeWriter.Close(); err != nil { logrus.Debugf("Can't close pipe writer: %s", err) } }() // this buffer is needed for the duration of this piped stream defer pools.BufioWriter32KPool.Put(ta.Buffer) // In general we log errors here but ignore them because // during e.g. a diff operation the container can continue // mutating the filesystem and we can see transient errors // from this stat, err := os.Lstat(srcPath) if err != nil { return } if !stat.IsDir() { // We can't later join a non-dir with any includes because the // 'walk' will error if "file/." is stat-ed and "file" is not a // directory. So, we must split the source path and use the // basename as the include. if len(options.IncludeFiles) > 0 { logrus.Warn("Tar: Can't archive a file with includes") } dir, base := SplitPathDirEntry(srcPath) srcPath = dir options.IncludeFiles = []string{base} } if len(options.IncludeFiles) == 0 { options.IncludeFiles = []string{"."} } seen := make(map[string]bool) for _, include := range options.IncludeFiles { rebaseName := options.RebaseNames[include] walkRoot := getWalkRoot(srcPath, include) filepath.Walk(walkRoot, func(filePath string, f os.FileInfo, err error) error { if err != nil { logrus.Debugf("Tar: Can't stat file %s to tar: %s", srcPath, err) return nil } relFilePath, err := filepath.Rel(srcPath, filePath) if err != nil || (!options.IncludeSourceDir && relFilePath == "." && f.IsDir()) { // Error getting relative path OR we are looking // at the source directory path. Skip in both situations. return nil } if options.IncludeSourceDir && include == "." && relFilePath != "." { relFilePath = strings.Join([]string{".", relFilePath}, string(filepath.Separator)) } skip := false // If "include" is an exact match for the current file // then even if there's an "excludePatterns" pattern that // matches it, don't skip it. IOW, assume an explicit 'include' // is asking for that file no matter what - which is true // for some files, like .dockerignore and Dockerfile (sometimes) if include != relFilePath { skip, err = fileutils.OptimizedMatches(relFilePath, patterns, patDirs) if err != nil { logrus.Debugf("Error matching %s: %v", relFilePath, err) return err } } if skip { if !exceptions && f.IsDir() { return filepath.SkipDir } return nil } if seen[relFilePath] { return nil } seen[relFilePath] = true // Rename the base resource. if rebaseName != "" { var replacement string if rebaseName != string(filepath.Separator) { // Special case the root directory to replace with an // empty string instead so that we don't end up with // double slashes in the paths. replacement = rebaseName } relFilePath = strings.Replace(relFilePath, include, replacement, 1) } if err := ta.addTarFile(filePath, relFilePath); err != nil { logrus.Debugf("Can't add file %s to tar: %s", filePath, err) } return nil }) } }() return pipeReader, nil } // Unpack unpacks the decompressedArchive to dest with options. func Unpack(decompressedArchive io.Reader, dest string, options *TarOptions) error { tr := tar.NewReader(decompressedArchive) trBuf := pools.BufioReader32KPool.Get(nil) defer pools.BufioReader32KPool.Put(trBuf) var dirs []*tar.Header remappedRootUID, remappedRootGID, err := idtools.GetRootUIDGID(options.UIDMaps, options.GIDMaps) if err != nil { return err } // Iterate through the files in the archive. loop: for { hdr, err := tr.Next() if err == io.EOF { // end of tar archive break } if err != nil { return err } // Normalize name, for safety and for a simple is-root check // This keeps "../" as-is, but normalizes "/../" to "/". Or Windows: // This keeps "..\" as-is, but normalizes "\..\" to "\". hdr.Name = filepath.Clean(hdr.Name) for _, exclude := range options.ExcludePatterns { if strings.HasPrefix(hdr.Name, exclude) { continue loop } } // After calling filepath.Clean(hdr.Name) above, hdr.Name will now be in // the filepath format for the OS on which the daemon is running. Hence // the check for a slash-suffix MUST be done in an OS-agnostic way. if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) { // Not the root directory, ensure that the parent directory exists parent := filepath.Dir(hdr.Name) parentPath := filepath.Join(dest, parent) if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { err = system.MkdirAll(parentPath, 0777) if err != nil { return err } } } path := filepath.Join(dest, hdr.Name) rel, err := filepath.Rel(dest, path) if err != nil { return err } if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { return breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest)) } // If path exits we almost always just want to remove and replace it // The only exception is when it is a directory *and* the file from // the layer is also a directory. Then we want to merge them (i.e. // just apply the metadata from the layer). if fi, err := os.Lstat(path); err == nil { if options.NoOverwriteDirNonDir && fi.IsDir() && hdr.Typeflag != tar.TypeDir { // If NoOverwriteDirNonDir is true then we cannot replace // an existing directory with a non-directory from the archive. return fmt.Errorf("cannot overwrite directory %q with non-directory %q", path, dest) } if options.NoOverwriteDirNonDir && !fi.IsDir() && hdr.Typeflag == tar.TypeDir { // If NoOverwriteDirNonDir is true then we cannot replace // an existing non-directory with a directory from the archive. return fmt.Errorf("cannot overwrite non-directory %q with directory %q", path, dest) } if fi.IsDir() && hdr.Name == "." { continue } if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) { if err := os.RemoveAll(path); err != nil { return err } } } trBuf.Reset(tr) // if the options contain a uid & gid maps, convert header uid/gid // entries using the maps such that lchown sets the proper mapped // uid/gid after writing the file. We only perform this mapping if // the file isn't already owned by the remapped root UID or GID, as // that specific uid/gid has no mapping from container -> host, and // those files already have the proper ownership for inside the // container. if hdr.Uid != remappedRootUID { xUID, err := idtools.ToHost(hdr.Uid, options.UIDMaps) if err != nil { return err } hdr.Uid = xUID } if hdr.Gid != remappedRootGID { xGID, err := idtools.ToHost(hdr.Gid, options.GIDMaps) if err != nil { return err } hdr.Gid = xGID } if err := createTarFile(path, dest, hdr, trBuf, !options.NoLchown, options.ChownOpts); err != nil { return err } // Directory mtimes must be handled at the end to avoid further // file creation in them to modify the directory mtime if hdr.Typeflag == tar.TypeDir { dirs = append(dirs, hdr) } } for _, hdr := range dirs { path := filepath.Join(dest, hdr.Name) if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil { return err } } return nil } // Untar reads a stream of bytes from `archive`, parses it as a tar archive, // and unpacks it into the directory at `dest`. // The archive may be compressed with one of the following algorithms: // identity (uncompressed), gzip, bzip2, xz. // FIXME: specify behavior when target path exists vs. doesn't exist. func Untar(tarArchive io.Reader, dest string, options *TarOptions) error { return untarHandler(tarArchive, dest, options, true) } // UntarUncompressed reads a stream of bytes from `archive`, parses it as a tar archive, // and unpacks it into the directory at `dest`. // The archive must be an uncompressed stream. func UntarUncompressed(tarArchive io.Reader, dest string, options *TarOptions) error { return untarHandler(tarArchive, dest, options, false) } // Handler for teasing out the automatic decompression func untarHandler(tarArchive io.Reader, dest string, options *TarOptions, decompress bool) error { if tarArchive == nil { return fmt.Errorf("Empty archive") } dest = filepath.Clean(dest) if options == nil { options = &TarOptions{} } if options.ExcludePatterns == nil { options.ExcludePatterns = []string{} } r := tarArchive if decompress { decompressedArchive, err := DecompressStream(tarArchive) if err != nil { return err } defer decompressedArchive.Close() r = decompressedArchive } return Unpack(r, dest, options) } // TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other. // If either Tar or Untar fails, TarUntar aborts and returns the error. func (archiver *Archiver) TarUntar(src, dst string) error { logrus.Debugf("TarUntar(%s %s)", src, dst) archive, err := TarWithOptions(src, &TarOptions{Compression: Uncompressed}) if err != nil { return err } defer archive.Close() var options *TarOptions if archiver.UIDMaps != nil || archiver.GIDMaps != nil { options = &TarOptions{ UIDMaps: archiver.UIDMaps, GIDMaps: archiver.GIDMaps, } } return archiver.Untar(archive, dst, options) } // TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other. // If either Tar or Untar fails, TarUntar aborts and returns the error. func TarUntar(src, dst string) error { return defaultArchiver.TarUntar(src, dst) } // UntarPath untar a file from path to a destination, src is the source tar file path. func (archiver *Archiver) UntarPath(src, dst string) error { archive, err := os.Open(src) if err != nil { return err } defer archive.Close() var options *TarOptions if archiver.UIDMaps != nil || archiver.GIDMaps != nil { options = &TarOptions{ UIDMaps: archiver.UIDMaps, GIDMaps: archiver.GIDMaps, } } if err := archiver.Untar(archive, dst, options); err != nil { return err } return nil } // UntarPath is a convenience function which looks for an archive // at filesystem path `src`, and unpacks it at `dst`. func UntarPath(src, dst string) error { return defaultArchiver.UntarPath(src, dst) } // CopyWithTar creates a tar archive of filesystem path `src`, and // unpacks it at filesystem path `dst`. // The archive is streamed directly with fixed buffering and no // intermediary disk IO. func (archiver *Archiver) CopyWithTar(src, dst string) error { srcSt, err := os.Stat(src) if err != nil { return err } if !srcSt.IsDir() { return archiver.CopyFileWithTar(src, dst) } // Create dst, copy src's content into it logrus.Debugf("Creating dest directory: %s", dst) if err := system.MkdirAll(dst, 0755); err != nil { return err } logrus.Debugf("Calling TarUntar(%s, %s)", src, dst) return archiver.TarUntar(src, dst) } // CopyWithTar creates a tar archive of filesystem path `src`, and // unpacks it at filesystem path `dst`. // The archive is streamed directly with fixed buffering and no // intermediary disk IO. func CopyWithTar(src, dst string) error { return defaultArchiver.CopyWithTar(src, dst) } // CopyFileWithTar emulates the behavior of the 'cp' command-line // for a single file. It copies a regular file from path `src` to // path `dst`, and preserves all its metadata. func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { logrus.Debugf("CopyFileWithTar(%s, %s)", src, dst) srcSt, err := os.Stat(src) if err != nil { return err } if srcSt.IsDir() { return fmt.Errorf("Can't copy a directory") } // Clean up the trailing slash. This must be done in an operating // system specific manner. if dst[len(dst)-1] == os.PathSeparator { dst = filepath.Join(dst, filepath.Base(src)) } // Create the holding directory if necessary if err := system.MkdirAll(filepath.Dir(dst), 0700); err != nil { return err } r, w := io.Pipe() errC := promise.Go(func() error { defer w.Close() srcF, err := os.Open(src) if err != nil { return err } defer srcF.Close() hdr, err := tar.FileInfoHeader(srcSt, "") if err != nil { return err } hdr.Name = filepath.Base(dst) hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) remappedRootUID, remappedRootGID, err := idtools.GetRootUIDGID(archiver.UIDMaps, archiver.GIDMaps) if err != nil { return err } // only perform mapping if the file being copied isn't already owned by the // uid or gid of the remapped root in the container if remappedRootUID != hdr.Uid { xUID, err := idtools.ToHost(hdr.Uid, archiver.UIDMaps) if err != nil { return err } hdr.Uid = xUID } if remappedRootGID != hdr.Gid { xGID, err := idtools.ToHost(hdr.Gid, archiver.GIDMaps) if err != nil { return err } hdr.Gid = xGID } tw := tar.NewWriter(w) defer tw.Close() if err := tw.WriteHeader(hdr); err != nil { return err } if _, err := io.Copy(tw, srcF); err != nil { return err } return nil }) defer func() { if er := <-errC; err != nil { err = er } }() err = archiver.Untar(r, filepath.Dir(dst), nil) if err != nil { r.CloseWithError(err) } return err } // CopyFileWithTar emulates the behavior of the 'cp' command-line // for a single file. It copies a regular file from path `src` to // path `dst`, and preserves all its metadata. // // Destination handling is in an operating specific manner depending // where the daemon is running. If `dst` ends with a trailing slash // the final destination path will be `dst/base(src)` (Linux) or // `dst\base(src)` (Windows). func CopyFileWithTar(src, dst string) (err error) { return defaultArchiver.CopyFileWithTar(src, dst) } // cmdStream executes a command, and returns its stdout as a stream. // If the command fails to run or doesn't complete successfully, an error // will be returned, including anything written on stderr. func cmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, <-chan struct{}, error) { chdone := make(chan struct{}) cmd.Stdin = input pipeR, pipeW := io.Pipe() cmd.Stdout = pipeW var errBuf bytes.Buffer cmd.Stderr = &errBuf // Run the command and return the pipe if err := cmd.Start(); err != nil { return nil, nil, err } // Copy stdout to the returned pipe go func() { if err := cmd.Wait(); err != nil { pipeW.CloseWithError(fmt.Errorf("%s: %s", err, errBuf.String())) } else { pipeW.Close() } close(chdone) }() return pipeR, chdone, nil } // NewTempArchive reads the content of src into a temporary file, and returns the contents // of that file as an archive. The archive can only be read once - as soon as reading completes, // the file will be deleted. func NewTempArchive(src Archive, dir string) (*TempArchive, error) { f, err := ioutil.TempFile(dir, "") if err != nil { return nil, err } if _, err := io.Copy(f, src); err != nil { return nil, err } if _, err := f.Seek(0, 0); err != nil { return nil, err } st, err := f.Stat() if err != nil { return nil, err } size := st.Size() return &TempArchive{File: f, Size: size}, nil } // TempArchive is a temporary archive. The archive can only be read once - as soon as reading completes, // the file will be deleted. type TempArchive struct { *os.File Size int64 // Pre-computed from Stat().Size() as a convenience read int64 closed bool } // Close closes the underlying file if it's still open, or does a no-op // to allow callers to try to close the TempArchive multiple times safely. func (archive *TempArchive) Close() error { if archive.closed { return nil } archive.closed = true return archive.File.Close() } func (archive *TempArchive) Read(data []byte) (int, error) { n, err := archive.File.Read(data) archive.read += int64(n) if err != nil || archive.read == archive.Size { archive.Close() os.Remove(archive.File.Name()) } return n, err }
apache-2.0
fungku/netsuite-php
src/Classes/TaxDetails.php
1445
<?php /** * This file is part of the SevenShores/NetSuite library * AND originally from the NetSuite PHP Toolkit. * * New content: * @package ryanwinchester/netsuite-php * @copyright Copyright (c) Ryan Winchester * @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 * @link https://github.com/ryanwinchester/netsuite-php * * Original content: * @copyright Copyright (c) NetSuite Inc. * @license https://raw.githubusercontent.com/ryanwinchester/netsuite-php/master/original/NetSuite%20Application%20Developer%20License%20Agreement.txt * @link http://www.netsuite.com/portal/developers/resources/suitetalk-sample-applications.shtml * * generated: 2019-06-12 10:27:00 AM PDT */ namespace NetSuite\Classes; class TaxDetails { public $taxDetailsReference; public $lineType; public $lineName; public $netAmount; public $grossAmount; public $taxType; public $taxCode; public $taxBasis; public $taxRate; public $taxAmount; public $calcDetail; static $paramtypesmap = array( "taxDetailsReference" => "string", "lineType" => "string", "lineName" => "string", "netAmount" => "float", "grossAmount" => "float", "taxType" => "RecordRef", "taxCode" => "RecordRef", "taxBasis" => "float", "taxRate" => "float", "taxAmount" => "float", "calcDetail" => "string", ); }
apache-2.0
m3db/m3cluster
etcd/watchmanager/manager.go
5176
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package watchmanager import ( "context" "fmt" "time" "github.com/m3db/m3x/log" "github.com/coreos/etcd/clientv3" "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes" "github.com/uber-go/tally" ) // NewWatchManager creates a new watch manager func NewWatchManager(opts Options) (WatchManager, error) { if err := opts.Validate(); err != nil { return nil, err } scope := opts.InstrumentsOptions().MetricsScope() return &manager{ opts: opts, logger: opts.InstrumentsOptions().Logger(), m: metrics{ etcdWatchCreate: scope.Counter("etcd-watch-create"), etcdWatchError: scope.Counter("etcd-watch-error"), etcdWatchReset: scope.Counter("etcd-watch-reset"), }, updateFn: opts.UpdateFn(), tickAndStopFn: opts.TickAndStopFn(), }, nil } type manager struct { opts Options logger log.Logger m metrics updateFn UpdateFn tickAndStopFn TickAndStopFn } type metrics struct { etcdWatchCreate tally.Counter etcdWatchError tally.Counter etcdWatchReset tally.Counter } func (w *manager) watchChanWithTimeout(key string, rev int64) (clientv3.WatchChan, context.CancelFunc, error) { doneCh := make(chan struct{}) ctx, cancelFn := context.WithCancel(clientv3.WithRequireLeader(context.Background())) var watchChan clientv3.WatchChan go func() { wOpts := w.opts.WatchOptions() if rev > 0 { wOpts = append(wOpts, clientv3.WithRev(rev)) } watchChan = w.opts.Watcher().Watch( ctx, key, wOpts..., ) close(doneCh) }() timeout := w.opts.WatchChanInitTimeout() select { case <-doneCh: return watchChan, cancelFn, nil case <-time.After(timeout): cancelFn() return nil, nil, fmt.Errorf("etcd watch create timed out after %s for key: %s", timeout.String(), key) } } func (w *manager) Watch(key string) { ticker := time.Tick(w.opts.WatchChanCheckInterval()) //nolint: megacheck var ( revOverride int64 watchChan clientv3.WatchChan cancelFn context.CancelFunc err error ) for { if watchChan == nil { w.m.etcdWatchCreate.Inc(1) watchChan, cancelFn, err = w.watchChanWithTimeout(key, revOverride) if err != nil { w.logger.Errorf("could not create etcd watch: %v", err) // NB(cw) when we failed to create a etcd watch channel // we do a get for now and will try to recreate the watch chan later if err = w.updateFn(key, nil); err != nil { w.logger.Errorf("failed to get value for key %s: %v", key, err) } // avoid recreating watch channel too frequently time.Sleep(w.opts.WatchChanResetInterval()) continue } } select { case r, ok := <-watchChan: if !ok { // the watch chan is closed, set it to nil so it will be recreated // this is unlikely to happen but just to be defensive cancelFn() watchChan = nil w.logger.Warnf("etcd watch channel closed on key %s, recreating a watch channel", key) // avoid recreating watch channel too frequently time.Sleep(w.opts.WatchChanResetInterval()) w.m.etcdWatchReset.Inc(1) continue } // handle the update if err = r.Err(); err != nil { w.logger.Errorf("received error on watch channel: %v", err) w.m.etcdWatchError.Inc(1) // do not stop here, even though the update contains an error // we still take this chance to attempt a Get() for the latest value // If the current revision has been compacted, set watchChan to // nil so the watch is recreated with a valid start revision if err == rpctypes.ErrCompacted { w.logger.Warnf("recreating watch at revision %d", r.CompactRevision) revOverride = r.CompactRevision watchChan = nil } } if r.IsProgressNotify() { // Do not call updateFn on ProgressNotify as it happens periodically with no update events continue } if err = w.updateFn(key, r.Events); err != nil { w.logger.Errorf("received notification for key %s, but failed to get value: %v", key, err) } case <-ticker: if w.tickAndStopFn(key) { w.logger.Infof("watch on key %s ended", key) return } } } }
apache-2.0
epfl-lara/stainless
frontends/library/stainless/proof/Internal.scala
1754
/* Copyright 2009-2021 EPFL, Lausanne */ package stainless.proof import stainless.lang._ import stainless.annotation._ import stainless.lang.StaticChecks._ /** Internal helper classes and methods for the 'proof' package. */ object Internal { /*** Helper classes for relational reasoning ***/ @library case class WithRel[A, B](x: A, r: (A, B) => Boolean, prop: Boolean) { /** Continue with the next relation. */ def ^^(y: B): RelReasoning[B] = { require(prop ==> r(x, y)) RelReasoning(y, prop && r(x, y)) } /** Add a proof. */ def ^^|(proof: Boolean): WithProof[A, B] = { require(proof) WithProof(x, r, proof, prop) } /** Short-hand for equational reasoning. */ def ==|(proof: Boolean): WithProof[A, A] = { require(proof) WithProof(x, _ == _, proof, prop) } def qed: Boolean = prop } @library case class WithProof[A, B]( x: A, r: (A, B) => Boolean, proof: Boolean, prop: Boolean) { /** Close a proof. */ def |[C](that: WithProof[B, C]): WithProof[B, C] = { require(this.prop && this.proof ==> this.r(this.x, that.x)) WithProof( that.x, that.r, that.proof, this.prop && this.proof && this.r(this.x, that.x)) } /** Close a proof. */ def |[C](that: WithRel[B, C]): WithRel[B, C] = { require(this.prop && this.proof ==> this.r(this.x, that.x)) WithRel( that.x, that.r, this.prop && this.proof && this.r(this.x, that.x)) } /** Close a proof. */ def |(that: RelReasoning[B]): RelReasoning[B] = { require(this.prop && this.proof ==> this.r(this.x, that.x)) RelReasoning( that.x, this.prop && this.proof && this.r(this.x, that.x)) } } }
apache-2.0