code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
// 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 com.cloud.offerings;
import java.util.Date;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import com.cloud.network.Network;
import com.cloud.network.Networks.TrafficType;
import com.cloud.offering.NetworkOffering;
import com.cloud.utils.db.GenericDao;
@Entity
@Table(name = "network_offerings")
public class NetworkOfferingVO implements NetworkOffering {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
long id;
@Column(name = "name")
String name;
@Column(name = "unique_name")
private String uniqueName;
@Column(name = "display_text")
String displayText;
@Column(name = "nw_rate")
Integer rateMbps;
@Column(name = "mc_rate")
Integer multicastRateMbps;
@Column(name = "traffic_type")
@Enumerated(value = EnumType.STRING)
TrafficType trafficType;
@Column(name = "specify_vlan")
boolean specifyVlan;
@Column(name = "system_only")
boolean systemOnly;
@Column(name = "service_offering_id")
Long serviceOfferingId;
@Column(name = "tags", length = 4096)
String tags;
@Column(name = "default")
boolean isDefault;
@Column(name = "availability")
@Enumerated(value = EnumType.STRING)
Availability availability;
@Column(name = "state")
@Enumerated(value = EnumType.STRING)
State state = State.Disabled;
@Column(name = GenericDao.REMOVED_COLUMN)
Date removed;
@Column(name = GenericDao.CREATED_COLUMN)
Date created;
@Column(name = "guest_type")
@Enumerated(value = EnumType.STRING)
Network.GuestType guestType;
@Column(name = "dedicated_lb_service")
boolean dedicatedLB;
@Column(name = "shared_source_nat_service")
boolean sharedSourceNat;
@Column(name = "specify_ip_ranges")
boolean specifyIpRanges = false;
@Column(name = "sort_key")
int sortKey;
@Column(name = "uuid")
String uuid;
@Column(name = "redundant_router_service")
boolean redundantRouter;
@Column(name = "conserve_mode")
boolean conserveMode;
@Column(name = "elastic_ip_service")
boolean elasticIp;
@Column(name = "eip_associate_public_ip")
boolean eipAssociatePublicIp;
@Column(name = "elastic_lb_service")
boolean elasticLb;
@Column(name = "inline")
boolean inline;
@Column(name = "is_persistent")
boolean isPersistent;
@Column(name = "egress_default_policy")
boolean egressdefaultpolicy;
@Column(name = "concurrent_connections")
Integer concurrentConnections;
@Override
public String getDisplayText() {
return displayText;
}
@Column(name = "internal_lb")
boolean internalLb;
@Column(name = "public_lb")
boolean publicLb;
@Override
public long getId() {
return id;
}
@Override
public TrafficType getTrafficType() {
return trafficType;
}
@Override
public Integer getMulticastRateMbps() {
return multicastRateMbps;
}
@Override
public String getName() {
return name;
}
@Override
public Integer getRateMbps() {
return rateMbps;
}
public Date getCreated() {
return created;
}
@Override
public boolean isSystemOnly() {
return systemOnly;
}
public Date getRemoved() {
return removed;
}
@Override
public String getTags() {
return tags;
}
public void setName(String name) {
this.name = name;
}
public void setDisplayText(String displayText) {
this.displayText = displayText;
}
public void setRateMbps(Integer rateMbps) {
this.rateMbps = rateMbps;
}
public void setMulticastRateMbps(Integer multicastRateMbps) {
this.multicastRateMbps = multicastRateMbps;
}
@Override
public boolean isDefault() {
return isDefault;
}
@Override
public boolean getSpecifyVlan() {
return specifyVlan;
}
@Override
public Availability getAvailability() {
return availability;
}
public void setAvailability(Availability availability) {
this.availability = availability;
}
@Override
public String getUniqueName() {
return uniqueName;
}
@Override
public void setState(State state) {
this.state = state;
}
@Override
public State getState() {
return state;
}
@Override
public Network.GuestType getGuestType() {
return guestType;
}
public void setServiceOfferingId(Long serviceOfferingId) {
this.serviceOfferingId = serviceOfferingId;
}
@Override
public Long getServiceOfferingId() {
return serviceOfferingId;
}
@Override
public boolean getDedicatedLB() {
return dedicatedLB;
}
public void setDedicatedLB(boolean dedicatedLB) {
this.dedicatedLB = dedicatedLB;
}
@Override
public boolean getSharedSourceNat() {
return sharedSourceNat;
}
public void setSharedSourceNat(boolean sharedSourceNat) {
this.sharedSourceNat = sharedSourceNat;
}
@Override
public boolean getRedundantRouter() {
return redundantRouter;
}
public void setRedundantRouter(boolean redundantRouter) {
this.redundantRouter = redundantRouter;
}
public boolean getEgressDefaultPolicy() {
return egressdefaultpolicy;
}
public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, boolean isDefault,
Availability availability, String tags, Network.GuestType guestType, boolean conserveMode, boolean specifyIpRanges, boolean isPersistent, boolean internalLb, boolean publicLb) {
this.name = name;
this.displayText = displayText;
this.rateMbps = rateMbps;
this.multicastRateMbps = multicastRateMbps;
this.trafficType = trafficType;
this.systemOnly = systemOnly;
this.specifyVlan = specifyVlan;
this.isDefault = isDefault;
this.availability = availability;
this.uniqueName = name;
this.uuid = UUID.randomUUID().toString();
this.tags = tags;
this.guestType = guestType;
this.conserveMode = conserveMode;
this.dedicatedLB = true;
this.sharedSourceNat = false;
this.redundantRouter = false;
this.elasticIp = false;
this.eipAssociatePublicIp = true;
this.elasticLb = false;
this.inline = false;
this.specifyIpRanges = specifyIpRanges;
this.isPersistent=isPersistent;
this.publicLb = publicLb;
this.internalLb = internalLb;
}
public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, boolean isDefault,
Availability availability, String tags, Network.GuestType guestType, boolean conserveMode, boolean dedicatedLb, boolean sharedSourceNat, boolean redundantRouter, boolean elasticIp, boolean elasticLb,
boolean specifyIpRanges, boolean inline, boolean isPersistent, boolean associatePublicIP, boolean publicLb, boolean internalLb, boolean egressdefaultpolicy) {
this(name, displayText, trafficType, systemOnly, specifyVlan, rateMbps, multicastRateMbps, isDefault, availability, tags, guestType, conserveMode, specifyIpRanges, isPersistent, internalLb, publicLb);
this.dedicatedLB = dedicatedLb;
this.sharedSourceNat = sharedSourceNat;
this.redundantRouter = redundantRouter;
this.elasticIp = elasticIp;
this.elasticLb = elasticLb;
this.inline = inline;
this.eipAssociatePublicIp = associatePublicIP;
this.egressdefaultpolicy = egressdefaultpolicy;
}
public NetworkOfferingVO() {
}
/**
* Network Offering for all system vms.
*
* @param name
* @param trafficType
* @param specifyIpRanges
* TODO
*/
public NetworkOfferingVO(String name, TrafficType trafficType, boolean specifyIpRanges) {
this(name, "System Offering for " + name, trafficType, true, false, 0, 0, true, Availability.Required, null, null, true, specifyIpRanges, false, false, false);
this.state = State.Enabled;
}
public NetworkOfferingVO(String name, Network.GuestType guestType) {
this(name, "System Offering for " + name, TrafficType.Guest, true, true, 0, 0, true, Availability.Optional,
null, Network.GuestType.Isolated, true, false, false, false, false);
this.state = State.Enabled;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder("[Network Offering [");
return buf.append(id).append("-").append(trafficType).append("-").append(name).append("]").toString();
}
@Override
public String getUuid() {
return this.uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public void setSortKey(int key) {
sortKey = key;
}
public int getSortKey() {
return sortKey;
}
public void setUniqueName(String uniqueName) {
this.uniqueName = uniqueName;
}
@Override
public boolean isConserveMode() {
return conserveMode;
}
@Override
public boolean getElasticIp() {
return elasticIp;
}
@Override
public boolean getAssociatePublicIP() {
return eipAssociatePublicIp;
}
@Override
public boolean getElasticLb() {
return elasticLb;
}
@Override
public boolean getSpecifyIpRanges() {
return specifyIpRanges;
}
@Override
public boolean isInline() {
return inline;
}
public void setIsPersistent(Boolean isPersistent) {
this.isPersistent = isPersistent;
}
public boolean getIsPersistent() {
return isPersistent;
}
@Override
public boolean getInternalLb() {
return internalLb;
}
@Override
public boolean getPublicLb() {
return publicLb;
}
public void setInternalLb(boolean internalLb) {
this.internalLb = internalLb;
}
public void setPublicLb(boolean publicLb) {
this.publicLb = publicLb;
}
public Integer getConcurrentConnections() {
return this.concurrentConnections;
}
public void setConcurrentConnections(Integer concurrent_connections) {
this.concurrentConnections = concurrent_connections;
}
}
|
mufaddalq/cloudstack-datera-driver
|
engine/schema/src/com/cloud/offerings/NetworkOfferingVO.java
|
Java
|
apache-2.0
| 11,734 |
/**********************************************************************
Copyright (c) 2003 Andy Jefferson and others. 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.
Contributors:
...
**********************************************************************/
package org.jpox.samples.interfaces;
import java.io.Serializable;
/**
* Circle class.
* @version $Revision: 1.2 $
*/
public class Circle implements Shape, Cloneable, Serializable
{
private int id;
protected double radius=0.0;
public Circle(int id, double radius)
{
this.id = id;
this.radius = radius;
}
public String getName()
{
return "Circle";
}
public void setRadius(double radius)
{
this.radius = radius;
}
public double getRadius()
{
return radius;
}
public double getArea()
{
return Math.PI*radius*radius;
}
public double getCircumference()
{
return Math.PI*radius*2;
}
/**
* @return Returns the id.
*/
public int getId()
{
return id;
}
/**
* @param id The id to set.
*/
public void setId(int id)
{
this.id = id;
}
public Object clone()
{
try
{
return super.clone();
}
catch (CloneNotSupportedException cnse)
{
return null;
}
}
public boolean equals(Object o)
{
if (o == null || !o.getClass().equals(this.getClass()))
{
return false;
}
Circle rhs = (Circle)o;
return radius == rhs.radius;
}
public String toString()
{
return "Circle [radius=" + radius + "]";
}
public static class Oid implements Serializable
{
public int id;
public Oid()
{
}
public Oid(String s)
{
this.id = Integer.valueOf(s).intValue();
}
public int hashCode()
{
return id;
}
public boolean equals(Object other)
{
if (other != null && (other instanceof Oid))
{
Oid k = (Oid)other;
return k.id == this.id;
}
return false;
}
public String toString()
{
return String.valueOf(id);
}
}
}
|
hopecee/texsts
|
samples/src/java/org/jpox/samples/interfaces/Circle.java
|
Java
|
apache-2.0
| 3,009 |
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import {
ReactiveBase,
DataSearch,
ResultList,
ReactiveList,
SelectedFilters,
} from '@appbaseio/reactivesearch';
import './index.css';
class Main extends Component {
render() {
return (
<ReactiveBase
app="good-books-ds"
url="https://a03a1cb71321:75b6603d-9456-4a5a-af6b-a487b309eb61@appbase-demo-ansible-abxiydt-arc.searchbase.io"
enableAppbase
>
<div className="row">
<div className="col">
<DataSearch
dataField="original_title.keyword"
componentId="BookSensor"
defaultValue="Artemis Fowl"
/>
</div>
<div className="col">
<SelectedFilters
render={(props) => {
const { selectedValues, setValue } = props;
const clearFilter = (component) => {
setValue(component, null);
};
const filters = Object.keys(selectedValues).map((component) => {
if (!selectedValues[component].value) return null;
return (
<button
key={component}
onClick={() => clearFilter(component)}
>
{selectedValues[component].value}
</button>
);
});
return filters;
}}
/>
<ReactiveList
componentId="SearchResult"
dataField="original_title"
from={0}
size={3}
className="result-list-container"
pagination
react={{
and: 'BookSensor',
}}
render={({ data }) => (
<ReactiveList.ResultListWrapper>
{data.map(item => (
<ResultList key={item._id}>
<ResultList.Image src={item.image} />
<ResultList.Content>
<ResultList.Title>
<div
className="book-title"
dangerouslySetInnerHTML={{
__html: item.original_title,
}}
/>
</ResultList.Title>
<ResultList.Description>
<div className="flex column justify-space-between">
<div>
<div>
by{' '}
<span className="authors-list">
{item.authors}
</span>
</div>
<div className="ratings-list flex align-center">
<span className="stars">
{Array(
item.average_rating_rounded,
)
.fill('x')
.map((item, index) => (
<i
className="fas fa-star"
key={index}
/>
)) // eslint-disable-line
}
</span>
<span className="avg-rating">
({item.average_rating} avg)
</span>
</div>
</div>
<span className="pub-year">
Pub {item.original_publication_year}
</span>
</div>
</ResultList.Description>
</ResultList.Content>
</ResultList>
))}
</ReactiveList.ResultListWrapper>
)}
/>
</div>
</div>
</ReactiveBase>
);
}
}
export default Main;
ReactDOM.render(<Main />, document.getElementById('root'));
|
appbaseio/reactivesearch
|
packages/web/examples/CustomSelectedFilters/src/index.js
|
JavaScript
|
apache-2.0
| 3,322 |
package hypervisors
import (
"math/rand"
"os/exec"
"strings"
"time"
)
const powerOff = "Power is off"
func (m *Manager) probeUnreachable(h *hypervisorType) probeStatus {
if m.ipmiPasswordFile == "" || m.ipmiUsername == "" {
return probeStatusUnreachable
}
var hostname string
if len(h.machine.IPMI.HostIpAddress) > 0 {
hostname = h.machine.IPMI.HostIpAddress.String()
} else if h.machine.IPMI.Hostname != "" {
hostname = h.machine.IPMI.Hostname
} else {
return probeStatusUnreachable
}
h.mutex.RLock()
previousProbeStatus := h.probeStatus
h.mutex.RUnlock()
mimimumProbeInterval := time.Second * time.Duration(30+rand.Intn(30))
if previousProbeStatus == probeStatusOff &&
time.Until(h.lastIpmiProbe.Add(mimimumProbeInterval)) > 0 {
return probeStatusOff
}
cmd := exec.Command("ipmitool", "-f", m.ipmiPasswordFile, "-H", hostname,
"-I", "lanplus", "-U", m.ipmiUsername, "chassis", "power", "status")
h.lastIpmiProbe = time.Now()
if output, err := cmd.Output(); err != nil {
if previousProbeStatus == probeStatusOff {
return probeStatusOff
} else {
return probeStatusUnreachable
}
} else if strings.Contains(string(output), powerOff) {
return probeStatusOff
}
return probeStatusUnreachable
}
|
Symantec/Dominator
|
fleetmanager/hypervisors/ipmi.go
|
GO
|
apache-2.0
| 1,243 |
/**
* Created by guofengrong on 15/10/26.
*/
var dataImg = {
"data": [{
"src": "1.jpg"
}, {
"src": "1.jpg"
}, {
"src": "2.jpg"
}, {
"src": "3.jpg"
}, {
"src": "4.jpg"
}, {
"src": "10.jpg"
}]
};
$(document).ready(function() {
$(window).on("load", function() {
imgLocation();
//当点击回到顶部的按钮时,页面回到顶部
$("#back-to-top").click(function() {
$('body,html').animate({
scrollTop: 0
}, 1000);
});
$(window).scroll(function() {
//当页面滚动大于100px时,右下角出现返回页面顶端的按钮,否则消失
if ($(window).scrollTop() > 100) {
$("#back-to-top").show(500);
//$("#back-to-top").css("top",($(window).height()+$(window).scrollTop()-50));
} else {
$("#back-to-top").hide(500);
}
//当返回true时,图片开始自动加载,加载的图片通过调用imgLocation函数进行瀑布流式的摆放
if (picAutoLoad()) {
$.each(dataImg.data, function(index, value) {
var box = $("<div>").addClass("pic-box").appendTo($(".content"));
var pic = $("<div>").addClass("pic").appendTo(box);
var img = $("<img>").attr("src", "./img/" + $(value).attr("src")).appendTo(pic);
});
imgLocation();
}
});
});
});
//用于摆放图片的函数:
// 先计算当前页面下,横向摆放图片的张数,当当前所需要摆放的图片的序号小于该数字时,则依次向左浮动摆放;
// 当超过这一数字时,则需要找到已经摆放的图片中最小高度的值(摆放图片的高度存放于数组boxHeightArr中),并在数组中找到具有最小高度的图片的位置;
//然后对需要摆放的图片设置位置信息进行摆放,摆放完成后将数组中的最小高度加上当前摆放图片的高度,然后进行下一次摆放
function imgLocation() {
var picBox = $('.pic-box');
var boxWidth = picBox.eq(0).width();
var contentWidth = $('.content').width();
// console.log(contentWidth);
var num = Math.floor(contentWidth / boxWidth);
var boxHeightArr = [];
picBox.each(function(index, value) {
var boxHeight = picBox.eq(index).height();
if (index < num) {
boxHeightArr[index] = boxHeight;
} else {
var minBoxHeight = Math.min.apply(null, boxHeightArr);
var minHeightIndex = $.inArray(minBoxHeight, boxHeightArr);
$(value).css({
"position": "absolute",
"top": minBoxHeight,
"left": picBox.eq(minHeightIndex).position().left
});
boxHeightArr[minHeightIndex] += picBox.eq(index).height();
}
});
}
//用于自动加载图片用:
//lastBoxHeight获取最后一个图片的高度;
//当最后一张图片的高度小于鼠标滚轮滚过的距离加上显示器高度的时候,则放回true,否则返回false;
function picAutoLoad() {
var box = $('.pic-box');
var lastBoxHeight = box.last().get(0).offsetTop + Math.floor(box.last().height() / 2);
var windowHeight = $(window).height();
var scrollHeight = $(window).scrollTop();
return (lastBoxHeight < windowHeight + scrollHeight) ? true : false;
}
|
guofengrong/HomeworkOfJikexueyuan
|
Lesson7/百度图片瀑布流布局/js/baidu-pic.js
|
JavaScript
|
apache-2.0
| 3,505 |
package daemon
import (
"context"
"runtime"
"time"
"github.com/docker/docker/api/types"
containertypes "github.com/docker/docker/api/types/container"
"github.com/docker/docker/container"
"github.com/docker/docker/errdefs"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// ContainerStart starts a container.
func (daemon *Daemon) ContainerStart(name string, hostConfig *containertypes.HostConfig, checkpoint string, checkpointDir string) error {
if checkpoint != "" && !daemon.HasExperimental() {
return errdefs.InvalidParameter(errors.New("checkpoint is only supported in experimental mode"))
}
container, err := daemon.GetContainer(name)
if err != nil {
return err
}
validateState := func() error {
container.Lock()
defer container.Unlock()
if container.Paused {
return errdefs.Conflict(errors.New("cannot start a paused container, try unpause instead"))
}
if container.Running {
return containerNotModifiedError{running: true}
}
if container.RemovalInProgress || container.Dead {
return errdefs.Conflict(errors.New("container is marked for removal and cannot be started"))
}
return nil
}
if err := validateState(); err != nil {
return err
}
// Windows does not have the backwards compatibility issue here.
if runtime.GOOS != "windows" {
// This is kept for backward compatibility - hostconfig should be passed when
// creating a container, not during start.
if hostConfig != nil {
logrus.Warn("DEPRECATED: Setting host configuration options when the container starts is deprecated and has been removed in Docker 1.12")
oldNetworkMode := container.HostConfig.NetworkMode
if err := daemon.setSecurityOptions(container, hostConfig); err != nil {
return errdefs.InvalidParameter(err)
}
if err := daemon.mergeAndVerifyLogConfig(&hostConfig.LogConfig); err != nil {
return errdefs.InvalidParameter(err)
}
if err := daemon.setHostConfig(container, hostConfig); err != nil {
return errdefs.InvalidParameter(err)
}
newNetworkMode := container.HostConfig.NetworkMode
if string(oldNetworkMode) != string(newNetworkMode) {
// if user has change the network mode on starting, clean up the
// old networks. It is a deprecated feature and has been removed in Docker 1.12
container.NetworkSettings.Networks = nil
if err := container.CheckpointTo(daemon.containersReplica); err != nil {
return errdefs.System(err)
}
}
container.InitDNSHostConfig()
}
} else {
if hostConfig != nil {
return errdefs.InvalidParameter(errors.New("Supplying a hostconfig on start is not supported. It should be supplied on create"))
}
}
// check if hostConfig is in line with the current system settings.
// It may happen cgroups are umounted or the like.
if _, err = daemon.verifyContainerSettings(container.OS, container.HostConfig, nil, false); err != nil {
return errdefs.InvalidParameter(err)
}
// Adapt for old containers in case we have updates in this function and
// old containers never have chance to call the new function in create stage.
if hostConfig != nil {
if err := daemon.adaptContainerSettings(container.HostConfig, false); err != nil {
return errdefs.InvalidParameter(err)
}
}
return daemon.containerStart(container, checkpoint, checkpointDir, true)
}
// containerStart prepares the container to run by setting up everything the
// container needs, such as storage and networking, as well as links
// between containers. The container is left waiting for a signal to
// begin running.
func (daemon *Daemon) containerStart(container *container.Container, checkpoint string, checkpointDir string, resetRestartManager bool) (err error) {
start := time.Now()
container.Lock()
defer container.Unlock()
if resetRestartManager && container.Running { // skip this check if already in restarting step and resetRestartManager==false
return nil
}
if container.RemovalInProgress || container.Dead {
return errdefs.Conflict(errors.New("container is marked for removal and cannot be started"))
}
if checkpointDir != "" {
// TODO(mlaventure): how would we support that?
return errdefs.Forbidden(errors.New("custom checkpointdir is not supported"))
}
// if we encounter an error during start we need to ensure that any other
// setup has been cleaned up properly
defer func() {
if err != nil {
container.SetError(err)
// if no one else has set it, make sure we don't leave it at zero
if container.ExitCode() == 0 {
container.SetExitCode(128)
}
if err := container.CheckpointTo(daemon.containersReplica); err != nil {
logrus.Errorf("%s: failed saving state on start failure: %v", container.ID, err)
}
container.Reset(false)
daemon.Cleanup(container)
// if containers AutoRemove flag is set, remove it after clean up
if container.HostConfig.AutoRemove {
container.Unlock()
if err := daemon.ContainerRm(container.ID, &types.ContainerRmConfig{ForceRemove: true, RemoveVolume: true}); err != nil {
logrus.Errorf("can't remove container %s: %v", container.ID, err)
}
container.Lock()
}
}
}()
if err := daemon.conditionalMountOnStart(container); err != nil {
return err
}
if err := daemon.initializeNetworking(container); err != nil {
return err
}
spec, err := daemon.createSpec(container)
if err != nil {
return errdefs.System(err)
}
if resetRestartManager {
container.ResetRestartManager(true)
}
if daemon.saveApparmorConfig(container); err != nil {
return err
}
if checkpoint != "" {
checkpointDir, err = getCheckpointDir(checkpointDir, checkpoint, container.Name, container.ID, container.CheckpointDir(), false)
if err != nil {
return err
}
}
createOptions, err := daemon.getLibcontainerdCreateOptions(container)
if err != nil {
return err
}
err = daemon.containerd.Create(context.Background(), container.ID, spec, createOptions)
if err != nil {
return translateContainerdStartErr(container.Path, container.SetExitCode, err)
}
// TODO(mlaventure): we need to specify checkpoint options here
pid, err := daemon.containerd.Start(context.Background(), container.ID, checkpointDir,
container.StreamConfig.Stdin() != nil || container.Config.Tty,
container.InitializeStdio)
if err != nil {
if err := daemon.containerd.Delete(context.Background(), container.ID); err != nil {
logrus.WithError(err).WithField("container", container.ID).
Error("failed to delete failed start container")
}
return translateContainerdStartErr(container.Path, container.SetExitCode, err)
}
container.SetRunning(pid, true)
container.HasBeenManuallyStopped = false
container.HasBeenStartedBefore = true
daemon.setStateCounter(container)
daemon.initHealthMonitor(container)
if err := container.CheckpointTo(daemon.containersReplica); err != nil {
logrus.WithError(err).WithField("container", container.ID).
Errorf("failed to store container")
}
daemon.LogContainerEvent(container, "start")
containerActions.WithValues("start").UpdateSince(start)
return nil
}
// Cleanup releases any network resources allocated to the container along with any rules
// around how containers are linked together. It also unmounts the container's root filesystem.
func (daemon *Daemon) Cleanup(container *container.Container) {
daemon.releaseNetwork(container)
if err := container.UnmountIpcMount(detachMounted); err != nil {
logrus.Warnf("%s cleanup: failed to unmount IPC: %s", container.ID, err)
}
if err := daemon.conditionalUnmountOnCleanup(container); err != nil {
// FIXME: remove once reference counting for graphdrivers has been refactored
// Ensure that all the mounts are gone
if mountid, err := daemon.stores[container.OS].layerStore.GetMountID(container.ID); err == nil {
daemon.cleanupMountsByID(mountid)
}
}
if err := container.UnmountSecrets(); err != nil {
logrus.Warnf("%s cleanup: failed to unmount secrets: %s", container.ID, err)
}
for _, eConfig := range container.ExecCommands.Commands() {
daemon.unregisterExecCommand(container, eConfig)
}
if container.BaseFS != nil && container.BaseFS.Path() != "" {
if err := container.UnmountVolumes(daemon.LogVolumeEvent); err != nil {
logrus.Warnf("%s cleanup: Failed to umount volumes: %v", container.ID, err)
}
}
container.CancelAttachContext()
if err := daemon.containerd.Delete(context.Background(), container.ID); err != nil {
logrus.Errorf("%s cleanup: failed to delete container from containerd: %v", container.ID, err)
}
}
|
ripcurld0/moby
|
daemon/start.go
|
GO
|
apache-2.0
| 8,522 |
import { expect } from 'chai';
import * as utilities from '../../src/utilities';
describe('utilities.capitalize()', () => {
it('capitalize', () => {
expect( utilities.capitalize('capitalize') == 'Capitalize' );
});
it('Capitalize', () => {
expect( utilities.capitalize('Capitalize') == 'Capitalize' );
});
it('poweranalytics', () => {
expect( utilities.capitalize('poweranalytics') == 'Poweranalytics' );
});
});
describe('utilities.loadScript()', () => {
});
describe('utilities.domReady()', () => {
});
describe('utilities.random()', () => {
it('length', () => {
expect( utilities.random(1).length == 1 );
expect( utilities.random(5).length == 5 );
expect( utilities.random(20).length == 20 );
});
it('character', () => {
expect( utilities.random(5).match(/^[0-9a-zA-Z]{5}$/) );
});
});
describe('utilities.timestamp()', () => {
it('format', () => {
const timestamp = utilities.timestamp();
expect(timestamp.match(/[0-9]{4}\/[0-9]{2}\/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}:[0-9]{3}/))
});
});
|
1987yama3/power-analytics.appspot.com
|
test/unit/utilities.test.js
|
JavaScript
|
apache-2.0
| 1,060 |
package com.metaui.fxbase.view.desktop;
import com.metaui.fxbase.model.AppModel;
import com.metaui.fxbase.model.NavMenuModel;
import com.metaui.fxbase.ui.IDesktop;
import com.metaui.fxbase.ui.view.MUTabPane;
import com.metaui.fxbase.view.tree.MUTree;
import javafx.collections.ListChangeListener;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.ListView;
import javafx.scene.control.Tab;
import javafx.scene.layout.BorderPane;
import org.controlsfx.control.MasterDetailPane;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Tabs 桌面
*
* @author wei_jc
* @since 1.0.0
*/
public class MUTabsDesktop extends BorderPane implements IDesktop {
private AppModel app;
private Map<String, Tab> tabCache = new HashMap<>();
protected MUTabPane tabPane;
private MUTree navTree;
private MasterDetailPane masterDetailPane;
public MUTabsDesktop(AppModel app) {
this.app = app;
}
@Override
public void initUI() {
masterDetailPane = new MasterDetailPane(Side.LEFT);
masterDetailPane.setShowDetailNode(true);
// 左边
masterDetailPane.setDetailNode(getLeftNode());
// 右边
createTabPane();
setCenter(masterDetailPane);
}
public Node getLeftNode() {
return getNavTree();
}
@Override
public void initAfter() {
}
@Override
public Parent getDesktop() {
return this;
}
public MUTree getNavTree() {
if (navTree == null) {
navTree = new MUTree();
}
return navTree;
}
private void createNavMenu() {
ListView<NavMenuModel> listView = new ListView<>();
listView.itemsProperty().bind(app.navMenusProperty());
listView.setOnMouseClicked(event -> {
NavMenuModel model = listView.getSelectionModel().getSelectedItem();
if (model == null) {
return;
}
Tab tab = tabCache.get(model.getId());
if (tab == null) {
tab = new Tab();
tab.idProperty().bind(model.idProperty());
tab.textProperty().bind(model.titleProperty());
// tab.setClosable(false);
tab.setContent((Node) model.getView());
tabPane.getTabs().add(tab);
tabCache.put(model.getId(), tab);
}
// 选择当前
tabPane.getSelectionModel().select(tab);
});
this.setLeft(listView);
}
private void createTabPane() {
tabPane = new MUTabPane();
Tab desktopTab = new Tab("桌面");
desktopTab.setClosable(false);
tabPane.getTabs().add(desktopTab);
// 监听tab删除,删除时从缓存中移除
tabPane.getTabs().addListener((ListChangeListener<Tab>) change -> {
if(change.next() && change.wasRemoved()) {
List<? extends Tab> removed = change.getRemoved();
if(removed.size() > 0) {
for (Tab tab : removed) {
tabCache.remove(tab.getId());
}
}
}
});
masterDetailPane.setMasterNode(tabPane);
}
public void addTab(Tab tab) {
if (tabCache.get(tab.getId()) == null) {
tabPane.getTabs().add(tab);
tabCache.put(tab.getId(), tab);
}
// 选择当前
tabPane.getSelectionModel().select(tab);
}
}
|
weijiancai/metaui
|
fxbase/src/main/java/com/metaui/fxbase/view/desktop/MUTabsDesktop.java
|
Java
|
apache-2.0
| 3,558 |
package timely.configuration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.validation.Valid;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
@Validated
@Component
@ConfigurationProperties(prefix = "timely")
public class Configuration {
private String metricsTable = "timely.metrics";
private String metaTable = "timely.meta";
private HashMap<String, Integer> metricAgeOffDays = new HashMap<>();
private List<String> metricsReportIgnoredTags = new ArrayList<>();
private String instance = null;
private String defaultVisibility = null;
@Valid
@NestedConfigurationProperty
private Accumulo accumulo = new Accumulo();
@Valid
@NestedConfigurationProperty
private Security security = new Security();
@Valid
@NestedConfigurationProperty
private Server server = new Server();
@Valid
@NestedConfigurationProperty
private Http http = new Http();
@Valid
@NestedConfigurationProperty
private MetaCache metaCache = new MetaCache();
@Valid
@NestedConfigurationProperty
private Cache cache = new Cache();
@Valid
@NestedConfigurationProperty
private VisibilityCache visibilityCache = new VisibilityCache();
@Valid
@NestedConfigurationProperty
private Websocket websocket = new Websocket();
public String getMetricsTable() {
return metricsTable;
}
public Configuration setMetricsTable(String metricsTable) {
this.metricsTable = metricsTable;
return this;
}
public String getMetaTable() {
return metaTable;
}
public Configuration setMetaTable(String metaTable) {
this.metaTable = metaTable;
return this;
}
public void setInstance(String instance) {
this.instance = instance;
}
public String getInstance() {
return instance;
}
public String getDefaultVisibility() {
return defaultVisibility;
}
public void setDefaultVisibility(String defaultVisibility) {
this.defaultVisibility = defaultVisibility;
}
public HashMap<String, Integer> getMetricAgeOffDays() {
return metricAgeOffDays;
}
public void setMetricAgeOffDays(HashMap<String, Integer> metricAgeOffDays) {
this.metricAgeOffDays = metricAgeOffDays;
}
public List<String> getMetricsReportIgnoredTags() {
return metricsReportIgnoredTags;
}
public Configuration setMetricsReportIgnoredTags(List<String> metricsReportIgnoredTags) {
this.metricsReportIgnoredTags = metricsReportIgnoredTags;
return this;
}
public Accumulo getAccumulo() {
return accumulo;
}
public Security getSecurity() {
return security;
}
public Server getServer() {
return server;
}
public Http getHttp() {
return http;
}
public Websocket getWebsocket() {
return websocket;
}
public MetaCache getMetaCache() {
return metaCache;
}
public Cache getCache() {
return cache;
}
public VisibilityCache getVisibilityCache() {
return visibilityCache;
}
}
|
NationalSecurityAgency/timely
|
server/src/main/java/timely/configuration/Configuration.java
|
Java
|
apache-2.0
| 3,399 |
package psidev.psi.mi.jami.tab.io.writer.extended;
import psidev.psi.mi.jami.binary.ModelledBinaryInteraction;
import psidev.psi.mi.jami.binary.expansion.ComplexExpansionMethod;
import psidev.psi.mi.jami.model.ModelledInteraction;
import psidev.psi.mi.jami.tab.MitabVersion;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
/**
* Mitab 2.6 writer for Modelled interaction
*
* @author Marine Dumousseau (marine@ebi.ac.uk)
* @version $Id$
* @since <pre>20/06/13</pre>
*/
public class Mitab26ModelledWriter extends Mitab25ModelledWriter {
/**
* <p>Constructor for Mitab26ModelledWriter.</p>
*/
public Mitab26ModelledWriter() {
super();
}
/**
* <p>Constructor for Mitab26ModelledWriter.</p>
*
* @param file a {@link java.io.File} object.
* @throws java.io.IOException if any.
*/
public Mitab26ModelledWriter(File file) throws IOException {
super(file);
}
/**
* <p>Constructor for Mitab26ModelledWriter.</p>
*
* @param output a {@link java.io.OutputStream} object.
*/
public Mitab26ModelledWriter(OutputStream output) {
super(output);
}
/**
* <p>Constructor for Mitab26ModelledWriter.</p>
*
* @param writer a {@link java.io.Writer} object.
*/
public Mitab26ModelledWriter(Writer writer) {
super(writer);
}
/**
* <p>Constructor for Mitab26ModelledWriter.</p>
*
* @param file a {@link java.io.File} object.
* @param expansionMethod a {@link psidev.psi.mi.jami.binary.expansion.ComplexExpansionMethod} object.
* @throws java.io.IOException if any.
*/
public Mitab26ModelledWriter(File file, ComplexExpansionMethod<ModelledInteraction, ModelledBinaryInteraction> expansionMethod) throws IOException {
super(file, expansionMethod);
}
/**
* <p>Constructor for Mitab26ModelledWriter.</p>
*
* @param output a {@link java.io.OutputStream} object.
* @param expansionMethod a {@link psidev.psi.mi.jami.binary.expansion.ComplexExpansionMethod} object.
*/
public Mitab26ModelledWriter(OutputStream output, ComplexExpansionMethod<ModelledInteraction, ModelledBinaryInteraction> expansionMethod) {
super(output, expansionMethod);
}
/**
* <p>Constructor for Mitab26ModelledWriter.</p>
*
* @param writer a {@link java.io.Writer} object.
* @param expansionMethod a {@link psidev.psi.mi.jami.binary.expansion.ComplexExpansionMethod} object.
*/
public Mitab26ModelledWriter(Writer writer, ComplexExpansionMethod<ModelledInteraction, ModelledBinaryInteraction> expansionMethod) {
super(writer, expansionMethod);
}
/** {@inheritDoc} */
@Override
public MitabVersion getVersion() {
return MitabVersion.v2_6;
}
/** {@inheritDoc} */
@Override
protected void initialiseWriter(Writer writer){
setBinaryWriter(new Mitab26ModelledBinaryWriter(writer));
}
/** {@inheritDoc} */
@Override
protected void initialiseOutputStream(OutputStream output) {
setBinaryWriter(new Mitab26ModelledBinaryWriter(output));
}
/** {@inheritDoc} */
@Override
protected void initialiseFile(File file) throws IOException {
setBinaryWriter(new Mitab26ModelledBinaryWriter(file));
}
}
|
MICommunity/psi-jami
|
jami-mitab/src/main/java/psidev/psi/mi/jami/tab/io/writer/extended/Mitab26ModelledWriter.java
|
Java
|
apache-2.0
| 3,389 |
/*
* 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.cassandra.io.sstable;
import java.io.File;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;
import com.google.common.collect.Sets;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.db.DataTracker;
import org.apache.cassandra.db.SystemKeyspace;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.utils.FBUtilities;
public class SSTableDeletingTask implements Runnable
{
private static final Logger logger = LoggerFactory.getLogger(SSTableDeletingTask.class);
// Deleting sstables is tricky because the mmapping might not have been finalized yet,
// and delete will fail (on Windows) until it is (we only force the unmapping on SUN VMs).
// Additionally, we need to make sure to delete the data file first, so on restart the others
// will be recognized as GCable.
private static final Set<SSTableDeletingTask> failedTasks = new CopyOnWriteArraySet<SSTableDeletingTask>();
private final SSTableReader referent;
private final Descriptor desc;
private final Set<Component> components;
private DataTracker tracker;
public SSTableDeletingTask(SSTableReader referent)
{
this.referent = referent;
if (referent.openReason == SSTableReader.OpenReason.EARLY)
{
this.desc = referent.descriptor.asType(Descriptor.Type.TEMPLINK);
this.components = Sets.newHashSet(Component.DATA, Component.PRIMARY_INDEX);
}
else
{
this.desc = referent.descriptor;
this.components = referent.components;
}
}
public void setTracker(DataTracker tracker)
{
this.tracker = tracker;
}
public void schedule()
{
StorageService.tasks.submit(this);
}
public void run()
{
long size = referent.bytesOnDisk();
if (tracker != null)
tracker.notifyDeleting(referent);
if (referent.readMeter != null)
SystemKeyspace.clearSSTableReadMeter(referent.getKeyspaceName(), referent.getColumnFamilyName(), referent.descriptor.generation);
// If we can't successfully delete the DATA component, set the task to be retried later: see above
File datafile = new File(desc.filenameFor(Component.DATA));
if (!datafile.delete())
{
logger.error("Unable to delete {} (it will be removed on server restart; we'll also retry after GC)", datafile);
failedTasks.add(this);
return;
}
// let the remainder be cleaned up by delete
SSTable.delete(desc, Sets.difference(components, Collections.singleton(Component.DATA)));
if (tracker != null)
tracker.spaceReclaimed(size);
}
/**
* Retry all deletions that failed the first time around (presumably b/c the sstable was still mmap'd.)
* Useful because there are times when we know GC has been invoked; also exposed as an mbean.
*/
public static void rescheduleFailedTasks()
{
for (SSTableDeletingTask task : failedTasks)
{
failedTasks.remove(task);
task.schedule();
}
}
/** for tests */
public static void waitForDeletions()
{
Runnable runnable = new Runnable()
{
public void run()
{
}
};
FBUtilities.waitOnFuture(StorageService.tasks.schedule(runnable, 0, TimeUnit.MILLISECONDS));
}
}
|
qinjin/mdtc-cassandra
|
src/java/org/apache/cassandra/io/sstable/SSTableDeletingTask.java
|
Java
|
apache-2.0
| 4,449 |
package minefantasy.mf2.api.knowledge.client;
import org.lwjgl.opengl.GL11;
import minefantasy.mf2.api.helpers.RenderHelper;
import minefantasy.mf2.api.helpers.TextureHelperMF;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.util.StatCollector;
public class EntryPageImage extends EntryPage
{
private Minecraft mc = Minecraft.getMinecraft();
private String[] paragraphs;
/**
* Recommend size: 48x48
*/
private String image;
private int[] sizes;
public EntryPageImage(String tex, String... paragraphs)
{
this(tex, 128, 128, paragraphs);
}
public EntryPageImage(String tex, int width, int height, String... paragraphs)
{
this.paragraphs = paragraphs;
this.image = tex;
this.sizes = new int[]{width, height};
}
@Override
public void render(GuiScreen parent, int x, int y, float f, int posX, int posY, boolean onTick)
{
String text = "";
for(String s: paragraphs)
{
text += StatCollector.translateToLocal(s);
text += "\n\n";
}
mc.fontRenderer.drawSplitString(text, posX+14, posY+117, 117, 0);
}
@Override
public void preRender(GuiScreen parent, int x, int y, float f, int posX, int posY, boolean onTick)
{
mc.renderEngine.bindTexture(TextureHelperMF.getResource(image));
RenderHelper.drawTexturedModalRect(posX+14, posY+8, 2, 0, 0, sizes[0], sizes[1], 1F/(float)sizes[0], 1F/(float)sizes[1]);
}
}
|
AnonymousProductions/MineFantasy2
|
src/main/java/minefantasy/mf2/api/knowledge/client/EntryPageImage.java
|
Java
|
apache-2.0
| 1,405 |
package org.testng.xml;
import static org.testng.internal.Utils.isStringBlank;
import org.testng.ITestObjectFactory;
import org.testng.TestNGException;
import org.testng.collections.Lists;
import org.testng.collections.Maps;
import org.testng.internal.RuntimeBehavior;
import org.testng.internal.Utils;
import org.testng.log4testng.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Stack;
/**
* Suite definition parser utility.
*
* @author Cedric Beust
* @author <a href='mailto:the_mindstorm@evolva.ro'>Alexandru Popescu</a>
*/
public class TestNGContentHandler extends DefaultHandler {
private XmlSuite m_currentSuite = null;
private XmlTest m_currentTest = null;
private List<String> m_currentDefines = null;
private List<String> m_currentRuns = null;
private List<XmlClass> m_currentClasses = null;
private int m_currentTestIndex = 0;
private int m_currentClassIndex = 0;
private int m_currentIncludeIndex = 0;
private List<XmlPackage> m_currentPackages = null;
private XmlPackage m_currentPackage = null;
private List<XmlSuite> m_suites = Lists.newArrayList();
private XmlGroups m_currentGroups = null;
private List<String> m_currentIncludedGroups = null;
private List<String> m_currentExcludedGroups = null;
private Map<String, String> m_currentTestParameters = null;
private Map<String, String> m_currentSuiteParameters = null;
private Map<String, String> m_currentClassParameters = null;
private Include m_currentInclude;
private List<String> m_currentMetaGroup = null;
private String m_currentMetaGroupName;
enum Location {
SUITE,
TEST,
CLASS,
INCLUDE,
EXCLUDE
}
private Stack<Location> m_locations = new Stack<>();
private XmlClass m_currentClass = null;
private ArrayList<XmlInclude> m_currentIncludedMethods = null;
private List<String> m_currentExcludedMethods = null;
private ArrayList<XmlMethodSelector> m_currentSelectors = null;
private XmlMethodSelector m_currentSelector = null;
private String m_currentLanguage = null;
private String m_currentExpression = null;
private List<String> m_suiteFiles = Lists.newArrayList();
private boolean m_enabledTest;
private List<String> m_listeners;
private String m_fileName;
private boolean m_loadClasses;
private boolean m_validate = false;
private boolean m_hasWarn = false;
public TestNGContentHandler(String fileName, boolean loadClasses) {
m_fileName = fileName;
m_loadClasses = loadClasses;
}
/*
* (non-Javadoc)
*
* @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String,
* java.lang.String)
*/
@Override
public InputSource resolveEntity(String systemId, String publicId)
throws IOException, SAXException {
if (Parser.isUnRecognizedPublicId(publicId)) {
//The Url is not TestNG recognized
boolean isHttps = publicId != null && publicId.trim().toLowerCase().startsWith("https");
if (isHttps || RuntimeBehavior.useHttpUrlForDtd()) {
return super.resolveEntity(systemId, publicId);
} else {
String msg = "TestNG by default disables loading DTD from unsecure Urls. " +
"If you need to explicitly load the DTD from a http url, please do so " +
"by using the JVM argument [-D" + RuntimeBehavior.TESTNG_USE_UNSECURE_URL + "=true]";
throw new TestNGException(msg);
}
}
m_validate = true;
InputStream is = loadDtdUsingClassLoader();
if (is != null) {
return new InputSource(is);
}
System.out.println(
"WARNING: couldn't find in classpath "
+ publicId
+ "\n"
+ "Fetching it from " + Parser.HTTPS_TESTNG_DTD_URL);
return super.resolveEntity(systemId, Parser.HTTPS_TESTNG_DTD_URL);
}
private InputStream loadDtdUsingClassLoader() {
InputStream is = getClass().getClassLoader().getResourceAsStream(Parser.TESTNG_DTD);
if (is != null) {
return is;
}
return Thread.currentThread().getContextClassLoader().getResourceAsStream(Parser.TESTNG_DTD);
}
/** Parse <suite-file> */
private void xmlSuiteFile(boolean start, Attributes attributes) {
if (start) {
String path = attributes.getValue("path");
pushLocation(Location.SUITE);
m_suiteFiles.add(path);
} else {
m_currentSuite.setSuiteFiles(m_suiteFiles);
popLocation();
}
}
/** Parse <suite> */
private void xmlSuite(boolean start, Attributes attributes) {
if (start) {
pushLocation(Location.SUITE);
String name = attributes.getValue("name");
if (isStringBlank(name)) {
throw new TestNGException("The <suite> tag must define the name attribute");
}
m_currentSuite = new XmlSuite();
m_currentSuite.setFileName(m_fileName);
m_currentSuite.setName(name);
m_currentSuiteParameters = Maps.newHashMap();
String verbose = attributes.getValue("verbose");
if (null != verbose) {
m_currentSuite.setVerbose(Integer.parseInt(verbose));
}
String jUnit = attributes.getValue("junit");
if (null != jUnit) {
m_currentSuite.setJUnit(Boolean.valueOf(jUnit));
}
String parallel = attributes.getValue("parallel");
if (parallel != null) {
XmlSuite.ParallelMode mode = XmlSuite.ParallelMode.getValidParallel(parallel);
if (mode != null) {
m_currentSuite.setParallel(mode);
} else {
Utils.log(
"Parser",
1,
"[WARN] Unknown value of attribute 'parallel' at suite level: '" + parallel + "'.");
}
}
String parentModule = attributes.getValue("parent-module");
if (parentModule != null) {
m_currentSuite.setParentModule(parentModule);
}
String guiceStage = attributes.getValue("guice-stage");
if (guiceStage != null) {
m_currentSuite.setGuiceStage(guiceStage);
}
XmlSuite.FailurePolicy configFailurePolicy =
XmlSuite.FailurePolicy.getValidPolicy(attributes.getValue("configfailurepolicy"));
if (null != configFailurePolicy) {
m_currentSuite.setConfigFailurePolicy(configFailurePolicy);
}
String groupByInstances = attributes.getValue("group-by-instances");
if (groupByInstances != null) {
m_currentSuite.setGroupByInstances(Boolean.valueOf(groupByInstances));
}
String skip = attributes.getValue("skipfailedinvocationcounts");
if (skip != null) {
m_currentSuite.setSkipFailedInvocationCounts(Boolean.valueOf(skip));
}
String threadCount = attributes.getValue("thread-count");
if (null != threadCount) {
m_currentSuite.setThreadCount(Integer.parseInt(threadCount));
}
String dataProviderThreadCount = attributes.getValue("data-provider-thread-count");
if (null != dataProviderThreadCount) {
m_currentSuite.setDataProviderThreadCount(Integer.parseInt(dataProviderThreadCount));
}
String timeOut = attributes.getValue("time-out");
if (null != timeOut) {
m_currentSuite.setTimeOut(timeOut);
}
String objectFactory = attributes.getValue("object-factory");
if (null != objectFactory && m_loadClasses) {
try {
m_currentSuite.setObjectFactory(
(ITestObjectFactory) Class.forName(objectFactory).newInstance());
} catch (Exception e) {
Utils.log(
"Parser",
1,
"[ERROR] Unable to create custom object factory '" + objectFactory + "' :" + e);
}
}
String preserveOrder = attributes.getValue("preserve-order");
if (preserveOrder != null) {
m_currentSuite.setPreserveOrder(Boolean.valueOf(preserveOrder));
}
String allowReturnValues = attributes.getValue("allow-return-values");
if (allowReturnValues != null) {
m_currentSuite.setAllowReturnValues(Boolean.valueOf(allowReturnValues));
}
} else {
m_currentSuite.setParameters(m_currentSuiteParameters);
m_suites.add(m_currentSuite);
m_currentSuiteParameters = null;
popLocation();
}
}
/** Parse <define> */
private void xmlDefine(boolean start, Attributes attributes) {
if (start) {
String name = attributes.getValue("name");
m_currentDefines = Lists.newArrayList();
m_currentMetaGroup = Lists.newArrayList();
m_currentMetaGroupName = name;
} else {
if (m_currentTest != null) {
m_currentTest.addMetaGroup(m_currentMetaGroupName, m_currentMetaGroup);
} else {
XmlDefine define = new XmlDefine();
define.setName(m_currentMetaGroupName);
define.getIncludes().addAll(m_currentMetaGroup);
m_currentGroups.addDefine(define);
}
m_currentDefines = null;
}
}
/** Parse <script> */
private void xmlScript(boolean start, Attributes attributes) {
if (start) {
m_currentLanguage = attributes.getValue("language");
m_currentExpression = "";
} else {
XmlScript script = new XmlScript();
script.setExpression(m_currentExpression);
script.setLanguage(m_currentLanguage);
m_currentSelector.setScript(script);
if (m_locations.peek() == Location.TEST) {
m_currentTest.setScript(script);
}
m_currentLanguage = null;
m_currentExpression = null;
}
}
/** Parse <test> */
private void xmlTest(boolean start, Attributes attributes) {
if (start) {
m_currentTest = new XmlTest(m_currentSuite, m_currentTestIndex++);
pushLocation(Location.TEST);
m_currentTestParameters = Maps.newHashMap();
final String testName = attributes.getValue("name");
if (isStringBlank(testName)) {
throw new TestNGException("The <test> tag must define the name attribute");
}
m_currentTest.setName(attributes.getValue("name"));
String verbose = attributes.getValue("verbose");
if (null != verbose) {
m_currentTest.setVerbose(Integer.parseInt(verbose));
}
String jUnit = attributes.getValue("junit");
if (null != jUnit) {
m_currentTest.setJUnit(Boolean.valueOf(jUnit));
}
String skip = attributes.getValue("skipfailedinvocationcounts");
if (skip != null) {
m_currentTest.setSkipFailedInvocationCounts(Boolean.valueOf(skip));
}
String groupByInstances = attributes.getValue("group-by-instances");
if (groupByInstances != null) {
m_currentTest.setGroupByInstances(Boolean.valueOf(groupByInstances));
}
String preserveOrder = attributes.getValue("preserve-order");
if (preserveOrder != null) {
m_currentTest.setPreserveOrder(Boolean.valueOf(preserveOrder));
}
String parallel = attributes.getValue("parallel");
if (parallel != null) {
XmlSuite.ParallelMode mode = XmlSuite.ParallelMode.getValidParallel(parallel);
if (mode != null) {
m_currentTest.setParallel(mode);
} else {
Utils.log(
"Parser",
1,
"[WARN] Unknown value of attribute 'parallel' for test '"
+ m_currentTest.getName()
+ "': '"
+ parallel
+ "'");
}
}
String threadCount = attributes.getValue("thread-count");
if (null != threadCount) {
m_currentTest.setThreadCount(Integer.parseInt(threadCount));
}
String timeOut = attributes.getValue("time-out");
if (null != timeOut) {
m_currentTest.setTimeOut(Long.parseLong(timeOut));
}
m_enabledTest = true;
String enabledTestString = attributes.getValue("enabled");
if (null != enabledTestString) {
m_enabledTest = Boolean.valueOf(enabledTestString);
}
} else {
if (null != m_currentTestParameters && m_currentTestParameters.size() > 0) {
m_currentTest.setParameters(m_currentTestParameters);
}
if (null != m_currentClasses) {
m_currentTest.setXmlClasses(m_currentClasses);
}
m_currentClasses = null;
m_currentTest = null;
m_currentTestParameters = null;
popLocation();
if (!m_enabledTest) {
List<XmlTest> tests = m_currentSuite.getTests();
tests.remove(tests.size() - 1);
}
}
}
/** Parse <classes> */
public void xmlClasses(boolean start, Attributes attributes) {
if (start) {
m_currentClasses = Lists.newArrayList();
m_currentClassIndex = 0;
} else {
m_currentTest.setXmlClasses(m_currentClasses);
m_currentClasses = null;
}
}
/** Parse <listeners> */
public void xmlListeners(boolean start, Attributes attributes) {
if (start) {
m_listeners = Lists.newArrayList();
} else {
if (null != m_listeners) {
m_currentSuite.setListeners(m_listeners);
m_listeners = null;
}
}
}
/** Parse <listener> */
public void xmlListener(boolean start, Attributes attributes) {
if (start) {
String listener = attributes.getValue("class-name");
m_listeners.add(listener);
}
}
/** Parse <packages> */
public void xmlPackages(boolean start, Attributes attributes) {
if (start) {
m_currentPackages = Lists.newArrayList();
} else {
if (null != m_currentPackages) {
Location location = m_locations.peek();
switch (location) {
case TEST:
m_currentTest.setXmlPackages(m_currentPackages);
break;
case SUITE:
m_currentSuite.setXmlPackages(m_currentPackages);
break;
case CLASS:
throw new UnsupportedOperationException("CLASS");
default:
throw new AssertionError("Unexpected value: " + location);
}
}
m_currentPackages = null;
m_currentPackage = null;
}
}
/** Parse <method-selectors> */
public void xmlMethodSelectors(boolean start, Attributes attributes) {
if (start) {
m_currentSelectors = new ArrayList<>();
return;
}
if (m_locations.peek() == Location.TEST) {
m_currentTest.setMethodSelectors(m_currentSelectors);
} else {
m_currentSuite.setMethodSelectors(m_currentSelectors);
}
m_currentSelectors = null;
}
/** Parse <selector-class> */
public void xmlSelectorClass(boolean start, Attributes attributes) {
if (start) {
m_currentSelector.setName(attributes.getValue("name"));
String priority = attributes.getValue("priority");
if (priority == null) {
priority = "0";
}
m_currentSelector.setPriority(Integer.parseInt(priority));
}
}
/** Parse <method-selector> */
public void xmlMethodSelector(boolean start, Attributes attributes) {
if (start) {
m_currentSelector = new XmlMethodSelector();
} else {
m_currentSelectors.add(m_currentSelector);
m_currentSelector = null;
}
}
private void xmlMethod(boolean start) {
if (start) {
m_currentIncludedMethods = new ArrayList<>();
m_currentExcludedMethods = Lists.newArrayList();
m_currentIncludeIndex = 0;
} else {
m_currentClass.setIncludedMethods(m_currentIncludedMethods);
m_currentClass.setExcludedMethods(m_currentExcludedMethods);
m_currentIncludedMethods = null;
m_currentExcludedMethods = null;
}
}
/** Parse <run> */
public void xmlRun(boolean start, Attributes attributes) {
if (start) {
m_currentRuns = Lists.newArrayList();
} else {
if (m_currentTest != null) {
m_currentTest.setIncludedGroups(m_currentIncludedGroups);
m_currentTest.setExcludedGroups(m_currentExcludedGroups);
} else {
m_currentSuite.setIncludedGroups(m_currentIncludedGroups);
m_currentSuite.setExcludedGroups(m_currentExcludedGroups);
}
m_currentRuns = null;
}
}
/** Parse <group> */
public void xmlGroup(boolean start, Attributes attributes) {
if (start) {
m_currentTest.addXmlDependencyGroup(
attributes.getValue("name"), attributes.getValue("depends-on"));
}
}
/** Parse <groups> */
public void xmlGroups(boolean start, Attributes attributes) {
if (start) {
m_currentGroups = new XmlGroups();
m_currentIncludedGroups = Lists.newArrayList();
m_currentExcludedGroups = Lists.newArrayList();
} else {
if (m_currentTest == null) {
m_currentSuite.setGroups(m_currentGroups);
}
m_currentGroups = null;
}
}
/**
* NOTE: I only invoke xml*methods (e.g. xmlSuite()) if I am acting on both the start and the end
* of the tag. This way I can keep the treatment of this tag in one place. If I am only doing
* something when the tag opens, the code is inlined below in the startElement() method.
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) {
if (!m_validate && !m_hasWarn) {
String msg = String.format(
"It is strongly recommended to add "
+ "\"<!DOCTYPE suite SYSTEM \"%s\" >\" at the top of your file, "
+ "otherwise TestNG may fail or not work as expected.", Parser.HTTPS_TESTNG_DTD_URL
);
Logger.getLogger(TestNGContentHandler.class).warn(msg);
m_hasWarn = true;
}
String name = attributes.getValue("name");
// ppp("START ELEMENT uri:" + uri + " sName:" + localName + " qName:" + qName +
// " " + attributes);
if ("suite".equals(qName)) {
xmlSuite(true, attributes);
} else if ("suite-file".equals(qName)) {
xmlSuiteFile(true, attributes);
} else if ("test".equals(qName)) {
xmlTest(true, attributes);
} else if ("script".equals(qName)) {
xmlScript(true, attributes);
} else if ("method-selector".equals(qName)) {
xmlMethodSelector(true, attributes);
} else if ("method-selectors".equals(qName)) {
xmlMethodSelectors(true, attributes);
} else if ("selector-class".equals(qName)) {
xmlSelectorClass(true, attributes);
} else if ("classes".equals(qName)) {
xmlClasses(true, attributes);
} else if ("packages".equals(qName)) {
xmlPackages(true, attributes);
} else if ("listeners".equals(qName)) {
xmlListeners(true, attributes);
} else if ("listener".equals(qName)) {
xmlListener(true, attributes);
} else if ("class".equals(qName)) {
// If m_currentClasses is null, the XML is invalid and SAX
// will complain, but in the meantime, dodge the NPE so SAX
// can finish parsing the file.
if (null != m_currentClasses) {
m_currentClass = new XmlClass(name, m_currentClassIndex++, m_loadClasses);
m_currentClass.setXmlTest(m_currentTest);
m_currentClassParameters = Maps.newHashMap();
m_currentClasses.add(m_currentClass);
pushLocation(Location.CLASS);
}
} else if ("package".equals(qName)) {
if (null != m_currentPackages) {
m_currentPackage = new XmlPackage();
m_currentPackage.setName(name);
m_currentPackages.add(m_currentPackage);
}
} else if ("define".equals(qName)) {
xmlDefine(true, attributes);
} else if ("run".equals(qName)) {
xmlRun(true, attributes);
} else if ("group".equals(qName)) {
xmlGroup(true, attributes);
} else if ("groups".equals(qName)) {
xmlGroups(true, attributes);
} else if ("methods".equals(qName)) {
xmlMethod(true);
} else if ("include".equals(qName)) {
xmlInclude(true, attributes);
} else if ("exclude".equals(qName)) {
xmlExclude(true, attributes);
} else if ("parameter".equals(qName)) {
String value = expandValue(attributes.getValue("value"));
Location location = m_locations.peek();
switch (location) {
case TEST:
m_currentTestParameters.put(name, value);
break;
case SUITE:
m_currentSuiteParameters.put(name, value);
break;
case CLASS:
m_currentClassParameters.put(name, value);
break;
case INCLUDE:
m_currentInclude.parameters.put(name, value);
break;
default:
throw new AssertionError("Unexpected value: " + location);
}
}
}
private static class Include {
String name;
String invocationNumbers;
String description;
Map<String, String> parameters = Maps.newHashMap();
Include(String name, String numbers) {
this.name = name;
this.invocationNumbers = numbers;
}
}
private void xmlInclude(boolean start, Attributes attributes) {
if (start) {
m_locations.push(Location.INCLUDE);
m_currentInclude =
new Include(attributes.getValue("name"), attributes.getValue("invocation-numbers"));
m_currentInclude.description = attributes.getValue("description");
} else {
String name = m_currentInclude.name;
if (null != m_currentIncludedMethods) {
String in = m_currentInclude.invocationNumbers;
XmlInclude include;
if (!Utils.isStringEmpty(in)) {
include = new XmlInclude(name, stringToList(in), m_currentIncludeIndex++);
} else {
include = new XmlInclude(name, m_currentIncludeIndex++);
}
for (Map.Entry<String, String> entry : m_currentInclude.parameters.entrySet()) {
include.addParameter(entry.getKey(), entry.getValue());
}
include.setDescription(m_currentInclude.description);
m_currentIncludedMethods.add(include);
} else if (null != m_currentDefines) {
m_currentMetaGroup.add(name);
} else if (null != m_currentRuns) {
m_currentIncludedGroups.add(name);
} else if (null != m_currentPackage) {
m_currentPackage.getInclude().add(name);
}
popLocation();
m_currentInclude = null;
}
}
private void xmlExclude(boolean start, Attributes attributes) {
if (start) {
m_locations.push(Location.EXCLUDE);
String name = attributes.getValue("name");
if (null != m_currentExcludedMethods) {
m_currentExcludedMethods.add(name);
} else if (null != m_currentRuns) {
m_currentExcludedGroups.add(name);
} else if (null != m_currentPackage) {
m_currentPackage.getExclude().add(name);
}
} else {
popLocation();
}
}
private void pushLocation(Location l) {
m_locations.push(l);
}
private void popLocation() {
m_locations.pop();
}
private List<Integer> stringToList(String in) {
String[] numbers = in.split(" ");
List<Integer> result = Lists.newArrayList();
for (String n : numbers) {
result.add(Integer.parseInt(n));
}
return result;
}
@Override
public void endElement(String uri, String localName, String qName) {
if ("suite".equals(qName)) {
xmlSuite(false, null);
} else if ("suite-file".equals(qName)) {
xmlSuiteFile(false, null);
} else if ("test".equals(qName)) {
xmlTest(false, null);
} else if ("define".equals(qName)) {
xmlDefine(false, null);
} else if ("run".equals(qName)) {
xmlRun(false, null);
} else if ("groups".equals(qName)) {
xmlGroups(false, null);
} else if ("methods".equals(qName)) {
xmlMethod(false);
} else if ("classes".equals(qName)) {
xmlClasses(false, null);
} else if ("packages".equals(qName)) {
xmlPackages(false, null);
} else if ("class".equals(qName)) {
m_currentClass.setParameters(m_currentClassParameters);
m_currentClassParameters = null;
popLocation();
} else if ("listeners".equals(qName)) {
xmlListeners(false, null);
} else if ("method-selector".equals(qName)) {
xmlMethodSelector(false, null);
} else if ("method-selectors".equals(qName)) {
xmlMethodSelectors(false, null);
} else if ("selector-class".equals(qName)) {
xmlSelectorClass(false, null);
} else if ("script".equals(qName)) {
xmlScript(false, null);
} else if ("include".equals(qName)) {
xmlInclude(false, null);
} else if ("exclude".equals(qName)) {
xmlExclude(false, null);
}
}
@Override
public void error(SAXParseException e) throws SAXException {
if (m_validate) {
throw e;
}
}
private boolean areWhiteSpaces(char[] ch, int start, int length) {
for (int i = start; i < start + length; i++) {
char c = ch[i];
if (c != '\n' && c != '\t' && c != ' ') {
return false;
}
}
return true;
}
@Override
public void characters(char[] ch, int start, int length) {
if (null != m_currentLanguage && !areWhiteSpaces(ch, start, length)) {
m_currentExpression += new String(ch, start, length);
}
}
public XmlSuite getSuite() {
return m_currentSuite;
}
private static String expandValue(String value) {
StringBuilder result = null;
int startIndex;
int endIndex;
int startPosition = 0;
String property;
while ((startIndex = value.indexOf("${", startPosition)) > -1
&& (endIndex = value.indexOf("}", startIndex + 3)) > -1) {
property = value.substring(startIndex + 2, endIndex);
if (result == null) {
result = new StringBuilder(value.substring(startPosition, startIndex));
} else {
result.append(value, startPosition, startIndex);
}
String propertyValue = System.getProperty(property);
if (propertyValue == null) {
propertyValue = System.getenv(property);
}
if (propertyValue != null) {
result.append(propertyValue);
} else {
result.append("${");
result.append(property);
result.append("}");
}
startPosition = startIndex + 3 + property.length();
}
if (result != null) {
result.append(value.substring(startPosition));
return result.toString();
} else {
return value;
}
}
}
|
missedone/testng
|
src/main/java/org/testng/xml/TestNGContentHandler.java
|
Java
|
apache-2.0
| 26,284 |
package org.jdesktop.core.animation.timing;
import self.philbrown.javaQuery.Modified;
import com.surelogic.ThreadSafe;
/**
* Implements the {@link TimingTarget} interface, providing stubs for all timing
* target methods. Subclasses may extend this adapter rather than implementing
* the {@link TimingTarget} interface if they only care about a subset of the
* events provided. For example, sequencing animations may only require
* monitoring the {@link TimingTarget#end} method, so subclasses of this adapter
* may ignore the other methods such as timingEvent.
* <p>
* This class provides a useful "debug" name via {@link #setDebugName(String)}
* and {@link #getDebugName()}. The debug name is also output by
* {@link #toString()}. This feature is intended to aid debugging.
*
* @author Chet Haase
* @author Tim Halloran
* @author Phil Brown
*/
@Modified(author="Phil Brown", summary="Cleaned up and added inheritDocs documentation to improve javadocs.")
@ThreadSafe(implementationOnly = true)
public class TimingTargetAdapter implements TimingTarget {
/**
* {@inheritDoc}
*/
@Override
public void begin(Animator source) {
}
/**
* {@inheritDoc}
*/
@Override
public void end(Animator source) {
}
/**
* {@inheritDoc}
*/
@Override
public void cancel(Animator source) {
}
/**
* {@inheritDoc}
*/
@Override
public void repeat(Animator source) {
}
/**
* {@inheritDoc}
*/
@Override
public void reverse(Animator source) {
}
/**
* {@inheritDoc}
*/
@Override
public void timingEvent(Animator source, double fraction) {
}
private volatile String f_debugName = null;
public final void setDebugName(String name) {
f_debugName = name;
}
public final String getDebugName() {
return f_debugName;
}
@Override
public String toString() {
final String debugName = f_debugName;
final StringBuilder b = new StringBuilder();
b.append(getClass().getSimpleName()).append('@');
b.append(debugName != null ? debugName : Integer.toHexString(hashCode()));
return b.toString();
}
}
|
phil-brown/javaQuery
|
src/org/jdesktop/core/animation/timing/TimingTargetAdapter.java
|
Java
|
apache-2.0
| 2,073 |
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreNotificationTemplateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string,array<string>>
*/
public function rules(): array
{
return [
'name' => [
'required',
'string',
],
'subject' => [
'required',
'string',
],
'body_markdown' => [
'required',
],
];
}
/**
* Get the error messages for the defined validation rules.
*
* @return array<string,string>
*/
public function messages(): array
{
return [];
}
}
|
RoboJackets/apiary
|
app/Http/Requests/StoreNotificationTemplateRequest.php
|
PHP
|
apache-2.0
| 982 |
package com.praetoriandroid.cameraremote;
public class ServiceNotSupportedException extends RpcException {
private static final long serialVersionUID = -4740335873344202486L;
public ServiceNotSupportedException(String serviceType) {
super(serviceType);
}
}
|
praetoriandroid/sony-camera-remote-java
|
sony-camera-remote-lib/src/main/java/com/praetoriandroid/cameraremote/ServiceNotSupportedException.java
|
Java
|
apache-2.0
| 279 |
"""Test the TcEx Batch Module."""
# third-party
import pytest
# pylint: disable=no-self-use
class TestIndicator3:
"""Test the TcEx Batch Module."""
def setup_class(self):
"""Configure setup before all tests."""
@pytest.mark.parametrize(
'indicator,description,label,tag',
[
('3.33.33.1', 'Example #1', 'PYTEST1', 'PyTest1'),
('3.33.33.2', 'Example #2', 'PYTEST2', 'PyTest2'),
('3.33.33.3', 'Example #3', 'PYTEST3', 'PyTest3'),
('3.33.33.4', 'Example #4', 'PYTEST4', 'PyTest4'),
],
)
def test_address(self, indicator, description, label, tag, tcex):
"""Test address creation"""
batch = tcex.batch(owner='TCI')
xid = batch.generate_xid(['pytest', 'address', indicator])
ti = batch.add_indicator(
{
'type': 'Address',
'rating': 5.00,
'confidence': 100,
'summary': indicator,
'xid': xid,
'attribute': [{'displayed': True, 'type': 'Description', 'value': description}],
'securityLabel': [
{'color': 'ffc0cb', 'name': label, 'description': 'Pytest Label Description'}
],
'tag': [{'name': tag}],
}
)
batch.save(ti)
batch_status = batch.submit_all()
assert batch_status[0].get('status') == 'Completed'
assert batch_status[0].get('successCount') == 1
@pytest.mark.parametrize(
'indicator,description,label,tag',
[
('pytest-email_address-i3-001@test.com', 'Example #1', 'PYTEST:1', 'PyTest1'),
('pytest-email_address-i3-002@test.com', 'Example #2', 'PYTEST:2', 'PyTest2'),
('pytest-email_address-i3-003@test.com', 'Example #3', 'PYTEST:3', 'PyTest3'),
('pytest-email_address-i3-004@test.com', 'Example #4', 'PYTEST:4', 'PyTest4'),
],
)
def test_email_address(self, indicator, description, label, tag, tcex):
"""Test email_address creation"""
batch = tcex.batch(owner='TCI')
xid = batch.generate_xid(['pytest', 'email_address', indicator])
ti = batch.add_indicator(
{
'type': 'EmailAddress',
'rating': 5.00,
'confidence': 100,
'summary': indicator,
'xid': xid,
'attribute': [{'displayed': True, 'type': 'Description', 'value': description}],
'securityLabel': [
{'color': 'ffc0cb', 'name': label, 'description': 'Pytest Label Description'}
],
'tag': [{'name': tag}],
}
)
batch.save(ti)
batch_status = batch.submit_all()
assert batch_status[0].get('status') == 'Completed'
assert batch_status[0].get('successCount') == 1
@pytest.mark.parametrize(
'md5,sha1,sha256,description,label,tag',
[
('a3', 'a3', 'a3', 'Example #1', 'PYTEST:1', 'PyTest1'),
('b3', 'b3', 'b3', 'Example #2', 'PYTEST:2', 'PyTest2'),
('c3', 'c3', 'c3', 'Example #3', 'PYTEST:3', 'PyTest3'),
('d3', 'd3', 'd3', 'Example #4', 'PYTEST:4', 'PyTest4'),
],
)
def test_file(self, md5, sha1, sha256, description, label, tag, tcex):
"""Test file creation"""
batch = tcex.batch(owner='TCI')
xid = batch.generate_xid(['pytest', 'file', md5, sha1, sha256])
ti = batch.add_indicator(
{
'type': 'File',
'rating': 5.00,
'confidence': 100,
'summary': f'{md5 * 16} : {sha1 * 20} : {sha256 * 32}',
'xid': xid,
'attribute': [{'displayed': True, 'type': 'Description', 'value': description}],
'securityLabel': [
{'color': 'ffc0cb', 'name': label, 'description': 'Pytest Label Description'}
],
'tag': [{'name': tag}],
}
)
batch.save(ti)
batch_status = batch.submit_all()
assert batch_status[0].get('status') == 'Completed'
assert batch_status[0].get('successCount') == 1
@pytest.mark.parametrize(
'indicator,description,label,tag',
[
('pytest-host-i3-001.com', 'Example #1', 'PYTEST:1', 'PyTest1'),
('pytest-host-i3-002.com', 'Example #2', 'PYTEST:2', 'PyTest2'),
('pytest-host-i3-003.com', 'Example #3', 'PYTEST:3', 'PyTest3'),
('pytest-host-i3-004.com', 'Example #4', 'PYTEST:4', 'PyTest4'),
],
)
def test_host(self, indicator, description, label, tag, tcex):
"""Test host creation"""
batch = tcex.batch(owner='TCI')
xid = batch.generate_xid(['pytest', 'host', indicator])
ti = batch.add_indicator(
{
'type': 'Host',
'rating': 5.00,
'confidence': 100,
'summary': indicator,
'xid': xid,
'attribute': [{'displayed': True, 'type': 'Description', 'value': description}],
'securityLabel': [
{'color': 'ffc0cb', 'name': label, 'description': 'Pytest Label Description'}
],
'tag': [{'name': tag}],
}
)
batch.save(ti)
batch_status = batch.submit_all()
assert batch_status[0].get('status') == 'Completed'
assert batch_status[0].get('successCount') == 1
@pytest.mark.parametrize(
'indicator,description,label,tag',
[
('https://pytest-url-i3-001.com', 'Example #1', 'PYTEST:1', 'PyTest1'),
('https://pytest-url-i3-002.com', 'Example #2', 'PYTEST:2', 'PyTest2'),
('https://pytest-url-i3-003.com', 'Example #3', 'PYTEST:3', 'PyTest3'),
('https://pytest-url-i3-004.com', 'Example #4', 'PYTEST:4', 'PyTest4'),
],
)
def test_url(self, indicator, description, label, tag, tcex):
"""Test url creation"""
batch = tcex.batch(owner='TCI')
xid = batch.generate_xid(['pytest', 'url', indicator])
ti = batch.add_indicator(
{
'type': 'Url',
'rating': 5.00,
'confidence': 100,
'summary': indicator,
'xid': xid,
'attribute': [{'displayed': True, 'type': 'Description', 'value': description}],
'securityLabel': [
{'color': 'ffc0cb', 'name': label, 'description': 'Pytest Label Description'}
],
'tag': [{'name': tag}],
}
)
batch.save(ti)
batch_status = batch.submit_all()
assert batch_status[0].get('status') == 'Completed'
assert batch_status[0].get('successCount') == 1
|
kstilwell/tcex
|
tests/batch/test_indicator_interface_3.py
|
Python
|
apache-2.0
| 6,925 |
using java.lang;
using java.util;
using stab.query;
public class ToIntTMap5 {
public static bool test() {
var map1 = new HashMap<Integer, string> { { 1, "V1" }, { 2, "V2" }, { 3, "V3" }};
var list = new ArrayList<string> { "V1", "V2", "V3" };
var key = 1;
var map2 = list.toMap(p => key++);
int i = 0;
foreach (var k in map2.keySet()) {
if (!map1[k].equals(map2.get(k))) {
return false;
}
i++;
}
return map2.size() == 3 && i == 3;
}
}
|
monoman/cnatural-language
|
tests/resources/LibraryTest/sources/ToIntTMap5.stab.cs
|
C#
|
apache-2.0
| 467 |
import invocation_pb from '../../api/invocation_pb';
import { State as PageWrapperState } from '../SearchWrapper';
export interface Data {
status: string;
name: string;
labels: string;
date: string;
duration: string;
user: string;
}
export interface Column {
id: 'status' | 'name' | 'labels' | 'date' | 'duration' | 'user';
label: string;
minWidth?: number;
align?: 'right';
}
export interface InvocationTableProps {
invocations: Array<invocation_pb.Invocation>;
pageToken: PageWrapperState['pageToken'];
next: (newQuery: boolean, pageToken: string) => void;
isNextPageLoading: boolean;
tokenID: string;
}
export interface ModalState {
isOpen: boolean;
index: number;
}
export interface HoverState {
isHovered: boolean;
rowIndex: number;
}
|
google/resultstoreui
|
resultstoresearch/client/src/components/InvocationTable/types.ts
|
TypeScript
|
apache-2.0
| 821 |
/*
* Copyright 2020 The Netty Project
*
* The Netty Project 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 io.netty.example.http2.helloworld.frame.client;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2StreamFrame;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* Handles HTTP/2 stream frame responses. This is a useful approach if you specifically want to check
* the main HTTP/2 response DATA/HEADERs, but in this example it's used purely to see whether
* our request (for a specific stream id) has had a final response (for that same stream id).
*/
public final class Http2ClientStreamFrameResponseHandler extends SimpleChannelInboundHandler<Http2StreamFrame> {
private final CountDownLatch latch = new CountDownLatch(1);
@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2StreamFrame msg) throws Exception {
System.out.println("Received HTTP/2 'stream' frame: " + msg);
// isEndStream() is not from a common interface, so we currently must check both
if (msg instanceof Http2DataFrame && ((Http2DataFrame) msg).isEndStream()) {
latch.countDown();
} else if (msg instanceof Http2HeadersFrame && ((Http2HeadersFrame) msg).isEndStream()) {
latch.countDown();
}
}
/**
* Waits for the latch to be decremented (i.e. for an end of stream message to be received), or for
* the latch to expire after 5 seconds.
* @return true if a successful HTTP/2 end of stream message was received.
*/
public boolean responseSuccessfullyCompleted() {
try {
return latch.await(5, TimeUnit.SECONDS);
} catch (InterruptedException ie) {
System.err.println("Latch exception: " + ie.getMessage());
return false;
}
}
}
|
fenik17/netty
|
example/src/main/java/io/netty/example/http2/helloworld/frame/client/Http2ClientStreamFrameResponseHandler.java
|
Java
|
apache-2.0
| 2,568 |
package cn.brent.console.table;
/**
* <p>
* 实体类-
* </p>
* <p>
* Table: sys_uid_sysid
* </p>
*
* @since 2015-08-18 05:00:27
*/
public class TSysUidSysid {
/** */
public static final String UID = "UID";
/** */
public static final String SYS = "SYS";
/** */
public static final String SysID = "SysID";
/** */
public static final String AddTime = "AddTime";
}
|
brenthub/brent-console
|
brent-console-interface/src/main/java/cn/brent/console/table/TSysUidSysid.java
|
Java
|
apache-2.0
| 388 |
/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.dc.smarteam.test.entity;
import com.fasterxml.jackson.annotation.JsonBackReference;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import com.dc.smarteam.common.persistence.TreeEntity;
/**
* 树结构生成Entity
* @author ThinkGem
* @version 2015-04-06
*/
public class TestTree extends TreeEntity<TestTree> {
private static final long serialVersionUID = 1L;
private TestTree parent; // 父级编号
private String parentIds; // 所有父级编号
private String name; // 名称
private Integer sort; // 排序
public TestTree() {
super();
}
public TestTree(String id){
super(id);
}
@JsonBackReference
@NotNull(message="父级编号不能为空")
public TestTree getParent() {
return parent;
}
public void setParent(TestTree parent) {
this.parent = parent;
}
@Length(min=1, max=2000, message="所有父级编号长度必须介于 1 和 2000 之间")
public String getParentIds() {
return parentIds;
}
public void setParentIds(String parentIds) {
this.parentIds = parentIds;
}
@Length(min=1, max=100, message="名称长度必须介于 1 和 100 之间")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@NotNull(message="排序不能为空")
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public String getParentId() {
return parent != null && parent.getId() != null ? parent.getId() : "0";
}
}
|
VincentFxz/EAM
|
src/main/java/com/dc/smarteam/test/entity/TestTree.java
|
Java
|
apache-2.0
| 1,652 |
#include "ContentSearcher.h"
#include "FileNameSearcher.h"
#include "FileSizeSearcher.h"
#include "FileTimeSearcher.h"
#include "Searcher.h"
#include "SearcherFactory.h"
#include "../SearchParameter.h"
Searcher* SearcherFactory::BuildSearcher(const SearchParameter& param)
{
PhaseOneParameter oneParam = *param.phaseOneParam;
Searcher* searcher = new FileNameSearcher(oneParam); // need to build anyhow
if (oneParam.HasSizeConstraint())
{
searcher = new FileSizeSearcher(searcher, oneParam);
}
if (oneParam.HasTimeConstraints())
{
searcher = new FileTimeSearcher(searcher, oneParam);
}
// for performance issue, we should always construct ContentSearcher at last so this content searcher will performed at a minimum time
if (param.PhaseTwoSearchNeeded())
{
searcher = new ContentSearcher(searcher, *param.phaseTwoParam);
}
return searcher;
}
|
obarnet/Teste
|
SearchMonkeySRC/engine/SearcherFactory.cpp
|
C++
|
apache-2.0
| 952 |
package com.lianyu.tech.website.web.controller.verify;
import com.lianyu.tech.core.platform.exception.InvalidRequestException;
import com.lianyu.tech.core.util.StringUtils;
import com.lianyu.tech.website.web.SessionConstants;
import com.lianyu.tech.website.web.SiteContext;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
/**
* @author bowen
*/
@Service
public class VerifyCodeValidator {
@Inject
SiteContext siteContext;
public void setVerifyCode(String code) {
siteContext.addSession(SessionConstants.VERIFY_CODE_IMG, code);
}
public void verify(String code) {
String sessionCode = siteContext.getSession(SessionConstants.VERIFY_CODE_IMG);
if (!StringUtils.hasText(sessionCode)) {
throw new InvalidRequestException("验证码不存在");
}
if (!sessionCode.equalsIgnoreCase(code)) {
throw new InvalidRequestException("验证码不正确");
}
}
}
|
howbigbobo/com.lianyu.tech
|
website/src/main/java/com/lianyu/tech/website/web/controller/verify/VerifyCodeValidator.java
|
Java
|
apache-2.0
| 978 |
package metrics
import (
"time"
"github.com/prebid/prebid-server/openrtb_ext"
"github.com/stretchr/testify/mock"
)
// MetricsEngineMock is mock for the MetricsEngine interface
type MetricsEngineMock struct {
mock.Mock
}
// RecordRequest mock
func (me *MetricsEngineMock) RecordRequest(labels Labels) {
me.Called(labels)
}
// RecordConnectionAccept mock
func (me *MetricsEngineMock) RecordConnectionAccept(success bool) {
me.Called(success)
}
// RecordConnectionClose mock
func (me *MetricsEngineMock) RecordConnectionClose(success bool) {
me.Called(success)
}
// RecordImps mock
func (me *MetricsEngineMock) RecordImps(labels ImpLabels) {
me.Called(labels)
}
// RecordRequestTime mock
func (me *MetricsEngineMock) RecordRequestTime(labels Labels, length time.Duration) {
me.Called(labels, length)
}
// RecordStoredDataFetchTime mock
func (me *MetricsEngineMock) RecordStoredDataFetchTime(labels StoredDataLabels, length time.Duration) {
me.Called(labels, length)
}
// RecordStoredDataError mock
func (me *MetricsEngineMock) RecordStoredDataError(labels StoredDataLabels) {
me.Called(labels)
}
// RecordAdapterPanic mock
func (me *MetricsEngineMock) RecordAdapterPanic(labels AdapterLabels) {
me.Called(labels)
}
// RecordAdapterRequest mock
func (me *MetricsEngineMock) RecordAdapterRequest(labels AdapterLabels) {
me.Called(labels)
}
// RecordAdapterConnections mock
func (me *MetricsEngineMock) RecordAdapterConnections(bidderName openrtb_ext.BidderName, connWasReused bool, connWaitTime time.Duration) {
me.Called(bidderName, connWasReused, connWaitTime)
}
// RecordDNSTime mock
func (me *MetricsEngineMock) RecordDNSTime(dnsLookupTime time.Duration) {
me.Called(dnsLookupTime)
}
func (me *MetricsEngineMock) RecordTLSHandshakeTime(tlsHandshakeTime time.Duration) {
me.Called(tlsHandshakeTime)
}
// RecordAdapterBidReceived mock
func (me *MetricsEngineMock) RecordAdapterBidReceived(labels AdapterLabels, bidType openrtb_ext.BidType, hasAdm bool) {
me.Called(labels, bidType, hasAdm)
}
// RecordAdapterPrice mock
func (me *MetricsEngineMock) RecordAdapterPrice(labels AdapterLabels, cpm float64) {
me.Called(labels, cpm)
}
// RecordAdapterTime mock
func (me *MetricsEngineMock) RecordAdapterTime(labels AdapterLabels, length time.Duration) {
me.Called(labels, length)
}
// RecordCookieSync mock
func (me *MetricsEngineMock) RecordCookieSync(status CookieSyncStatus) {
me.Called(status)
}
// RecordSyncerRequest mock
func (me *MetricsEngineMock) RecordSyncerRequest(key string, status SyncerCookieSyncStatus) {
me.Called(key, status)
}
// RecordSetUid mock
func (me *MetricsEngineMock) RecordSetUid(status SetUidStatus) {
me.Called(status)
}
// RecordSyncerSet mock
func (me *MetricsEngineMock) RecordSyncerSet(key string, status SyncerSetUidStatus) {
me.Called(key, status)
}
// RecordStoredReqCacheResult mock
func (me *MetricsEngineMock) RecordStoredReqCacheResult(cacheResult CacheResult, inc int) {
me.Called(cacheResult, inc)
}
// RecordStoredImpCacheResult mock
func (me *MetricsEngineMock) RecordStoredImpCacheResult(cacheResult CacheResult, inc int) {
me.Called(cacheResult, inc)
}
// RecordAccountCacheResult mock
func (me *MetricsEngineMock) RecordAccountCacheResult(cacheResult CacheResult, inc int) {
me.Called(cacheResult, inc)
}
// RecordPrebidCacheRequestTime mock
func (me *MetricsEngineMock) RecordPrebidCacheRequestTime(success bool, length time.Duration) {
me.Called(success, length)
}
// RecordRequestQueueTime mock
func (me *MetricsEngineMock) RecordRequestQueueTime(success bool, requestType RequestType, length time.Duration) {
me.Called(success, requestType, length)
}
// RecordTimeoutNotice mock
func (me *MetricsEngineMock) RecordTimeoutNotice(success bool) {
me.Called(success)
}
// RecordRequestPrivacy mock
func (me *MetricsEngineMock) RecordRequestPrivacy(privacy PrivacyLabels) {
me.Called(privacy)
}
// RecordAdapterGDPRRequestBlocked mock
func (me *MetricsEngineMock) RecordAdapterGDPRRequestBlocked(adapterName openrtb_ext.BidderName) {
me.Called(adapterName)
}
|
prebid/prebid-server
|
metrics/metrics_mock.go
|
GO
|
apache-2.0
| 4,060 |
/*
* Copyright 2013 Romain Gilles
*
* 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.javabits.yar;
import java.util.EventListener;
/**
* TODO comment
* Date: 4/2/13
* Time: 10:16 PM
*
* @author Romain Gilles
*/
public interface SupplierListener extends EventListener {
void supplierChanged(SupplierEvent supplierEvent);
}
|
javabits/yar
|
yar-api/src/main/java/org/javabits/yar/SupplierListener.java
|
Java
|
apache-2.0
| 886 |
using JetBrains.Annotations;
using JetBrains.Diagnostics;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Daemon;
using JetBrains.ReSharper.Feature.Services.CSharp.ContextActions;
using JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.PerformanceCriticalCodeAnalysis.ContextSystem;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Feature.Services.CallGraph.PerformanceAnalysis
{
public abstract class PerformanceAnalysisContextActionBase: CallGraphContextActionBase
{
[NotNull] protected readonly PerformanceCriticalContextProvider PerformanceContextProvider;
[NotNull] protected readonly ExpensiveInvocationContextProvider ExpensiveContextProvider;
[NotNull] protected readonly SolutionAnalysisService SolutionAnalysisService;
protected PerformanceAnalysisContextActionBase([NotNull] ICSharpContextActionDataProvider dataProvider)
: base(dataProvider)
{
ExpensiveContextProvider = dataProvider.Solution.GetComponent<ExpensiveInvocationContextProvider>().NotNull();
PerformanceContextProvider = dataProvider.Solution.GetComponent<PerformanceCriticalContextProvider>().NotNull();
SolutionAnalysisService = dataProvider.Solution.GetComponent<SolutionAnalysisService>().NotNull();
}
protected override bool IsAvailable(IUserDataHolder cache, IMethodDeclaration containingMethod)
{
return PerformanceAnalysisUtil.IsAvailable(containingMethod);
}
}
}
|
JetBrains/resharper-unity
|
resharper/resharper-unity/src/Unity/CSharp/Feature/Services/CallGraph/PerformanceAnalysis/PerformanceAnalysisContextActionBase.cs
|
C#
|
apache-2.0
| 1,574 |
/*
* Copyright 2000-2009 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.extapi.psi;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.impl.source.tree.SharedImplUtil;
import javax.annotation.Nonnull;
/**
* @author max
*/
public class ASTWrapperPsiElement extends ASTDelegatePsiElement {
private final ASTNode myNode;
public ASTWrapperPsiElement(@Nonnull final ASTNode node) {
myNode = node;
}
@Override
public PsiElement getParent() {
return SharedImplUtil.getParent(getNode());
}
@Override
@Nonnull
public ASTNode getNode() {
return myNode;
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + myNode.getElementType().toString() + ")";
}
}
|
consulo/consulo
|
modules/base/core-impl/src/main/java/com/intellij/extapi/psi/ASTWrapperPsiElement.java
|
Java
|
apache-2.0
| 1,314 |
package com.zabbix.sisyphus.contract.entity;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* 借贷产品
*@author zabbix
*2016年10月19日
*/
@Entity
@Table(name="con_t_credit_pro")
public class CreditPro extends com.zabbix.sisyphus.base.entity.IdEntity implements Serializable {
private static final long serialVersionUID = 1L;
private BigDecimal amount;
@Temporal(TemporalType.DATE)
@Column(name="end_time")
private Date endTime;
private BigDecimal fee;
private BigDecimal interest;
@Column(name="into_amount")
private BigDecimal intoAmount;
@Column(name="manger_free")
private BigDecimal mangerFree;
private String memo;
private BigDecimal number;
@Column(name="pay_way")
private String payWay;
@Column(name="product_code")
private String productCode;
@Column(name="product_name")
private String productName;
@Column(name="repayment_amount")
private BigDecimal repaymentAmount;
@Column(name="service_charge")
private BigDecimal serviceCharge;
@Temporal(TemporalType.DATE)
@Column(name="start_time")
private Date startTime;
private String status;
@Column(name="total_cost")
private BigDecimal totalCost;
@Column(name="total_fee")
private BigDecimal totalFee;
public CreditPro() {
}
public BigDecimal getAmount() {
return this.amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Date getEndTime() {
return this.endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public BigDecimal getFee() {
return this.fee;
}
public void setFee(BigDecimal fee) {
this.fee = fee;
}
public BigDecimal getInterest() {
return this.interest;
}
public void setInterest(BigDecimal interest) {
this.interest = interest;
}
public BigDecimal getIntoAmount() {
return this.intoAmount;
}
public void setIntoAmount(BigDecimal intoAmount) {
this.intoAmount = intoAmount;
}
public BigDecimal getMangerFree() {
return this.mangerFree;
}
public void setMangerFree(BigDecimal mangerFree) {
this.mangerFree = mangerFree;
}
public String getMemo() {
return this.memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public BigDecimal getNumber() {
return this.number;
}
public void setNumber(BigDecimal number) {
this.number = number;
}
public String getPayWay() {
return this.payWay;
}
public void setPayWay(String payWay) {
this.payWay = payWay;
}
public String getProductCode() {
return this.productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public BigDecimal getRepaymentAmount() {
return this.repaymentAmount;
}
public void setRepaymentAmount(BigDecimal repaymentAmount) {
this.repaymentAmount = repaymentAmount;
}
public BigDecimal getServiceCharge() {
return this.serviceCharge;
}
public void setServiceCharge(BigDecimal serviceCharge) {
this.serviceCharge = serviceCharge;
}
public Date getStartTime() {
return this.startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public BigDecimal getTotalCost() {
return this.totalCost;
}
public void setTotalCost(BigDecimal totalCost) {
this.totalCost = totalCost;
}
public BigDecimal getTotalFee() {
return this.totalFee;
}
public void setTotalFee(BigDecimal totalFee) {
this.totalFee = totalFee;
}
}
|
adolfmc/zabbix-parent
|
zabbix-sisyphus/src/main/java/com/zabbix/sisyphus/contract/entity/CreditPro.java
|
Java
|
apache-2.0
| 4,070 |
import java.io.IOException;
import java.net.Socket;
public class Shutdown {
public static void main(String[] args) throws IOException {
try (Socket socket = new Socket("localhost", 8005)) {
socket.getOutputStream().write("SHUTDOWN".getBytes());
}
}
}
|
xqbase/util
|
util/src/test/java/Shutdown.java
|
Java
|
apache-2.0
| 269 |
import { forOwn, forEach, keys, values, isNil, isEmpty as _isEmpty, isObject, bind } from 'lodash'
import { Promise } from 'bluebird'
function InputModel(vals) {
let modelValue = (vals['value'] ? vals['value'] : null )
let viewValue = modelValue
let valid = true
let pristine = true
let listeners = setupListeners(vals['listeners'])
let validators = (vals['validators'] ? vals['validators'] : {} )
var self = {
name: (vals['name'] ? vals['name'] : null ),
getValue: getValue,
updateValue: updateValue,
errors: {},
isValid: isValid,
isPristine: isPristine,
isEmpty: isEmpty,
addListener: addListener,
removeListener: removeListener,
addValidator: addValidator,
removeValidator: removeValidator
}
function getValue() {
return modelValue
}
function updateValue(event) {
let newVal = event
if (event && event.target && event.target.value !== undefined) {
event.stopPropagation()
newVal = event.target.value
if (newVal === '') {
newVal = null;
}
}
if (newVal === viewValue && newVal === modelValue && !isObject(newVal)) {
return
}
pristine = false
viewValue = newVal
return processViewUpdate()
}
function isValid() {
return valid
}
function isPristine() {
return pristine
}
function isEmpty() {
return (isNil(modelValue) || _isEmpty(modelValue))
}
function addListener(listener, listenerName) {
const listenerKey = listenerName || listener
listeners[listenerKey] = Promise.method(listener)
}
function removeListener(listenerKey) {
delete listeners[listenerKey]
}
function addValidator(validatorName, validatorFunc ) {
validators[validatorName] = validatorFunc
}
function removeValidator(validatorName) {
delete validators[validatorName]
}
function processViewUpdate() {
const localViewValue = viewValue
self.errors = processValidators(localViewValue)
valid = (keys(self.errors).length === 0)
modelValue = localViewValue
return processListeners(localViewValue)
}
function processValidators(localViewValue) {
let newErrors = {}
let validatorResult
forOwn(validators, function(validator, vName){
try {
validatorResult = validator(localViewValue)
if (validatorResult) {
newErrors[vName] = validatorResult
}
} catch (err) {
console.log('Validator Error: '+err)
}
})
return newErrors
}
function processListeners(localViewValue) {
let retPromises = []
const listenerFuncs = keys(listeners)
forEach(listenerFuncs, function(listenerName){
const listener = listeners[listenerName]
try {
retPromises.push(listener(localViewValue, listenerName))
} catch (err) {
console.log('Listener Error: '+err)
}
})
return Promise.all(retPromises)
}
function setupListeners(requestedListeners) {
const ret = {}
forEach(requestedListeners, function(listener){
ret[listener] = Promise.method(listener)
})
return ret
}
self.errors = processValidators(viewValue)
valid = (keys(self.errors).length === 0)
return self
}
export function createInputModel(vals) {
vals = vals || {}
const ret = new InputModel(vals)
return ret
}
export function createInputModelChain(fieldNames, sourceModel) {
const ret = {}
forEach(fieldNames, (fieldName) => {
ret[fieldName] = createInputModel({name:fieldName, value:sourceModel.getValue()[fieldName] })
ret[fieldName].addListener( bind(inputModelMapFunc, undefined, sourceModel, ret[fieldName], fieldName), fieldName )
})
return ret
}
export function setupInputModelListenerMapping(fieldNames, destModel, sourceModels, mapFunc) {
forEach(fieldNames, (fieldName) => {
sourceModels[fieldName].addListener( bind(mapFunc, undefined, destModel, sourceModels[fieldName], fieldName), fieldName )
})
}
export function inputModelListenerCleanUp(fieldNames, sourceModels) {
forEach(fieldNames, (fieldName) => {
sourceModels[fieldName].removeListener( fieldName )
})
}
export function inputModelMapFunc(destModel, sourceModel, fieldName) {
const obj = destModel.getValue()
obj[fieldName] = sourceModel.getValue()
destModel.updateValue(obj)
}
export function inputModelAddValidators(inputModel, valsObj) {
forOwn(valsObj, function(validator, vName){
inputModel.addValidator(vName, validator)
})
}
|
sword42/react-ui-helpers
|
src/input/InputModel.js
|
JavaScript
|
apache-2.0
| 4,219 |
package org.domeos.framework.api.model.deployment.related;
/**
* Created by xupeng on 16-2-25.
*/
public enum DeploymentAccessType {
K8S_SERVICE,
DIY
}
|
domeos/server
|
src/main/java/org/domeos/framework/api/model/deployment/related/DeploymentAccessType.java
|
Java
|
apache-2.0
| 163 |
setTimeout(function(){
(function(){
id = Ti.App.Properties.getString("tisink", "");
var param, xhr;
file = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,"examples/contacts_picker.js");
text = (file.read()).text
xhr = Titanium.Network.createHTTPClient();
xhr.open("POST", "http://tisink.nodester.com/");
xhr.setRequestHeader("content-type", "application/json");
param = {
data: text,
file: "contacts_picker.js",
id: id
};
xhr.send(JSON.stringify(param));
})();
},0);
//TISINK----------------
var win = Ti.UI.currentWindow;
var values = {cancel:function() {info.text = 'Cancelled';}};
if (Ti.Platform.osname === 'android') {
// android doesn't have the selectedProperty support, so go ahead and force selectedPerson
values.selectedPerson = function(e) {info.text = e.person.fullName;};
}
var show = Ti.UI.createButton({
title:'Show picker',
bottom:20,
width:200,
height:40
});
show.addEventListener('click', function() {
Titanium.Contacts.showContacts(values);
});
win.add(show);
var info = Ti.UI.createLabel({
text:'',
bottom:70,
height:'auto',
width:'auto'
});
win.add(info);
var v1 = Ti.UI.createView({
top:20,
width:300,
height:40,
left:10
});
if (Ti.Platform.osname !== 'android') {
var l1 = Ti.UI.createLabel({
text:'Animated:',
left:0
});
var s1 = Ti.UI.createSwitch({
value:true,
right:10,
top:5
});
s1.addEventListener('change', function() {
if (s1.value) {
values.animated = true;
}
else {
values.animated = false;
}
});
v1.add(l1);
v1.add(s1);
var v2 = Ti.UI.createView({
top:70,
width:300,
height:40,
left:10
});
var l2 = Ti.UI.createLabel({
text:'Address only:',
left:0
});
var s2 = Ti.UI.createSwitch({
value:false,
right:10,
top:5
});
s2.addEventListener('change', function() {
if (s2.value) {
values.fields = ['address'];
}
else {
delete values.fields;
}
});
v2.add(l2);
v2.add(s2);
var v3 = Ti.UI.createView({
top:120,
width:300,
height:40,
left:10
});
var l3 = Ti.UI.createLabel({
text:'Stop on person:',
left:0
});
var s3 = Ti.UI.createSwitch({
value:false,
right:10,
top:5
});
s3.addEventListener('change', function() {
if (s3.value) {
values.selectedPerson = function(e) {
info.text = e.person.fullName;
};
if (s4.value) {
s4.value = false;
}
}
else {
delete values.selectedPerson;
}
});
v3.add(l3);
v3.add(s3);
var v4 = Ti.UI.createView({
top:170,
width:300,
height:40,
left:10
});
var l4 = Ti.UI.createLabel({
text:'Stop on property:',
left:0
});
var s4 = Ti.UI.createSwitch({
value:false,
right:10,
top:5
});
s4.addEventListener('change', function() {
if (s4.value) {
values.selectedProperty = function(e) {
if (e.property == 'address') {
Ti.API.log(e.value);
info.text = e.value.Street;
}
else {
info.text = e.value;
}
};
if (s3.value) {
s3.value = false;
}
}
else {
delete values.selectedProperty;
}
});
v4.add(l4);
v4.add(s4);
win.add(v1);
win.add(v2);
win.add(v3);
win.add(v4);
}
|
steerapi/KichenSinkLive
|
Resources/examples/contacts_picker.js
|
JavaScript
|
apache-2.0
| 3,139 |
/*
* @license Apache-2.0
*
* Copyright (c) 2021 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.
*/
import safeCasts = require( './index' );
// TESTS //
// The function returns an object, array of strings, or null...
{
safeCasts(); // $ExpectType any
safeCasts( 'float32' ); // $ExpectType any
safeCasts( 'float' ); // $ExpectType any
}
// The function does not compile if provided more than one argument...
{
safeCasts( 'float32', 123 ); // $ExpectError
}
|
stdlib-js/stdlib
|
lib/node_modules/@stdlib/ndarray/safe-casts/docs/types/test.ts
|
TypeScript
|
apache-2.0
| 982 |
package org.semanticweb.ontop.protege.utils;
/*
* #%L
* ontop-protege4
* %%
* Copyright (C) 2009 - 2013 KRDB Research Centre. Free University of Bozen Bolzano.
* %%
* 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.
* #L%
*/
import it.unibz.krdb.obda.model.OBDADataSource;
public interface DatasourceSelectorListener
{
public void datasourceChanged(OBDADataSource oldSource, OBDADataSource newSource);
}
|
eschwert/ontop
|
ontop-protege/src/main/java/org/semanticweb/ontop/protege/utils/DatasourceSelectorListener.java
|
Java
|
apache-2.0
| 922 |
package com.wei.you.zhihu.spider.task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.wei.you.zhihu.spider.service.IZhihuRecommendationService;
/**
* 定时任务
*
* @author sunzc
*
* 2017年6月10日 下午7:18:42
*/
@Component
public class SpiderTask {
// 注入分析知乎Recommendation获取的网页数据
@Autowired
private IZhihuRecommendationService zhihuRecommendationService;
/**
* Druid的监控数据定时发送至ES
*/
@Scheduled(cron = "0 */1 * * * * ")
public void work() {
zhihuRecommendationService.anaylicsRecommendation();
}
}
|
sdc1234/zhihu-spider
|
src/main/java/com/wei/you/zhihu/spider/task/SpiderTask.java
|
Java
|
apache-2.0
| 720 |
/*
*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.apimgt.rest.api.common.impl;
import com.google.gson.reflect.TypeToken;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.apimgt.core.api.APIDefinition;
import org.wso2.carbon.apimgt.core.exception.APIManagementException;
import org.wso2.carbon.apimgt.core.exception.ErrorHandler;
import org.wso2.carbon.apimgt.core.exception.ExceptionCodes;
import org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20;
import org.wso2.carbon.apimgt.core.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.core.models.AccessTokenInfo;
import org.wso2.carbon.apimgt.rest.api.common.APIConstants;
import org.wso2.carbon.apimgt.rest.api.common.RestApiConstants;
import org.wso2.carbon.apimgt.rest.api.common.api.RESTAPIAuthenticator;
import org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException;
import org.wso2.carbon.apimgt.rest.api.common.util.RestApiUtil;
import org.wso2.carbon.apimgt.rest.api.configurations.ConfigurationService;
import org.wso2.carbon.messaging.Headers;
import org.wso2.msf4j.Request;
import org.wso2.msf4j.Response;
import org.wso2.msf4j.ServiceMethodInfo;
import org.wso2.msf4j.util.SystemVariableUtil;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
/**
* OAuth2 implementation class
*/
public class OAuth2Authenticator implements RESTAPIAuthenticator {
private static final Logger log = LoggerFactory.getLogger(OAuth2Authenticator.class);
private static final String LOGGED_IN_USER = "LOGGED_IN_USER";
private static String authServerURL;
static {
authServerURL = SystemVariableUtil.getValue(RestApiConstants.AUTH_SERVER_URL_KEY,
RestApiConstants.AUTH_SERVER_URL);
if (authServerURL == null) {
throw new RuntimeException(RestApiConstants.AUTH_SERVER_URL_KEY + " is not specified.");
}
}
/*
* This method performs authentication and authorization
* @param Request
* @param Response
* @param ServiceMethodInfo
* throws Exception
* */
@Override
public boolean authenticate(Request request, Response responder, ServiceMethodInfo serviceMethodInfo)
throws APIMgtSecurityException {
ErrorHandler errorHandler = null;
boolean isTokenValid = false;
Headers headers = request.getHeaders();
if (headers != null && headers.contains(RestApiConstants.COOKIE_HEADER) && isCookieExists(headers,
APIConstants.AccessTokenConstants.AM_TOKEN_MSF4J)) {
String accessToken = null;
String cookies = headers.get(RestApiConstants.COOKIE_HEADER);
String partialTokenFromCookie = extractPartialAccessTokenFromCookie(cookies);
if (partialTokenFromCookie != null && headers.contains(RestApiConstants.AUTHORIZATION_HTTP_HEADER)) {
String authHeader = headers.get(RestApiConstants.AUTHORIZATION_HTTP_HEADER);
String partialTokenFromHeader = extractAccessToken(authHeader);
accessToken = (partialTokenFromHeader != null) ?
partialTokenFromHeader + partialTokenFromCookie :
partialTokenFromCookie;
}
isTokenValid = validateTokenAndScopes(request, serviceMethodInfo, accessToken);
request.setProperty(LOGGED_IN_USER, getEndUserName(accessToken));
} else if (headers != null && headers.contains(RestApiConstants.AUTHORIZATION_HTTP_HEADER)) {
String authHeader = headers.get(RestApiConstants.AUTHORIZATION_HTTP_HEADER);
String accessToken = extractAccessToken(authHeader);
if (accessToken != null) {
isTokenValid = validateTokenAndScopes(request, serviceMethodInfo, accessToken);
request.setProperty(LOGGED_IN_USER, getEndUserName(accessToken));
}
} else {
throw new APIMgtSecurityException("Missing Authorization header in the request.`",
ExceptionCodes.MALFORMED_AUTHORIZATION_HEADER_OAUTH);
}
return isTokenValid;
}
private boolean validateTokenAndScopes(Request request, ServiceMethodInfo serviceMethodInfo, String accessToken)
throws APIMgtSecurityException {
//Map<String, String> tokenInfo = validateToken(accessToken);
AccessTokenInfo accessTokenInfo = validateToken(accessToken);
String restAPIResource = getRestAPIResource(request);
//scope validation
return validateScopes(request, serviceMethodInfo, accessTokenInfo.getScopes(), restAPIResource);
}
/**
* Extract the EndUsername from accessToken.
*
* @param accessToken the access token
* @return loggedInUser if the token is a valid token
*/
private String getEndUserName(String accessToken) throws APIMgtSecurityException {
String loggedInUser;
loggedInUser = validateToken(accessToken).getEndUserName();
return loggedInUser.substring(0, loggedInUser.lastIndexOf("@"));
}
/**
* Extract the accessToken from the give Authorization header value and validates the accessToken
* with an external key manager.
*
* @param accessToken the access token
* @return responseData if the token is a valid token
*/
private AccessTokenInfo validateToken(String accessToken) throws APIMgtSecurityException {
// 1. Send a request to key server's introspect endpoint to validate this token
AccessTokenInfo accessTokenInfo = getValidatedTokenResponse(accessToken);
// 2. Process the response and return true if the token is valid.
if (!accessTokenInfo.isTokenValid()) {
throw new APIMgtSecurityException("Invalid Access token.", ExceptionCodes.ACCESS_TOKEN_INACTIVE);
}
return accessTokenInfo;
/*
// 1. Send a request to key server's introspect endpoint to validate this token
String responseStr = getValidatedTokenResponse(accessToken);
Map<String, String> responseData = getResponseDataMap(responseStr);
// 2. Process the response and return true if the token is valid.
if (responseData == null || !Boolean.parseBoolean(responseData.get(IntrospectionResponse.ACTIVE))) {
throw new APIMgtSecurityException("Invalid Access token.", ExceptionCodes.ACCESS_TOKEN_INACTIVE);
}
return responseData;
*/
}
/**
* @param cookie Cookies header which contains the access token
* @return partial access token present in the cookie.
* @throws APIMgtSecurityException if the Authorization header is invalid
*/
private String extractPartialAccessTokenFromCookie(String cookie) {
//Append unique environment name in deployment.yaml
String environmentName = ConfigurationService.getEnvironmentName();
if (cookie != null) {
cookie = cookie.trim();
String[] cookies = cookie.split(";");
String token2 = Arrays.stream(cookies)
.filter(name -> name.contains(
APIConstants.AccessTokenConstants.AM_TOKEN_MSF4J + "_" + environmentName
)).findFirst().orElse("");
String tokensArr[] = token2.split("=");
if (tokensArr.length == 2) {
return tokensArr[1];
}
}
return null;
}
private boolean isCookieExists(Headers headers, String cookieName) {
String cookie = headers.get(RestApiConstants.COOKIE_HEADER);
String token2 = null;
//Append unique environment name in deployment.yaml
String environmentName = ConfigurationService.getEnvironmentName();
if (cookie != null) {
cookie = cookie.trim();
String[] cookies = cookie.split(";");
token2 = Arrays.stream(cookies)
.filter(name -> name.contains(cookieName + "_" + environmentName))
.findFirst().orElse(null);
}
return (token2 != null);
}
/*
* This methos is used to get the rest api resource based on the api context
* @param Request
* @return String : api resource object
* @throws APIMgtSecurityException if resource could not be found.
* */
private String getRestAPIResource(Request request) throws APIMgtSecurityException {
//todo improve to get appname as a property in the Request
String path = (String) request.getProperty(APIConstants.REQUEST_URL);
String restAPIResource = null;
//this is publisher API so pick that API
try {
if (path.contains(RestApiConstants.REST_API_PUBLISHER_CONTEXT)) {
restAPIResource = RestApiUtil.getPublisherRestAPIResource();
} else if (path.contains(RestApiConstants.REST_API_STORE_CONTEXT)) {
restAPIResource = RestApiUtil.getStoreRestAPIResource();
} else if (path.contains(RestApiConstants.REST_API_ADMIN_CONTEXT)) {
restAPIResource = RestApiUtil.getAdminRestAPIResource();
} else if (path.contains(RestApiConstants.REST_API_ANALYTICS_CONTEXT)) {
restAPIResource = RestApiUtil.getAnalyticsRestAPIResource();
} else {
throw new APIMgtSecurityException("No matching Rest Api definition found for path:" + path);
}
} catch (APIManagementException e) {
throw new APIMgtSecurityException(e.getMessage(), ExceptionCodes.AUTH_GENERAL_ERROR);
}
return restAPIResource;
}
/*
* This method validates the given scope against scopes defined in the api resource
* @param Request
* @param ServiceMethodInfo
* @param scopesToValidate scopes extracted from the access token
* @return true if scope validation successful
* */
@SuppressFBWarnings({"DLS_DEAD_LOCAL_STORE"})
private boolean validateScopes(Request request, ServiceMethodInfo serviceMethodInfo, String scopesToValidate,
String restAPIResource) throws APIMgtSecurityException {
final boolean authorized[] = {false};
String path = (String) request.getProperty(APIConstants.REQUEST_URL);
String verb = (String) request.getProperty(APIConstants.HTTP_METHOD);
if (log.isDebugEnabled()) {
log.debug("Invoking rest api resource path " + verb + " " + path + " ");
log.debug("LoggedIn user scopes " + scopesToValidate);
}
String[] scopesArr = new String[0];
if (scopesToValidate != null) {
scopesArr = scopesToValidate.split(" ");
}
if (scopesToValidate != null && scopesArr.length > 0) {
final List<String> scopes = Arrays.asList(scopesArr);
if (restAPIResource != null) {
APIDefinition apiDefinition = new APIDefinitionFromSwagger20();
try {
String apiResourceDefinitionScopes = apiDefinition.getScopeOfResourcePath(restAPIResource, request,
serviceMethodInfo);
if (apiResourceDefinitionScopes == null) {
if (log.isDebugEnabled()) {
log.debug("Scope not defined in swagger for matching resource " + path + " and verb "
+ verb + " . Hence consider as anonymous permission and let request to continue.");
}
// scope validation gets through if no scopes found in the api definition
authorized[0] = true;
} else {
Arrays.stream(apiResourceDefinitionScopes.split(" "))
.forEach(scopeKey -> {
Optional<String> key = scopes.stream().filter(scp -> {
return scp.equalsIgnoreCase(scopeKey);
}).findAny();
if (key.isPresent()) {
authorized[0] = true; //scope validation success if one of the
// apiResourceDefinitionScopes found.
}
});
}
} catch (APIManagementException e) {
String message = "Error while validating scopes";
log.error(message, e);
throw new APIMgtSecurityException(message, ExceptionCodes.INVALID_SCOPE);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Rest API resource could not be found for request path '" + path + "'");
}
}
} else { // scope validation gets through if access token does not contain scopes to validate
authorized[0] = true;
}
if (!authorized[0]) {
String message = "Scope validation fails for the scopes " + scopesToValidate;
throw new APIMgtSecurityException(message, ExceptionCodes.INVALID_SCOPE);
}
return authorized[0];
}
/**
* @param authHeader Authorization Bearer header which contains the access token
* @return access token
* @throws APIMgtSecurityException if the Authorization header is invalid
*/
private String extractAccessToken(String authHeader) throws APIMgtSecurityException {
authHeader = authHeader.trim();
if (authHeader.toLowerCase(Locale.US).startsWith(RestApiConstants.BEARER_PREFIX)) {
// Split the auth header to get the access token.
// Value should be in this format ("Bearer" 1*SP b64token)
String[] authHeaderParts = authHeader.split(" ");
if (authHeaderParts.length == 2) {
return authHeaderParts[1];
} else if (authHeaderParts.length < 2) {
return null;
}
}
throw new APIMgtSecurityException("Invalid Authorization : Bearer header " +
authHeader, ExceptionCodes.MALFORMED_AUTHORIZATION_HEADER_OAUTH);
}
/**
* Validated the given accessToken with an external key server.
*
* @param accessToken AccessToken to be validated.
* @return the response from the key manager server.
*/
private AccessTokenInfo getValidatedTokenResponse(String accessToken) throws APIMgtSecurityException {
try {
AccessTokenInfo accessTokenInfo = APIManagerFactory.getInstance().getIdentityProvider()
.getTokenMetaData(accessToken);
return accessTokenInfo;
/*
url = new URL(authServerURL);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoOutput(true);
urlConn.setRequestMethod(HttpMethod.POST);
String payload = "token=" + accessToken + "&token_type_hint=" + RestApiConstants.BEARER_PREFIX;
urlConn.getOutputStream().write(payload.getBytes(Charsets.UTF_8));
String response = new String(IOUtils.toByteArray(urlConn.getInputStream()), Charsets.UTF_8);
log.debug("Response received from Auth Server : " + response);
return response;
} catch (java.io.IOException e) {
log.error("Error invoking Authorization Server", e);
throw new APIMgtSecurityException("Error invoking Authorization Server", ExceptionCodes.AUTH_GENERAL_ERROR);
*/
} catch (APIManagementException e) {
log.error("Error while validating access token", e);
throw new APIMgtSecurityException("Error while validating access token", ExceptionCodes.AUTH_GENERAL_ERROR);
}
}
/**
* @param responseStr validated token response string returned from the key server.
* @return a Map of key, value pairs available the response String.
*/
/*private Map<String, String> getResponseDataMap(String responseStr) {
Gson gson = new Gson();
Type typeOfMapOfStrings = new ExtendedTypeToken<Map<String, String>>() {
}.getType();
return gson.fromJson(responseStr, typeOfMapOfStrings);
}*/
/**
* This class extends the {@link com.google.gson.reflect.TypeToken}.
* Created due to the findbug issue when passing anonymous inner class.
*
* @param <T> Generic type
*/
private static class ExtendedTypeToken<T> extends TypeToken {
}
}
|
ChamNDeSilva/carbon-apimgt
|
components/apimgt/org.wso2.carbon.apimgt.rest.api.commons/src/main/java/org/wso2/carbon/apimgt/rest/api/common/impl/OAuth2Authenticator.java
|
Java
|
apache-2.0
| 17,387 |
package org.myrobotlab.service.data;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.myrobotlab.test.AbstractTest;
public class PinTest extends AbstractTest {
@Test
public void testPin() {
Pin p = new Pin();
assertNotNull(p);
Pin p2 = new Pin(1, 2, 3, "foo");
assertEquals(1, p2.pin);
assertEquals(2, p2.type);
assertEquals(3, p2.value);
assertEquals("foo", p2.source);
Pin p3 = new Pin(p2);
p2.pin = 4;
assertEquals(p3.pin, 1);
}
}
|
MyRobotLab/myrobotlab
|
src/test/java/org/myrobotlab/service/data/PinTest.java
|
Java
|
apache-2.0
| 566 |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* 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;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Securities;
namespace QuantConnect
{
/// <summary>
/// Public static helper class that does parsing/generation of symbol representations (options, futures)
/// </summary>
public static class SymbolRepresentation
{
/// <summary>
/// Class contains future ticker properties returned by ParseFutureTicker()
/// </summary>
public class FutureTickerProperties
{
/// <summary>
/// Underlying name
/// </summary>
public string Underlying { get; set; }
/// <summary>
/// Short expiration year
/// </summary>
public int ExpirationYearShort { get; set; }
/// <summary>
/// Expiration month
/// </summary>
public int ExpirationMonth { get; set; }
}
/// <summary>
/// Class contains option ticker properties returned by ParseOptionTickerIQFeed()
/// </summary>
public class OptionTickerProperties
{
/// <summary>
/// Underlying name
/// </summary>
public string Underlying { get; set; }
/// <summary>
/// Option right
/// </summary>
public OptionRight OptionRight { get; set; }
/// <summary>
/// Option strike
/// </summary>
public decimal OptionStrike { get; set; }
/// <summary>
/// Expiration date
/// </summary>
public DateTime ExpirationDate { get; set; }
}
/// <summary>
/// Function returns underlying name, expiration year, expiration month for the future contract ticker. Function detects if
/// the format is used either XYZH6 or XYZH16. Returns null, if parsing failed.
/// </summary>
/// <param name="ticker"></param>
/// <returns>Results containing 1) underlying name, 2) short expiration year, 3) expiration month</returns>
public static FutureTickerProperties ParseFutureTicker(string ticker)
{
// we first check if we have XYZH6 or XYZH16 format
if (char.IsDigit(ticker.Substring(ticker.Length - 2, 1)[0]))
{
// XYZH16 format
var expirationYearString = ticker.Substring(ticker.Length - 2, 2);
var expirationMonthString = ticker.Substring(ticker.Length - 3, 1);
var underlyingString = ticker.Substring(0, ticker.Length - 3);
int expirationYearShort;
if (!int.TryParse(expirationYearString, out expirationYearShort))
{
return null;
}
if (!_futuresMonthCodeLookup.ContainsKey(expirationMonthString))
{
return null;
}
var expirationMonth = _futuresMonthCodeLookup[expirationMonthString];
return new FutureTickerProperties
{
Underlying = underlyingString,
ExpirationYearShort = expirationYearShort,
ExpirationMonth = expirationMonth
};
}
else
{
// XYZH6 format
var expirationYearString = ticker.Substring(ticker.Length - 1, 1);
var expirationMonthString = ticker.Substring(ticker.Length - 2, 1);
var underlyingString = ticker.Substring(0, ticker.Length - 2);
int expirationYearShort;
if (!int.TryParse(expirationYearString, out expirationYearShort))
{
return null;
}
if (!_futuresMonthCodeLookup.ContainsKey(expirationMonthString))
{
return null;
}
var expirationMonth = _futuresMonthCodeLookup[expirationMonthString];
return new FutureTickerProperties
{
Underlying = underlyingString,
ExpirationYearShort = expirationYearShort,
ExpirationMonth = expirationMonth
};
}
}
/// <summary>
/// Returns future symbol ticker from underlying and expiration date. Function can generate tickers of two formats: one and two digits year
/// </summary>
/// <param name="underlying">String underlying</param>
/// <param name="expiration">Expiration date</param>
/// <param name="doubleDigitsYear">True if year should represented by two digits; False - one digit</param>
/// <returns></returns>
public static string GenerateFutureTicker(string underlying, DateTime expiration, bool doubleDigitsYear = true)
{
var year = doubleDigitsYear ? expiration.Year % 100 : expiration.Year % 10;
var month = expiration.Month;
// These futures expire in the month before the contract month
if (underlying == Futures.Energies.CrudeOilWTI ||
underlying == Futures.Energies.Gasoline ||
underlying == Futures.Energies.HeatingOil ||
underlying == Futures.Energies.NaturalGas)
{
if (month < 12)
{
month++;
}
else
{
month = 1;
year++;
}
}
return $"{underlying}{_futuresMonthLookup[month]}{year}";
}
/// <summary>
/// Returns option symbol ticker in accordance with OSI symbology
/// More information can be found at http://www.optionsclearing.com/components/docs/initiatives/symbology/symbology_initiative_v1_8.pdf
/// </summary>
/// <param name="underlying">Underlying string</param>
/// <param name="right">Option right</param>
/// <param name="strikePrice">Option strike</param>
/// <param name="expiration">Option expiration date</param>
/// <returns></returns>
public static string GenerateOptionTickerOSI(string underlying, OptionRight right, decimal strikePrice, DateTime expiration)
{
if (underlying.Length > 5) underlying += " ";
return string.Format("{0,-6}{1}{2}{3:00000000}", underlying, expiration.ToString(DateFormat.SixCharacter), right.ToString()[0], strikePrice * 1000m);
}
/// <summary>
/// Function returns option contract parameters (underlying name, expiration date, strike, right) from IQFeed option ticker
/// Symbology details: http://www.iqfeed.net/symbolguide/index.cfm?symbolguide=guide&displayaction=support%C2%A7ion=guide&web=iqfeed&guide=options&web=IQFeed&type=stock
/// </summary>
/// <param name="ticker">IQFeed option ticker</param>
/// <returns>Results containing 1) underlying name, 2) option right, 3) option strike 4) expiration date</returns>
public static OptionTickerProperties ParseOptionTickerIQFeed(string ticker)
{
// This table describes IQFeed option symbology
var symbology = new Dictionary<string, Tuple<int, OptionRight>>
{
{ "A", Tuple.Create(1, OptionRight.Call) }, { "M", Tuple.Create(1, OptionRight.Put) },
{ "B", Tuple.Create(2, OptionRight.Call) }, { "N", Tuple.Create(2, OptionRight.Put) },
{ "C", Tuple.Create(3, OptionRight.Call) }, { "O", Tuple.Create(3, OptionRight.Put) },
{ "D", Tuple.Create(4, OptionRight.Call) }, { "P", Tuple.Create(4, OptionRight.Put) },
{ "E", Tuple.Create(5, OptionRight.Call) }, { "Q", Tuple.Create(5, OptionRight.Put) },
{ "F", Tuple.Create(6, OptionRight.Call) }, { "R", Tuple.Create(6, OptionRight.Put) },
{ "G", Tuple.Create(7, OptionRight.Call) }, { "S", Tuple.Create(7, OptionRight.Put) },
{ "H", Tuple.Create(8, OptionRight.Call) }, { "T", Tuple.Create(8, OptionRight.Put) },
{ "I", Tuple.Create(9, OptionRight.Call) }, { "U", Tuple.Create(9, OptionRight.Put) },
{ "J", Tuple.Create(10, OptionRight.Call) }, { "V", Tuple.Create(10, OptionRight.Put) },
{ "K", Tuple.Create(11, OptionRight.Call) }, { "W", Tuple.Create(11, OptionRight.Put) },
{ "L", Tuple.Create(12, OptionRight.Call) }, { "X", Tuple.Create(12, OptionRight.Put) },
};
var letterRange = symbology.Keys
.Select(x => x[0])
.ToArray();
var optionTypeDelimiter = ticker.LastIndexOfAny(letterRange);
var strikePriceString = ticker.Substring(optionTypeDelimiter + 1, ticker.Length - optionTypeDelimiter - 1);
var lookupResult = symbology[ticker[optionTypeDelimiter].ToString()];
var month = lookupResult.Item1;
var optionRight = lookupResult.Item2;
var dayString = ticker.Substring(optionTypeDelimiter - 2, 2);
var yearString = ticker.Substring(optionTypeDelimiter - 4, 2);
var underlying = ticker.Substring(0, optionTypeDelimiter - 4);
// if we cannot parse strike price, we ignore this contract, but log the information.
decimal strikePrice;
if (!Decimal.TryParse(strikePriceString, out strikePrice))
{
return null;
}
int day;
if (!int.TryParse(dayString, out day))
{
return null;
}
int year;
if (!int.TryParse(yearString, out year))
{
return null;
}
var expirationDate = new DateTime(2000 + year, month, day);
return new OptionTickerProperties
{
Underlying = underlying,
OptionRight = optionRight,
OptionStrike = strikePrice,
ExpirationDate = expirationDate
};
}
private static IReadOnlyDictionary<string, int> _futuresMonthCodeLookup = new Dictionary<string, int>
{
{ "F", 1 },
{ "G", 2 },
{ "H", 3 },
{ "J", 4 },
{ "K", 5 },
{ "M", 6 },
{ "N", 7 },
{ "Q", 8 },
{ "U", 9 },
{ "V", 10 },
{ "X", 11 },
{ "Z", 12 }
};
private static IReadOnlyDictionary<int, string> _futuresMonthLookup = _futuresMonthCodeLookup.ToDictionary(kv => kv.Value, kv => kv.Key);
}
}
|
redmeros/Lean
|
Common/SymbolRepresentation.cs
|
C#
|
apache-2.0
| 11,972 |
/*
* Copyright (C) 2012-2014 Open Source Robotics Foundation
*
* 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.
*
*/
/*
* Desc: Factory for creating sensors
* Author: Andrew Howard
* Date: 18 May 2003
*/
#ifndef _SENSORFACTORY_HH_
#define _SENSORFACTORY_HH_
#include <string>
#include <map>
#include <vector>
#include "gazebo/sensors/SensorTypes.hh"
#include "gazebo/util/system.hh"
namespace gazebo
{
/// \ingroup gazebo_sensors
/// \brief Sensors namespace
namespace sensors
{
/// \def Sensor
/// \brief Prototype for sensor factory functions
typedef Sensor* (*SensorFactoryFn) ();
/// \addtogroup gazebo_sensors
/// \{
/// \class SensorFactor SensorFactory.hh sensors/sensors.hh
/// \brief The sensor factory; the class is just for namespacing purposes.
class GAZEBO_VISIBLE SensorFactory
{
/// \brief Register all known sensors
/// \li sensors::CameraSensor
/// \li sensors::DepthCameraSensor
/// \li sensors::GpuRaySensor
/// \li sensors::RaySensor
/// \li sensors::ContactSensor
/// \li sensors::RFIDSensor
/// \li sensors::RFIDTag
/// \li sensors::WirelessTransmitter
/// \li sensors::WirelessReceiver
public: static void RegisterAll();
/// \brief Register a sensor class (called by sensor registration function).
/// \param[in] _className Name of class of sensor to register.
/// \param[in] _factoryfn Function handle for registration.
public: static void RegisterSensor(const std::string &_className,
SensorFactoryFn _factoryfn);
/// \brief Create a new instance of a sensor. Used by the world when
/// reading the world file.
/// \param[in] _className Name of sensor class
/// \return Pointer to Sensor
public: static SensorPtr NewSensor(const std::string &_className);
/// \brief Get all the sensor types
/// \param _types Vector of strings of the sensor types,
/// populated by function
public: static void GetSensorTypes(std::vector<std::string> &_types);
/// \brief A list of registered sensor classes
private: static std::map<std::string, SensorFactoryFn> sensorMap;
};
/// \brief Static sensor registration macro
///
/// Use this macro to register sensors with the server.
/// @param name Sensor type name, as it appears in the world file.
/// @param classname C++ class name for the sensor.
#define GZ_REGISTER_STATIC_SENSOR(name, classname) \
GAZEBO_VISIBLE Sensor *New##classname() \
{ \
return new gazebo::sensors::classname(); \
} \
GAZEBO_VISIBLE \
void Register##classname() \
{\
SensorFactory::RegisterSensor(name, New##classname);\
}
/// \}
}
}
#endif
|
arpg/Gazebo
|
gazebo/sensors/SensorFactory.hh
|
C++
|
apache-2.0
| 3,223 |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace PiCalculator.Tests
{
[TestClass]
public class PiCalculatorTestsPart1
{
private PiCalculator piCalculator;
[TestInitialize]
public void TestInitialize()
{
piCalculator = new PiCalculator();
}
[TestCleanup]
public void TestCleanup()
{
piCalculator = null;
}
[TestMethod]
public void PiCalculator_GetPi_returns_314_for_input_2()
{
var result = piCalculator.GetPi(2);
Assert.AreEqual("3.14", result);
}
}
}
|
AlanBarber/CodeKatas
|
src/PiCalculator.Tests/PiCalculatorTestsPart1.cs
|
C#
|
apache-2.0
| 654 |
package uk.co.jtnet.security.kerberos.pac;
public interface PacConstants {
static final int PAC_VERSION = 0;
static final int LOGON_INFO = 1;
static final int KERB_VALIDATION_INFO = 1;
static final int PAC_CREDENTIALS = 2;
static final int SERVER_CHECKSUM = 6;
static final int KDC_PRIVSERVER_CHECKSUM = 7;
static final int PAC_CLIENT_INFO = 10;
static final int CONSTRAINED_DELEGATION_INFO = 11;
static final int UPN_DNS_INFO = 12;
static final int PAC_CLIENT_CLAIMS_INFO = 13;
static final int PAC_DEVICE_INFO = 14;
static final int PAC_DEVICE_CLAIMS_INFO = 15;
static final int KERB_NON_KERB_SALT = 16;
static final int KERB_NON_KERB_CKSUM_SALT = 17;
}
|
jcmturner/java-kerberos-utils
|
KerberosUtils/src/main/java/uk/co/jtnet/security/kerberos/pac/PacConstants.java
|
Java
|
apache-2.0
| 716 |
/*
* 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.mklab.taskit.shared;
import org.mklab.taskit.server.domain.User;
import java.util.List;
import com.google.web.bindery.requestfactory.shared.InstanceRequest;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.RequestContext;
import com.google.web.bindery.requestfactory.shared.Service;
/**
* @see User
* @author ishikura
*/
@Service(User.class)
@SuppressWarnings("javadoc")
public interface UserRequest extends RequestContext {
Request<Void> changeMyUserName(String userName);
Request<Void> changeUserName(String accountId, String userName);
Request<List<UserProxy>> getAllUsers();
Request<UserProxy> getUserByAccountId(String accountId);
Request<UserProxy> getLoginUser();
Request<List<UserProxy>> getAllStudents();
InstanceRequest<UserProxy, Void> update();
}
|
mklab/taskit
|
src/main/java/org/mklab/taskit/shared/UserRequest.java
|
Java
|
apache-2.0
| 1,428 |
package gr.plushost.prototypeapp.fragments;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.beardedhen.androidbootstrap.BootstrapButton;
import com.beardedhen.androidbootstrap.BootstrapEditText;
import com.github.johnpersano.supertoasts.SuperToast;
import com.github.johnpersano.supertoasts.util.Style;
import org.apache.http.cookie.Cookie;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.List;
import gr.plushost.prototypeapp.R;
import gr.plushost.prototypeapp.activities.CategoriesActivity;
import gr.plushost.prototypeapp.activities.CustomerOrdersActivity;
import gr.plushost.prototypeapp.activities.ForgotPasswordActivity;
import gr.plushost.prototypeapp.activities.LoginActivity;
import gr.plushost.prototypeapp.activities.MainActivity;
import gr.plushost.prototypeapp.activities.ProductActivity;
import gr.plushost.prototypeapp.activities.ProductsActivity;
import gr.plushost.prototypeapp.activities.ProfileActivity;
import gr.plushost.prototypeapp.activities.SettingsActivity;
import gr.plushost.prototypeapp.activities.ShoppingCartActivity;
import gr.plushost.prototypeapp.aplications.StoreApplication;
import gr.plushost.prototypeapp.network.NoNetworkHandler;
import gr.plushost.prototypeapp.network.PersistentCookieStore;
import gr.plushost.prototypeapp.network.ServiceHandler;
/**
* Created by billiout on 17/2/2015.
*/
public class NavigationDrawerFragment extends Fragment {
Activity act;
RelativeLayout accountLogout;
RelativeLayout accountLoggedin;
DrawerLayout drawerLayout;
View view;
BootstrapButton btnCart;
NoNetworkHandler noNetworkHandler;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_nav_drawer, container, false);
act = getActivity();
noNetworkHandler = new NoNetworkHandler(act);
final BootstrapEditText email = (BootstrapEditText) view.findViewById(R.id.editTextEmail);
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (Character.isSpaceChar(source.charAt(i))) {
return "";
}
}
return null;
}
};
email.setFilters(new InputFilter[]{filter});
TextView tmpText = (TextView) view.findViewById(R.id.txtNewsTitle);
Typeface type = Typeface.createFromAsset(act.getAssets(), "fonts/mistral.ttf");
tmpText.setTypeface(type, Typeface.BOLD);
tmpText = (TextView) view.findViewById(R.id.txtAccountTitle);
type = Typeface.createFromAsset(act.getAssets(), "fonts/mistral.ttf");
tmpText.setTypeface(type, Typeface.BOLD);
tmpText = (TextView) view.findViewById(R.id.txtCartTitle);
type = Typeface.createFromAsset(act.getAssets(), "fonts/mistral.ttf");
tmpText.setTypeface(type, Typeface.BOLD);
tmpText = (TextView) view.findViewById(R.id.txtAccountTitle2);
type = Typeface.createFromAsset(act.getAssets(), "fonts/mistral.ttf");
tmpText.setTypeface(type, Typeface.BOLD);
accountLogout = (RelativeLayout) view.findViewById(R.id.accountLay);
accountLoggedin = (RelativeLayout) view.findViewById(R.id.accountLayLogged);
btnCart = (BootstrapButton) view.findViewById(R.id.swipeCart);
btnCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
drawerLayout.closeDrawers();
if(getActivity().getSharedPreferences("ShopPrefs", 0).getBoolean("is_connected", false)){
Intent i = new Intent(act, ShoppingCartActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
else{
openLogin(view);
}
}
});
BootstrapButton btnLogin = (BootstrapButton) view.findViewById(R.id.sundesiBtn);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openLogin(v);
}
});
BootstrapButton btnRegister = (BootstrapButton) view.findViewById(R.id.newAccountBtn);
btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openRegister(v);
}
});
if(act.getSharedPreferences("ShopPrefs", 0).getBoolean("is_connected", false)){
accountLoggedin.setVisibility(View.VISIBLE);
accountLogout.setVisibility(View.GONE);
if(!act.getSharedPreferences("ShopPrefs", 0).getString("user_name", "").trim().equals("")) {
((TextView) view.findViewById(R.id.userName)).setVisibility(View.VISIBLE);
((TextView) view.findViewById(R.id.email)).setVisibility(View.VISIBLE);
((TextView) view.findViewById(R.id.userName)).setText(act.getSharedPreferences("ShopPrefs", 0).getString("user_name", ""));
((TextView) view.findViewById(R.id.email)).setText(act.getSharedPreferences("ShopPrefs", 0).getString("user_email", ""));
}
else {
((TextView) view.findViewById(R.id.userName)).setVisibility(View.VISIBLE);
((TextView) view.findViewById(R.id.email)).setVisibility(View.GONE);
((TextView) view.findViewById(R.id.userName)).setText(act.getSharedPreferences("ShopPrefs", 0).getString("user_email", ""));
}
}
else {
accountLoggedin.setVisibility(View.GONE);
accountLogout.setVisibility(View.VISIBLE);
}
if(StoreApplication.getCartCount() > 0){
if(StoreApplication.getCartCount() == 1)
btnCart.setText(String.format(getResources().getString(R.string.btn_cart_text_product),StoreApplication.getCartCount()));
else
btnCart.setText(String.format(getResources().getString(R.string.btn_cart_text_products),StoreApplication.getCartCount()));
}
else {
btnCart.setText(act.getResources().getString(R.string.btn_cart_text_empty));
}
BootstrapButton btnLogout = (BootstrapButton) view.findViewById(R.id.userLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(act.getSharedPreferences("ShopPrefs", 0).getBoolean("is_connected", false)) {
drawerLayout.closeDrawers();
if(noNetworkHandler.showDialog())
new LogoutSession().execute();
}
else {
SuperToast.create(act, getResources().getString(R.string.btn_logout_fail), SuperToast.Duration.SHORT, Style.getStyle(Style.RED, SuperToast.Animations.POPUP)).show();
}
}
});
BootstrapButton btnProfile = (BootstrapButton) view.findViewById(R.id.userProfile);
btnProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawerLayout.closeDrawers();
Intent i = new Intent(act, ProfileActivity.class);
startActivity(i);
act.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
BootstrapButton btnOrders = (BootstrapButton) view.findViewById(R.id.userOrders);
btnOrders.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawerLayout.closeDrawers();
Intent i = new Intent(act, CustomerOrdersActivity.class);
startActivity(i);
act.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
update();
view.findViewById(R.id.newPassBtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
drawerLayout.closeDrawers();
Intent intent = new Intent(act, ForgotPasswordActivity.class);
act.startActivity(intent);
act.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
view.findViewById(R.id.btnNewsletterSignUp).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BootstrapEditText editTextEmail = (BootstrapEditText) view.findViewById(R.id.editTextEmail);
if(!editTextEmail.getText().toString().trim().equals("") || isValidEmail(editTextEmail.getText().toString().trim())){
if(noNetworkHandler.showDialog())
new NewsletterSignUp().execute(editTextEmail.getText().toString().trim());
}
else {
SuperToast.create(act, getResources().getString(R.string.newsletter_missing_email_msg), SuperToast.Duration.SHORT, Style.getStyle(Style.RED, SuperToast.Animations.POPUP)).show();
}
}
});
view.findViewById(R.id.homeBtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!(getActivity() instanceof MainActivity)) {
Intent i = new Intent(getActivity(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
else{
drawerLayout.closeDrawers();
}
}
});
return view;
}
public void setDrawerLayout(DrawerLayout drawerLayout){
this.drawerLayout = drawerLayout;
}
public void update(){
if(noNetworkHandler.showDialog())
new GetCartCount().execute();
if(getActivity().getSharedPreferences("ShopPrefs", 0).getBoolean("is_connected", false)){
accountLoggedin.setVisibility(View.VISIBLE);
accountLogout.setVisibility(View.GONE);
if(!act.getSharedPreferences("ShopPrefs", 0).getString("user_name", "").trim().equals("")) {
((TextView) view.findViewById(R.id.userName)).setVisibility(View.VISIBLE);
((TextView) view.findViewById(R.id.email)).setVisibility(View.VISIBLE);
((TextView) view.findViewById(R.id.userName)).setText(act.getSharedPreferences("ShopPrefs", 0).getString("user_name", ""));
((TextView) view.findViewById(R.id.email)).setText(act.getSharedPreferences("ShopPrefs", 0).getString("user_email", ""));
}
else {
((TextView) view.findViewById(R.id.userName)).setVisibility(View.VISIBLE);
((TextView) view.findViewById(R.id.email)).setVisibility(View.GONE);
((TextView) view.findViewById(R.id.userName)).setText(act.getSharedPreferences("ShopPrefs", 0).getString("user_email", ""));
}
}
else {
accountLoggedin.setVisibility(View.GONE);
accountLogout.setVisibility(View.VISIBLE);
}
}
public void openLogin(View view){
drawerLayout.closeDrawers();
Intent i = new Intent(act, LoginActivity.class);
i.putExtra("page", 0);
startActivity(i);
}
public void openRegister(View view){
drawerLayout.closeDrawers();
Intent i = new Intent(act, LoginActivity.class);
i.putExtra("page", 1);
startActivity(i);
}
public boolean isValidEmail(CharSequence target) {
return target != null && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
class NewsletterSignUp extends AsyncTask<String, Void, Boolean>{
@Override
protected Boolean doInBackground(String... params) {
try {
String response = StoreApplication.getServiceHandler(act).makeServiceCall(act, true, String.format(act.getResources().getString(R.string.url_newsletter_signup), act.getSharedPreferences("ShopPrefs", 0).getString("store_language", ""), act.getSharedPreferences("ShopPrefs", 0).getString("store_currency", ""), URLEncoder.encode(params[0], "UTF-8")), ServiceHandler.GET);
JSONObject jsonObject = new JSONObject(response);
return jsonObject.getString("code").equals("0x0000");
}
catch (Exception e){
e.printStackTrace();
}
return false;
}
@Override
protected void onPostExecute(Boolean result){
drawerLayout.closeDrawers();
if(result){
SuperToast.create(act, getResources().getString(R.string.newsletter_success_msg), SuperToast.Duration.SHORT, Style.getStyle(Style.RED, SuperToast.Animations.POPUP)).show();
}
else {
SuperToast.create(act, getResources().getString(R.string.btn_logout_fail), SuperToast.Duration.SHORT, Style.getStyle(Style.RED, SuperToast.Animations.POPUP)).show();
}
}
}
class GetCartCount extends AsyncTask<Void, Void, Integer>{
@Override
protected void onPreExecute(){
if(isAdded() && getActivity() != null) {
int result = StoreApplication.getCartCount();
if (result > 0) {
if (result == 1)
btnCart.setText(String.format(getResources().getString(R.string.btn_cart_text_product), StoreApplication.getCartCount()));
else
btnCart.setText(String.format(getResources().getString(R.string.btn_cart_text_products), StoreApplication.getCartCount()));
} else {
btnCart.setText(act.getResources().getString(R.string.btn_cart_text_empty));
}
}
}
@Override
protected Integer doInBackground(Void... voids) {
if(isAdded() && getActivity() != null) {
String response = StoreApplication.getServiceHandler(act).makeServiceCall(act, true, String.format(act.getResources().getString(R.string.url_cart_count), act.getSharedPreferences("ShopPrefs", 0).getString("store_language", ""), act.getSharedPreferences("ShopPrefs", 0).getString("store_currency", "")), ServiceHandler.GET);
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("code").equals("0x0000")) {
return jsonObject.getJSONObject("info").getInt("cart_items_count");
}
return 0;
} catch (Exception e) {
e.printStackTrace();
}
}
return 0;
}
@Override
protected void onPostExecute(Integer result){
if(isAdded() && getActivity() != null) {
StoreApplication.setCartCount(result);
if (result > 0) {
if (result == 1)
btnCart.setText(String.format(getResources().getString(R.string.btn_cart_text_product), StoreApplication.getCartCount()));
else
btnCart.setText(String.format(getResources().getString(R.string.btn_cart_text_products), StoreApplication.getCartCount()));
} else {
btnCart.setText(act.getResources().getString(R.string.btn_cart_text_empty));
}
}
}
}
class LogoutSession extends AsyncTask<Void, Void, Boolean>{
@Override
protected Boolean doInBackground(Void... params) {
ServiceHandler sh = StoreApplication.getServiceHandler(act);
String response = sh.makeServiceCall(act, true, String.format(getResources().getString(R.string.url_logout_user), act.getSharedPreferences("ShopPrefs", 0).getString("store_language", ""), act.getSharedPreferences("ShopPrefs", 0).getString("store_currency", "")), ServiceHandler.GET);
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.getString("code").equals("0x0000")){
return true;
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
@Override
protected void onPostExecute(Boolean result){
if(result){
act.getSharedPreferences("ShopPrefs", 0).edit().putBoolean("is_connected", false).apply();
SuperToast.create(act, getResources().getString(R.string.btn_logout_success), SuperToast.Duration.SHORT, Style.getStyle(Style.RED, SuperToast.Animations.POPUP)).show();
if(noNetworkHandler.showDialog()) {
if (act instanceof MainActivity) {
((MainActivity) act).new GetCartCount().execute();
} else if (act instanceof CategoriesActivity) {
((CategoriesActivity) act).new GetCartCount().execute();
} else if (act instanceof ProductsActivity) {
((ProductsActivity) act).new GetCartCount().execute();
} else if (act instanceof ProductActivity) {
((ProductActivity) act).new GetCartCount().execute();
}
}
}
else {
SuperToast.create(act, getResources().getString(R.string.btn_logout_fail), SuperToast.Duration.SHORT, Style.getStyle(Style.RED, SuperToast.Animations.POPUP)).show();
}
}
}
}
|
lioutasb/CSCartApp
|
app/src/main/java/gr/plushost/prototypeapp/fragments/NavigationDrawerFragment.java
|
Java
|
apache-2.0
| 18,920 |
#ifndef color_cmyk_akin_xyz
#define color_cmyk_akin_xyz
#include "../../generic/akin/cmyk.hpp"
#include "../category.hpp"
#include "../../xyz/category.hpp"
namespace color
{
namespace akin
{
template< >struct cmyk< ::color::category::xyz_uint8 >{ typedef ::color::category::cmyk_uint8 akin_type; };
template< >struct cmyk< ::color::category::xyz_uint16 >{ typedef ::color::category::cmyk_uint16 akin_type; };
template< >struct cmyk< ::color::category::xyz_uint32 >{ typedef ::color::category::cmyk_uint32 akin_type; };
template< >struct cmyk< ::color::category::xyz_uint64 >{ typedef ::color::category::cmyk_uint64 akin_type; };
template< >struct cmyk< ::color::category::xyz_float >{ typedef ::color::category::cmyk_float akin_type; };
template< >struct cmyk< ::color::category::xyz_double >{ typedef ::color::category::cmyk_double akin_type; };
template< >struct cmyk< ::color::category::xyz_ldouble >{ typedef ::color::category::cmyk_ldouble akin_type; };
}
}
#endif
|
dmilos/color
|
src/color/cmyk/akin/xyz.hpp
|
C++
|
apache-2.0
| 1,053 |
from __future__ import division
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
import os
import string
plt.ioff()
data = np.load("attn_weights.npz")
lines = map(lambda x: x.split('\t'), open("sanitycheck.txt", 'r').readlines())
save_dir = "attn_plots3"
sentences = []
current_sent = []
for line in lines:
if len(line) < 10:
sentences.append(map(list, zip(*current_sent)))
current_sent = []
else:
current_sent.append(map(string.strip, (line[1], line[6], line[7], line[8], line[9])))
sentences.append(map(list, zip(*current_sent)))
max_layer = 3
remove_padding = True
plot = False
batch_sum = 0
fig, axes = plt.subplots(nrows=2, ncols=4)
# For each batch+layer
for arr_name in sorted(data.files):
print("Processing %s" % arr_name)
batch_size = data[arr_name].shape[0]
batch = int(arr_name[1])
layer = int(arr_name.split(':')[1][-1])
idx_in_batch = 0
# For each element in the batch (one layer)
# if layer == max_layer and batch > 0:
for b_i, arrays in enumerate(data[arr_name]):
sentence_idx = batch_sum + b_i
width = arrays.shape[-1]
name = "sentence%d_layer%d" % (sentence_idx, layer)
print("Batch: %d, sentence: %d, layer: %d" % (batch, sentence_idx, layer))
sentence = sentences[sentence_idx]
words = sentence[0]
pred_deps = np.array(map(int, sentence[1]))
pred_labels = sentence[2]
gold_deps = np.array(map(int, sentence[3]))
gold_labels = sentence[4]
sent_len = len(words)
text = words + [] if remove_padding else (['PAD'] * (width - sent_len))
gold_deps_xy = np.array(list(enumerate(gold_deps)))
pred_deps_xy = np.array(list(enumerate(pred_deps)))
labels_incorrect = map(lambda x: x[0] != x[1], zip(pred_labels, gold_labels))
incorrect_indices = np.where((pred_deps != gold_deps) | labels_incorrect)
pred_deps_xy_incorrect = pred_deps_xy[incorrect_indices]
pred_labels_incorrect = np.array(pred_labels)[incorrect_indices]
if 'prep' in pred_labels_incorrect:
print(' '.join(text))
print(' '.join(pred_labels))
print(' '.join(gold_labels))
if plot:
correct_dir = "correct" if len(incorrect_indices[0]) == 0 else "incorrect"
fig.suptitle(name, fontsize=16)
# For each attention head
for arr, ax in zip(arrays, axes.flat):
res = ax.imshow(arr[:sent_len, :sent_len], cmap=plt.cm.viridis, interpolation=None)
ax.set_xticks(range(sent_len))
ax.set_yticks(range(sent_len))
ax.set_xticklabels(text, rotation=75, fontsize=2)
ax.set_yticklabels(text, fontsize=2)
map(lambda x: ax.text(x[0][1], x[0][0], x[1], ha="center", va="center", fontsize=1), zip(gold_deps_xy, gold_labels))
map(lambda x: ax.text(x[0][1], x[0][0], x[1], ha="center", va="bottom", fontsize=1, color='red'), zip(pred_deps_xy_incorrect, pred_labels_incorrect))
fig.tight_layout()
fig.savefig(os.path.join(save_dir, correct_dir, name + ".pdf"))
map(lambda x: x.clear(), axes.flat)
if layer == max_layer:
batch_sum += batch_size
|
strubell/Parser
|
bin/plot_attn.py
|
Python
|
apache-2.0
| 3,315 |
/**
* Copyright (c) 2016 - 2018 Syncleus, 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.aparapi.codegen.test;
public class EmptyIfBlock {
public void run() {
int idx = 34;
if(idx < 5) {
}
}
}
/**{Throws{ClassParseException}Throws}**/
|
Syncleus/aparapi
|
src/test/java/com/aparapi/codegen/test/EmptyIfBlock.java
|
Java
|
apache-2.0
| 802 |
package com.niedzielski.pixipedia.android.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.niedzielski.pixipedia.android.R;
import com.niedzielski.pixipedia.android.util.ImageUtil;
import butterknife.InjectView;
public class ImageFragment extends DefaultFragment {
/*default*/ static final String FRAGMENT_ARG_IMAGE_URL_KEY = "imageUrl";
@InjectView(R.id.image)
protected ImageView mImageView;
private String mImageUrl;
public static ImageFragment newInstance(String imageUrl) {
ImageFragment fragment = new ImageFragment();
fragment.setArguments(buildFragmentArgs(imageUrl));
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
ImageUtil.load(mImageUrl, mImageView);
return view;
}
@Override
protected int getLayout() {
return R.layout.fragment_page_image;
}
@Override
protected void initFromFragmentArgs() {
mImageUrl = getArguments().getString(FRAGMENT_ARG_IMAGE_URL_KEY);
}
private static Bundle buildFragmentArgs(String imageUrl) {
Bundle ret = new Bundle();
ret.putString(FRAGMENT_ARG_IMAGE_URL_KEY, imageUrl);
return ret;
}
}
|
niedzielski/pixipedia
|
app/src/main/java/com/niedzielski/pixipedia/android/activity/ImageFragment.java
|
Java
|
apache-2.0
| 1,551 |
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package net.sf.mmm.code.base.arg;
import java.io.IOException;
import java.lang.reflect.Executable;
import java.lang.reflect.Parameter;
import java.util.List;
import java.util.function.Consumer;
import net.sf.mmm.code.api.arg.CodeParameter;
import net.sf.mmm.code.api.arg.CodeParameters;
import net.sf.mmm.code.api.copy.CodeCopyMapper;
import net.sf.mmm.code.api.language.CodeLanguage;
import net.sf.mmm.code.api.member.CodeOperation;
import net.sf.mmm.code.api.merge.CodeMergeStrategy;
import net.sf.mmm.code.base.member.BaseOperation;
/**
* Base implementation of {@link CodeParameters}.
*
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
* @since 1.0.0
*/
public class BaseParameters extends BaseOperationArgs<CodeParameter> implements CodeParameters {
/**
* The constructor.
*
* @param parent the {@link #getParent() parent}.
*/
public BaseParameters(BaseOperation parent) {
super(parent);
}
/**
* The copy-constructor.
*
* @param template the {@link BaseParameters} to copy.
* @param mapper the {@link CodeCopyMapper}.
*/
public BaseParameters(BaseParameters template, CodeCopyMapper mapper) {
super(template, mapper);
}
@Override
protected void doInitialize() {
super.doInitialize();
Executable reflectiveObject = getParent().getReflectiveObject();
List<? extends CodeParameter> sourceParams = null;
int sourceParamsCount = 0;
CodeParameters sourceParameters = getSourceCodeObject();
if (sourceParameters != null) {
sourceParams = sourceParameters.getDeclared();
sourceParamsCount = sourceParams.size();
}
if (reflectiveObject != null) {
List<CodeParameter> list = getList();
int i = 0;
for (Parameter param : reflectiveObject.getParameters()) {
String name = null;
CodeParameter baseParameter = null;
if ((i < sourceParamsCount) && (sourceParams != null)) {
baseParameter = sourceParams.get(i++);
name = baseParameter.getName();
}
if (name == null) {
name = param.getName();
}
BaseParameter parameter = new BaseParameter(this, name, param, baseParameter);
list.add(parameter);
}
}
}
@Override
public CodeParameter getDeclared(String name) {
initialize();
return getByName(name);
}
@Override
public CodeParameter add(String name) {
BaseParameter parameter = new BaseParameter(this, name);
add(parameter);
return parameter;
}
@Override
public CodeParameters getSourceCodeObject() {
CodeOperation sourceOperation = getParent().getSourceCodeObject();
if (sourceOperation != null) {
return sourceOperation.getParameters();
}
return null;
}
@Override
protected void rename(CodeParameter child, String oldName, String newName, Consumer<String> renamer) {
super.rename(child, oldName, newName, renamer);
}
@Override
public CodeParameters merge(CodeParameters o, CodeMergeStrategy strategy) {
if (strategy == CodeMergeStrategy.KEEP) {
return this;
}
BaseParameters other = (BaseParameters) o;
List<? extends CodeParameter> otherParameters = other.getDeclared();
if (strategy == CodeMergeStrategy.OVERRIDE) {
clear();
for (CodeParameter otherParameter : otherParameters) {
CodeParameter copyParameter = doCopyNode(otherParameter, this);
add(copyParameter);
}
} else {
List<? extends CodeParameter> myParameters = getDeclared();
int i = 0;
int len = myParameters.size();
assert (len == otherParameters.size());
for (CodeParameter otherParameter : otherParameters) {
CodeParameter myParameter = null;
if (i < len) {
myParameter = myParameters.get(i++); // merging via index as by name could cause errors on mismatch
}
if (myParameter == null) {
CodeParameter copyParameter = doCopyNode(otherParameter, this);
add(copyParameter);
} else {
myParameter.merge(otherParameter, strategy);
}
}
}
return this;
}
@Override
public BaseParameters copy() {
return copy(getDefaultCopyMapper());
}
@Override
public BaseParameters copy(CodeCopyMapper mapper) {
return new BaseParameters(this, mapper);
}
@Override
protected void doWrite(Appendable sink, String newline, String defaultIndent, String currentIndent, CodeLanguage language) throws IOException {
writeReference(sink, newline, true);
}
void writeReference(Appendable sink, String newline, boolean declaration) throws IOException {
String prefix = "";
for (CodeParameter parameter : getList()) {
sink.append(prefix);
parameter.write(sink, newline, null, null);
prefix = ", ";
}
}
}
|
m-m-m/code
|
base/src/main/java/net/sf/mmm/code/base/arg/BaseParameters.java
|
Java
|
apache-2.0
| 4,951 |
package org.apereo.cas.validation;
import org.apereo.cas.TestOneTimePasswordAuthenticationHandler;
import org.apereo.cas.authentication.AcceptUsersAuthenticationHandler;
import org.apereo.cas.authentication.AuthenticationHandler;
import org.apereo.cas.authentication.AuthenticationPolicy;
import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.authentication.Credential;
import org.apereo.cas.authentication.DefaultAuthenticationEventExecutionPlan;
import org.apereo.cas.authentication.credential.OneTimePasswordCredential;
import org.apereo.cas.authentication.credential.UsernamePasswordCredential;
import org.apereo.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler;
import org.apereo.cas.authentication.policy.AllAuthenticationHandlersSucceededAuthenticationPolicy;
import org.apereo.cas.authentication.policy.AllCredentialsValidatedAuthenticationPolicy;
import org.apereo.cas.authentication.policy.AtLeastOneCredentialValidatedAuthenticationPolicy;
import org.apereo.cas.authentication.policy.RequiredHandlerAuthenticationPolicy;
import org.apereo.cas.config.CasCoreAuthenticationConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationHandlersConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationMetadataConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationPolicyConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationPrincipalConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationSupportConfiguration;
import org.apereo.cas.config.CasCoreConfiguration;
import org.apereo.cas.config.CasCoreHttpConfiguration;
import org.apereo.cas.config.CasCoreServicesAuthenticationConfiguration;
import org.apereo.cas.config.CasCoreServicesConfiguration;
import org.apereo.cas.config.CasCoreTicketCatalogConfiguration;
import org.apereo.cas.config.CasCoreTicketIdGeneratorsConfiguration;
import org.apereo.cas.config.CasCoreTicketsConfiguration;
import org.apereo.cas.config.CasCoreUtilConfiguration;
import org.apereo.cas.config.CasCoreWebConfiguration;
import org.apereo.cas.config.CasPersonDirectoryTestConfiguration;
import org.apereo.cas.config.CasRegisteredServicesTestConfiguration;
import org.apereo.cas.config.support.CasWebApplicationServiceFactoryConfiguration;
import org.apereo.cas.logout.config.CasCoreLogoutConfiguration;
import org.apereo.cas.services.ServicesManager;
import lombok.val;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
/**
* This is {@link AuthenticationPolicyAwareServiceTicketValidationAuthorizerTests}.
*
* @author Misagh Moayyed
* @since 6.2.0
*/
@SpringBootTest(classes = {
RefreshAutoConfiguration.class,
CasPersonDirectoryTestConfiguration.class,
CasRegisteredServicesTestConfiguration.class,
CasCoreAuthenticationConfiguration.class,
CasCoreServicesAuthenticationConfiguration.class,
CasCoreAuthenticationPrincipalConfiguration.class,
CasCoreAuthenticationPolicyConfiguration.class,
CasCoreAuthenticationMetadataConfiguration.class,
CasCoreAuthenticationSupportConfiguration.class,
CasCoreAuthenticationHandlersConfiguration.class,
CasCoreWebConfiguration.class,
CasCoreHttpConfiguration.class,
CasCoreUtilConfiguration.class,
CasCoreTicketsConfiguration.class,
CasCoreTicketCatalogConfiguration.class,
CasCoreTicketIdGeneratorsConfiguration.class,
CasCoreLogoutConfiguration.class,
CasCoreConfiguration.class,
CasCoreServicesConfiguration.class,
CasWebApplicationServiceFactoryConfiguration.class,
MailSenderAutoConfiguration.class
})
public class AuthenticationPolicyAwareServiceTicketValidationAuthorizerTests {
@Autowired
@Qualifier("servicesManager")
private ServicesManager servicesManager;
@Autowired
private ConfigurableApplicationContext applicationContext;
private static Assertion getAssertion(final Map<Credential, ? extends AuthenticationHandler> handlers) {
val assertion = mock(Assertion.class);
val principal = CoreAuthenticationTestUtils.getPrincipal("casuser");
val authentication = CoreAuthenticationTestUtils.getAuthenticationBuilder(principal, handlers,
Map.of(AuthenticationHandler.SUCCESSFUL_AUTHENTICATION_HANDLERS,
handlers.values().stream().map(AuthenticationHandler::getName).collect(Collectors.toList()))).build();
when(assertion.getPrimaryAuthentication()).thenReturn(authentication);
return assertion;
}
private static SimpleTestUsernamePasswordAuthenticationHandler getSimpleTestAuthenticationHandler() {
return new SimpleTestUsernamePasswordAuthenticationHandler();
}
private static AcceptUsersAuthenticationHandler getAcceptUsersAuthenticationHandler() {
return new AcceptUsersAuthenticationHandler(Map.of("casuser", "Mellon"));
}
private static OneTimePasswordCredential getOtpCredential() {
return new OneTimePasswordCredential("test", "123456789");
}
private static TestOneTimePasswordAuthenticationHandler getTestOtpAuthenticationHandler() {
return new TestOneTimePasswordAuthenticationHandler(Map.of("casuser", "123456789"));
}
@Test
public void verifyAllAuthenticationHandlersSucceededAuthenticationPolicy() {
val handlers = List.of(getTestOtpAuthenticationHandler(), getAcceptUsersAuthenticationHandler(), getSimpleTestAuthenticationHandler());
val service = CoreAuthenticationTestUtils.getService("https://example.com/high/");
val authz = getAuthorizer(new AllAuthenticationHandlersSucceededAuthenticationPolicy(), handlers);
val map = (Map) Map.of(
new UsernamePasswordCredential(), getAcceptUsersAuthenticationHandler(),
getOtpCredential(), getTestOtpAuthenticationHandler());
val assertion = getAssertion(map);
assertDoesNotThrow(new Executable() {
@Override
public void execute() {
authz.authorize(new MockHttpServletRequest(), service, assertion);
}
});
}
@Test
public void verifyAllCredentialsValidatedAuthenticationPolicy() {
val handlers = List.of(getTestOtpAuthenticationHandler(), getAcceptUsersAuthenticationHandler(), getSimpleTestAuthenticationHandler());
val service = CoreAuthenticationTestUtils.getService("https://example.com/high/");
val authz = getAuthorizer(new AllCredentialsValidatedAuthenticationPolicy(), handlers);
val map = (Map) Map.of(
new UsernamePasswordCredential(), getAcceptUsersAuthenticationHandler(),
getOtpCredential(), getTestOtpAuthenticationHandler());
val assertion = getAssertion(map);
assertDoesNotThrow(new Executable() {
@Override
public void execute() {
authz.authorize(new MockHttpServletRequest(), service, assertion);
}
});
}
@Test
public void verifyRequiredHandlerAuthenticationPolicy() {
val handler = getAcceptUsersAuthenticationHandler();
val handlers = List.of(getTestOtpAuthenticationHandler(), handler, getSimpleTestAuthenticationHandler());
val service = CoreAuthenticationTestUtils.getService("https://example.com/high/");
val authz = getAuthorizer(new RequiredHandlerAuthenticationPolicy(handler.getName()), handlers);
val map = (Map) Map.of(
new UsernamePasswordCredential(), handler,
getOtpCredential(), getTestOtpAuthenticationHandler());
val assertion = getAssertion(map);
assertDoesNotThrow(new Executable() {
@Override
public void execute() {
authz.authorize(new MockHttpServletRequest(), service, assertion);
}
});
}
@Test
public void verifyRequiredHandlerAuthenticationPolicyTryAll() {
val handler = getAcceptUsersAuthenticationHandler();
val handlers = List.of(getTestOtpAuthenticationHandler(), handler, getSimpleTestAuthenticationHandler());
val service = CoreAuthenticationTestUtils.getService("https://example.com/high/");
val authz = getAuthorizer(new RequiredHandlerAuthenticationPolicy(handler.getName(), true), handlers);
val map = (Map) Map.of(
new UsernamePasswordCredential(), handler,
getOtpCredential(), getTestOtpAuthenticationHandler());
val assertion = getAssertion(map);
assertDoesNotThrow(new Executable() {
@Override
public void execute() {
authz.authorize(new MockHttpServletRequest(), service, assertion);
}
});
}
@Test
public void verifyOperationWithHandlersAndAtLeastOneCredential() {
val handlers = List.of(getTestOtpAuthenticationHandler(), getAcceptUsersAuthenticationHandler(), getSimpleTestAuthenticationHandler());
val service = CoreAuthenticationTestUtils.getService("https://example.com/high/");
val authz = getAuthorizer(new AtLeastOneCredentialValidatedAuthenticationPolicy(), handlers);
val map = (Map) Map.of(
new UsernamePasswordCredential(), getAcceptUsersAuthenticationHandler(),
getOtpCredential(), getTestOtpAuthenticationHandler());
val assertion = getAssertion(map);
assertDoesNotThrow(new Executable() {
@Override
public void execute() {
authz.authorize(new MockHttpServletRequest(), service, assertion);
}
});
}
@Test
public void verifyOperationWithHandlersAndAtLeastOneCredentialMustTryAll() {
val handlers = List.of(getTestOtpAuthenticationHandler(), getAcceptUsersAuthenticationHandler(), getSimpleTestAuthenticationHandler());
val service = CoreAuthenticationTestUtils.getService("https://example.com/high/");
val authz = getAuthorizer(new AtLeastOneCredentialValidatedAuthenticationPolicy(true), handlers);
val map = (Map) Map.of(
new UsernamePasswordCredential(), getAcceptUsersAuthenticationHandler(),
getOtpCredential(), getTestOtpAuthenticationHandler());
val assertion = getAssertion(map);
assertDoesNotThrow(new Executable() {
@Override
public void execute() {
authz.authorize(new MockHttpServletRequest(), service, assertion);
}
});
}
private ServiceTicketValidationAuthorizer getAuthorizer(final AuthenticationPolicy policy,
final List<? extends AuthenticationHandler> authenticationHandlers) {
val plan = new DefaultAuthenticationEventExecutionPlan();
plan.registerAuthenticationHandlers(authenticationHandlers);
plan.registerAuthenticationPolicy(policy);
return new AuthenticationPolicyAwareServiceTicketValidationAuthorizer(servicesManager, plan, applicationContext);
}
}
|
leleuj/cas
|
core/cas-server-core-validation/src/test/java/org/apereo/cas/validation/AuthenticationPolicyAwareServiceTicketValidationAuthorizerTests.java
|
Java
|
apache-2.0
| 11,612 |
package com.tngtech.archunit.core.importer.testexamples.hierarchicalmethodcall;
public class SuperclassWithCalledMethod {
public static final String method = "method";
String method() {
return null;
}
int maskedMethod() {
return 0;
}
}
|
TNG/ArchUnit
|
archunit/src/test/java/com/tngtech/archunit/core/importer/testexamples/hierarchicalmethodcall/SuperclassWithCalledMethod.java
|
Java
|
apache-2.0
| 275 |
/**
* Copyright 2015-present Amberfog
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.amberfog.mapslidingtest.app;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ListView;
public class LockableRecyclerView extends RecyclerView {
private boolean mScrollable = true;
public LockableRecyclerView(Context context) {
super(context);
}
public LockableRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LockableRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setScrollingEnabled(boolean enabled) {
mScrollable = enabled;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
// if we can scroll pass the event to the superclass
if (mScrollable) {
return super.onTouchEvent(ev);
}
// only continue to handle the touch event if scrolling enabled
return mScrollable; // mScrollable is always false at this point
default:
return super.onTouchEvent(ev);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// Don't do anything with intercepted touch events if
// we are not scrollable
if (!mScrollable) {
return false;
} else {
return super.onInterceptTouchEvent(ev);
}
}
}
|
dlukashev/AndroidSlidingUpPanel-foursquare-map-demo
|
app/src/main/java/com/amberfog/mapslidingtest/app/LockableRecyclerView.java
|
Java
|
apache-2.0
| 2,219 |
import markdownIt from 'markdown-it'
import plusImagePlugin from 'markdown-it-plus-image'
import highlight from 'highlight.js'
import container from 'markdown-it-container'
import { baseURL } from '@/api'
/**
* Create a markdown it instance.
*
* @type {Object}
*/
export const markdown = markdownIt({
breaks: true,
html: true,
highlight: function (code) {
return highlight ? highlight.highlightAuto(code).value : code
},
}).use(plusImagePlugin, `${baseURL}/files/`)
.use(container, 'hljs-left') /* align left */
.use(container, 'hljs-center')/* align center */
.use(container, 'hljs-right')
/**
* Markdown render.
*
* @param {string} markdownText
* @return {String}
* @author Seven Du <shiweidu@outlook.com>
*/
export function render (markdownText) {
return markdown.render(String(markdownText))
}
/**
* Synyax Text AND images.
*
* @param {string} markdownText
* @return {Object: { text: String, images: Array }}
* @author Seven Du <shiweidu@outlook.com>
*/
export function syntaxTextAndImage (markdownText) {
/**
* Get markdown text rende to HTML string.
*
* @type {string}
*/
const html = render(markdownText)
/**
* Match all images HTML code in `html`
*
* @type {Array}
*/
const imageHtmlCodes = html.match(/<img.*?(?:>|\/>)/gi)
/**
* Images.
*
* @type {Array}
*/
let images = []
// For each all image.
if (imageHtmlCodes instanceof Array) {
imageHtmlCodes.forEach(function (imageHtmlCode) {
/**
* Match img HTML tag src attr.
*
* @type {Array}
*/
let result = imageHtmlCode.match(/src=['"]?([^'"]*)['"]?/i)
// If matched push to images array.
if (result !== null && result[1]) {
images.push(result[1])
}
})
}
/**
* Replace all HTML tag to '', And replace img HTML tag to "[图片]"
*
* @type {string}
*/
const text = html
.replace(/<img.*?(?:>|\/>)/gi, '[图片]') // Replace img HTML tag to "[图片]"
.replace(/<\/?.+?>/gi, '') // Removed all HTML tags.
.replace(/ /g, '') // Removed all empty character.
// Return all matched result.
// {
// images: Array,
// text: string
// }
return { images, text }
}
/**
* Export default, export render function.
*/
export default render
|
slimkit/thinksns-plus
|
resources/spa/src/util/markdown.js
|
JavaScript
|
apache-2.0
| 2,304 |
package org.smartx.demo.domain;
import org.springframework.stereotype.Repository;
/**
* <p>
*
* </p>
*
* <b>Creation Time:</b> 16/11/23
*
* @author kext
*/
@Repository
public interface UserRepository {
}
|
luffyke/springboot-demo
|
src/main/java/org/smartx/demo/domain/UserRepository.java
|
Java
|
apache-2.0
| 214 |
from turbo import register
import app
import api
register.register_group_urls('', [
('/', app.HomeHandler),
('/plus', app.IncHandler),
('/minus', app.MinusHandler),
])
register.register_group_urls('/v1', [
('', api.HomeHandler),
])
|
wecatch/app-turbo
|
demos/jinja2-support/apps/app/__init__.py
|
Python
|
apache-2.0
| 253 |
/*
* Copyright The OpenTelemetry 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
*
* https://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 { diag } from '@opentelemetry/api';
import { getEnv } from '@opentelemetry/core';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
import { Resource } from '../Resource';
import { Detector, ResourceAttributes } from '../types';
import { ResourceDetectionConfig } from '../config';
/**
* EnvDetector can be used to detect the presence of and create a Resource
* from the OTEL_RESOURCE_ATTRIBUTES environment variable.
*/
class EnvDetector implements Detector {
// Type, attribute keys, and attribute values should not exceed 256 characters.
private readonly _MAX_LENGTH = 255;
// OTEL_RESOURCE_ATTRIBUTES is a comma-separated list of attributes.
private readonly _COMMA_SEPARATOR = ',';
// OTEL_RESOURCE_ATTRIBUTES contains key value pair separated by '='.
private readonly _LABEL_KEY_VALUE_SPLITTER = '=';
private readonly _ERROR_MESSAGE_INVALID_CHARS =
'should be a ASCII string with a length greater than 0 and not exceed ' +
this._MAX_LENGTH +
' characters.';
private readonly _ERROR_MESSAGE_INVALID_VALUE =
'should be a ASCII string with a length not exceed ' +
this._MAX_LENGTH +
' characters.';
/**
* Returns a {@link Resource} populated with attributes from the
* OTEL_RESOURCE_ATTRIBUTES environment variable. Note this is an async
* function to conform to the Detector interface.
*
* @param config The resource detection config
*/
async detect(_config?: ResourceDetectionConfig): Promise<Resource> {
const attributes: ResourceAttributes = {};
const env = getEnv();
const rawAttributes = env.OTEL_RESOURCE_ATTRIBUTES;
const serviceName = env.OTEL_SERVICE_NAME;
if (rawAttributes) {
try {
const parsedAttributes = this._parseResourceAttributes(rawAttributes);
Object.assign(attributes, parsedAttributes);
} catch (e) {
diag.debug(`EnvDetector failed: ${e.message}`);
}
}
if (serviceName) {
attributes[SemanticResourceAttributes.SERVICE_NAME] = serviceName;
}
return new Resource(attributes);
}
/**
* Creates an attribute map from the OTEL_RESOURCE_ATTRIBUTES environment
* variable.
*
* OTEL_RESOURCE_ATTRIBUTES: A comma-separated list of attributes describing
* the source in more detail, e.g. “key1=val1,key2=val2”. Domain names and
* paths are accepted as attribute keys. Values may be quoted or unquoted in
* general. If a value contains whitespaces, =, or " characters, it must
* always be quoted.
*
* @param rawEnvAttributes The resource attributes as a comma-seperated list
* of key/value pairs.
* @returns The sanitized resource attributes.
*/
private _parseResourceAttributes(
rawEnvAttributes?: string
): ResourceAttributes {
if (!rawEnvAttributes) return {};
const attributes: ResourceAttributes = {};
const rawAttributes: string[] = rawEnvAttributes.split(
this._COMMA_SEPARATOR,
-1
);
for (const rawAttribute of rawAttributes) {
const keyValuePair: string[] = rawAttribute.split(
this._LABEL_KEY_VALUE_SPLITTER,
-1
);
if (keyValuePair.length !== 2) {
continue;
}
let [key, value] = keyValuePair;
// Leading and trailing whitespaces are trimmed.
key = key.trim();
value = value.trim().split('^"|"$').join('');
if (!this._isValidAndNotEmpty(key)) {
throw new Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`);
}
if (!this._isValid(value)) {
throw new Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`);
}
attributes[key] = value;
}
return attributes;
}
/**
* Determines whether the given String is a valid printable ASCII string with
* a length not exceed _MAX_LENGTH characters.
*
* @param str The String to be validated.
* @returns Whether the String is valid.
*/
private _isValid(name: string): boolean {
return name.length <= this._MAX_LENGTH && this._isPrintableString(name);
}
private _isPrintableString(str: string): boolean {
for (let i = 0; i < str.length; i++) {
const ch: string = str.charAt(i);
if (ch <= ' ' || ch >= '~') {
return false;
}
}
return true;
}
/**
* Determines whether the given String is a valid printable ASCII string with
* a length greater than 0 and not exceed _MAX_LENGTH characters.
*
* @param str The String to be validated.
* @returns Whether the String is valid and not empty.
*/
private _isValidAndNotEmpty(str: string): boolean {
return str.length > 0 && this._isValid(str);
}
}
export const envDetector = new EnvDetector();
|
open-telemetry/opentelemetry-js
|
packages/opentelemetry-resources/src/detectors/EnvDetector.ts
|
TypeScript
|
apache-2.0
| 5,327 |
/*
* Copyright 2000-2009 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.roots.ui.configuration;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ModuleRootModel;
import com.intellij.facet.FacetModel;
import com.intellij.facet.FacetManager;
/**
* @author nik
*/
public class DefaultModulesProvider implements ModulesProvider {
private final Project myProject;
public DefaultModulesProvider(final Project project) {
myProject = project;
}
public Module[] getModules() {
return ModuleManager.getInstance(myProject).getModules();
}
public Module getModule(String name) {
return ModuleManager.getInstance(myProject).findModuleByName(name);
}
public ModuleRootModel getRootModel(Module module) {
return ModuleRootManager.getInstance(module);
}
public FacetModel getFacetModel(Module module) {
return FacetManager.getInstance(module);
}
}
|
jexp/idea2
|
platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/DefaultModulesProvider.java
|
Java
|
apache-2.0
| 1,618 |
"""
thainlp tag command line.
"""
import argparse
from pythainlp import cli
from pythainlp.tag import locations, named_entity, pos_tag
class SubAppBase:
def __init__(self, name, argv):
parser = argparse.ArgumentParser(**cli.make_usage("tag " + name))
parser.add_argument(
"text", type=str, help="input text",
)
parser.add_argument(
"-s",
"--sep",
dest="separator",
type=str,
help=f"Token separator for input text. default: {self.separator}",
default=self.separator,
)
args = parser.parse_args(argv)
self.args = args
tokens = args.text.split(args.separator)
result = self.run(tokens)
for word, tag in result:
print(word, "/", tag)
class POSTaggingApp(SubAppBase):
def __init__(self, *args, **kwargs):
self.separator = "|"
self.run = pos_tag
super().__init__(*args, **kwargs)
class App:
def __init__(self, argv):
parser = argparse.ArgumentParser(
prog="tag",
description="Annotate a text with linguistic information",
usage=(
'thainlp tag <tag_type> [--sep "<separator>"] "<text>"\n\n'
"tag_type:\n\n"
"pos part-of-speech\n\n"
"<separator> and <text> should be inside double quotes.\n"
"<text> should be a tokenized text, "
"with tokens separated by <separator>.\n\n"
"Example:\n\n"
'thainlp tag pos -s " " "แรงดึงดูด เก็บ หัว คุณ ลง"\n\n'
"--"
),
)
parser.add_argument("tag_type", type=str, help="[pos]")
args = parser.parse_args(argv[2:3])
cli.exit_if_empty(args.tag_type, parser)
tag_type = str.lower(args.tag_type)
argv = argv[3:]
if tag_type == "pos":
POSTaggingApp("Part-of-Speech tagging", argv)
else:
print(f"Tag type not available: {tag_type}")
|
PyThaiNLP/pythainlp
|
pythainlp/cli/tag.py
|
Python
|
apache-2.0
| 2,123 |
/*
* Copyright 2012-2015 Red Hat 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.ovirt.engine.extension.aaa.ldap;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Util {
private static final Pattern VAR_PATTERN = Pattern.compile("\\$\\{((?<namespace>[^:}]*):)?(?<var>[^}]*)\\}");
private static final Map<Class<?>, Class<?>> typeBox = new HashMap<>();
static {
typeBox.put(boolean.class, Boolean.class);
typeBox.put(byte.class, Byte.class);
typeBox.put(char.class, Character.class);
typeBox.put(double.class, Double.class);
typeBox.put(float.class, Float.class);
typeBox.put(int.class, Integer.class);
typeBox.put(long.class, Long.class);
typeBox.put(short.class, Short.class);
typeBox.put(void.class, Void.class);
}
public static String toString(Object o, String def) {
return o != null ? o.toString() : def;
}
public static String toString(Object o) {
return toString(o, "");
}
public static void removeKeysWithPrefix(Map<String, Object> map, String prefix) {
Iterator<Map.Entry<String, Object>> iter = map.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry<String, Object> e = iter.next();
if (e.getKey().startsWith(prefix)) {
iter.remove();
}
}
}
public static String expandString(String s, String namespace, Map<? extends Object, ? extends Object> vars) {
StringBuilder ret = new StringBuilder();
Matcher m = VAR_PATTERN.matcher(s);
int last = 0;
while (m.find()) {
ret.append(s.substring(last, m.start()));
if (
(namespace == null && m.group("namespace") == null) ||
(namespace != null && namespace.equals(m.group("namespace")))
) {
Object o = vars.get(m.group("var"));
if (o != null) {
ret.append(o);
}
} else {
ret.append(m.group(0));
}
last = m.end();
}
ret.append(s.substring(last, m.regionEnd()));
return ret.toString();
}
public static void _expandMap(MapProperties props, String namespace, Map<? extends Object, ? extends Object> vars) {
if (props.getValue() != null) {
props.setValue(expandString(props.getValue(), namespace, vars));
}
for (MapProperties entry : props.getMap().values()) {
_expandMap(entry, namespace, vars);
}
}
public static MapProperties expandMap(MapProperties props, String namespace, Map<? extends Object, ? extends Object> vars) {
MapProperties ret = new MapProperties(props);
MapProperties old;
do {
old = new MapProperties(ret);
_expandMap(ret, namespace, vars);
} while(!old.equals(ret));
return ret;
}
public static Properties expandProperties(
Properties props,
String namespace,
Map<? extends Object, ? extends Object> vars,
boolean recursive
) {
Properties ret = new Properties();
ret.putAll(props);
Properties old;
do {
old = new Properties();
old.putAll(ret);
for (Map.Entry<Object, Object> entry : ret.entrySet()) {
entry.setValue(expandString(entry.getValue().toString(), namespace, vars));
}
} while(recursive && !old.equals(ret));
return ret;
}
public static List<String> stringPropertyNames(Properties props, String prefix) {
if (prefix.endsWith(".")) {
prefix = prefix.substring(0, prefix.length()-1);
}
List<String> keys = new LinkedList<>();
for (String key : props.stringPropertyNames()) {
if (key.equals(prefix) || key.startsWith(prefix + ".")) {
keys.add(key);
}
}
Collections.sort(keys);
return keys;
}
public static void includeProperties(
Properties out,
String includeKey,
List<File> includeDirectories,
File file
) throws IOException {
Properties props = new Properties();
try (
InputStream is = new FileInputStream(file);
Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
) {
props.load(reader);
}
props.put("_basedir", file.getParent());
props = expandProperties(props, "local", props, true);
for (String key : stringPropertyNames(props, includeKey)) {
String include = props.getProperty(key);
File includeFile = null;
if (include.startsWith("<") && include.endsWith(">")) {
include = include.substring(1, include.length()-1);
for (File i : includeDirectories) {
File t = new File(i, include);
if (t.exists()) {
includeFile = t;
break;
}
}
if (includeFile == null) {
throw new FileNotFoundException(
String.format(
"Cannot include file '%s' from search path %s",
include,
includeDirectories
)
);
}
} else {
includeFile = new File(include);
if (!includeFile.isAbsolute()) {
includeFile = new File(file.getParentFile(), include);
}
}
includeProperties(out, includeKey, includeDirectories, includeFile);
}
for (Map.Entry<Object, Object> entry : props.entrySet()) {
out.put(entry.getKey(), entry.getValue());
}
}
public static Properties loadProperties(List<File> includeDirectories, File... file) throws IOException {
Properties props = new Properties();
for (File f : file) {
includeProperties(props, "include", includeDirectories, f);
}
props = expandProperties(props, "global", props, true);
props = expandProperties(props, "sys", System.getProperties(), false);
return props;
}
public static int[] asIntArray(List<?> l, int def, int size) {
int[] ret = new int[size];
Arrays.fill(ret, def);
for (int i = 0; i < l.size() && i < size; i++) {
ret[i] = Integer.valueOf(l.get(i).toString());
}
return ret;
}
public static List<String> getValueFromMapRecord(MapProperties props, String key) {
List<String> ret = new ArrayList<>();
for (MapProperties entry : props.getMap().values()) {
String v = entry.getString(null, key);
if (v != null) {
ret.add(v);
}
}
return ret;
}
public static Object getObjectValueByString(Class<?> clazz, String value) {
Object v = null;
if (clazz.isPrimitive()) {
clazz = typeBox.get(clazz);
}
if (v == null) {
if (clazz.equals(Collection.class)) {
List<Object> r = new ArrayList<>();
for (String c : value.trim().split(" *, *")) {
if (!c.isEmpty()) {
r.add(getObjectValueByString(String.class, c));
}
}
v = r;
}
}
if (v == null) {
if (clazz.isArray() && Object.class.isAssignableFrom(clazz.getComponentType())) {
List<Object> r = new ArrayList<>();
for (String c : value.trim().split(" *, *")) {
if (!c.isEmpty()) {
r.add(getObjectValueByString(clazz.getComponentType(), c));
}
}
v = (Object)r.toArray((Object[]) Array.newInstance(clazz.getComponentType(), 0));
}
}
if (v == null) {
try {
Field f = clazz.getField(value);
if (Modifier.isStatic(f.getModifiers())) {
v = f.get(null);
}
} catch(ReflectiveOperationException e) {}
}
if (v == null) {
try {
Method convert = clazz.getMethod("valueOf", String.class);
if (Modifier.isStatic(convert.getModifiers())) {
v = convert.invoke(null, value);
}
} catch(ReflectiveOperationException e) {}
}
if (v == null) {
try {
Method convert = clazz.getMethod("valueOf", Object.class);
if (Modifier.isStatic(convert.getModifiers())) {
v = convert.invoke(null, value);
}
} catch(ReflectiveOperationException e) {}
}
if (v == null) {
try {
Constructor<?> constructor = clazz.getDeclaredConstructor(String.class);
v = constructor.newInstance(value);
} catch(ReflectiveOperationException e) {}
}
return v;
}
public static void setObjectByProperties(Object o, MapProperties props, String... methodPrefixes) {
if (props == null) {
return;
}
for (Method m : o.getClass().getMethods()) {
for (String p : methodPrefixes) {
String methodName = m.getName();
if (methodName.startsWith(p)) {
String name = (
methodName.substring(p.length(), p.length()+1).toLowerCase() +
methodName.substring(p.length()+1)
);
try {
List<String> values = new ArrayList<>();
MapProperties valueProps = props.getOrEmpty(name);
values.add(valueProps.getValue());
for (MapProperties valueProps1 : valueProps.getMap().values()) {
values.add(valueProps1.getValue());
}
for (String value : values) {
if (value != null) {
Class<?>[] args = m.getParameterTypes();
if (args.length == 1) {
Object v = getObjectValueByString(args[0], value);
if (v != null) {
m.invoke(o, v);
}
}
}
}
} catch(Exception e) {
throw new RuntimeException(
String.format(
"Cannot set key '%s', error: %s",
name,
e.getMessage()
),
e
);
}
}
}
}
}
public static <T extends Enum<T>> List<T> getEnumFromString(Class<T> clazz, String value) {
List<T> ret = new ArrayList<>();
if (value != null) {
String[] comps = value.trim().split(" *, *");
for (String c : comps) {
if (!c.isEmpty()) {
ret.add(T.valueOf(clazz, c));
}
}
}
return ret;
}
public static KeyStore loadKeyStore(String provider, String type, String file, String password)
throws GeneralSecurityException, IOException {
KeyStore store = null;
if (file != null) {
try (InputStream in = new FileInputStream(file)) {
if (type == null) {
type = KeyStore.getDefaultType();
}
if (provider == null) {
store = KeyStore.getInstance(
type
);
} else {
store = KeyStore.getInstance(
type,
provider
);
}
store.load(in, password.toCharArray());
}
}
return store;
}
}
// vim: expandtab tabstop=4 shiftwidth=4
|
oVirt/ovirt-engine-extension-aaa-ldap
|
src/main/java/org/ovirt/engine/extension/aaa/ldap/Util.java
|
Java
|
apache-2.0
| 13,912 |
/*
* Copyright (c) 2014 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 io.werval.modules.xml.internal;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.validation.Schema;
import io.werval.modules.xml.SAX;
import io.werval.modules.xml.UncheckedXMLException;
import org.xml.sax.HandlerBase;
import org.xml.sax.InputSource;
import org.xml.sax.Parser;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import static io.werval.modules.xml.internal.Internal.ACCESS_EXTERNAL_ALL;
import static io.werval.modules.xml.internal.Internal.ACCESS_EXTERNAL_NONE;
import static io.werval.modules.xml.internal.Internal.LOG;
/**
* SAXParserFactory implementation for XMLPlugin.
* <p>
* Factory API that enables applications to configure and obtain a SAX based parser to parse XML documents.
*
* @see SAXParserFactory
*/
public final class SAXParserFactoryImpl
extends SAXParserFactory
{
// Aalto
// private final SAXParserFactory delegate = new com.fasterxml.aalto.sax.SAXParserFactoryImpl();
// Woodstox
// private final SAXParserFactory delegate = new com.ctc.wstx.sax.WstxSAXParserFactory();
// Xerces
private final SAXParserFactory delegate = new org.apache.xerces.jaxp.SAXParserFactoryImpl();
public SAXParserFactoryImpl()
throws ParserConfigurationException, SAXException
{
// Aalto & Woodstox & Xerces
delegate.setFeature( SAX.Features.EXTERNAL_GENERAL_ENTITIES, Internal.EXTERNAL_ENTITIES.get() );
delegate.setFeature( SAX.Features.EXTERNAL_PARAMETER_ENTITIES, Internal.EXTERNAL_ENTITIES.get() );
// Xerces
delegate.setFeature( XMLConstants.FEATURE_SECURE_PROCESSING, true );
delegate.setFeature( "http://apache.org/xml/features/standard-uri-conformant", true );
setValidating( false );
// No support but should be disabled anyway, belt'n braces
delegate.setXIncludeAware( false );
}
@Override
public void setNamespaceAware( boolean namespaceAware )
{
delegate.setNamespaceAware( namespaceAware );
}
@Override
public void setValidating( boolean dtdValidation )
{
try
{
// Xerces
delegate.setFeature( "http://apache.org/xml/features/validation/balance-syntax-trees", dtdValidation );
delegate.setFeature( "http://apache.org/xml/features/nonvalidating/load-dtd-grammar", dtdValidation );
delegate.setFeature(
"http://apache.org/xml/features/nonvalidating/load-external-dtd",
dtdValidation && Internal.EXTERNAL_ENTITIES.get()
);
delegate.setFeature( "http://apache.org/xml/features/disallow-doctype-decl", !dtdValidation );
}
catch( ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException ex )
{
throw new UncheckedXMLException( ex );
}
delegate.setValidating( dtdValidation );
if( dtdValidation )
{
LOG.warn( "SAXParserFactory.setValidating( true ) Unsafe DTD support enabled" );
}
}
@Override
public boolean isNamespaceAware()
{
return delegate.isNamespaceAware();
}
@Override
public boolean isValidating()
{
return delegate.isValidating();
}
@Override
public Schema getSchema()
{
return delegate.getSchema();
}
@Override
public void setSchema( Schema schema )
{
delegate.setSchema( schema );
}
@Override
public void setXIncludeAware( boolean xIncludeAware )
{
delegate.setXIncludeAware( xIncludeAware );
}
@Override
public boolean isXIncludeAware()
{
return delegate.isXIncludeAware();
}
@Override
public SAXParser newSAXParser()
throws ParserConfigurationException, SAXException
{
return new SAXParserImpl( delegate.newSAXParser() );
}
@Override
public void setFeature( String name, boolean value )
throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException
{
delegate.setFeature( name, value );
}
@Override
public boolean getFeature( String name )
throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException
{
return delegate.getFeature( name );
}
private static final class SAXParserImpl
extends SAXParser
{
private final SAXParser parser;
protected SAXParserImpl( SAXParser saxParser )
throws SAXException
{
this.parser = saxParser;
try
{
this.parser.setProperty(
XMLConstants.ACCESS_EXTERNAL_DTD,
Internal.EXTERNAL_ENTITIES.get() ? ACCESS_EXTERNAL_ALL : ACCESS_EXTERNAL_NONE
);
}
catch( SAXException ex )
{
LOG.trace( "JAXP<1.5 - {} on {}", ex.getMessage(), this.parser );
}
try
{
this.parser.setProperty(
XMLConstants.ACCESS_EXTERNAL_SCHEMA,
Internal.EXTERNAL_ENTITIES.get() ? ACCESS_EXTERNAL_ALL : ACCESS_EXTERNAL_NONE
);
}
catch( SAXException ex )
{
LOG.trace( "JAXP<1.5 - {} on {}", ex.getMessage(), this.parser );
}
}
@Override
public void reset()
{
parser.reset();
}
@Override
public void parse( InputStream inputStream, HandlerBase handlerBase )
throws SAXException, IOException
{
parser.parse( inputStream, handlerBase );
}
@Override
public void parse( InputStream inputStream, HandlerBase handlerBase, String systemId )
throws SAXException, IOException
{
parser.parse( inputStream, handlerBase, systemId );
}
@Override
public void parse( InputStream inputStream, DefaultHandler defaultHandler )
throws SAXException, IOException
{
parser.parse( inputStream, defaultHandler );
}
@Override
public void parse( InputStream inputStream, DefaultHandler defaultHandler, String systemId )
throws SAXException, IOException
{
parser.parse( inputStream, defaultHandler, systemId );
}
@Override
public void parse( String s, HandlerBase handlerBase )
throws SAXException, IOException
{
parser.parse( s, handlerBase );
}
@Override
public void parse( String s, DefaultHandler defaultHandler )
throws SAXException, IOException
{
parser.parse( s, defaultHandler );
}
@Override
public void parse( File file, HandlerBase handlerBase )
throws SAXException, IOException
{
parser.parse( file, handlerBase );
}
@Override
public void parse( File file, DefaultHandler defaultHandler )
throws SAXException, IOException
{
parser.parse( file, defaultHandler );
}
@Override
public void parse( InputSource inputSource, HandlerBase handlerBase )
throws SAXException, IOException
{
parser.parse( inputSource, handlerBase );
}
@Override
public void parse( InputSource inputSource, DefaultHandler defaultHandler )
throws SAXException, IOException
{
parser.parse( inputSource, defaultHandler );
}
@Override
public Parser getParser()
throws SAXException
{
return parser.getParser();
}
@Override
public XMLReader getXMLReader()
throws SAXException
{
XMLReader reader = parser.getXMLReader();
try
{
reader.setFeature( XMLConstants.FEATURE_SECURE_PROCESSING, true );
}
catch( SAXNotRecognizedException ex )
{
LOG.trace( "JAXP<1.5 - {} on {}", ex.getMessage(), reader );
}
reader.setFeature( SAX.Features.EXTERNAL_GENERAL_ENTITIES, Internal.EXTERNAL_ENTITIES.get() );
reader.setFeature( SAX.Features.EXTERNAL_PARAMETER_ENTITIES, Internal.EXTERNAL_ENTITIES.get() );
reader.setEntityResolver( Internal.RESOLVER.get() );
reader.setErrorHandler( Errors.INSTANCE );
return reader;
}
@Override
public boolean isNamespaceAware()
{
return parser.isNamespaceAware();
}
@Override
public boolean isValidating()
{
return parser.isValidating();
}
@Override
public void setProperty( String name, Object value )
throws SAXNotRecognizedException, SAXNotSupportedException
{
parser.setProperty( name, value );
}
@Override
public Object getProperty( String name )
throws SAXNotRecognizedException, SAXNotSupportedException
{
return parser.getProperty( name );
}
@Override
public Schema getSchema()
{
return parser.getSchema();
}
@Override
public boolean isXIncludeAware()
{
return parser.isXIncludeAware();
}
}
}
|
werval/werval
|
io.werval.modules/io.werval.modules.xml/src/main/java/io/werval/modules/xml/internal/SAXParserFactoryImpl.java
|
Java
|
apache-2.0
| 10,474 |
/*
* (C) Copyright 2016 Kurento (http://kurento.org/)
*
* 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.
*
*/
#include <gst/gst.h>
#include "MediaType.hpp"
#include "MediaPipeline.hpp"
#include "MediaProfileSpecType.hpp"
#include "GapsFixMethod.hpp"
#include <RecorderEndpointImplFactory.hpp>
#include "RecorderEndpointImpl.hpp"
#include <jsonrpc/JsonSerializer.hpp>
#include <KurentoException.hpp>
#include <gst/gst.h>
#include <commons/kmsrecordingprofile.h>
#include "StatsType.hpp"
#include "EndpointStats.hpp"
#include <commons/kmsutils.h>
#include <commons/kmsstats.h>
#include <SignalHandler.hpp>
#include <functional>
#define GST_CAT_DEFAULT kurento_recorder_endpoint_impl
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoRecorderEndpointImpl"
#define FACTORY_NAME "recorderendpoint"
#define PARAM_GAPS_FIX "gapsFix"
#define PROP_GAPS_FIX "gaps-fix"
#define TIMEOUT 4 /* seconds */
namespace kurento
{
typedef enum {
KMS_URI_END_POINT_STATE_STOP,
KMS_URI_END_POINT_STATE_START,
KMS_URI_END_POINT_STATE_PAUSE
} KmsUriEndPointState;
bool RecorderEndpointImpl::support_ksr;
static bool
check_support_for_ksr ()
{
GstPlugin *plugin = nullptr;
bool supported;
plugin = gst_plugin_load_by_name ("kmsrecorder");
supported = plugin != nullptr;
g_clear_object (&plugin);
return supported;
}
RecorderEndpointImpl::RecorderEndpointImpl (const boost::property_tree::ptree
&conf,
std::shared_ptr<MediaPipeline> mediaPipeline, const std::string &uri,
std::shared_ptr<MediaProfileSpecType> mediaProfile,
bool stopOnEndOfStream) : UriEndpointImpl (conf,
std::dynamic_pointer_cast<MediaObjectImpl> (mediaPipeline), FACTORY_NAME, uri)
{
g_object_set (G_OBJECT (getGstreamerElement() ), "accept-eos",
stopOnEndOfStream, NULL);
switch (mediaProfile->getValue() ) {
case MediaProfileSpecType::WEBM:
g_object_set ( G_OBJECT (element), "profile", KMS_RECORDING_PROFILE_WEBM, NULL);
GST_INFO ("Set WEBM profile");
break;
case MediaProfileSpecType::MP4:
g_object_set ( G_OBJECT (element), "profile", KMS_RECORDING_PROFILE_MP4, NULL);
GST_INFO ("Set MP4 profile");
break;
case MediaProfileSpecType::MKV:
g_object_set ( G_OBJECT (element), "profile", KMS_RECORDING_PROFILE_MKV, NULL);
GST_INFO ("Set MKV profile");
break;
case MediaProfileSpecType::WEBM_VIDEO_ONLY:
g_object_set ( G_OBJECT (element), "profile",
KMS_RECORDING_PROFILE_WEBM_VIDEO_ONLY, NULL);
GST_INFO ("Set WEBM VIDEO ONLY profile");
break;
case MediaProfileSpecType::WEBM_AUDIO_ONLY:
g_object_set ( G_OBJECT (element), "profile",
KMS_RECORDING_PROFILE_WEBM_AUDIO_ONLY, NULL);
GST_INFO ("Set WEBM AUDIO ONLY profile");
break;
case MediaProfileSpecType::MKV_VIDEO_ONLY:
g_object_set ( G_OBJECT (element), "profile",
KMS_RECORDING_PROFILE_MKV_VIDEO_ONLY, NULL);
GST_INFO ("Set MKV VIDEO ONLY profile");
break;
case MediaProfileSpecType::MKV_AUDIO_ONLY:
g_object_set ( G_OBJECT (element), "profile",
KMS_RECORDING_PROFILE_MKV_AUDIO_ONLY, NULL);
GST_INFO ("Set MKV AUDIO ONLY profile");
break;
case MediaProfileSpecType::MP4_VIDEO_ONLY:
g_object_set ( G_OBJECT (element), "profile",
KMS_RECORDING_PROFILE_MP4_VIDEO_ONLY, NULL);
GST_INFO ("Set MP4 VIDEO ONLY profile");
break;
case MediaProfileSpecType::MP4_AUDIO_ONLY:
g_object_set ( G_OBJECT (element), "profile",
KMS_RECORDING_PROFILE_MP4_AUDIO_ONLY, NULL);
GST_INFO ("Set MP4 AUDIO ONLY profile");
break;
case MediaProfileSpecType::JPEG_VIDEO_ONLY:
g_object_set ( G_OBJECT (element), "profile",
KMS_RECORDING_PROFILE_JPEG_VIDEO_ONLY, NULL);
GST_INFO ("Set JPEG profile");
break;
case MediaProfileSpecType::KURENTO_SPLIT_RECORDER:
if (!RecorderEndpointImpl::support_ksr) {
throw KurentoException (MEDIA_OBJECT_ILLEGAL_PARAM_ERROR,
"Kurento Split Recorder not supported");
}
g_object_set ( G_OBJECT (element), "profile", KMS_RECORDING_PROFILE_KSR, NULL);
GST_INFO ("Set KSR profile");
break;
}
GapsFixMethod gapsFix;
if (getConfigValue<GapsFixMethod, RecorderEndpoint> (
&gapsFix, PARAM_GAPS_FIX)) {
GST_INFO ("Set RecorderEndpoint gaps fix mode: %s",
gapsFix.getString ().c_str ());
g_object_set (getGstreamerElement (),
PROP_GAPS_FIX, gapsFix.getValue (), NULL);
}
}
void RecorderEndpointImpl::postConstructor()
{
UriEndpointImpl::postConstructor();
handlerOnStateChanged = register_signal_handler (G_OBJECT (element),
"state-changed",
std::function <void (GstElement *, gint) >
(std::bind (&RecorderEndpointImpl::onStateChanged, this,
std::placeholders::_2) ),
std::dynamic_pointer_cast<RecorderEndpointImpl>
(shared_from_this() ) );
}
void
RecorderEndpointImpl::onStateChanged (gint newState)
{
switch (newState) {
case KMS_URI_END_POINT_STATE_STOP: {
GST_DEBUG_OBJECT (element, "State changed to Stopped");
try {
Stopped event (shared_from_this (), Stopped::getName ());
sigcSignalEmit(signalStopped, event);
} catch (const std::bad_weak_ptr &e) {
// shared_from_this()
GST_ERROR ("BUG creating %s: %s", Stopped::getName ().c_str (),
e.what ());
}
break;
}
case KMS_URI_END_POINT_STATE_START: {
GST_DEBUG_OBJECT (element, "State changed to Recording");
try {
Recording event (shared_from_this(), Recording::getName () );
sigcSignalEmit(signalRecording, event);
} catch (const std::bad_weak_ptr &e) {
// shared_from_this()
GST_ERROR ("BUG creating %s: %s", Recording::getName ().c_str (),
e.what ());
}
break;
}
case KMS_URI_END_POINT_STATE_PAUSE: {
GST_DEBUG_OBJECT (element, "State changed to Paused");
try {
Paused event (shared_from_this(), Paused::getName () );
sigcSignalEmit(signalPaused, event);
} catch (const std::bad_weak_ptr &e) {
// shared_from_this()
GST_ERROR ("BUG creating %s: %s", Paused::getName ().c_str (),
e.what ());
}
break;
}
}
std::unique_lock<std::mutex> lck (mtx);
GST_TRACE_OBJECT (element, "State changed to %d", newState);
state = newState;
cv.notify_one();
}
void RecorderEndpointImpl::waitForStateChange (gint expectedState)
{
std::unique_lock<std::mutex> lck (mtx);
if (!cv.wait_for (lck, std::chrono::seconds (TIMEOUT), [&] {return expectedState == state;}) ) {
GST_ERROR_OBJECT (element, "STATE did not changed to %d in %d seconds",
expectedState, TIMEOUT);
}
}
void
RecorderEndpointImpl::release ()
{
gint state = -1;
g_object_get (getGstreamerElement(), "state", &state, NULL);
if (state == 0 /* stop */) {
goto end;
}
stopAndWait();
end:
UriEndpointImpl::release();
}
RecorderEndpointImpl::~RecorderEndpointImpl()
{
gint state = -1;
if (handlerOnStateChanged > 0) {
unregister_signal_handler (element, handlerOnStateChanged);
}
g_object_get (getGstreamerElement(), "state", &state, NULL);
if (state != 0 /* stop */) {
GST_ERROR ("Recorder should be stopped when reaching this point");
}
}
void RecorderEndpointImpl::record ()
{
start();
}
void RecorderEndpointImpl::stopAndWait ()
{
stop();
waitForStateChange (KMS_URI_END_POINT_STATE_STOP);
}
static void
setDeprecatedProperties (std::shared_ptr<EndpointStats> eStats)
{
std::vector<std::shared_ptr<MediaLatencyStat>> inStats =
eStats->getE2ELatency();
for (auto &inStat : inStats) {
if (inStat->getName() == "sink_audio_default") {
eStats->setAudioE2ELatency(inStat->getAvg());
} else if (inStat->getName() == "sink_video_default") {
eStats->setVideoE2ELatency(inStat->getAvg());
}
}
}
void
RecorderEndpointImpl::collectEndpointStats (std::map
<std::string, std::shared_ptr<Stats>>
&statsReport, std::string id, const GstStructure *stats,
double timestamp, int64_t timestampMillis)
{
std::shared_ptr<Stats> endpointStats;
GstStructure *e2e_stats;
std::vector<std::shared_ptr<MediaLatencyStat>> inputStats;
std::vector<std::shared_ptr<MediaLatencyStat>> e2eStats;
if (gst_structure_get (stats, "e2e-latencies", GST_TYPE_STRUCTURE,
&e2e_stats, NULL) ) {
collectLatencyStats (e2eStats, e2e_stats);
gst_structure_free (e2e_stats);
}
endpointStats = std::make_shared <EndpointStats> (id,
std::make_shared <StatsType> (StatsType::endpoint), timestamp,
timestampMillis, 0.0, 0.0, inputStats, 0.0, 0.0, e2eStats);
setDeprecatedProperties (std::dynamic_pointer_cast <EndpointStats>
(endpointStats) );
statsReport[id] = endpointStats;
}
void
RecorderEndpointImpl::fillStatsReport (std::map
<std::string, std::shared_ptr<Stats>>
&report, const GstStructure *stats,
double timestamp, int64_t timestampMillis)
{
const GstStructure *e_stats;
e_stats = kms_utils_get_structure_by_name (stats, KMS_MEDIA_ELEMENT_FIELD);
if (e_stats != nullptr) {
collectEndpointStats (report, getId (), e_stats, timestamp, timestampMillis);
}
UriEndpointImpl::fillStatsReport (report, stats, timestamp, timestampMillis);
}
MediaObjectImpl *
RecorderEndpointImplFactory::createObject (const boost::property_tree::ptree
&conf, std::shared_ptr<MediaPipeline>
mediaPipeline, const std::string &uri,
std::shared_ptr<MediaProfileSpecType> mediaProfile,
bool stopOnEndOfStream) const
{
return new RecorderEndpointImpl (conf, mediaPipeline, uri, mediaProfile,
stopOnEndOfStream);
}
RecorderEndpointImpl::StaticConstructor RecorderEndpointImpl::staticConstructor;
RecorderEndpointImpl::StaticConstructor::StaticConstructor()
{
RecorderEndpointImpl::support_ksr = check_support_for_ksr();
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
}
} /* kurento */
|
Kurento/kms-elements
|
src/server/implementation/objects/RecorderEndpointImpl.cpp
|
C++
|
apache-2.0
| 10,886 |
# frozen_string_literal: true
module Hyrax
module SolrDocument
module Metadata
extend ActiveSupport::Concern
class_methods do
def attribute(name, type, field)
define_method name do
type.coerce(self[field])
end
end
end
module Solr
class Array
# @return [Array]
def self.coerce(input)
::Array.wrap(input)
end
end
class String
# @return [String]
def self.coerce(input)
::Array.wrap(input).first
end
end
class Date
# @return [Date]
def self.coerce(input)
field = String.coerce(input)
return if field.blank?
begin
::Date.parse(field)
rescue ArgumentError
Hyrax.logger.info "Unable to parse date: #{field.first.inspect}"
end
end
end
end
included do
attribute :alternative_title, Solr::Array, "alternative_title_tesim"
attribute :identifier, Solr::Array, "identifier_tesim"
attribute :based_near, Solr::Array, "based_near_tesim"
attribute :based_near_label, Solr::Array, "based_near_label_tesim"
attribute :related_url, Solr::Array, "related_url_tesim"
attribute :resource_type, Solr::Array, "resource_type_tesim"
attribute :edit_groups, Solr::Array, ::Ability.edit_group_field
attribute :edit_people, Solr::Array, ::Ability.edit_user_field
attribute :read_groups, Solr::Array, ::Ability.read_group_field
attribute :collection_ids, Solr::Array, 'collection_ids_tesim'
attribute :admin_set, Solr::Array, "admin_set_tesim"
attribute :admin_set_id, Solr::Array, "admin_set_id_ssim"
attribute :member_ids, Solr::Array, "member_ids_ssim"
attribute :member_of_collection_ids, Solr::Array, "member_of_collection_ids_ssim"
attribute :member_of_collections, Solr::Array, "member_of_collections_ssim"
attribute :description, Solr::Array, "description_tesim"
attribute :abstract, Solr::Array, "abstract_tesim"
attribute :title, Solr::Array, "title_tesim"
attribute :contributor, Solr::Array, "contributor_tesim"
attribute :subject, Solr::Array, "subject_tesim"
attribute :publisher, Solr::Array, "publisher_tesim"
attribute :language, Solr::Array, "language_tesim"
attribute :keyword, Solr::Array, "keyword_tesim"
attribute :license, Solr::Array, "license_tesim"
attribute :source, Solr::Array, "source_tesim"
attribute :date_created, Solr::Array, "date_created_tesim"
attribute :rights_statement, Solr::Array, "rights_statement_tesim"
attribute :rights_notes, Solr::Array, "rights_notes_tesim"
attribute :access_right, Solr::Array, "access_right_tesim"
attribute :mime_type, Solr::String, "mime_type_ssi"
attribute :workflow_state, Solr::String, "workflow_state_name_ssim"
attribute :human_readable_type, Solr::String, "human_readable_type_tesim"
attribute :representative_id, Solr::String, "hasRelatedMediaFragment_ssim"
# extract the term name from the rendering_predicate (it might be after the final / or #)
attribute :rendering_ids, Solr::Array, Hyrax.config.rendering_predicate.value.split(/#|\/|,/).last + "_ssim"
attribute :thumbnail_id, Solr::String, "hasRelatedImage_ssim"
attribute :thumbnail_path, Solr::String, CatalogController.blacklight_config.index.thumbnail_field
attribute :label, Solr::String, "label_tesim"
attribute :file_format, Solr::String, "file_format_tesim"
attribute :suppressed?, Solr::String, "suppressed_bsi"
attribute :original_file_id, Solr::String, "original_file_id_ssi"
attribute :date_modified, Solr::Date, "date_modified_dtsi"
attribute :date_uploaded, Solr::Date, "date_uploaded_dtsi"
attribute :create_date, Solr::Date, "system_create_dtsi"
attribute :modified_date, Solr::Date, "system_modified_dtsi"
attribute :embargo_release_date, Solr::Date, Hydra.config.permissions.embargo.release_date
attribute :lease_expiration_date, Solr::Date, Hydra.config.permissions.lease.expiration_date
end
end
end
end
|
samvera/hyrax
|
app/models/concerns/hyrax/solr_document/metadata.rb
|
Ruby
|
apache-2.0
| 4,358 |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* 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.example.android.sunshine.app.data;
import android.annotation.TargetApi;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
public class WeatherProvider extends ContentProvider {
// The URI Matcher used by this content provider.
private static final UriMatcher sUriMatcher = buildUriMatcher();
private WeatherDbHelper mOpenHelper;
static final int WEATHER = 100;
static final int WEATHER_WITH_LOCATION = 101;
static final int WEATHER_WITH_LOCATION_AND_DATE = 102;
static final int LOCATION = 300;
private static final SQLiteQueryBuilder sWeatherByLocationSettingQueryBuilder;
static {
sWeatherByLocationSettingQueryBuilder = new SQLiteQueryBuilder();
//This is an inner join which looks like
//weather INNER JOIN location ON weather.location_id = location._id
sWeatherByLocationSettingQueryBuilder.setTables(
WeatherContract.WeatherEntry.TABLE_NAME + " INNER JOIN " +
WeatherContract.LocationEntry.TABLE_NAME +
" ON " + WeatherContract.WeatherEntry.TABLE_NAME +
"." + WeatherContract.WeatherEntry.COLUMN_LOC_KEY +
" = " + WeatherContract.LocationEntry.TABLE_NAME +
"." + WeatherContract.LocationEntry._ID);
}
//location.location_setting = ?
private static final String sLocationSettingSelection =
WeatherContract.LocationEntry.TABLE_NAME +
"." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? ";
//location.location_setting = ? AND date >= ?
private static final String sLocationSettingWithStartDateSelection =
WeatherContract.LocationEntry.TABLE_NAME +
"." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " +
WeatherContract.WeatherEntry.COLUMN_DATE + " >= ? ";
//location.location_setting = ? AND date = ?
private static final String sLocationSettingAndDaySelection =
WeatherContract.LocationEntry.TABLE_NAME +
"." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " +
WeatherContract.WeatherEntry.COLUMN_DATE + " = ? ";
private Cursor getWeatherByLocationSetting(Uri uri, String[] projection, String sortOrder) {
String locationSetting = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri);
long startDate = WeatherContract.WeatherEntry.getStartDateFromUri(uri);
String[] selectionArgs;
String selection;
if (startDate == 0) {
selection = sLocationSettingSelection;
selectionArgs = new String[]{locationSetting};
} else {
selectionArgs = new String[]{locationSetting, Long.toString(startDate)};
selection = sLocationSettingWithStartDateSelection;
}
return sWeatherByLocationSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(),
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
}
private Cursor getWeatherByLocationSettingAndDate(
Uri uri, String[] projection, String sortOrder) {
String locationSetting = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri);
long date = WeatherContract.WeatherEntry.getDateFromUri(uri);
return sWeatherByLocationSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(),
projection,
sLocationSettingAndDaySelection,
new String[]{locationSetting, Long.toString(date)},
null,
null,
sortOrder
);
}
/*
Students: Here is where you need to create the UriMatcher. This UriMatcher will
match each URI to the WEATHER, WEATHER_WITH_LOCATION, WEATHER_WITH_LOCATION_AND_DATE,
and LOCATION integer constants defined above. You can test this by uncommenting the
testUriMatcher test within TestUriMatcher.
*/
static UriMatcher buildUriMatcher() {
// I know what you're thinking. Why create a UriMatcher when you can use regular
// expressions instead? Because you're not crazy, that's why.
// All paths added to the UriMatcher have a corresponding code to return when a match is
// found. The code passed into the constructor represents the code to return for the root
// URI. It's common to use NO_MATCH as the code for this case.
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = WeatherContract.CONTENT_AUTHORITY;
// For each type of URI you want to add, create a corresponding code.
matcher.addURI(authority, WeatherContract.PATH_WEATHER, WEATHER);
matcher.addURI(authority, WeatherContract.PATH_WEATHER + "/*", WEATHER_WITH_LOCATION);
matcher.addURI(authority, WeatherContract.PATH_WEATHER + "/*/#", WEATHER_WITH_LOCATION_AND_DATE);
matcher.addURI(authority, WeatherContract.PATH_LOCATION, LOCATION);
return matcher;
}
/*
Students: We've coded this for you. We just create a new WeatherDbHelper for later use
here.
*/
@Override
public boolean onCreate() {
mOpenHelper = new WeatherDbHelper(getContext());
return true;
}
/*
Students: Here's where you'll code the getType function that uses the UriMatcher. You can
test this by uncommenting testGetType in TestProvider.
*/
@Override
public String getType(Uri uri) {
// Use the Uri Matcher to determine what kind of URI this is.
final int match = sUriMatcher.match(uri);
switch (match) {
// Student: Uncomment and fill out these two cases
case WEATHER_WITH_LOCATION_AND_DATE:
return WeatherContract.WeatherEntry.CONTENT_ITEM_TYPE;
case WEATHER_WITH_LOCATION:
return WeatherContract.WeatherEntry.CONTENT_TYPE;
case WEATHER:
return WeatherContract.WeatherEntry.CONTENT_TYPE;
case LOCATION:
return WeatherContract.LocationEntry.CONTENT_TYPE;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// Here's the switch statement that, given a URI, will determine what kind of request it is,
// and query the database accordingly.
Cursor retCursor;
switch (sUriMatcher.match(uri)) {
// "weather/*/*"
case WEATHER_WITH_LOCATION_AND_DATE:
retCursor = getWeatherByLocationSettingAndDate(uri, projection, sortOrder);
break;
// "weather/*"
case WEATHER_WITH_LOCATION:
retCursor = getWeatherByLocationSetting(uri, projection, sortOrder);
break;
// "weather"
case WEATHER:
retCursor = mOpenHelper.getReadableDatabase().query(
WeatherContract.WeatherEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
// "location"
case LOCATION:
retCursor = mOpenHelper.getReadableDatabase().query(
WeatherContract.LocationEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
retCursor.setNotificationUri(getContext().getContentResolver(), uri);
return retCursor;
}
/*
Student: Add the ability to insert Locations to the implementation of this function.
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
Uri returnUri;
switch (match) {
case WEATHER: {
normalizeDate(values);
long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, values);
if (_id > 0)
returnUri = WeatherContract.WeatherEntry.buildWeatherUri(_id);
else
throw new android.database.SQLException("Failed to insert row into " + uri);
break;
}
case LOCATION: {
long _id = db.insert(WeatherContract.LocationEntry.TABLE_NAME, null, values);
if (_id > 0)
returnUri = WeatherContract.LocationEntry.buildLocationUri(_id);
else
throw new android.database.SQLException("Failed to insert row into " + uri);
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
db.close();
return returnUri;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int rowsDeleted;
// this makes delete all rows return the number of rows deleted
if (null == selection) selection = "1";
switch (match) {
case WEATHER:
rowsDeleted = db.delete(
WeatherContract.WeatherEntry.TABLE_NAME, selection, selectionArgs);
break;
case LOCATION:
rowsDeleted = db.delete(
WeatherContract.LocationEntry.TABLE_NAME, selection, selectionArgs);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
// Because a null deletes all rows
if (rowsDeleted != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
db.close();
return rowsDeleted;
}
private void normalizeDate(ContentValues values) {
// normalize the date value
if (values.containsKey(WeatherContract.WeatherEntry.COLUMN_DATE)) {
long dateValue = values.getAsLong(WeatherContract.WeatherEntry.COLUMN_DATE);
values.put(WeatherContract.WeatherEntry.COLUMN_DATE, WeatherContract.normalizeDate(dateValue));
}
}
@Override
public int update(
Uri uri, ContentValues values, String selection, String[] selectionArgs) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int rowsUpdated;
switch (match) {
case WEATHER:
normalizeDate(values);
rowsUpdated = db.update(WeatherContract.WeatherEntry.TABLE_NAME, values, selection,
selectionArgs);
break;
case LOCATION:
rowsUpdated = db.update(WeatherContract.LocationEntry.TABLE_NAME, values, selection,
selectionArgs);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
if (rowsUpdated != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
db.close();
return rowsUpdated;
}
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
switch (match) {
case WEATHER:
db.beginTransaction();
int returnCount = 0;
try {
for (ContentValues value : values) {
normalizeDate(value);
long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value);
if (_id != -1) {
returnCount++;
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
getContext().getContentResolver().notifyChange(uri, null);
return returnCount;
default:
return super.bulkInsert(uri, values);
}
}
// You do not need to call this method. This is a method specifically to assist the testing
// framework in running smoothly. You can read more at:
// http://developer.android.com/reference/android/content/ContentProvider.html#shutdown()
@Override
@TargetApi(11)
public void shutdown() {
mOpenHelper.close();
super.shutdown();
}
}
|
jhpx/Sunshine-Version-2
|
app/src/main/java/com/example/android/sunshine/app/data/WeatherProvider.java
|
Java
|
apache-2.0
| 14,322 |
/*
* Autopsy Forensic Browser
*
* Copyright 2011-2017 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.datamodel;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.stream.Collectors;
import javax.swing.Action;
import org.apache.commons.lang3.StringUtils;
import org.openide.nodes.Children;
import org.openide.nodes.Sheet;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.util.lookup.Lookups;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.MessageNotifyUtil;
import org.sleuthkit.autopsy.casemodule.events.BlackBoardArtifactTagAddedEvent;
import org.sleuthkit.autopsy.casemodule.events.BlackBoardArtifactTagDeletedEvent;
import org.sleuthkit.autopsy.casemodule.events.ContentTagAddedEvent;
import org.sleuthkit.autopsy.casemodule.events.ContentTagDeletedEvent;
import static org.sleuthkit.autopsy.datamodel.DisplayableItemNode.findLinked;
import org.sleuthkit.autopsy.timeline.actions.ViewArtifactInTimelineAction;
import org.sleuthkit.autopsy.timeline.actions.ViewFileInTimelineAction;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE;
import org.sleuthkit.datamodel.BlackboardAttribute;
import org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.Tag;
import org.sleuthkit.datamodel.TskCoreException;
/**
* Node wrapping a blackboard artifact object. This is generated from several
* places in the tree.
*/
public class BlackboardArtifactNode extends DisplayableItemNode {
private final BlackboardArtifact artifact;
private final Content associated;
private List<NodeProperty<? extends Object>> customProperties;
private static final Logger LOGGER = Logger.getLogger(BlackboardArtifactNode.class.getName());
/*
* Artifact types which should have the full unique path of the associated
* content as a property.
*/
private static final Integer[] SHOW_UNIQUE_PATH = new Integer[]{
BlackboardArtifact.ARTIFACT_TYPE.TSK_HASHSET_HIT.getTypeID(),
BlackboardArtifact.ARTIFACT_TYPE.TSK_KEYWORD_HIT.getTypeID(),
BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_FILE_HIT.getTypeID(),
BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_ARTIFACT_HIT.getTypeID(),};
// TODO (RC): This is an unattractive alternative to subclassing BlackboardArtifactNode,
// cut from the same cloth as the equally unattractive SHOW_UNIQUE_PATH array
// above. It should be removed when and if the subclassing is implemented.
private static final Integer[] SHOW_FILE_METADATA = new Integer[]{
BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_FILE_HIT.getTypeID(),};
private final PropertyChangeListener pcl = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
String eventType = evt.getPropertyName();
if (eventType.equals(Case.Events.BLACKBOARD_ARTIFACT_TAG_ADDED.toString())) {
BlackBoardArtifactTagAddedEvent event = (BlackBoardArtifactTagAddedEvent) evt;
if (event.getAddedTag().getArtifact().equals(artifact)) {
updateSheet();
}
} else if (eventType.equals(Case.Events.BLACKBOARD_ARTIFACT_TAG_DELETED.toString())) {
BlackBoardArtifactTagDeletedEvent event = (BlackBoardArtifactTagDeletedEvent) evt;
if (event.getDeletedTagInfo().getArtifactID() == artifact.getArtifactID()) {
updateSheet();
}
} else if (eventType.equals(Case.Events.CONTENT_TAG_ADDED.toString())) {
ContentTagAddedEvent event = (ContentTagAddedEvent) evt;
if (event.getAddedTag().getContent().equals(associated)) {
updateSheet();
}
} else if (eventType.equals(Case.Events.CONTENT_TAG_DELETED.toString())) {
ContentTagDeletedEvent event = (ContentTagDeletedEvent) evt;
if (event.getDeletedTagInfo().getContentID() == associated.getId()) {
updateSheet();
}
} else if (eventType.equals(Case.Events.CURRENT_CASE.toString())) {
if (evt.getNewValue() == null) {
// case was closed. Remove listeners so that we don't get called with a stale case handle
removeListeners();
}
}
}
};
/**
* Construct blackboard artifact node from an artifact and using provided
* icon
*
* @param artifact artifact to encapsulate
* @param iconPath icon to use for the artifact
*/
public BlackboardArtifactNode(BlackboardArtifact artifact, String iconPath) {
super(Children.LEAF, createLookup(artifact));
this.artifact = artifact;
//this.associated = getAssociatedContent(artifact);
this.associated = this.getLookup().lookup(Content.class);
this.setName(Long.toString(artifact.getArtifactID()));
this.setDisplayName();
this.setIconBaseWithExtension(iconPath);
Case.addPropertyChangeListener(pcl);
}
/**
* Construct blackboard artifact node from an artifact and using default
* icon for artifact type
*
* @param artifact artifact to encapsulate
*/
public BlackboardArtifactNode(BlackboardArtifact artifact) {
super(Children.LEAF, createLookup(artifact));
this.artifact = artifact;
//this.associated = getAssociatedContent(artifact);
this.associated = this.getLookup().lookup(Content.class);
this.setName(Long.toString(artifact.getArtifactID()));
this.setDisplayName();
this.setIconBaseWithExtension(ExtractedContent.getIconFilePath(artifact.getArtifactTypeID())); //NON-NLS
Case.addPropertyChangeListener(pcl);
}
private void removeListeners() {
Case.removePropertyChangeListener(pcl);
}
@Override
@NbBundle.Messages({
"BlackboardArtifactNode.getAction.errorTitle=Error getting actions",
"BlackboardArtifactNode.getAction.resultErrorMessage=There was a problem getting actions for the selected result."
+ " The 'View Result in Timeline' action will not be available.",
"BlackboardArtifactNode.getAction.linkedFileMessage=There was a problem getting actions for the selected result. "
+ " The 'View File in Timeline' action will not be available."})
public Action[] getActions(boolean context) {
List<Action> actionsList = new ArrayList<>();
actionsList.addAll(Arrays.asList(super.getActions(context)));
//if this artifact has a time stamp add the action to view it in the timeline
try {
if (ViewArtifactInTimelineAction.hasSupportedTimeStamp(artifact)) {
actionsList.add(new ViewArtifactInTimelineAction(artifact));
}
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, MessageFormat.format("Error getting arttribute(s) from blackboard artifact{0}.", artifact.getArtifactID()), ex); //NON-NLS
MessageNotifyUtil.Notify.error(Bundle.BlackboardArtifactNode_getAction_errorTitle(), Bundle.BlackboardArtifactNode_getAction_resultErrorMessage());
}
// if the artifact links to another file, add an action to go to that file
try {
AbstractFile c = findLinked(artifact);
if (c != null) {
actionsList.add(ViewFileInTimelineAction.createViewFileAction(c));
}
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, MessageFormat.format("Error getting linked file from blackboard artifact{0}.", artifact.getArtifactID()), ex); //NON-NLS
MessageNotifyUtil.Notify.error(Bundle.BlackboardArtifactNode_getAction_errorTitle(), Bundle.BlackboardArtifactNode_getAction_linkedFileMessage());
}
//if this artifact has associated content, add the action to view the content in the timeline
AbstractFile file = getLookup().lookup(AbstractFile.class);
if (null != file) {
actionsList.add(ViewFileInTimelineAction.createViewSourceFileAction(file));
}
return actionsList.toArray(new Action[actionsList.size()]);
}
@NbBundle.Messages({"# {0} - artifactDisplayName", "BlackboardArtifactNode.displayName.artifact={0} Artifact"})
/**
* Set the filter node display name. The value will either be the file name
* or something along the lines of e.g. "Messages Artifact" for keyword hits
* on artifacts.
*/
private void setDisplayName() {
String displayName = ""; //NON-NLS
if (associated != null) {
displayName = associated.getName();
}
// If this is a node for a keyword hit on an artifact, we set the
// display name to be the artifact type name followed by " Artifact"
// e.g. "Messages Artifact".
if (artifact != null
&& (artifact.getArtifactTypeID() == ARTIFACT_TYPE.TSK_KEYWORD_HIT.getTypeID()
|| artifact.getArtifactTypeID() == ARTIFACT_TYPE.TSK_INTERESTING_ARTIFACT_HIT.getTypeID())) {
try {
for (BlackboardAttribute attribute : artifact.getAttributes()) {
if (attribute.getAttributeType().getTypeID() == ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT.getTypeID()) {
BlackboardArtifact associatedArtifact = Case.getCurrentCase().getSleuthkitCase().getBlackboardArtifact(attribute.getValueLong());
if (associatedArtifact != null) {
if (artifact.getArtifactTypeID() == ARTIFACT_TYPE.TSK_INTERESTING_ARTIFACT_HIT.getTypeID()) {
artifact.getDisplayName();
} else {
displayName = NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.displayName.artifact", associatedArtifact.getDisplayName());
}
}
}
}
} catch (TskCoreException ex) {
// Do nothing since the display name will be set to the file name.
}
}
this.setDisplayName(displayName);
}
@NbBundle.Messages({
"BlackboardArtifactNode.createSheet.artifactType.displayName=Artifact Type",
"BlackboardArtifactNode.createSheet.artifactType.name=Artifact Type",
"BlackboardArtifactNode.createSheet.artifactDetails.displayName=Artifact Details",
"BlackboardArtifactNode.createSheet.artifactDetails.name=Artifact Details",
"BlackboardArtifactNode.artifact.displayName=Artifact"})
@Override
protected Sheet createSheet() {
Sheet s = super.createSheet();
Sheet.Set ss = s.get(Sheet.PROPERTIES);
if (ss == null) {
ss = Sheet.createPropertiesSet();
s.put(ss);
}
final String NO_DESCR = NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.noDesc.text");
Map<String, Object> map = new LinkedHashMap<>();
fillPropertyMap(map, artifact);
ss.put(new NodeProperty<>(NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.createSheet.srcFile.name"),
NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.createSheet.srcFile.displayName"),
NO_DESCR,
this.getDisplayName()));
if (artifact.getArtifactTypeID() == ARTIFACT_TYPE.TSK_INTERESTING_ARTIFACT_HIT.getTypeID()) {
try {
BlackboardAttribute attribute = artifact.getAttribute(new BlackboardAttribute.Type(ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT));
if (attribute != null) {
BlackboardArtifact associatedArtifact = Case.getCurrentCase().getSleuthkitCase().getBlackboardArtifact(attribute.getValueLong());
ss.put(new NodeProperty<>(NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.createSheet.artifactType.name"),
NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.createSheet.artifactType.displayName"),
NO_DESCR,
associatedArtifact.getDisplayName() + " " + NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.artifact.displayName")));
ss.put(new NodeProperty<>(NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.createSheet.artifactDetails.name"),
NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.createSheet.artifactDetails.displayName"),
NO_DESCR,
associatedArtifact.getShortDescription()));
}
} catch (TskCoreException ex) {
// Do nothing since the display name will be set to the file name.
}
}
for (Map.Entry<String, Object> entry : map.entrySet()) {
ss.put(new NodeProperty<>(entry.getKey(),
entry.getKey(),
NO_DESCR,
entry.getValue()));
}
//append custom node properties
if (customProperties != null) {
for (NodeProperty<? extends Object> np : customProperties) {
ss.put(np);
}
}
final int artifactTypeId = artifact.getArtifactTypeID();
// If mismatch, add props for extension and file type
if (artifactTypeId == BlackboardArtifact.ARTIFACT_TYPE.TSK_EXT_MISMATCH_DETECTED.getTypeID()) {
String ext = ""; //NON-NLS
String actualMimeType = ""; //NON-NLS
if (associated instanceof AbstractFile) {
AbstractFile af = (AbstractFile) associated;
ext = af.getNameExtension();
actualMimeType = af.getMIMEType();
if (actualMimeType == null) {
actualMimeType = ""; //NON-NLS
}
}
ss.put(new NodeProperty<>(NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.createSheet.ext.name"),
NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.createSheet.ext.displayName"),
NO_DESCR,
ext));
ss.put(new NodeProperty<>(
NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.createSheet.mimeType.name"),
NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.createSheet.mimeType.displayName"),
NO_DESCR,
actualMimeType));
}
if (Arrays.asList(SHOW_UNIQUE_PATH).contains(artifactTypeId)) {
String sourcePath = ""; //NON-NLS
try {
sourcePath = associated.getUniquePath();
} catch (TskCoreException ex) {
LOGGER.log(Level.WARNING, "Failed to get unique path from: {0}", associated.getName()); //NON-NLS
}
if (sourcePath.isEmpty() == false) {
ss.put(new NodeProperty<>(
NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.createSheet.filePath.name"),
NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.createSheet.filePath.displayName"),
NO_DESCR,
sourcePath));
}
if (Arrays.asList(SHOW_FILE_METADATA).contains(artifactTypeId)) {
AbstractFile file = associated instanceof AbstractFile ? (AbstractFile) associated : null;
ss.put(new NodeProperty<>(NbBundle.getMessage(BlackboardArtifactNode.class, "ContentTagNode.createSheet.fileModifiedTime.name"),
NbBundle.getMessage(BlackboardArtifactNode.class, "ContentTagNode.createSheet.fileModifiedTime.displayName"),
"",
file != null ? ContentUtils.getStringTime(file.getMtime(), file) : ""));
ss.put(new NodeProperty<>(NbBundle.getMessage(BlackboardArtifactNode.class, "ContentTagNode.createSheet.fileChangedTime.name"),
NbBundle.getMessage(BlackboardArtifactNode.class, "ContentTagNode.createSheet.fileChangedTime.displayName"),
"",
file != null ? ContentUtils.getStringTime(file.getCtime(), file) : ""));
ss.put(new NodeProperty<>(NbBundle.getMessage(BlackboardArtifactNode.class, "ContentTagNode.createSheet.fileAccessedTime.name"),
NbBundle.getMessage(BlackboardArtifactNode.class, "ContentTagNode.createSheet.fileAccessedTime.displayName"),
"",
file != null ? ContentUtils.getStringTime(file.getAtime(), file) : ""));
ss.put(new NodeProperty<>(NbBundle.getMessage(BlackboardArtifactNode.class, "ContentTagNode.createSheet.fileCreatedTime.name"),
NbBundle.getMessage(BlackboardArtifactNode.class, "ContentTagNode.createSheet.fileCreatedTime.displayName"),
"",
file != null ? ContentUtils.getStringTime(file.getCrtime(), file) : ""));
ss.put(new NodeProperty<>(NbBundle.getMessage(BlackboardArtifactNode.class, "ContentTagNode.createSheet.fileSize.name"),
NbBundle.getMessage(BlackboardArtifactNode.class, "ContentTagNode.createSheet.fileSize.displayName"),
"",
associated.getSize()));
}
} else {
String dataSourceStr = "";
try {
Content dataSource = associated.getDataSource();
if (dataSource != null) {
dataSourceStr = dataSource.getName();
} else {
dataSourceStr = getRootParentName();
}
} catch (TskCoreException ex) {
LOGGER.log(Level.WARNING, "Failed to get image name from {0}", associated.getName()); //NON-NLS
}
if (dataSourceStr.isEmpty() == false) {
ss.put(new NodeProperty<>(
NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.createSheet.dataSrc.name"),
NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.createSheet.dataSrc.displayName"),
NO_DESCR,
dataSourceStr));
}
}
// add properties for tags
List<Tag> tags = new ArrayList<>();
try {
tags.addAll(Case.getCurrentCase().getServices().getTagsManager().getBlackboardArtifactTagsByArtifact(artifact));
tags.addAll(Case.getCurrentCase().getServices().getTagsManager().getContentTagsByContent(associated));
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Failed to get tags for artifact " + artifact.getDisplayName(), ex);
}
ss.put(new NodeProperty<>("Tags", NbBundle.getMessage(AbstractAbstractFileNode.class, "BlackboardArtifactNode.createSheet.tags.displayName"),
NO_DESCR, tags.stream().map(t -> t.getName().getDisplayName()).collect(Collectors.joining(", "))));
return s;
}
private void updateSheet() {
this.setSheet(createSheet());
}
private String getRootParentName() {
String parentName = associated.getName();
Content parent = associated;
try {
while ((parent = parent.getParent()) != null) {
parentName = parent.getName();
}
} catch (TskCoreException ex) {
LOGGER.log(Level.WARNING, "Failed to get parent name from {0}", associated.getName()); //NON-NLS
return "";
}
return parentName;
}
/**
* Add an additional custom node property to that node before it is
* displayed
*
* @param np NodeProperty to add
*/
public void addNodeProperty(NodeProperty<?> np) {
if (null == customProperties) {
//lazy create the list
customProperties = new ArrayList<>();
}
customProperties.add(np);
}
/**
* Fill map with Artifact properties
*
* @param map map with preserved ordering, where property names/values
* are put
* @param artifact to extract properties from
*/
@SuppressWarnings("deprecation")
private void fillPropertyMap(Map<String, Object> map, BlackboardArtifact artifact) {
try {
for (BlackboardAttribute attribute : artifact.getAttributes()) {
final int attributeTypeID = attribute.getAttributeType().getTypeID();
//skip some internal attributes that user shouldn't see
if (attributeTypeID == ATTRIBUTE_TYPE.TSK_PATH_ID.getTypeID()
|| attributeTypeID == ATTRIBUTE_TYPE.TSK_TAGGED_ARTIFACT.getTypeID()
|| attributeTypeID == ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT.getTypeID()
|| attributeTypeID == ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID()
|| attributeTypeID == ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_TYPE.getTypeID()) {
}
else if (artifact.getArtifactTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_EMAIL_MSG.getTypeID()) {
addEmailMsgProperty (map, attribute);
}
else if (attribute.getAttributeType().getValueType() == BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.DATETIME) {
map.put(attribute.getAttributeType().getDisplayName(), ContentUtils.getStringTime(attribute.getValueLong(), associated));
} else if (artifact.getArtifactTypeID() == ARTIFACT_TYPE.TSK_TOOL_OUTPUT.getTypeID()
&& attributeTypeID == ATTRIBUTE_TYPE.TSK_TEXT.getTypeID()) {
/*
* This was added because the RegRipper output would often
* cause the UI to get a black line accross it and hang if
* you hovered over large output or selected it. This
* reduces the amount of data in the table. Could consider
* doing this for all fields in the UI.
*/
String value = attribute.getDisplayString();
if (value.length() > 512) {
value = value.substring(0, 512);
}
map.put(attribute.getAttributeType().getDisplayName(), value);
}
else {
map.put(attribute.getAttributeType().getDisplayName(), attribute.getDisplayString());
}
}
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Getting attributes failed", ex); //NON-NLS
}
}
/**
* Fill map with EmailMsg properties, not all attributes are filled
*
* @param map map with preserved ordering, where property names/values
* are put
* @param attribute attribute to check/fill as property
*/
private void addEmailMsgProperty(Map<String, Object> map, BlackboardAttribute attribute ) {
final int attributeTypeID = attribute.getAttributeType().getTypeID();
// Skip certain Email msg attributes
if (attributeTypeID == ATTRIBUTE_TYPE.TSK_DATETIME_SENT.getTypeID()
|| attributeTypeID == ATTRIBUTE_TYPE.TSK_EMAIL_CONTENT_HTML.getTypeID()
|| attributeTypeID == ATTRIBUTE_TYPE.TSK_EMAIL_CONTENT_RTF.getTypeID()
|| attributeTypeID == ATTRIBUTE_TYPE.TSK_EMAIL_BCC.getTypeID()
|| attributeTypeID == ATTRIBUTE_TYPE.TSK_EMAIL_CC.getTypeID()
|| attributeTypeID == ATTRIBUTE_TYPE.TSK_HEADERS.getTypeID()
) {
// do nothing
}
else if (attributeTypeID == ATTRIBUTE_TYPE.TSK_EMAIL_CONTENT_PLAIN.getTypeID()) {
String value = attribute.getDisplayString();
if (value.length() > 160) {
value = value.substring(0, 160) + "...";
}
map.put(attribute.getAttributeType().getDisplayName(), value);
}
else if (attribute.getAttributeType().getValueType() == BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.DATETIME) {
map.put(attribute.getAttributeType().getDisplayName(), ContentUtils.getStringTime(attribute.getValueLong(), associated));
}
else {
map.put(attribute.getAttributeType().getDisplayName(), attribute.getDisplayString());
}
}
@Override
public <T> T accept(DisplayableItemNodeVisitor<T> v) {
return v.visit(this);
}
/**
* Create a Lookup based on what is in the passed in artifact.
*
* @param artifact
*
* @return
*/
private static Lookup createLookup(BlackboardArtifact artifact) {
List<Object> forLookup = new ArrayList<>();
forLookup.add(artifact);
// Add the content the artifact is associated with
Content content = getAssociatedContent(artifact);
if (content != null) {
forLookup.add(content);
}
return Lookups.fixed(forLookup.toArray(new Object[forLookup.size()]));
}
private static Content getAssociatedContent(BlackboardArtifact artifact) {
try {
return artifact.getSleuthkitCase().getContentById(artifact.getObjectID());
} catch (TskCoreException ex) {
LOGGER.log(Level.WARNING, "Getting file failed", ex); //NON-NLS
}
throw new IllegalArgumentException(
NbBundle.getMessage(BlackboardArtifactNode.class, "BlackboardArtifactNode.getAssocCont.exception.msg"));
}
@Override
public boolean isLeafTypeNode() {
return true;
}
@Override
public String getItemType() {
return getClass().getName();
}
}
|
narfindustries/autopsy
|
Core/src/org/sleuthkit/autopsy/datamodel/BlackboardArtifactNode.java
|
Java
|
apache-2.0
| 27,314 |
package com.bazaarvoice.emodb.databus.repl;
import com.bazaarvoice.emodb.databus.core.UpdateRefSerializer;
import com.bazaarvoice.emodb.event.api.EventData;
import com.bazaarvoice.emodb.event.api.EventStore;
import com.bazaarvoice.emodb.sor.core.UpdateRef;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import java.util.Collection;
import java.util.List;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
public class DefaultReplicationSource implements ReplicationSource {
private final EventStore _eventStore;
@Inject
public DefaultReplicationSource(EventStore eventStore) {
_eventStore = eventStore;
}
@Override
public List<ReplicationEvent> get(String channel, int limit) {
requireNonNull(channel, "channel");
checkArgument(limit > 0, "Limit must be >0");
List<EventData> rawEvents = _eventStore.peek(channel, limit);
return Lists.transform(rawEvents, new Function<EventData, ReplicationEvent>() {
@Override
public ReplicationEvent apply(EventData rawEvent) {
UpdateRef ref = UpdateRefSerializer.fromByteBuffer(rawEvent.getData());
return new ReplicationEvent(rawEvent.getId(), ref);
}
});
}
@Override
public void delete(String channel, Collection<String> eventIds) {
requireNonNull(channel, "channel");
requireNonNull(eventIds, "eventIds");
_eventStore.delete(channel, eventIds, false);
}
}
|
bazaarvoice/emodb
|
databus/src/main/java/com/bazaarvoice/emodb/databus/repl/DefaultReplicationSource.java
|
Java
|
apache-2.0
| 1,617 |
<?php
namespace CHStudio\LaravelTransclude\Exceptions;
class MissingTranscludeDirective extends \RuntimeException
{
}
|
CHStudio/laravel-transclude
|
src/Exceptions/MissingTranscludeDirective.php
|
PHP
|
apache-2.0
| 121 |
package com.boot.service;
import com.boot.model.User;
import org.springframework.stereotype.Component;
/**
* Created by Admin on 2017/6/29.
* 熔断机制
*/
@Component
public class HelloServiceFallback implements HelloService {
@Override
public String hello() {
return "error";
}
@Override
public String hello(String name) {
return "error";
}
@Override
public User hello(String name, Integer age) {
return new User("未知", 0);
}
@Override
public String hello(User user) {
return "error";
}
}
|
TianYunZi/15springcloud
|
6.1.1.spring-cloud-feign/src/main/java/com/boot/service/HelloServiceFallback.java
|
Java
|
apache-2.0
| 583 |
package nl.jqno.equalsverifier.internal.reflection;
import static nl.jqno.equalsverifier.internal.util.Rethrow.rethrow;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Set;
import java.util.function.Predicate;
import nl.jqno.equalsverifier.internal.prefabvalues.PrefabValues;
import nl.jqno.equalsverifier.internal.prefabvalues.TypeTag;
import nl.jqno.equalsverifier.internal.reflection.annotations.AnnotationCache;
import nl.jqno.equalsverifier.internal.reflection.annotations.NonnullAnnotationVerifier;
/**
* Instantiates and populates objects of a given class. {@link ClassAccessor} can create two
* different instances of T, which are guaranteed not to be equal to each other, and which contain
* no null values.
*
* @param <T> A class.
*/
public class ClassAccessor<T> {
private final Class<T> type;
private final PrefabValues prefabValues;
/** Private constructor. Call {@link #of(Class, PrefabValues)} instead. */
ClassAccessor(Class<T> type, PrefabValues prefabValues) {
this.type = type;
this.prefabValues = prefabValues;
}
/**
* Factory method.
*
* @param <T> The class on which {@link ClassAccessor} operates.
* @param type The class on which {@link ClassAccessor} operates. Should be the same as T.
* @param prefabValues Prefabricated values with which to fill instantiated objects.
* @return A {@link ClassAccessor} for T.
*/
public static <T> ClassAccessor<T> of(Class<T> type, PrefabValues prefabValues) {
return new ClassAccessor<>(type, prefabValues);
}
/** @return The class on which {@link ClassAccessor} operates. */
public Class<T> getType() {
return type;
}
/**
* Determines whether T is a Java Record.
*
* @return true if T is a Java Record.
*/
public boolean isRecord() {
return RecordsHelper.isRecord(type);
}
/**
* Determines whether T is a sealed class.
*
* @return true if T is a sealed class
*/
public boolean isSealed() {
return SealedClassesHelper.isSealed(type);
}
/**
* Determines whether T declares a field. This does not include inherited fields.
*
* @param field The field that we want to detect.
* @return True if T declares the field.
*/
public boolean declaresField(Field field) {
try {
type.getDeclaredField(field.getName());
return true;
} catch (NoSuchFieldException e) {
return false;
}
}
/**
* Determines whether T has an {@code equals} method.
*
* @return True if T has an {@code equals} method.
*/
public boolean declaresEquals() {
return declaresMethod("equals", Object.class);
}
/**
* Determines whether T has an {@code hashCode} method.
*
* @return True if T has an {@code hashCode} method.
*/
public boolean declaresHashCode() {
return declaresMethod("hashCode");
}
private boolean declaresMethod(String name, Class<?>... parameterTypes) {
try {
type.getDeclaredMethod(name, parameterTypes);
return true;
} catch (NoSuchMethodException e) {
return false;
}
}
/**
* Determines whether T's {@code equals} method is abstract.
*
* @return True if T's {@code equals} method is abstract.
*/
public boolean isEqualsAbstract() {
return isMethodAbstract("equals", Object.class);
}
/**
* Determines whether T's {@code hashCode} method is abstract.
*
* @return True if T's {@code hashCode} method is abstract.
*/
public boolean isHashCodeAbstract() {
return isMethodAbstract("hashCode");
}
private boolean isMethodAbstract(String name, Class<?>... parameterTypes) {
return rethrow(() ->
Modifier.isAbstract(type.getMethod(name, parameterTypes).getModifiers())
);
}
/**
* Determines whether T's {@code equals} method is inherited from {@link Object}.
*
* @return true if T's {@code equals} method is inherited from {@link Object}; false if it is
* overridden in T or in any of its superclasses (except {@link Object}).
*/
public boolean isEqualsInheritedFromObject() {
ClassAccessor<? super T> i = this;
while (i.getType() != Object.class) {
if (i.declaresEquals() && !i.isEqualsAbstract()) {
return false;
}
i = i.getSuperAccessor();
}
return true;
}
/**
* Returns an accessor for T's superclass.
*
* @return An accessor for T's superclass.
*/
public ClassAccessor<? super T> getSuperAccessor() {
return ClassAccessor.of(type.getSuperclass(), prefabValues);
}
/**
* Returns an instance of T that is not equal to the instance of T returned by {@link
* #getBlueObject(TypeTag)}.
*
* @param enclosingType Describes the type that contains this object as a field, to determine
* any generic parameters it may contain.
* @return An instance of T.
*/
public T getRedObject(TypeTag enclosingType) {
return getRedAccessor(enclosingType).get();
}
/**
* Returns an {@link ObjectAccessor} for {@link #getRedObject(TypeTag)}.
*
* @param enclosingType Describes the type that contains this object as a field, to determine
* any generic parameters it may contain.
* @return An {@link ObjectAccessor} for {@link #getRedObject(TypeTag)}.
*/
public ObjectAccessor<T> getRedAccessor(TypeTag enclosingType) {
return buildObjectAccessor().scramble(prefabValues, enclosingType);
}
/**
* Returns an instance of T that is not equal to the instance of T returned by {@link
* #getRedObject(TypeTag)}.
*
* @param enclosingType Describes the type that contains this object as a field, to determine
* any generic parameters it may contain.
* @return An instance of T.
*/
public T getBlueObject(TypeTag enclosingType) {
return getBlueAccessor(enclosingType).get();
}
/**
* Returns an {@link ObjectAccessor} for {@link #getBlueObject(TypeTag)}.
*
* @param enclosingType Describes the type that contains this object as a field, to determine
* any generic parameters it may contain.
* @return An {@link ObjectAccessor} for {@link #getBlueObject(TypeTag)}.
*/
public ObjectAccessor<T> getBlueAccessor(TypeTag enclosingType) {
return buildObjectAccessor()
.scramble(prefabValues, enclosingType)
.scramble(prefabValues, enclosingType);
}
/**
* Returns an {@link ObjectAccessor} for an instance of T where all the fields are initialized
* to their default values. I.e., 0 for ints, and null for objects (except when the field is
* marked with a NonNull annotation).
*
* @param enclosingType Describes the type that contains this object as a field, to determine
* any generic parameters it may contain.
* @param nonnullFields Fields which are not allowed to be set to null.
* @param annotationCache To check for any NonNull annotations.
* @return An {@link ObjectAccessor} for an instance of T where all the fields are initialized
* to their default values.
*/
public ObjectAccessor<T> getDefaultValuesAccessor(
TypeTag enclosingType,
Set<String> nonnullFields,
AnnotationCache annotationCache
) {
Predicate<Field> canBeDefault = f ->
!NonnullAnnotationVerifier.fieldIsNonnull(f, annotationCache) &&
!nonnullFields.contains(f.getName());
return buildObjectAccessor().clear(canBeDefault, prefabValues, enclosingType);
}
private ObjectAccessor<T> buildObjectAccessor() {
T object = Instantiator.of(type).instantiate();
return ObjectAccessor.of(object);
}
}
|
jqno/equalsverifier
|
equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/ClassAccessor.java
|
Java
|
apache-2.0
| 8,056 |
package org.nd4j.linalg.api.ndarray;
import org.nd4j.linalg.api.buffer.DataBuffer;
import org.nd4j.linalg.api.shape.Shape;
/**
* @author raver119@gmail.com
*/
public abstract class BaseShapeInfoProvider implements ShapeInfoProvider {
@Override
public DataBuffer createShapeInformation(int[] shape, int[] stride, int offset, int elementWiseStride, char order) {
return Shape.createShapeInformation(shape, stride, offset, elementWiseStride, order);
}
}
|
drlebedev/nd4j
|
nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ndarray/BaseShapeInfoProvider.java
|
Java
|
apache-2.0
| 475 |
var clientSettings = require('../lib/plugins/client-settings');
var express = require('express');
var supertest = require('supertest');
var assert = require('assert');
describe('logout()', function() {
var server;
var clientConfigOptions;
beforeEach(function() {
server = express();
server.use(function(req, res, next) {
req.ext = {clientConfig: {}};
next();
});
server.use(function(req, res, next) {
clientSettings(clientConfigOptions)(req, res, next);
});
server.get('/', function(req, res, next) {
res.json(req.ext.clientConfig);
});
});
it('should redirect to index page', function(done) {
clientConfigOptions = {
option1: 'foo',
option2: { name: 'joe'}
};
supertest(server)
.get('/')
.expect(200)
.expect(function(res) {
assert.deepEqual(res.body.settings, clientConfigOptions);
})
.end(done);
});
});
|
4front/apphost
|
test/plugin.client-settings.js
|
JavaScript
|
apache-2.0
| 940 |
'use strict';
var express = require('express');
var app = express();
app.use('/components/gh-issues', express.static( __dirname));
app.use('/components', express.static(__dirname + '/bower_components'));
app.get('/', function(req, res){
res.redirect('/components/gh-issues/');
});
app.get('/hello', function (req, res) {
res.status(200).send('Hello, world!');
});
var server = app.listen(process.env.PORT || '8080', function () {
console.log('App listening on port %s', server.address().port);
});
|
koopaworks/polymer-gh-issues
|
index.js
|
JavaScript
|
apache-2.0
| 510 |
/*-
* #%L
* Bobcat
* %%
* Copyright (C) 2018 Cognifide 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.
* #L%
*/
package com.cognifide.qa.bb.junit5;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
/**
* Contains common constants for the whole JUnit 5 module.
*/
public final class JUnit5Constants {
public static final Namespace NAMESPACE =
Namespace.create("com", "cognifide", "qa", "bb", "junit", "guice");
private JUnit5Constants() {
//util
}
}
|
Cognifide/bobcat
|
bb-junit5/src/main/java/com/cognifide/qa/bb/junit5/JUnit5Constants.java
|
Java
|
apache-2.0
| 1,013 |
const CLI = require('CLI');
describe('CLI', () => {
function args(...arr) {
return [ 'node', 'polymer-lint.js', ...arr ];
}
let Options, Linter;
const filenames = [
'./spec/integration/good-component.html',
'./spec/integration/bad-component.html',
];
beforeEach(() => {
Options = require('Options');
spyOn(console, 'log');
});
describe('execute', () => {
describe('with no arguments', () => {
it('displays help', () => {
spyOn(Options, 'generateHelp').and.returnValue('Help');
CLI.execute(args('--help'));
expect(Options.generateHelp).toHaveBeenCalled();
expect(console.log).toHaveBeenCalledWith('Help');
});
});
describe('with filename arguments', () => {
let mockPromise;
beforeEach(() => {
mockPromise = jasmine.createSpyObj('promise', ['then']);
Linter = require('Linter');
spyOn(Linter, 'lintFiles').and.returnValue(mockPromise);
});
it('calls Linter.lintFiles with the given filenames', () => {
CLI.execute(args(...filenames));
expect(Linter.lintFiles).toHaveBeenCalledWith(
filenames, jasmine.objectContaining({ _: filenames }));
expect(mockPromise.then).toHaveBeenCalledWith(jasmine.any(Function));
});
describe('and --rules', () => {
it('calls Linter.lintFiles with the expected `rules` option', () => {
const ruleNames = ['no-missing-import', 'no-unused-import'];
CLI.execute(args('--rules', ruleNames.join(','), ...filenames));
expect(Linter.lintFiles).toHaveBeenCalledTimes(1);
const [ actualFilenames, { rules: actualRules } ] = Linter.lintFiles.calls.argsFor(0);
expect(actualFilenames).toEqual(filenames);
expect(actualRules).toEqual(ruleNames);
expect(mockPromise.then).toHaveBeenCalledWith(jasmine.any(Function));
});
});
});
describe('with --help', () => {
it('displays help', () => {
spyOn(Options, 'generateHelp').and.returnValue('Help');
CLI.execute(args('--help'));
expect(Options.generateHelp).toHaveBeenCalled();
expect(console.log).toHaveBeenCalledWith('Help');
});
});
describe('with --version', () => {
it('prints the version number', () => {
CLI.execute(args('--version'));
const expectedVersion = `v${require('../../package.json').version}`;
expect(console.log).toHaveBeenCalledWith(expectedVersion);
});
});
describe('with --color', () => {});
describe('with --no-color', () => {});
});
});
|
Banno/polymer-lint
|
spec/lib/CLISpec.js
|
JavaScript
|
apache-2.0
| 2,623 |
package cn.elvea.platform.commons.storage.oss;
import lombok.Data;
import java.io.Serializable;
/**
* 阿里云存储配置参数
*
* @author elvea
* @since 0.0.1
*/
@Data
public class OssStorageConfig implements Serializable {
/**
* Endpoint
*/
private String endpoint = "";
/**
* Access Key Id
*/
private String accessKeyId = "";
/**
* Access Key Secret
*/
private String accessKeySecret = "";
/**
* Bucket Name
*/
private String bucketName = "";
/**
* 自定义域名
*/
private String domain = "";
}
|
elveahuang/platform
|
platform-commons/platform-commons-storage/src/main/java/cn/elvea/platform/commons/storage/oss/OssStorageConfig.java
|
Java
|
apache-2.0
| 602 |
<?php
namespace VagueSoftware\Refuel2Bundle\Presenter;
use VagueSoftware\Refuel2Bundle\Exception\Presenter\PresenterNotFoundException;
/**
* Class PresenterFactory
* @package VagueSoftware\Refuel2Bundle\Presenter
*/
class PresenterFactory
{
/**
* @var array
*/
private $presenters = [];
/**
* @param string $class
* @param PresenterInterface $presenter
* @return PresenterFactory
*/
public function registerPresenter(string $class, PresenterInterface $presenter): PresenterFactory
{
$this->presenters[$class] = $presenter;
return $this;
}
/**
* @param string $class
* @return PresenterInterface
*/
public function getPresenter(string $class): PresenterInterface
{
if (!array_key_exists($class, $this->presenters)) {
throw new PresenterNotFoundException($class);
}
return $this->presenters[$class];
}
}
|
evilfirefox/refuel2
|
src/VagueSoftware/Refuel2Bundle/Presenter/PresenterFactory.php
|
PHP
|
apache-2.0
| 949 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Shrtn.Entity;
using Shrtn.Entity.Encoders;
namespace Shrtn
{
/// <summary>
/// Utility class that takes integers such as a primary key id and turns them into short strings using base conversion.
/// </summary>
public static class Shorten
{
/// <summary>
/// Encode an integer using the default encoder
/// </summary>
/// <param name="value">Value to be encoded</param>
/// <returns>An integer encoded to a string</returns>
public static string Encode(ulong value)
{
return Encode(value, EncoderTypes.CrockfordLower);
}
/// <summary>
/// Encode an integer and specify one of the builtin encoders
/// </summary>
/// <param name="value">Value to be encoded</param>
/// <param name="encoderType">The encoder to be used</param>
/// <returns>An integer encoded to a string</returns>
public static string Encode(ulong value, EncoderTypes encoderType)
{
EncoderFactory factory = new EncoderFactory();
BaseEncoder encoder = factory.GetEncoder(encoderType);
return encoder.Encode(value);
}
/// <summary>
/// Encode an integer using a custom encoder
/// </summary>
/// <param name="value">Value to be encoded</param>
/// <param name="encoder">The custom encoder to be used</param>
/// <returns>An integer encoded to a string</returns>
public static string Encode(ulong value, BaseEncoder encoder)
{
return encoder.Encode(value);
}
/// <summary>
/// Decode a string using the default encoder
/// </summary>
/// <param name="encodedValue">The encoded string</param>
/// <returns>A converted integer</returns>
public static ulong Decode(string encodedValue)
{
return Decode(encodedValue, EncoderTypes.CrockfordLower);
}
/// <summary>
/// Decode a string and specify one of the builtin encoders
/// </summary>
/// <param name="encodedValue">The encoded string</param>
/// <param name="encoderType">The encoder used on this string</param>
/// <returns>A converted integer</returns>
public static ulong Decode(string encodedValue, EncoderTypes encoderType)
{
EncoderFactory factory = new EncoderFactory();
BaseEncoder encoder = factory.GetEncoder(encoderType);
return encoder.Decode(encodedValue);
}
/// <summary>
/// Decode a string using a custom encoder
/// </summary>
/// <param name="encodedValue">The encoded string</param>
/// <param name="encoder">The custom encoder to be used</param>
/// <returns>A converted integer</returns>
public static ulong Decode(string encodedValue, BaseEncoder encoder)
{
return encoder.Decode(encodedValue);
}
}
}
|
ryan-nauman/Shrtn
|
Shrtn/Shrtn.cs
|
C#
|
apache-2.0
| 3,095 |
package org.schema;
/**
*
* A collection of music tracks.
*
* @fullPath Thing > CreativeWork > MusicPlaylist > MusicAlbum
*
* @author Texelz (by Onhate)
*
*/
public class MusicAlbum extends MusicPlaylist {
private MusicGroup byArtist;
/**
* The artist that performed this album or recording.
*/
public MusicGroup getByArtist() {
return this.byArtist;
}
/**
* The artist that performed this album or recording.
*/
public void setByArtist(MusicGroup byArtist) {
this.byArtist = byArtist;
}
}
|
onhate/schemorger
|
src/main/java/org/schema/MusicAlbum.java
|
Java
|
apache-2.0
| 525 |
package cl.puntocontrol.struts.action;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import cl.puntocontrol.hibernate.dao.DAOTransportista;
import cl.puntocontrol.hibernate.domain.Transportista;
import cl.puntocontrol.hibernate.domain.Usuario;
import cl.puntocontrol.struts.form.TransportistasForm;
public class TransportistasBuscarAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm _form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
TransportistasForm form = (TransportistasForm)_form;
try{
List<Transportista> transportistas = new ArrayList<Transportista>();
transportistas=DAOTransportista.list("","");
form.setTransportistas(transportistas);
form.setEstado(0);
form.setNombre_transportista("");
form.setRut_transportista("");
form.setSap_transportista("");
String userName = (String)request.getSession().getAttribute("userName");
String password = (String)request.getSession().getAttribute("password");
Usuario usuario = UsuarioUtil.checkUser(userName, password);
form.setUsuario(usuario);
form.setSuccessMessage("");
return mapping.findForward("success");
}catch(Exception ex){
form.setErrorMessage("Ha Ocurrido Un Error Inesperado.");
return mapping.findForward("error");
}finally{
}
}
}
|
Claudio1986/Punto_control
|
src/cl/puntocontrol/struts/action/TransportistasBuscarAction.java
|
Java
|
apache-2.0
| 1,697 |
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.nd4j.tensorflow.conversion;
import org.nd4j.shade.protobuf.InvalidProtocolBufferException;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.indexer.*;
import org.nd4j.linalg.api.buffer.DataBuffer;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.api.concurrency.AffinityManager;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.compression.CompressedDataBuffer;
import org.nd4j.linalg.compression.CompressionDescriptor;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.common.util.ArrayUtil;
import org.nd4j.tensorflow.conversion.graphrunner.SavedModelConfig;
import org.tensorflow.framework.MetaGraphDef;
import org.tensorflow.framework.SignatureDef;
import org.tensorflow.framework.TensorInfo;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import org.bytedeco.tensorflow.*;
import static org.bytedeco.tensorflow.global.tensorflow.*;
/**
* Interop between nd4j {@link INDArray}
* and {@link TF_Tensor}
*
* @author Adam Gibson
*/
public class TensorflowConversion {
//used for passing to tensorflow: this dummy de allocator
//allows us to use nd4j buffers for memory management
//rather than having them managed by tensorflow
private static Deallocator_Pointer_long_Pointer calling;
private static TensorflowConversion INSTANCE;
/**
* Get a singleton instance
* @return
*/
public static TensorflowConversion getInstance() {
if(INSTANCE == null)
INSTANCE = new TensorflowConversion();
return INSTANCE;
}
private TensorflowConversion() {
if(calling == null)
calling = DummyDeAllocator.getInstance();
}
/**
* Convert an {@link INDArray}
* to a {@link TF_Tensor}
* with zero copy.
* Uses a direct pointer to the underlying ndarray's
* data
* @param ndArray the ndarray to use
* @return the equivalent {@link TF_Tensor}
*/
public TF_Tensor tensorFromNDArray(INDArray ndArray) {
if(ndArray == null) {
throw new IllegalArgumentException("NDArray must not be null!");
}
//we infer data type from the ndarray.databuffer()
//for now we throw an exception
if(ndArray.data() == null) {
throw new IllegalArgumentException("Unable to infer data type from null databuffer");
}
if(ndArray.isView() || ndArray.ordering() != 'c') {
ndArray = ndArray.dup('c');
}
long[] ndShape = ndArray.shape();
long[] tfShape = new long[ndShape.length];
System.arraycopy(ndShape, 0, tfShape, 0, ndShape.length);
int type;
DataBuffer data = ndArray.data();
DataType dataType = data.dataType();
switch (dataType) {
case DOUBLE: type = DT_DOUBLE; break;
case FLOAT: type = DT_FLOAT; break;
case INT: type = DT_INT32; break;
case HALF: type = DT_HALF; break;
case COMPRESSED:
CompressedDataBuffer compressedData = (CompressedDataBuffer)data;
CompressionDescriptor desc = compressedData.getCompressionDescriptor();
String algo = desc.getCompressionAlgorithm();
switch (algo) {
case "FLOAT16": type = DT_HALF; break;
case "INT8": type = DT_INT8; break;
case "UINT8": type = DT_UINT8; break;
case "INT16": type = DT_INT16; break;
case "UINT16": type = DT_UINT16; break;
default: throw new IllegalArgumentException("Unsupported compression algorithm: " + algo);
}
break;
case SHORT: type = DT_INT16; break;
case LONG: type = DT_INT64; break;
case UTF8: type = DT_STRING; break;
case BYTE: type = DT_INT8; break;
case UBYTE: type = DT_UINT8; break;
case UINT16: type = DT_UINT16; break;
case UINT32: type = DT_UINT32; break;
case UINT64: type = DT_UINT64; break;
case BFLOAT16: type = DT_BFLOAT16; break;
case BOOL: type = DT_BOOL; break;
default: throw new IllegalArgumentException("Unsupported data type: " + dataType);
}
try {
Nd4j.getAffinityManager().ensureLocation(ndArray, AffinityManager.Location.HOST);
} catch (Exception e) {
// ND4J won't let us access compressed data in GPU memory, so we'll leave TensorFlow do the conversion instead
ndArray.getDouble(0); // forces decompression and data copy to host
data = ndArray.data();
dataType = data.dataType();
switch (dataType) {
case DOUBLE: type = DT_DOUBLE; break;
case FLOAT: type = DT_FLOAT; break;
case INT: type = DT_INT32; break;
case LONG: type = DT_INT64; break;
case UTF8: type = DT_STRING; break;
default: throw new IllegalArgumentException("Unsupported data type: " + dataType);
}
}
LongPointer longPointer = new LongPointer(tfShape);
TF_Tensor tf_tensor = null;
if (type == DT_STRING) {
long size = 0;
long length = ndArray.length();
BytePointer[] strings = new BytePointer[(int)length];
for (int i = 0; i < length; i++) {
strings[i] = new BytePointer(ndArray.getString(i));
size += TF_StringEncodedSize(strings[i].capacity());
}
tf_tensor = TF_AllocateTensor(
type,
longPointer,
tfShape.length,
8 * length + size);
long offset = 0;
BytePointer tf_data = new BytePointer(TF_TensorData(tf_tensor)).capacity(TF_TensorByteSize(tf_tensor));
TF_Status status = TF_NewStatus();
for (int i = 0; i < length; i++) {
tf_data.position(8 * i).putLong(offset);
offset += TF_StringEncode(strings[i], strings[i].capacity() - 1, tf_data.position(8 * length + offset), tf_data.capacity() - tf_data.position(), status);
if (TF_GetCode(status) != TF_OK) {
throw new IllegalStateException("ERROR: Unable to convert tensor " + TF_Message(status).getString());
}
}
TF_DeleteStatus(status);
} else {
tf_tensor = TF_NewTensor(
type,
longPointer,
tfShape.length,
data.pointer(),
data.length() * data.getElementSize(),
calling,null);
}
return tf_tensor;
}
/**
* Convert a {@link INDArray}
* to a {@link TF_Tensor}
* using zero copy.
* It will use the underlying
* pointer with in nd4j.
* @param tensor the tensor to use
* @return
*/
public INDArray ndArrayFromTensor(TF_Tensor tensor) {
int rank = TF_NumDims(tensor);
int[] ndShape;
if (rank == 0) {
// scalar
ndShape = new int[] { 1 };
} else {
ndShape = new int[rank];
for (int i = 0; i < ndShape.length; i++) {
ndShape[i] = (int) TF_Dim(tensor,i);
}
}
int tfType = TF_TensorType(tensor);
DataType nd4jType = typeFor(tfType);
int length = ArrayUtil.prod(ndShape);
INDArray array;
if (nd4jType == DataType.UTF8) {
String[] strings = new String[length];
BytePointer data = new BytePointer(TF_TensorData(tensor)).capacity(TF_TensorByteSize(tensor));
BytePointer str = new BytePointer((Pointer)null);
SizeTPointer size = new SizeTPointer(1);
TF_Status status = TF_NewStatus();
for (int i = 0; i < length; i++) {
long offset = data.position(8 * i).getLong();
TF_StringDecode(data.position(8 * length + offset), data.capacity() - data.position(), str, size, status);
if (TF_GetCode(status) != TF_OK) {
throw new IllegalStateException("ERROR: Unable to convert tensor " + TF_Message(status).getString());
}
strings[i] = str.position(0).capacity(size.get()).getString();
}
TF_DeleteStatus(status);
array = Nd4j.create(strings);
} else {
Pointer pointer = TF_TensorData(tensor).capacity(length);
Indexer indexer = indexerForType(nd4jType,pointer);
DataBuffer d = Nd4j.createBuffer(indexer.pointer(),nd4jType,length,indexer);
array = Nd4j.create(d,ndShape);
}
// we don't need this in this case. Device memory will be updated right in the constructor
//Nd4j.getAffinityManager().tagLocation(array, AffinityManager.Location.HOST);
return array;
}
private Indexer indexerForType(DataType type,Pointer pointer) {
switch(type) {
case DOUBLE: return DoubleIndexer.create(new DoublePointer(pointer));
case FLOAT: return FloatIndexer.create(new FloatPointer(pointer));
case INT: return IntIndexer.create(new IntPointer(pointer));
case LONG: return LongIndexer.create(new LongPointer(pointer));
case SHORT: return ShortIndexer.create(new ShortPointer(pointer));
case BYTE: return ByteIndexer.create(new BytePointer(pointer));
case UBYTE: return UByteIndexer.create(new BytePointer(pointer));
case UINT16: return UShortIndexer.create(new ShortPointer(pointer));
case UINT32: return UIntIndexer.create(new IntPointer(pointer));
case UINT64: return ULongIndexer.create(new LongPointer(pointer));
case BFLOAT16: return Bfloat16Indexer.create(new ShortPointer(pointer));
case HALF: return HalfIndexer.create(new ShortPointer(pointer));
case BOOL: return BooleanIndexer.create(new BooleanPointer(pointer));
default: throw new IllegalArgumentException("Illegal type " + type);
}
}
private DataType typeFor(int tensorflowType) {
switch(tensorflowType) {
case DT_DOUBLE: return DataType.DOUBLE;
case DT_FLOAT: return DataType.FLOAT;
case DT_HALF: return DataType.HALF;
case DT_INT16: return DataType.SHORT;
case DT_INT32: return DataType.INT;
case DT_INT64: return DataType.LONG;
case DT_STRING: return DataType.UTF8;
case DT_INT8: return DataType.BYTE;
case DT_UINT8: return DataType.UBYTE;
case DT_UINT16: return DataType.UINT16;
case DT_UINT32: return DataType.UINT32;
case DT_UINT64: return DataType.UINT64;
case DT_BFLOAT16: return DataType.BFLOAT16;
case DT_BOOL: return DataType.BOOL;
default: throw new IllegalArgumentException("Illegal type " + tensorflowType);
}
}
/**
* Get an initialized {@link TF_Graph}
* based on the passed in file
* (the file must be a binary protobuf/pb file)
* The graph will be modified to be associated
* with the device associated with this current thread.
*
* Depending on the active {@link Nd4j#getBackend()}
* the device will either be the gpu pinned to the current thread
* or the cpu
* @param filePath the path to the file to read
* @return the initialized graph
* @throws IOException
*/
public TF_Graph loadGraph(String filePath, TF_Status status) throws IOException {
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
return loadGraph(bytes, status);
}
/**
* Infers the device for the given thread
* based on the {@link Nd4j#getAffinityManager()}
* Usually, this will either be a gpu or cpu
* reserved for the current device.
* You can think of the "current thread"
* as a worker. This is mainly useful with multiple gpus
* @return
*/
public static String defaultDeviceForThread() {
Integer deviceForThread = Nd4j.getAffinityManager().getDeviceForCurrentThread();
String deviceName = null;
//gpu
if(Nd4j.getBackend().getClass().getName().contains("JCublasBackend")) {
deviceName = "/device:gpu:" + deviceForThread;
}
else {
deviceName = "/device:cpu:" + deviceForThread;
}
return deviceName;
}
/**
* Get an initialized {@link TF_Graph}
* based on the passed in byte array content
* (the content must be a binary protobuf/pb file)
* The graph will be modified to be associated
* with the device associated with this current thread.
*
* Depending on the active {@link Nd4j#getBackend()}
* the device will either be the gpu pinned to the current thread
* or the content
* @param content the path to the file to read
* @return the initialized graph
* @throws IOException
*/
public TF_Graph loadGraph(byte[] content, TF_Status status) {
byte[] toLoad = content;
TF_Buffer graph_def = TF_NewBufferFromString(new BytePointer(toLoad), content.length);
TF_Graph graphC = TF_NewGraph();
TF_ImportGraphDefOptions opts = TF_NewImportGraphDefOptions();
TF_GraphImportGraphDef(graphC, graph_def, opts, status);
if (TF_GetCode(status) != TF_OK) {
throw new IllegalStateException("ERROR: Unable to import graph " + TF_Message(status).getString());
}
TF_DeleteImportGraphDefOptions(opts);
return graphC;
}
/**
* Load a session based on the saved model
* @param savedModelConfig the configuration for the saved model
* @param options the session options to use
* @param runOptions the run configuration to use
* @param graph the tf graph to use
* @param inputsMap the input map
* @param outputsMap the output names
* @param status the status object to use for verifying the results
* @return
*/
public TF_Session loadSavedModel(SavedModelConfig savedModelConfig, TF_SessionOptions options, TF_Buffer runOptions, TF_Graph graph, Map<String, String> inputsMap, Map<String, String> outputsMap, TF_Status status) {
TF_Buffer metaGraph = TF_Buffer.newBuffer();
TF_Session session = TF_LoadSessionFromSavedModel(options, runOptions, new BytePointer(savedModelConfig.getSavedModelPath()),
new BytePointer(savedModelConfig.getModelTag()), 1, graph, metaGraph, status);
if (TF_GetCode(status) != TF_OK) {
throw new IllegalStateException("ERROR: Unable to import model " + TF_Message(status).getString());
}
MetaGraphDef metaGraphDef;
try {
metaGraphDef = MetaGraphDef.parseFrom(metaGraph.data().capacity(metaGraph.length()).asByteBuffer());
} catch (InvalidProtocolBufferException ex) {
throw new IllegalStateException("ERROR: Unable to import model " + ex);
}
Map<String, SignatureDef> signatureDefMap = metaGraphDef.getSignatureDefMap();
SignatureDef signatureDef = signatureDefMap.get(savedModelConfig.getSignatureKey());
Map<String, TensorInfo> inputs = signatureDef.getInputsMap();
for (Map.Entry<String, TensorInfo> e : inputs.entrySet()) {
inputsMap.put(e.getKey(), e.getValue().getName());
}
Map<String, TensorInfo> outputs = signatureDef.getOutputsMap();
for (Map.Entry<String, TensorInfo> e : outputs.entrySet()) {
outputsMap.put(e.getKey(), e.getValue().getName());
}
return session;
}
}
|
deeplearning4j/deeplearning4j
|
nd4j/nd4j-tensorflow/src/main/java/org/nd4j/tensorflow/conversion/TensorflowConversion.java
|
Java
|
apache-2.0
| 16,741 |
/*
* 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 com.spatial4j.core.shape.jts;
import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.context.jts.JtsSpatialContext;
import com.spatial4j.core.exception.InvalidShapeException;
import com.spatial4j.core.shape.Circle;
import com.spatial4j.core.shape.Point;
import com.spatial4j.core.shape.Rectangle;
import com.spatial4j.core.shape.Shape;
import com.spatial4j.core.shape.SpatialRelation;
import com.spatial4j.core.shape.impl.BufferedLineString;
import com.spatial4j.core.shape.impl.PointImpl;
import com.spatial4j.core.shape.impl.Range;
import com.spatial4j.core.shape.impl.RectangleImpl;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.CoordinateSequenceFilter;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryCollection;
import com.vividsolutions.jts.geom.GeometryFilter;
import com.vividsolutions.jts.geom.IntersectionMatrix;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.Lineal;
import com.vividsolutions.jts.geom.LinearRing;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.geom.Puntal;
import com.vividsolutions.jts.geom.prep.PreparedGeometry;
import com.vividsolutions.jts.geom.prep.PreparedGeometryFactory;
import com.vividsolutions.jts.operation.union.UnaryUnionOp;
import com.vividsolutions.jts.operation.valid.IsValidOp;
import java.util.ArrayList;
import java.util.List;
/**
* Wraps a JTS {@link Geometry} (i.e. may be a polygon or basically anything).
* JTS does a great deal of the hard work, but there is work here in handling
* dateline wrap.
*/
public class JtsGeometry implements Shape {
/**
* System property boolean that can disable auto validation in an assert.
*/
public static final String SYSPROP_ASSERT_VALIDATE = "spatial4j.JtsGeometry.assertValidate";
private final Geometry geom;//cannot be a direct instance of GeometryCollection as it doesn't support relate()
private final boolean hasArea;
private final Rectangle bbox;
protected final JtsSpatialContext ctx;
protected PreparedGeometry preparedGeometry;
protected boolean validated = false;
public JtsGeometry(Geometry geom, JtsSpatialContext ctx, boolean dateline180Check, boolean allowMultiOverlap) {
this.ctx = ctx;
//GeometryCollection isn't supported in relate()
if (geom.getClass().equals(GeometryCollection.class))
throw new IllegalArgumentException("JtsGeometry does not support GeometryCollection but does support its subclasses.");
//NOTE: All this logic is fairly expensive. There are some short-circuit checks though.
if (ctx.isGeo()) {
//Unwraps the geometry across the dateline so it exceeds the standard geo bounds (-180 to +180).
if (dateline180Check)
unwrapDateline(geom);//potentially modifies geom
//If given multiple overlapping polygons, fix it by union
if (allowMultiOverlap)
geom = unionGeometryCollection(geom);//returns same or new geom
//Cuts an unwrapped geometry back into overlaid pages in the standard geo bounds.
geom = cutUnwrappedGeomInto360(geom);//returns same or new geom
assert geom.getEnvelopeInternal().getWidth() <= 360;
assert !geom.getClass().equals(GeometryCollection.class) : "GeometryCollection unsupported";//double check
//Compute bbox
bbox = computeGeoBBox(geom);
} else {//not geo
//If given multiple overlapping polygons, fix it by union
if (allowMultiOverlap)
geom = unionGeometryCollection(geom);//returns same or new geom
Envelope env = geom.getEnvelopeInternal();
bbox = new RectangleImpl(env.getMinX(), env.getMaxX(), env.getMinY(), env.getMaxY(), ctx);
}
geom.getEnvelopeInternal();//ensure envelope is cached internally, which is lazy evaluated. Keeps this thread-safe.
this.geom = geom;
assert assertValidate();//kinda expensive but caches valid state
this.hasArea = !((geom instanceof Lineal) || (geom instanceof Puntal));
}
/**
* called via assertion
*/
private boolean assertValidate() {
String assertValidate = System.getProperty(SYSPROP_ASSERT_VALIDATE);
if (assertValidate == null || Boolean.parseBoolean(assertValidate))
validate();
return true;
}
/**
* Validates the shape, throwing a descriptive error if it isn't valid. Note that this
* is usually called automatically by default, but that can be disabled.
*
* @throws InvalidShapeException with descriptive error if the shape isn't valid
*/
public void validate() throws InvalidShapeException {
if (!validated) {
IsValidOp isValidOp = new IsValidOp(geom);
if (!isValidOp.isValid())
throw new InvalidShapeException(isValidOp.getValidationError().toString());
validated = true;
}
}
/**
* Adds an index to this class internally to compute spatial relations faster. In JTS this
* is called a {@link com.vividsolutions.jts.geom.prep.PreparedGeometry}. This
* isn't done by default because it takes some time to do the optimization, and it uses more
* memory. Calling this method isn't thread-safe so be careful when this is done. If it was
* already indexed then nothing happens.
*/
public void index() {
if (preparedGeometry == null)
preparedGeometry = PreparedGeometryFactory.prepare(geom);
}
@Override
public boolean isEmpty() {
return geom.isEmpty();
}
/**
* Given {@code geoms} which has already been checked for being in world
* bounds, return the minimal longitude range of the bounding box.
*/
protected Rectangle computeGeoBBox(Geometry geoms) {
if (geoms.isEmpty())
return new RectangleImpl(Double.NaN, Double.NaN, Double.NaN, Double.NaN, ctx);
final Envelope env = geoms.getEnvelopeInternal();//for minY & maxY (simple)
if (env.getWidth() > 180 && geoms.getNumGeometries() > 1) {
// This is ShapeCollection's bbox algorithm
Range xRange = null;
for (int i = 0; i < geoms.getNumGeometries(); i++) {
Envelope envI = geoms.getGeometryN(i).getEnvelopeInternal();
Range xRange2 = new Range.LongitudeRange(envI.getMinX(), envI.getMaxX());
if (xRange == null) {
xRange = xRange2;
} else {
xRange = xRange.expandTo(xRange2);
}
if (xRange == Range.LongitudeRange.WORLD_180E180W)
break; // can't grow any bigger
}
return new RectangleImpl(xRange.getMin(), xRange.getMax(), env.getMinY(), env.getMaxY(), ctx);
} else {
return new RectangleImpl(env.getMinX(), env.getMaxX(), env.getMinY(), env.getMaxY(), ctx);
}
}
@Override
public JtsGeometry getBuffered(double distance, SpatialContext ctx) {
//TODO doesn't work correctly across the dateline. The buffering needs to happen
// when it's transiently unrolled, prior to being sliced.
return this.ctx.makeShape(geom.buffer(distance), true, true);
}
@Override
public boolean hasArea() {
return hasArea;
}
@Override
public double getArea(SpatialContext ctx) {
double geomArea = geom.getArea();
if (ctx == null || geomArea == 0)
return geomArea;
//Use the area proportional to how filled the bbox is.
double bboxArea = getBoundingBox().getArea(null);//plain 2d area
assert bboxArea >= geomArea;
double filledRatio = geomArea / bboxArea;
return getBoundingBox().getArea(ctx) * filledRatio;
// (Future: if we know we use an equal-area projection then we don't need to
// estimate)
}
@Override
public Rectangle getBoundingBox() {
return bbox;
}
@Override
public JtsPoint getCenter() {
if (isEmpty()) //geom.getCentroid == null
return new JtsPoint(ctx.getGeometryFactory().createPoint((Coordinate) null), ctx);
return new JtsPoint(geom.getCentroid(), ctx);
}
@Override
public SpatialRelation relate(Shape other) {
if (other instanceof Point)
return relate((Point) other);
else if (other instanceof Rectangle)
return relate((Rectangle) other);
else if (other instanceof Circle)
return relate((Circle) other);
else if (other instanceof JtsGeometry)
return relate((JtsGeometry) other);
else if (other instanceof BufferedLineString)
throw new UnsupportedOperationException("Can't use BufferedLineString with JtsGeometry");
return other.relate(this).transpose();
}
public SpatialRelation relate(Point pt) {
if (!getBoundingBox().relate(pt).intersects())
return SpatialRelation.DISJOINT;
Geometry ptGeom;
if (pt instanceof JtsPoint)
ptGeom = ((JtsPoint) pt).getGeom();
else
ptGeom = ctx.getGeometryFactory().createPoint(new Coordinate(pt.getX(), pt.getY()));
return relate(ptGeom);//is point-optimized
}
public SpatialRelation relate(Rectangle rectangle) {
SpatialRelation bboxR = bbox.relate(rectangle);
if (bboxR == SpatialRelation.WITHIN || bboxR == SpatialRelation.DISJOINT)
return bboxR;
// FYI, the right answer could still be DISJOINT or WITHIN, but we don't know yet.
return relate(ctx.getGeometryFrom(rectangle));
}
public SpatialRelation relate(Circle circle) {
SpatialRelation bboxR = bbox.relate(circle);
if (bboxR == SpatialRelation.WITHIN || bboxR == SpatialRelation.DISJOINT)
return bboxR;
//Test each point to see how many of them are outside of the circle.
//TODO consider instead using geom.apply(CoordinateSequenceFilter) -- maybe faster since avoids Coordinate[] allocation
Coordinate[] coords = geom.getCoordinates();
int outside = 0;
int i = 0;
for (Coordinate coord : coords) {
i++;
SpatialRelation sect = circle.relate(new PointImpl(coord.x, coord.y, ctx));
if (sect == SpatialRelation.DISJOINT)
outside++;
if (i != outside && outside != 0)//short circuit: partially outside, partially inside
return SpatialRelation.INTERSECTS;
}
if (i == outside) {
return (relate(circle.getCenter()) == SpatialRelation.DISJOINT)
? SpatialRelation.DISJOINT : SpatialRelation.CONTAINS;
}
assert outside == 0;
return SpatialRelation.WITHIN;
}
public SpatialRelation relate(JtsGeometry jtsGeometry) {
//don't bother checking bbox since geom.relate() does this already
return relate(jtsGeometry.geom);
}
protected SpatialRelation relate(Geometry oGeom) {
//see http://docs.geotools.org/latest/userguide/library/jts/dim9.html#preparedgeometry
if (oGeom instanceof com.vividsolutions.jts.geom.Point) {
if (preparedGeometry != null)
return preparedGeometry.disjoint(oGeom) ? SpatialRelation.DISJOINT : SpatialRelation.CONTAINS;
return geom.disjoint(oGeom) ? SpatialRelation.DISJOINT : SpatialRelation.CONTAINS;
}
if (preparedGeometry == null)
return intersectionMatrixToSpatialRelation(geom.relate(oGeom));
else if (preparedGeometry.covers(oGeom))
return SpatialRelation.CONTAINS;
else if (preparedGeometry.coveredBy(oGeom))
return SpatialRelation.WITHIN;
else if (preparedGeometry.intersects(oGeom))
return SpatialRelation.INTERSECTS;
return SpatialRelation.DISJOINT;
}
public static SpatialRelation intersectionMatrixToSpatialRelation(IntersectionMatrix matrix) {
//As indicated in SpatialRelation javadocs, Spatial4j CONTAINS & WITHIN are
// OGC's COVERS & COVEREDBY
if (matrix.isCovers())
return SpatialRelation.CONTAINS;
else if (matrix.isCoveredBy())
return SpatialRelation.WITHIN;
else if (matrix.isDisjoint())
return SpatialRelation.DISJOINT;
return SpatialRelation.INTERSECTS;
}
@Override
public String toString() {
return geom.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JtsGeometry that = (JtsGeometry) o;
return geom.equalsExact(that.geom);//fast equality for normalized geometries
}
@Override
public int hashCode() {
//FYI if geometry.equalsExact(that.geometry), then their envelopes are the same.
return geom.getEnvelopeInternal().hashCode();
}
public Geometry getGeom() {
return geom;
}
/**
* If <code>geom</code> spans the dateline, then this modifies it to be a
* valid JTS geometry that extends to the right of the standard -180 to +180
* width such that some points are greater than +180 but some remain less.
* Takes care to invoke {@link com.vividsolutions.jts.geom.Geometry#geometryChanged()}
* if needed.
*
* @return The number of times the geometry spans the dateline. >= 0
*/
private static int unwrapDateline(Geometry geom) {
if (geom.getEnvelopeInternal().getWidth() < 180)
return 0;//can't possibly cross the dateline
final int[] crossings = {0};//an array so that an inner class can modify it.
geom.apply(new GeometryFilter() {
@Override
public void filter(Geometry geom) {
int cross = 0;
if (geom instanceof LineString) {//note: LinearRing extends LineString
if (geom.getEnvelopeInternal().getWidth() < 180)
return;//can't possibly cross the dateline
cross = unwrapDateline((LineString) geom);
} else if (geom instanceof Polygon) {
if (geom.getEnvelopeInternal().getWidth() < 180)
return;//can't possibly cross the dateline
cross = unwrapDateline((Polygon) geom);
} else
return;
crossings[0] = Math.max(crossings[0], cross);
}
});//geom.apply()
return crossings[0];
}
/**
* See {@link #unwrapDateline(Geometry)}.
*/
private static int unwrapDateline(Polygon poly) {
LineString exteriorRing = poly.getExteriorRing();
int cross = unwrapDateline(exteriorRing);
if (cross > 0) {
//TODO TEST THIS! Maybe bug if doesn't cross but is in another page?
for (int i = 0; i < poly.getNumInteriorRing(); i++) {
LineString innerLineString = poly.getInteriorRingN(i);
unwrapDateline(innerLineString);
for (int shiftCount = 0; !exteriorRing.contains(innerLineString); shiftCount++) {
if (shiftCount > cross)
throw new IllegalArgumentException("The inner ring doesn't appear to be within the exterior: "
+ exteriorRing + " inner: " + innerLineString);
shiftGeomByX(innerLineString, 360);
}
}
poly.geometryChanged();
}
return cross;
}
/**
* See {@link #unwrapDateline(Geometry)}.
*/
private static int unwrapDateline(LineString lineString) {
CoordinateSequence cseq = lineString.getCoordinateSequence();
int size = cseq.size();
if (size <= 1)
return 0;
int shiftX = 0;//invariant: == shiftXPage*360
int shiftXPage = 0;
int shiftXPageMin = 0/* <= 0 */, shiftXPageMax = 0; /* >= 0 */
double prevX = cseq.getX(0);
for (int i = 1; i < size; i++) {
double thisX_orig = cseq.getX(i);
assert thisX_orig >= -180 && thisX_orig <= 180 : "X not in geo bounds";
double thisX = thisX_orig + shiftX;
if (prevX - thisX > 180) {//cross dateline from left to right
thisX += 360;
shiftX += 360;
shiftXPage += 1;
shiftXPageMax = Math.max(shiftXPageMax, shiftXPage);
} else if (thisX - prevX > 180) {//cross dateline from right to left
thisX -= 360;
shiftX -= 360;
shiftXPage -= 1;
shiftXPageMin = Math.min(shiftXPageMin, shiftXPage);
}
if (shiftXPage != 0)
cseq.setOrdinate(i, CoordinateSequence.X, thisX);
prevX = thisX;
}
if (lineString instanceof LinearRing) {
assert cseq.getCoordinate(0).equals(cseq.getCoordinate(size - 1));
assert shiftXPage == 0;//starts and ends at 0
}
assert shiftXPageMax >= 0 && shiftXPageMin <= 0;
//Unfortunately we are shifting again; it'd be nice to be smarter and shift once
shiftGeomByX(lineString, shiftXPageMin * -360);
int crossings = shiftXPageMax - shiftXPageMin;
if (crossings > 0)
lineString.geometryChanged();
return crossings;
}
private static void shiftGeomByX(Geometry geom, final int xShift) {
if (xShift == 0)
return;
geom.apply(new CoordinateSequenceFilter() {
@Override
public void filter(CoordinateSequence seq, int i) {
seq.setOrdinate(i, CoordinateSequence.X, seq.getX(i) + xShift);
}
@Override
public boolean isDone() {
return false;
}
@Override
public boolean isGeometryChanged() {
return true;
}
});
}
private static Geometry unionGeometryCollection(Geometry geom) {
if (geom instanceof GeometryCollection) {
return geom.union();
}
return geom;
}
/**
* This "pages" through standard geo boundaries offset by multiples of 360
* longitudinally that intersect geom, and the intersecting results of a page
* and the geom are shifted into the standard -180 to +180 and added to a new
* geometry that is returned.
*/
private static Geometry cutUnwrappedGeomInto360(Geometry geom) {
Envelope geomEnv = geom.getEnvelopeInternal();
if (geomEnv.getMinX() >= -180 && geomEnv.getMaxX() <= 180)
return geom;
assert geom.isValid() : "geom";
//TODO opt: support geom's that start at negative pages --
// ... will avoid need to previously shift in unwrapDateline(geom).
List<Geometry> geomList = new ArrayList<Geometry>();
//page 0 is the standard -180 to 180 range
for (int page = 0; true; page++) {
double minX = -180 + page * 360;
if (geomEnv.getMaxX() <= minX)
break;
Geometry rect = geom.getFactory().toGeometry(new Envelope(minX, minX + 360, -90, 90));
assert rect.isValid() : "rect";
Geometry pageGeom = rect.intersection(geom);//JTS is doing some hard work
assert pageGeom.isValid() : "pageGeom";
shiftGeomByX(pageGeom, page * -360);
geomList.add(pageGeom);
}
return UnaryUnionOp.union(geomList);
}
// private static Geometry removePolyHoles(Geometry geom) {
// //TODO this does a deep copy of geom even if no changes needed; be smarter
// GeometryTransformer gTrans = new GeometryTransformer() {
// @Override
// protected Geometry transformPolygon(Polygon geom, Geometry parent) {
// if (geom.getNumInteriorRing() == 0)
// return geom;
// return factory.createPolygon((LinearRing) geom.getExteriorRing(),null);
// }
// };
// return gTrans.transform(geom);
// }
//
// private static Geometry snapAndClean(Geometry geom) {
// return new GeometrySnapper(geom).snapToSelf(GeometrySnapper.computeOverlaySnapTolerance(geom), true);
// }
}
|
yipen9/spatial4j
|
src/main/java/com/spatial4j/core/shape/jts/JtsGeometry.java
|
Java
|
apache-2.0
| 21,456 |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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 proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v9.enums",
marshal="google.ads.googleads.v9",
manifest={"SimulationTypeEnum",},
)
class SimulationTypeEnum(proto.Message):
r"""Container for enum describing the field a simulation
modifies.
"""
class SimulationType(proto.Enum):
r"""Enum describing the field a simulation modifies."""
UNSPECIFIED = 0
UNKNOWN = 1
CPC_BID = 2
CPV_BID = 3
TARGET_CPA = 4
BID_MODIFIER = 5
TARGET_ROAS = 6
PERCENT_CPC_BID = 7
TARGET_IMPRESSION_SHARE = 8
BUDGET = 9
__all__ = tuple(sorted(__protobuf__.manifest))
|
googleads/google-ads-python
|
google/ads/googleads/v9/enums/types/simulation_type.py
|
Python
|
apache-2.0
| 1,302 |
package com.topie.asset;
import com.topie.core.dbmigrate.ModuleSpecification;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class AssetModuleSpecification implements ModuleSpecification {
private static final String MODULE_NAME = "asset";
private static final String MODULE_NAME_UPPER = MODULE_NAME.toUpperCase();
private String type;
private boolean enabled;
private boolean initData;
public boolean isEnabled() {
return enabled;
}
public String getSchemaTable() {
return "SCHEMA_VERSION_" + MODULE_NAME_UPPER;
}
public String getSchemaLocation() {
return "dbmigrate." + type + "." + MODULE_NAME;
}
public boolean isInitData() {
return initData;
}
public String getDataTable() {
return "SCHEMA_VERSION_DATA_" + MODULE_NAME_UPPER;
}
public String getDataLocation() {
return "dbmigrate." + type + ".data_" + MODULE_NAME;
}
@Value("${application.database.type}")
public void setType(String type) {
this.type = type;
}
@Value("${" + MODULE_NAME + ".dbmigrate.enabled}")
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Value("${" + MODULE_NAME + ".dbmigrate.initData}")
public void setInitData(boolean initData) {
this.initData = initData;
}
}
|
topie/topie-oa
|
src/main/java/com/topie/asset/AssetModuleSpecification.java
|
Java
|
apache-2.0
| 1,430 |
package com.netflix.governator.lifecycle;
import com.google.inject.Injector;
import com.netflix.governator.LifecycleInjectorBuilderProvider;
import com.netflix.governator.annotations.WarmUp;
import com.netflix.governator.guice.LifecycleInjector;
import com.netflix.governator.guice.LifecycleInjectorBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Singleton;
/**
* There is a infinite recursion in InternalLifecycleModule.warmUpIsInDag(InternalLifecycleModule.java:150)
* and InternalLifecycleModule.warmUpIsInDag(InternalLifecycleModule.java:171) that will ultimately lead to
* an StackOverflowError.
*/
public class CircularDAG extends LifecycleInjectorBuilderProvider
{
@Singleton
public static class A
{
@Inject
private B b;
}
@Singleton
public static class B
{
@Inject
private A a;
}
@Singleton
public static class Service
{
private final Logger log = LoggerFactory.getLogger(getClass());
@Inject
private A a;
@WarmUp
public void connect()
{
log.info("connect");
}
@PreDestroy
public void disconnect()
{
log.info("disconnect");
}
}
@Test(dataProvider = "builders")
public void circle(LifecycleInjectorBuilder lifecycleInjectorBuilder) throws Exception
{
Injector injector = lifecycleInjectorBuilder.createInjector();
injector.getInstance(Service.class);
LifecycleManager manager = injector.getInstance(LifecycleManager.class);
manager.start();
}
}
|
gorcz/governator
|
governator-core/src/test/java/com/netflix/governator/lifecycle/CircularDAG.java
|
Java
|
apache-2.0
| 1,747 |
/*
This file is part of TopPI - see https://github.com/slide-lig/TopPI/
Copyright 2016 Martin Kirchgessner, Vincent Leroy, Alexandre Termier, Sihem Amer-Yahia, Marie-Christine Rousset, Université Grenoble Alpes, LIG, CNRS
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
or see the LICENSE.txt file joined with this program.
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 fr.liglab.mining.mapred;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Mapper;
import fr.liglab.mining.mapred.writables.ItemAndSupportWritable;
import fr.liglab.mining.mapred.writables.SupportAndTransactionWritable;
public class AggregationMapper extends Mapper<IntWritable, SupportAndTransactionWritable, ItemAndSupportWritable, SupportAndTransactionWritable> {
private final ItemAndSupportWritable keyW = new ItemAndSupportWritable();
@Override
protected void map(IntWritable key, SupportAndTransactionWritable value, Context context)
throws IOException, InterruptedException {
keyW.set(key.get(), value.getSupport());
context.write(this.keyW, value);
}
}
|
slide-lig/TopPI
|
src/main/java/fr/liglab/mining/mapred/AggregationMapper.java
|
Java
|
apache-2.0
| 1,561 |
package dk.apaq.cordova.geolocationx;
import de.greenrobot.event.EventBus;
import java.util.List;
import java.util.Iterator;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.app.NotificationManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import static java.lang.Math.*;
public class LocationUpdateService extends Service implements LocationListener {
private static final String TAG = "LocationUpdateService";
public static final String ACTION_START = "dk.apaq.cordova.geolocationx.START";
public static final String ACTION_STOP = "dk.apaq.cordova.geolocationx.STOP";
public static final String ACTION_CONFIGURE = "dk.apaq.cordova.geolocationx.CONFIGURE";
public static final String ACTION_SET_MINIMUM_DISTANCE = "dk.apaq.cordova.geolocationx.SET_MINIMUM_DISTANCE";
public static final String ACTION_SET_MINIMUM_INTERVAL = "dk.apaq.cordova.geolocationx.SET_MINIMUM_INTERVAL";
public static final String ACTION_SET_PRECISION = "dk.apaq.cordova.geolocationx.SET_PRECISION";
private static final int TWO_MINUTES = 1000 * 60 * 2;
private Location lastLocation;
private Boolean isDebugging = false;
private String notificationTitle = "";
private String notificationText = "";
private Long locationTimeout;
private String activityType;
private LocationManager locationManager;
private NotificationManager notificationManager;
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "OnBind" + intent);
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "OnCreate");
locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
notificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Received start id " + startId + ": " + intent);
if (intent != null) {
Log.d(TAG, "Action: " + intent.getAction());
// debug intent values values
Bundle bundle = intent.getExtras();
if(bundle != null) {
for (String key : bundle.keySet()) {
Object value = bundle.get(key);
Log.d(TAG, String.format("%s %s (%s)", key,
value.toString(), value.getClass().getName()));
}
}
if(intent.getAction().equals(ACTION_START)) {
this.startRecording();
// Build a Notification required for running service in foreground.
Intent main = new Intent(this, BackgroundGpsPlugin.class);
main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, main, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle(notificationTitle);
builder.setContentText(notificationText);
builder.setSmallIcon(android.R.drawable.ic_menu_mylocation);
builder.setContentIntent(pendingIntent);
Notification notification;
notification = builder.build();
notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_NO_CLEAR;
startForeground(startId, notification);
}
if(intent.getAction().equals(ACTION_CONFIGURE)) {
locationTimeout = Long.parseLong(intent.getStringExtra("locationTimeout"));
isDebugging = Boolean.parseBoolean(intent.getStringExtra("isDebugging"));
notificationTitle = intent.getStringExtra("notificationTitle");
notificationText = intent.getStringExtra("notificationText");
activityType = intent.getStringExtra("activityType");
Log.i(TAG, "- notificationTitle: " + notificationTitle);
Log.i(TAG, "- notificationText: " + notificationText);
}
if(intent.getAction().equals(ACTION_SET_MINIMUM_DISTANCE)) {
// TODO
Log.i(TAG, "- minimumDistance: " + intent.getStringExtra("value"));
}
if(intent.getAction().equals(ACTION_SET_MINIMUM_INTERVAL)) {
// TODO
Log.i(TAG, "- minimumInterval: " + intent.getStringExtra("value"));
}
if(intent.getAction().equals(ACTION_SET_PRECISION)) {
// TODO
Log.i(TAG, "- precision: " + intent.getStringExtra("value"));
}
}
//We want this service to continue running until it is explicitly stopped
return START_REDELIVER_INTENT;
}
@Override
public void onDestroy() {
Log.w(TAG, "------------------------------------------ Destroyed Location update Service");
cleanUp();
super.onDestroy();
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void onTaskRemoved(Intent rootIntent) {
this.stopSelf();
super.onTaskRemoved(rootIntent);
}
@Override
public boolean stopService(Intent intent) {
Log.i(TAG, "- Received stop: " + intent);
cleanUp();
if (isDebugging) {
Toast.makeText(this, "Background location tracking stopped", Toast.LENGTH_SHORT).show();
}
return super.stopService(intent);
}
/**
* Start recording aggresively from all found providers
*/
private void startRecording() {
Log.i(TAG, "startRecording");
locationManager.removeUpdates(this);
// Turn on all providers aggressively
List<String> matchingProviders = locationManager.getAllProviders();
for (String provider: matchingProviders) {
if (provider != LocationManager.PASSIVE_PROVIDER) {
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
}
}
private void cleanUp() {
locationManager.removeUpdates(this);
stopForeground(true);
}
/** Determines whether one Location reading is better than the current Location fix
* @param location The new Location that you want to evaluate
* @param currentBestLocation The current Location fix, to which you want to compare the new one
*/
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
// ------------------ LOCATION LISTENER INTERFACE -------------------------
public void onLocationChanged(Location location) {
Log.d(TAG, "- onLocationChanged: " + location.getLatitude() + "," + location.getLongitude() + ", accuracy: " + location.getAccuracy() + ", speed: " + location.getSpeed());
if(isDebugging){
Toast.makeText(this, "acy:"+location.getAccuracy()+",v:"+location.getSpeed(), Toast.LENGTH_LONG).show();
}
if(isBetterLocation(location, lastLocation)){
Log.d(TAG, "Location is better");
lastLocation = location;
// send it via bus to activity
try{
JSONObject pos = new JSONObject();
JSONObject loc = new JSONObject();
loc.put("latitude", location.getLatitude());
loc.put("longitude", location.getLongitude());
loc.put("accuracy", location.getAccuracy());
loc.put("speed", location.getSpeed());
loc.put("bearing", location.getBearing());
loc.put("altitude", location.getAltitude());
pos.put("coords", loc);
pos.put("timestamp", new Date().getTime());
EventBus.getDefault().post(pos);
Log.d(TAG, "posting location to bus");
}catch(JSONException e){
Log.e(TAG, "could not parse location");
}
}else{
Log.d(TAG, "Location is no better than current");
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.d(TAG, "- onProviderDisabled: " + provider);
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.d(TAG, "- onProviderEnabled: " + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.d(TAG, "- onStatusChanged: " + provider + ", status: " + status);
}
// -------------------------- LOCATION LISTENER INTERFACE END -------------------------
}
|
michaelkrog/cordova-plugin-geolocation-x
|
src/android/dk/apaq/cordova/geolocationx/LocationUpdateService.java
|
Java
|
apache-2.0
| 11,318 |
package vandy.mooc.provider;
import android.content.ContentUris;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Defines table and column names for the Acronym database.
*/
public final class VideoContract {
/**
* The "Content authority" is a name for the entire content provider,
* similar to the relationship between a domain name and its website. A
* convenient string to use for the content authority is the package name
* for the app, which must be unique on the device.
*/
public static final String CONTENT_AUTHORITY = "vandy.mooc.video";
/**
* Use CONTENT_AUTHORITY to create the base of all URI's that apps will use
* to contact the content provider.
*/
public static final Uri BASE_CONTENT_URI = Uri.parse("content://"
+ CONTENT_AUTHORITY);
/**
* Possible paths (appended to base content URI for possible URI's), e.g.,
* content://vandy.mooc/acronym/ is a valid path for Acronym data. However,
* content://vandy.mooc/givemeroot/ will fail since the ContentProvider
* hasn't been given any information on what to do with "givemeroot".
*/
public static final String PATH_VIDEO = VideoEntry.TABLE_NAME;
/**
* Inner class that defines the contents of the Acronym table.
*/
public static final class VideoEntry implements BaseColumns {
/**
* Use BASE_CONTENT_URI to create the unique URI for Acronym Table that
* apps will use to contact the content provider.
*/
public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon()
.appendPath(PATH_VIDEO).build();
/**
* When the Cursor returned for a given URI by the ContentProvider
* contains 0..x items.
*/
public static final String CONTENT_ITEMS_TYPE = "vnd.android.cursor.dir/"
+ CONTENT_AUTHORITY + "/" + PATH_VIDEO;
/**
* When the Cursor returned for a given URI by the ContentProvider
* contains 1 item.
*/
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/"
+ CONTENT_AUTHORITY + "/" + PATH_VIDEO;
/**
* Name of the database table.
*/
public static final String TABLE_NAME = "video_table";
/**
* Columns to store Data of each Acronym Expansion.
*/
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_DURATION = "duration";
public static final String COLUMN_CONTENT_TYPE = "content_type";
public static final String COLUMN_DATA_URL = "data_url";
public static final String COLUMN_STAR_RATING = "star_rating";
/**
* Return a Uri that points to the row containing a given id.
*
* @param id
* @return Uri
*/
public static Uri buildVideoUri(Long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
}
}
|
dexter-at-git/coursera-android-spring
|
assignments/assignment3/client/src/vandy/mooc/provider/VideoContract.java
|
Java
|
apache-2.0
| 2,701 |
package org.jasig.cas.authentication.principal;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.jasig.cas.logout.SingleLogoutService;
import org.jasig.cas.validation.ValidationResponseType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URLDecoder;
import java.util.Map;
/**
* Abstract implementation of a WebApplicationService.
*
* @author Scott Battaglia
* @since 3.1
*/
public abstract class AbstractWebApplicationService implements SingleLogoutService {
private static final long serialVersionUID = 610105280927740076L;
private static final Map<String, Object> EMPTY_MAP = ImmutableMap.of();
/** Logger instance. **/
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
/** The id of the service. */
private final String id;
/** The original url provided, used to reconstruct the redirect url. */
private final String originalUrl;
private final String artifactId;
private Principal principal;
private boolean loggedOutAlready;
private final ResponseBuilder<WebApplicationService> responseBuilder;
private ValidationResponseType format = ValidationResponseType.XML;
/**
* Instantiates a new abstract web application service.
*
* @param id the id
* @param originalUrl the original url
* @param artifactId the artifact id
* @param responseBuilder the response builder
*/
protected AbstractWebApplicationService(final String id, final String originalUrl,
final String artifactId, final ResponseBuilder<WebApplicationService> responseBuilder) {
this.id = id;
this.originalUrl = originalUrl;
this.artifactId = artifactId;
this.responseBuilder = responseBuilder;
}
@Override
public final String toString() {
return this.id;
}
@Override
public final String getId() {
return this.id;
}
@Override
public final String getArtifactId() {
return this.artifactId;
}
@Override
public final Map<String, Object> getAttributes() {
return EMPTY_MAP;
}
/**
* Return the original url provided (as {@code service} or {@code targetService} request parameter).
* Used to reconstruct the redirect url.
*
* @return the original url provided.
*/
@Override
public final String getOriginalUrl() {
return this.originalUrl;
}
@Override
public boolean equals(final Object object) {
if (object == null) {
return false;
}
if (object instanceof Service) {
final Service service = (Service) object;
return getId().equals(service.getId());
}
return false;
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(this.id)
.toHashCode();
}
public Principal getPrincipal() {
return this.principal;
}
@Override
public void setPrincipal(final Principal principal) {
this.principal = principal;
}
@Override
public boolean matches(final Service service) {
try {
final String thisUrl = URLDecoder.decode(this.id, "UTF-8");
final String serviceUrl = URLDecoder.decode(service.getId(), "UTF-8");
logger.trace("Decoded urls and comparing [{}] with [{}]", thisUrl, serviceUrl);
return thisUrl.equalsIgnoreCase(serviceUrl);
} catch (final Exception e) {
logger.error(e.getMessage(), e);
}
return false;
}
/**
* Return if the service is already logged out.
*
* @return if the service is already logged out.
*/
@Override
public boolean isLoggedOutAlready() {
return loggedOutAlready;
}
/**
* Set if the service is already logged out.
*
* @param loggedOutAlready if the service is already logged out.
*/
@Override
public final void setLoggedOutAlready(final boolean loggedOutAlready) {
this.loggedOutAlready = loggedOutAlready;
}
protected ResponseBuilder<? extends WebApplicationService> getResponseBuilder() {
return responseBuilder;
}
@Override
public ValidationResponseType getFormat() {
return format;
}
public void setFormat(final ValidationResponseType format) {
this.format = format;
}
@Override
public Response getResponse(final String ticketId) {
return this.responseBuilder.build(this, ticketId);
}
}
|
PetrGasparik/cas
|
cas-server-core-services/src/main/java/org/jasig/cas/authentication/principal/AbstractWebApplicationService.java
|
Java
|
apache-2.0
| 4,645 |
/*
* Copyright 2008-2011 Wolfgang Keller
*
* 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.
*/
#include "GuiOpenGL/GuiComponentsBasic.h"
#ifdef _WIN32
#include <windows.h>
#endif
#include <GL/gl.h>
#include <cassert>
void createStraightBorder(Vertex2<float> prevVertex,
Vertex2<float> currVertex,
Vertex2<float> nextVertex,
std::vector<Vertex2<float> >* pBorderTriangleStrip,
float borderWidth,
size_t)
{
Vector2<float> prevToCurrVect = currVertex - prevVertex;
Vector2<float> currToNextVect = nextVertex - currVertex;
normalize(&prevToCurrVect);
normalize(&currToNextVect);
Vector2<float> direction = prevToCurrVect+currToNextVect;
normalize(&direction);
Vector2<float> rightFromDirection = normal(direction);
float scaleFactor =
-borderWidth/(currToNextVect.x*rightFromDirection.x+
currToNextVect.y*rightFromDirection.y);
pBorderTriangleStrip->push_back(currVertex);
pBorderTriangleStrip->push_back(currVertex+rightFromDirection*scaleFactor);
}
void createRoundBorder(Vertex2<float> prevVertex,
Vertex2<float> currVertex,
Vertex2<float> nextVertex,
std::vector<Vertex2<float> >* pBorderTriangleStrip,
float borderWidth,
size_t curveSegmentsCount)
{
assert(curveSegmentsCount>=1);
Vector2<float> prevToCurrVect = currVertex - prevVertex;
Vector2<float> currToNextVect = nextVertex - currVertex;
normalize(&prevToCurrVect);
normalize(&currToNextVect);
Vector2<float> prevToCurrNormal = normal(prevToCurrVect);
Vector2<float> currToNextNormal = normal(currToNextVect);
/*
* The orthogonal matrix that rotates (1, 0) to prevToCurrNormal is
*
* | prevToCurrNormal.x prevToCurrVect.x |
* | prevToCurrNormal.y prevToCurrVect.y |
*
* Since this is an orthogonal matrix the inverse one is this one transposed
*/
Matrix22<float> orth = Matrix22<float>(prevToCurrNormal.x, prevToCurrNormal.y,
prevToCurrVect.x, prevToCurrVect.y).transpose();
Vector2<float> angleVector = orth * currToNextNormal;
// The order has to be y, x -- see declaration of atan2f
float angle = atan2f(angleVector.y, angleVector.x);
for (size_t i=0; i<=curveSegmentsCount; i++)
{
float currentAngle = i*angle/curveSegmentsCount;
Matrix22<float> currentRotation = Matrix22<float>(
cosf(currentAngle), sinf(currentAngle),
-sinf(currentAngle), cosf(currentAngle));
Vector2<float> movement = currentRotation*prevToCurrNormal*borderWidth;
pBorderTriangleStrip->push_back(currVertex);
pBorderTriangleStrip->push_back(currVertex+movement);
}
}
/*!
* vertices output:
* [0]: bottom left
* [1]: bottom right
* [2]: top left
* [3]: top right
*/
void createBoxVertices(std::vector<Vertex2<float> >* boxVertices,
float left, float top, float width, float height,
float currentHeight)
{
/*
* 2-3
* |\|
* 0-1
*/
boxVertices->push_back(Vertex2<float>(left, currentHeight-top-height)); // bottom left
boxVertices->push_back(Vertex2<float>(left+width, currentHeight-top-height)); // bottom right
boxVertices->push_back(Vertex2<float>(left, currentHeight-top)); // top left
boxVertices->push_back(Vertex2<float>(left+width, currentHeight-top)); // top right
}
void drawVertexArray(const std::vector<Vertex2<float> >* vertices, Color4<float> colors[4])
{
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, &vertices->at(0));
glColorPointer(4, GL_FLOAT, 0, colors);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
}
void drawVertexArray(const std::vector<Vertex2<float> >* vertices, Color4<float> color)
{
glEnableClientState(GL_VERTEX_ARRAY);
glColor4fv(&color.r);
glVertexPointer(2, GL_FLOAT, 0, &vertices->at(0));
glDrawArrays(GL_TRIANGLE_STRIP, 0, (GLsizei) vertices->size());
glDisableClientState(GL_VERTEX_ARRAY);
}
|
dreamsxin/101_browser
|
src/GuiOpenGL/GuiComponentsBasic.cpp
|
C++
|
apache-2.0
| 4,410 |
/**
* Copyright (c) 2013-2021 Nikita Koksharov
*
* 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.redisson;
import org.redisson.api.RFuture;
import org.redisson.api.RPatternTopic;
import org.redisson.api.listener.PatternMessageListener;
import org.redisson.api.listener.PatternStatusListener;
import org.redisson.client.ChannelName;
import org.redisson.client.RedisPubSubListener;
import org.redisson.client.RedisTimeoutException;
import org.redisson.client.codec.Codec;
import org.redisson.client.protocol.pubsub.PubSubType;
import org.redisson.command.CommandAsyncExecutor;
import org.redisson.config.MasterSlaveServersConfig;
import org.redisson.misc.CompletableFutureWrapper;
import org.redisson.pubsub.AsyncSemaphore;
import org.redisson.pubsub.PubSubConnectionEntry;
import org.redisson.pubsub.PublishSubscribeService;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* Distributed topic implementation. Messages are delivered to all message listeners across Redis cluster.
*
* @author Nikita Koksharov
*
*/
public class RedissonPatternTopic implements RPatternTopic {
final PublishSubscribeService subscribeService;
final CommandAsyncExecutor commandExecutor;
private final String name;
private final ChannelName channelName;
private final Codec codec;
protected RedissonPatternTopic(CommandAsyncExecutor commandExecutor, String name) {
this(commandExecutor.getConnectionManager().getCodec(), commandExecutor, name);
}
protected RedissonPatternTopic(Codec codec, CommandAsyncExecutor commandExecutor, String name) {
this.commandExecutor = commandExecutor;
this.name = name;
this.channelName = new ChannelName(name);
this.codec = codec;
this.subscribeService = commandExecutor.getConnectionManager().getSubscribeService();
}
@Override
public int addListener(PatternStatusListener listener) {
return addListener(new PubSubPatternStatusListener(listener, name));
};
@Override
public <T> int addListener(Class<T> type, PatternMessageListener<T> listener) {
PubSubPatternMessageListener<T> pubSubListener = new PubSubPatternMessageListener<T>(type, listener, name);
return addListener(pubSubListener);
}
private int addListener(RedisPubSubListener<?> pubSubListener) {
CompletableFuture<Collection<PubSubConnectionEntry>> future = subscribeService.psubscribe(channelName, codec, pubSubListener);
commandExecutor.get(future);
return System.identityHashCode(pubSubListener);
}
@Override
public RFuture<Integer> addListenerAsync(PatternStatusListener listener) {
PubSubPatternStatusListener pubSubListener = new PubSubPatternStatusListener(listener, name);
return addListenerAsync(pubSubListener);
}
@Override
public <T> RFuture<Integer> addListenerAsync(Class<T> type, PatternMessageListener<T> listener) {
PubSubPatternMessageListener<T> pubSubListener = new PubSubPatternMessageListener<T>(type, listener, name);
return addListenerAsync(pubSubListener);
}
private RFuture<Integer> addListenerAsync(RedisPubSubListener<?> pubSubListener) {
CompletableFuture<Collection<PubSubConnectionEntry>> future = subscribeService.psubscribe(channelName, codec, pubSubListener);
CompletableFuture<Integer> f = future.thenApply(res -> {
return System.identityHashCode(pubSubListener);
});
return new CompletableFutureWrapper<>(f);
}
protected void acquire(AsyncSemaphore semaphore) {
MasterSlaveServersConfig config = commandExecutor.getConnectionManager().getConfig();
int timeout = config.getTimeout() + config.getRetryInterval() * config.getRetryAttempts();
if (!semaphore.tryAcquire(timeout)) {
throw new RedisTimeoutException("Remove listeners operation timeout: (" + timeout + "ms) for " + name + " topic");
}
}
@Override
public RFuture<Void> removeListenerAsync(int listenerId) {
CompletableFuture<Void> f = subscribeService.removeListenerAsync(PubSubType.PUNSUBSCRIBE, channelName, listenerId);
return new CompletableFutureWrapper<>(f);
}
@Override
public void removeListener(int listenerId) {
commandExecutor.get(removeListenerAsync(listenerId).toCompletableFuture());
}
@Override
public void removeAllListeners() {
AsyncSemaphore semaphore = subscribeService.getSemaphore(channelName);
acquire(semaphore);
PubSubConnectionEntry entry = subscribeService.getPubSubEntry(channelName);
if (entry == null) {
semaphore.release();
return;
}
if (entry.hasListeners(channelName)) {
subscribeService.unsubscribe(PubSubType.PUNSUBSCRIBE, channelName).toCompletableFuture().join();
}
semaphore.release();
}
@Override
public void removeListener(PatternMessageListener<?> listener) {
CompletableFuture<Void> future = subscribeService.removeListenerAsync(PubSubType.PUNSUBSCRIBE, channelName, listener);
commandExecutor.get(future);
}
@Override
public List<String> getPatternNames() {
return Collections.singletonList(name);
}
}
|
redisson/redisson
|
redisson/src/main/java/org/redisson/RedissonPatternTopic.java
|
Java
|
apache-2.0
| 5,917 |
#Please read "usefull links" before going on, they are necessary for better understanding
import StringIO
import json #Imports the json library that decodes json tokens recieved from telegram api
import logging #Imports the library that puts messages in the log info of the google app engine
import random #Library that creates random numbers
import urllib
import urllib2
# for sending images
from PIL import Image
import multipart
# standard app engine imports
from google.appengine.api import urlfetch
from google.appengine.ext import ndb
import webapp2
TOKEN = 'YOUR_BOT_TOKEN_HERE'
BASE_URL = 'https://api.telegram.org/bot' + TOKEN + '/'
# ================================
class EnableStatus(ndb.Model): #NDB entity called EnabledStatus
# key name: str(chat_id)
enabled = ndb.BooleanProperty(indexed=False, default=False) #Entity has atribute enabled
# ================================
def setEnabled(chat_id, yes):
es = ndb.Key(EnableStatus, str(chat_id)).get() #Gets the entity
if es: #If it exists
es.enabled = yes #Sets its enabled atribute
es.put()
return
es = EnableStatus(id = str(chat_id)) #If not creates a new entity
es.put()
def getEnabled(chat_id):
es = ndb.Key(EnableStatus, str(chat_id)).get()
if es:
return es.enabled #Return the atual state
es = EnableStatus(id = str(chat_id))
es.put()
return False
# ================================ This part makes the comunication google-telegram
class MeHandler(webapp2.RequestHandler):
def get(self):
urlfetch.set_default_fetch_deadline(60)
self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getMe'))))
class GetUpdatesHandler(webapp2.RequestHandler):
def get(self):
urlfetch.set_default_fetch_deadline(60)
self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getUpdates'))))
class SetWebhookHandler(webapp2.RequestHandler):
def get(self):
urlfetch.set_default_fetch_deadline(60)
url = self.request.get('url')
if url:
self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'setWebhook', urllib.urlencode({'url': url})))))
class WebhookHandler(webapp2.RequestHandler):
def post(self):
urlfetch.set_default_fetch_deadline(60)
body = json.loads(self.request.body)
logging.info('request body:')
logging.info(body)
self.response.write(json.dumps(body))
#From here you can take message information, now it only uses the chat_id and text,
#you can take more things from it, search how to use json on google
update_id = body['update_id']
message = body['message']
message_id = message.get('message_id')
date = message.get('date')
text = message.get('text') #Takes the 'text' string
fr = message.get('from')
chat = message['chat']
chat_id = chat['id'] #Chat id string
if not text:
logging.info('no text')
return
def reply(msg=None, img=None): #Function used to send messages, it recieves a string message or a binary image
if msg:
resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
'chat_id': str(chat_id),
'text': msg.encode('utf-8'),
'disable_web_page_preview': 'true',
'reply_to_message_id': str(message_id),
})).read()
elif img:
resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
('chat_id', str(chat_id)),
('reply_to_message_id', str(message_id)),
], [
('photo', 'image.jpg', img),
])
else:
logging.error('no msg or img specified') #If there is no image it puts in the google log the string
resp = None
logging.info('send response:')
logging.info(resp)
#From here you can make custom commands, just add an 'elif'
if text.startswith('/'):
if text == '/start':
reply('Bot enabled')
setEnabled(chat_id, True) #Sets the status to True (read above comments)
elif text == '/stop':
reply('Bot disabled')
setEnabled(chat_id, False) #Changes it to false
elif text == '/image': #Creates an aleatory image
img = Image.new('RGB', (512, 512)) #Size of the image
base = random.randint(0, 16777216)
pixels = [base+i*j for i in range(512) for j in range(512)] # generate sample image
img.putdata(pixels)
output = StringIO.StringIO()
img.save(output, 'JPEG')
reply(img=output.getvalue())
"""If you want to send a different image use this piece of code:
img = Image.open("image.jpg")
output = StringIO.StringIO()
img.save(output, 'JPEG')
reply(img=output.getvalue())"""
else:
reply('What command?')
#If it is not a command (does not start with /)
elif 'who are you' in text:
reply('telebot starter kit, created by yukuku: https://github.com/yukuku/telebot')
elif 'what time' in text:
reply('look at the top-right corner of your screen!')
else:
if getEnabled(chat_id): #If the status of the bot is enabled the bot answers you
try:
resp1 = json.load(urllib2.urlopen('http://www.simsimi.com/requestChat?lc=en&ft=1.0&req=' + urllib.quote_plus(text.encode('utf-8')))) #Sends you mesage to simsimi IA
back = resp1.get('res')
except urllib2.HTTPError, err:
logging.error(err)
back = str(err)
if not back:
reply('okay...')
elif 'I HAVE NO RESPONSE' in back:
reply('you said something with no meaning')
else:
reply(back)
else:
logging.info('not enabled for chat_id {}'.format(chat_id))
#Telegram comunication (dont change)
app = webapp2.WSGIApplication([
('/me', MeHandler),
('/updates', GetUpdatesHandler),
('/set_webhook', SetWebhookHandler),
('/webhook', WebhookHandler),
], debug=True)
|
0Cristofer/telebot
|
main.py
|
Python
|
apache-2.0
| 6,516 |
from flask import Blueprint, render_template, Response, current_app, send_from_directory
from pyox import ServiceError
from pyox.apps.monitor.api import get_cluster_client
from datetime import datetime
cluster_ui = Blueprint('cluster_ui',__name__,template_folder='templates')
@cluster_ui.route('/')
def index():
client = get_cluster_client()
try:
info = client.info();
scheduler = client.scheduler();
metrics = client.metrics();
info['startedOn'] = datetime.fromtimestamp(info['startedOn'] / 1e3).isoformat()
return render_template('cluster.html',info=info,scheduler=scheduler,metrics=metrics)
except ServiceError as err:
return Response(status=err.status_code,response=err.message if err.status_code!=401 else 'Authentication Required',mimetype="text/plain",headers={'WWW-Authenticate': 'Basic realm="Login Required"'})
assets = Blueprint('assets_ui',__name__)
@assets.route('/assets/<path:path>')
def send_asset(path):
dir = current_app.config.get('ASSETS')
if dir is None:
dir = __file__[:__file__.rfind('/')] + '/assets/'
return send_from_directory(dir, path)
|
alexmilowski/python-hadoop-rest-api
|
pyox/apps/monitor/views.py
|
Python
|
apache-2.0
| 1,129 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2013 Kitware 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.
###############################################################################
import base64
import codecs
import cherrypy
import io
import json
import logging
import os
import shutil
import signal
import six
import sys
import unittest
import uuid
from six import BytesIO
from six.moves import urllib
from girder.utility import model_importer
from girder.utility.server import setup as setupServer
from girder.constants import AccessType, ROOT_DIR, SettingKey
from girder.models import getDbConnection
from . import mock_smtp
from . import mock_s3
from . import mongo_replicaset
local = cherrypy.lib.httputil.Host('127.0.0.1', 30000)
remote = cherrypy.lib.httputil.Host('127.0.0.1', 30001)
mockSmtp = mock_smtp.MockSmtpReceiver()
mockS3Server = None
enabledPlugins = []
def startServer(mock=True, mockS3=False):
"""
Test cases that communicate with the server should call this
function in their setUpModule() function.
"""
server = setupServer(test=True, plugins=enabledPlugins)
if mock:
cherrypy.server.unsubscribe()
cherrypy.engine.start()
# Make server quiet (won't announce start/stop or requests)
cherrypy.config.update({'environment': 'embedded'})
# Log all requests if we asked to do so
if 'cherrypy' in os.environ.get('EXTRADEBUG', '').split():
cherrypy.config.update({'log.screen': True})
logHandler = logging.StreamHandler(sys.stdout)
logHandler.setLevel(logging.DEBUG)
cherrypy.log.error_log.addHandler(logHandler)
mockSmtp.start()
if mockS3:
global mockS3Server
mockS3Server = mock_s3.startMockS3Server()
return server
def stopServer():
"""
Test cases that communicate with the server should call this
function in their tearDownModule() function.
"""
cherrypy.engine.exit()
mockSmtp.stop()
def dropTestDatabase(dropModels=True):
"""
Call this to clear all contents from the test database. Also forces models
to reload.
"""
db_connection = getDbConnection()
dbName = cherrypy.config['database']['uri'].split('/')[-1]
if 'girder_test_' not in dbName:
raise Exception('Expected a testing database name, but got %s' % dbName)
db_connection.drop_database(dbName)
if dropModels:
model_importer.reinitializeAll()
def dropGridFSDatabase(dbName):
"""
Clear all contents from a gridFS database used as an assetstore.
:param dbName: the name of the database to drop.
"""
db_connection = getDbConnection()
db_connection.drop_database(dbName)
def dropFsAssetstore(path):
"""
Delete all of the files in a filesystem assetstore. This unlinks the path,
which is potentially dangerous.
:param path: the path to remove.
"""
if os.path.isdir(path):
shutil.rmtree(path)
class TestCase(unittest.TestCase, model_importer.ModelImporter):
"""
Test case base class for the application. Adds helpful utilities for
database and HTTP communication.
"""
def setUp(self, assetstoreType=None, dropModels=True):
"""
We want to start with a clean database each time, so we drop the test
database before each test. We then add an assetstore so the file model
can be used without 500 errors.
:param assetstoreType: if 'gridfs' or 's3', use that assetstore. For
any other value, use a filesystem assetstore.
"""
self.assetstoreType = assetstoreType
dropTestDatabase(dropModels=dropModels)
assetstoreName = os.environ.get('GIRDER_TEST_ASSETSTORE', 'test')
assetstorePath = os.path.join(
ROOT_DIR, 'tests', 'assetstore', assetstoreName)
if assetstoreType == 'gridfs':
# Name this as '_auto' to prevent conflict with assetstores created
# within test methods
gridfsDbName = 'girder_test_%s_assetstore_auto' % assetstoreName
dropGridFSDatabase(gridfsDbName)
self.assetstore = self.model('assetstore'). \
createGridFsAssetstore(name='Test', db=gridfsDbName)
elif assetstoreType == 'gridfsrs':
gridfsDbName = 'girder_test_%s_rs_assetstore_auto' % assetstoreName
mongo_replicaset.startMongoReplicaSet()
self.assetstore = self.model('assetstore'). \
createGridFsAssetstore(
name='Test', db=gridfsDbName,
mongohost='mongodb://127.0.0.1:27070,127.0.0.1:27071,'
'127.0.0.1:27072', replicaset='replicaset')
elif assetstoreType == 's3':
self.assetstore = self.model('assetstore'). \
createS3Assetstore(name='Test', bucket='bucketname',
accessKeyId='test', secret='test',
service=mockS3Server.service)
else:
dropFsAssetstore(assetstorePath)
self.assetstore = self.model('assetstore'). \
createFilesystemAssetstore(name='Test', root=assetstorePath)
addr = ':'.join(map(str, mockSmtp.address))
self.model('setting').set(SettingKey.SMTP_HOST, addr)
self.model('setting').set(SettingKey.UPLOAD_MINIMUM_CHUNK_SIZE, 0)
self.model('setting').set(SettingKey.PLUGINS_ENABLED, enabledPlugins)
def tearDown(self):
"""
Stop any services that we started just for this test.
"""
# If "self.setUp" is overridden, "self.assetstoreType" may not be set
if getattr(self, 'assetstoreType', None) == 'gridfsrs':
mongo_replicaset.stopMongoReplicaSet()
def assertStatusOk(self, response):
"""
Call this to assert that the response yielded a 200 OK output_status.
:param response: The response object.
"""
self.assertStatus(response, 200)
def assertStatus(self, response, code):
"""
Call this to assert that a given HTTP status code was returned.
:param response: The response object.
:param code: The status code.
:type code: int or str
"""
code = str(code)
if not response.output_status.startswith(code.encode()):
msg = 'Response status was %s, not %s.' % (response.output_status,
code)
if hasattr(response, 'json'):
msg += ' Response body was:\n%s' % json.dumps(
response.json, sort_keys=True, indent=4,
separators=(',', ': '))
self.fail(msg)
def assertHasKeys(self, obj, keys):
"""
Assert that the given object has the given list of keys.
:param obj: The dictionary object.
:param keys: The keys it must contain.
:type keys: list or tuple
"""
for k in keys:
self.assertTrue(k in obj, 'Object does not contain key "%s"' % k)
def assertRedirect(self, resp, url=None):
"""
Assert that we were given an HTTP redirect response, and optionally
assert that you were redirected to a specific URL.
:param resp: The response object.
:param url: If you know the URL you expect to be redirected to, you
should pass it here.
:type url: str
"""
self.assertStatus(resp, 303)
self.assertTrue('Location' in resp.headers)
if url:
self.assertEqual(url, resp.headers['Location'])
def assertNotHasKeys(self, obj, keys):
"""
Assert that the given object does not have any of the given list of
keys.
:param obj: The dictionary object.
:param keys: The keys it must not contain.
:type keys: list or tuple
"""
for k in keys:
self.assertFalse(k in obj, 'Object contains key "%s"' % k)
def assertValidationError(self, response, field=None):
"""
Assert that a ValidationException was thrown with the given field.
:param response: The response object.
:param field: The field that threw the validation exception.
:type field: str
"""
self.assertStatus(response, 400)
self.assertEqual(response.json['type'], 'validation')
self.assertEqual(response.json.get('field', None), field)
def assertAccessDenied(self, response, level, modelName, user=None):
if level == AccessType.READ:
ls = 'Read'
elif level == AccessType.WRITE:
ls = 'Write'
else:
ls = 'Admin'
if user is None:
self.assertStatus(response, 401)
else:
self.assertStatus(response, 403)
self.assertEqual('%s access denied for %s.' % (ls, modelName),
response.json['message'])
def assertMissingParameter(self, response, param):
"""
Assert that the response was a "parameter missing" error response.
:param response: The response object.
:param param: The name of the missing parameter.
:type param: str
"""
self.assertEqual("Parameter '%s' is required." % param,
response.json.get('message', ''))
self.assertStatus(response, 400)
def getSseMessages(self, resp):
messages = self.getBody(resp).strip().split('\n\n')
if not messages or messages == ['']:
return ()
return [json.loads(m.replace('data: ', '')) for m in messages]
def uploadFile(self, name, contents, user, parent, parentType='folder',
mimeType=None):
"""
Upload a file. This is meant for small testing files, not very large
files that should be sent in multiple chunks.
:param name: The name of the file.
:type name: str
:param contents: The file contents
:type contents: str
:param user: The user performing the upload.
:type user: dict
:param parent: The parent document.
:type parent: dict
:param parentType: The type of the parent ("folder" or "item")
:type parentType: str
:param mimeType: Explicit MIME type to set on the file.
:type mimeType: str
:returns: The file that was created.
:rtype: dict
"""
mimeType = mimeType or 'application/octet-stream'
resp = self.request(
path='/file', method='POST', user=user, params={
'parentType': parentType,
'parentId': str(parent['_id']),
'name': name,
'size': len(contents),
'mimeType': mimeType
})
self.assertStatusOk(resp)
fields = [('offset', 0), ('uploadId', resp.json['_id'])]
files = [('chunk', name, contents)]
resp = self.multipartRequest(
path='/file/chunk', user=user, fields=fields, files=files)
self.assertStatusOk(resp)
file = resp.json
self.assertHasKeys(file, ['itemId'])
self.assertEqual(file['name'], name)
self.assertEqual(file['size'], len(contents))
self.assertEqual(file['mimeType'], mimeType)
return self.model('file').load(file['_id'], force=True)
def ensureRequiredParams(self, path='/', method='GET', required=(),
user=None):
"""
Ensure that a set of parameters is required by the endpoint.
:param path: The endpoint path to test.
:param method: The HTTP method of the endpoint.
:param required: The required parameter set.
:type required: sequence of str
"""
for exclude in required:
params = dict.fromkeys([p for p in required if p != exclude], '')
resp = self.request(path=path, method=method, params=params,
user=user)
self.assertMissingParameter(resp, exclude)
def _genToken(self, user):
"""
Helper method for creating an authentication token for the user.
"""
token = self.model('token').createToken(user)
return str(token['_id'])
def _buildHeaders(self, headers, cookie, user, token, basicAuth,
authHeader):
if cookie is not None:
headers.append(('Cookie', cookie))
if user is not None:
headers.append(('Girder-Token', self._genToken(user)))
elif token is not None:
if isinstance(token, dict):
headers.append(('Girder-Token', token['_id']))
else:
headers.append(('Girder-Token', token))
if basicAuth is not None:
auth = base64.b64encode(basicAuth.encode('utf8'))
headers.append((authHeader, 'Basic %s' % auth.decode()))
def request(self, path='/', method='GET', params=None, user=None,
prefix='/api/v1', isJson=True, basicAuth=None, body=None,
type=None, exception=False, cookie=None, token=None,
additionalHeaders=None, useHttps=False,
authHeader='Girder-Authorization'):
"""
Make an HTTP request.
:param path: The path part of the URI.
:type path: str
:param method: The HTTP method.
:type method: str
:param params: The HTTP parameters.
:type params: dict
:param prefix: The prefix to use before the path.
:param isJson: Whether the response is a JSON object.
:param basicAuth: A string to pass with the Authorization: Basic header
of the form 'login:password'
:param exception: Set this to True if a 500 is expected from this call.
:param cookie: A custom cookie value to set.
:param token: If you want to use an existing token to login, pass
the token ID.
:type token: str
:param additionalHeaders: A list of headers to add to the
request. Each item is a tuple of the form
(header-name, header-value).
:param useHttps: If True, pretend to use HTTPS.
:param authHeader: The HTTP request header to use for authentication.
:type authHeader: str
:returns: The cherrypy response object from the request.
"""
if not params:
params = {}
headers = [('Host', '127.0.0.1'), ('Accept', 'application/json')]
qs = fd = None
if additionalHeaders:
headers.extend(additionalHeaders)
if method in ['POST', 'PUT', 'PATCH'] or body:
if isinstance(body, six.string_types):
body = body.encode('utf8')
qs = urllib.parse.urlencode(params).encode('utf8')
if type is None:
headers.append(('Content-Type',
'application/x-www-form-urlencoded'))
else:
headers.append(('Content-Type', type))
qs = body
headers.append(('Content-Length', '%d' % len(qs)))
fd = BytesIO(qs)
qs = None
elif params:
qs = urllib.parse.urlencode(params)
app = cherrypy.tree.apps['']
request, response = app.get_serving(
local, remote, 'http' if not useHttps else 'https', 'HTTP/1.1')
request.show_tracebacks = True
self._buildHeaders(headers, cookie, user, token, basicAuth, authHeader)
# Python2 will not match Unicode URLs
url = str(prefix + path)
try:
response = request.run(method, url, qs, 'HTTP/1.1', headers, fd)
finally:
if fd:
fd.close()
if isJson:
body = self.getBody(response)
try:
response.json = json.loads(body)
except Exception:
print(body)
raise AssertionError('Did not receive JSON response')
if not exception and response.output_status.startswith(b'500'):
raise AssertionError("Internal server error: %s" %
self.getBody(response))
return response
def getBody(self, response, text=True):
"""
Returns the response body as a text type or binary string.
:param response: The response object from the server.
:param text: If true, treat the data as a text string, otherwise, treat
as binary.
"""
data = '' if text else b''
for chunk in response.body:
if text and isinstance(chunk, six.binary_type):
chunk = chunk.decode('utf8')
elif not text and not isinstance(chunk, six.binary_type):
chunk = chunk.encode('utf8')
data += chunk
return data
def multipartRequest(self, fields, files, path, method='POST', user=None,
prefix='/api/v1', isJson=True):
"""
Make an HTTP request with multipart/form-data encoding. This can be
used to send files with the request.
:param fields: List of (name, value) tuples.
:param files: List of (name, filename, content) tuples.
:param path: The path part of the URI.
:type path: str
:param method: The HTTP method.
:type method: str
:param prefix: The prefix to use before the path.
:param isJson: Whether the response is a JSON object.
:returns: The cherrypy response object from the request.
"""
contentType, body, size = MultipartFormdataEncoder().encode(
fields, files)
headers = [('Host', '127.0.0.1'),
('Accept', 'application/json'),
('Content-Type', contentType),
('Content-Length', str(size))]
app = cherrypy.tree.apps['']
request, response = app.get_serving(local, remote, 'http', 'HTTP/1.1')
request.show_tracebacks = True
if user is not None:
headers.append(('Girder-Token', self._genToken(user)))
fd = io.BytesIO(body)
# Python2 will not match Unicode URLs
url = str(prefix + path)
try:
response = request.run(method, url, None, 'HTTP/1.1', headers, fd)
finally:
fd.close()
if isJson:
body = self.getBody(response)
try:
response.json = json.loads(body)
except Exception:
print(body)
raise AssertionError('Did not receive JSON response')
if response.output_status.startswith(b'500'):
raise AssertionError("Internal server error: %s" %
self.getBody(response))
return response
class MultipartFormdataEncoder(object):
"""
This class is adapted from http://stackoverflow.com/a/18888633/2550451
It is used as a helper for creating multipart/form-data requests to
simulate file uploads.
"""
def __init__(self):
self.boundary = uuid.uuid4().hex
self.contentType = \
'multipart/form-data; boundary=%s' % self.boundary
@classmethod
def u(cls, s):
if sys.hexversion < 0x03000000 and isinstance(s, str):
s = s.decode('utf-8')
if sys.hexversion >= 0x03000000 and isinstance(s, bytes):
s = s.decode('utf-8')
return s
def iter(self, fields, files):
encoder = codecs.getencoder('utf-8')
for (key, value) in fields:
key = self.u(key)
yield encoder('--%s\r\n' % self.boundary)
yield encoder(self.u('Content-Disposition: form-data; '
'name="%s"\r\n') % key)
yield encoder('\r\n')
if isinstance(value, int) or isinstance(value, float):
value = str(value)
yield encoder(self.u(value))
yield encoder('\r\n')
for (key, filename, content) in files:
key = self.u(key)
filename = self.u(filename)
yield encoder('--%s\r\n' % self.boundary)
yield encoder(self.u('Content-Disposition: form-data; name="%s";'
' filename="%s"\r\n' % (key, filename)))
yield encoder('Content-Type: application/octet-stream\r\n')
yield encoder('\r\n')
yield (content, len(content))
yield encoder('\r\n')
yield encoder('--%s--\r\n' % self.boundary)
def encode(self, fields, files):
body = io.BytesIO()
size = 0
for chunk, chunkLen in self.iter(fields, files):
if not isinstance(chunk, six.binary_type):
chunk = chunk.encode('utf8')
body.write(chunk)
size += chunkLen
return self.contentType, body.getvalue(), size
def _sigintHandler(*args):
print('Received SIGINT, shutting down mock SMTP server...')
mockSmtp.stop()
sys.exit(1)
signal.signal(signal.SIGINT, _sigintHandler)
|
salamb/girder
|
tests/base.py
|
Python
|
apache-2.0
| 21,800 |
# -*- coding: utf-8 -*-
'''
Module for listing programs that automatically run on startup
(very alpha...not tested on anything but my Win 7x64)
'''
# Import python libs
import os
# Import salt libs
import salt.utils
# Define a function alias in order not to shadow built-in's
__func_alias__ = {
'list_': 'list'
}
# Define the module's virtual name
__virtualname__ = 'autoruns'
def __virtual__():
'''
Only works on Windows systems
'''
if salt.utils.is_windows():
return __virtualname__
return False
def list_():
'''
Get a list of automatically running programs
CLI Example:
.. code-block:: bash
salt '*' autoruns.list
'''
autoruns = {}
# Find autoruns in registry
keys = ['HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run',
'HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /reg:64',
'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
]
winver = __grains__['osfullname']
for key in keys:
autoruns[key] = []
cmd = 'reg query ' + key
print cmd
for line in __salt__['cmd.run'](cmd).splitlines():
if line and line[0:4] != "HKEY" and line[0:5] != "ERROR": # Remove junk lines
autoruns[key].append(line)
# Find autoruns in user's startup folder
if '7' in winver:
user_dir = 'C:\\Users\\'
startup_dir = '\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup'
else:
user_dir = 'C:\\Documents and Settings\\'
startup_dir = '\\Start Menu\\Programs\\Startup'
for user in os.listdir(user_dir):
try:
full_dir = user_dir + user + startup_dir
files = os.listdir(full_dir)
autoruns[full_dir] = []
for afile in files:
autoruns[full_dir].append(afile)
except Exception:
pass
return autoruns
|
victorywang80/Maintenance
|
saltstack/src/salt/modules/win_autoruns.py
|
Python
|
apache-2.0
| 1,932 |
package com.github.snailycy.androidhybridlib;
import android.widget.Toast;
import com.github.snailycy.hybridlib.bridge.BaseJSPluginSync;
import org.json.JSONObject;
/**
* Created by ycy on 2017/9/27.
*/
public class JSGetCachePlugin extends BaseJSPluginSync {
@Override
public String jsCallNative(String requestParams) {
Toast.makeText(getContext(), "jsCallNative , requestParams = " + requestParams, Toast.LENGTH_LONG).show();
try {
JSONObject jsonObject1 = new JSONObject(requestParams);
JSONObject jsonObject = new JSONObject();
jsonObject.put("aaa", "hahahahah");
return jsonObject.toString();
} catch (Exception e) {
}
return null;
}
}
|
snailycy/AndroidHybridLib
|
sample/src/main/java/com/github/snailycy/androidhybridlib/JSGetCachePlugin.java
|
Java
|
apache-2.0
| 748 |
/**
* Copyright (c) 2016-present, RxJava Contributors.
*
* 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 io.reactivex;
import java.util.NoSuchElementException;
import java.util.concurrent.*;
import org.reactivestreams.*;
import io.reactivex.annotations.*;
import io.reactivex.disposables.Disposable;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.functions.*;
import io.reactivex.internal.functions.*;
import io.reactivex.internal.fuseable.*;
import io.reactivex.internal.observers.BlockingMultiObserver;
import io.reactivex.internal.operators.flowable.*;
import io.reactivex.internal.operators.maybe.*;
import io.reactivex.internal.operators.mixed.*;
import io.reactivex.internal.util.*;
import io.reactivex.observers.TestObserver;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.schedulers.Schedulers;
/**
* The {@code Maybe} class represents a deferred computation and emission of a single value, no value at all or an exception.
* <p>
* The {@code Maybe} class implements the {@link MaybeSource} base interface and the default consumer
* type it interacts with is the {@link MaybeObserver} via the {@link #subscribe(MaybeObserver)} method.
* <p>
* The {@code Maybe} operates with the following sequential protocol:
* <pre><code>
* onSubscribe (onSuccess | onError | onComplete)?
* </code></pre>
* <p>
* Note that {@code onSuccess}, {@code onError} and {@code onComplete} are mutually exclusive events; unlike {@code Observable},
* {@code onSuccess} is never followed by {@code onError} or {@code onComplete}.
* <p>
* Like {@link Observable}, a running {@code Maybe} can be stopped through the {@link Disposable} instance
* provided to consumers through {@link MaybeObserver#onSubscribe}.
* <p>
* Like an {@code Observable}, a {@code Maybe} is lazy, can be either "hot" or "cold", synchronous or
* asynchronous. {@code Maybe} instances returned by the methods of this class are <em>cold</em>
* and there is a standard <em>hot</em> implementation in the form of a subject:
* {@link io.reactivex.subjects.MaybeSubject MaybeSubject}.
* <p>
* The documentation for this class makes use of marble diagrams. The following legend explains these diagrams:
* <p>
* <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/maybe.png" alt="">
* <p>
* See {@link Flowable} or {@link Observable} for the
* implementation of the Reactive Pattern for a stream or vector of values.
* <p>
* Example:
* <pre><code>
* Disposable d = Maybe.just("Hello World")
* .delay(10, TimeUnit.SECONDS, Schedulers.io())
* .subscribeWith(new DisposableMaybeObserver<String>() {
* @Override
* public void onStart() {
* System.out.println("Started");
* }
*
* @Override
* public void onSuccess(String value) {
* System.out.println("Success: " + value);
* }
*
* @Override
* public void onError(Throwable error) {
* error.printStackTrace();
* }
*
* @Override
* public void onComplete() {
* System.out.println("Done!");
* }
* });
*
* Thread.sleep(5000);
*
* d.dispose();
* </code></pre>
* <p>
* Note that by design, subscriptions via {@link #subscribe(MaybeObserver)} can't be disposed
* from the outside (hence the
* {@code void} return of the {@link #subscribe(MaybeObserver)} method) and it is the
* responsibility of the implementor of the {@code MaybeObserver} to allow this to happen.
* RxJava supports such usage with the standard
* {@link io.reactivex.observers.DisposableMaybeObserver DisposableMaybeObserver} instance.
* For convenience, the {@link #subscribeWith(MaybeObserver)} method is provided as well to
* allow working with a {@code MaybeObserver} (or subclass) instance to be applied with in
* a fluent manner (such as in the example above).
*
* @param <T> the value type
* @since 2.0
* @see io.reactivex.observers.DisposableMaybeObserver
*/
public abstract class Maybe<T> implements MaybeSource<T> {
/**
* Runs multiple MaybeSources and signals the events of the first one that signals (disposing
* the rest).
* <p>
* <img width="640" height="519" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.amb.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <T> the value type
* @param sources the Iterable sequence of sources. A subscription to each source will
* occur in the same order as in the Iterable.
* @return the new Maybe instance
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Maybe<T> amb(final Iterable<? extends MaybeSource<? extends T>> sources) {
ObjectHelper.requireNonNull(sources, "sources is null");
return RxJavaPlugins.onAssembly(new MaybeAmb<T>(null, sources));
}
/**
* Runs multiple MaybeSources and signals the events of the first one that signals (disposing
* the rest).
* <p>
* <img width="640" height="519" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.ambArray.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code ambArray} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <T> the value type
* @param sources the array of sources. A subscription to each source will
* occur in the same order as in the array.
* @return the new Maybe instance
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
@SuppressWarnings("unchecked")
public static <T> Maybe<T> ambArray(final MaybeSource<? extends T>... sources) {
if (sources.length == 0) {
return empty();
}
if (sources.length == 1) {
return wrap((MaybeSource<T>)sources[0]);
}
return RxJavaPlugins.onAssembly(new MaybeAmb<T>(sources, null));
}
/**
* Concatenate the single values, in a non-overlapping fashion, of the MaybeSource sources provided by
* an Iterable sequence.
* <p>
* <img width="640" height="526" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concat.i.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <T> the value type
* @param sources the Iterable sequence of MaybeSource instances
* @return the new Flowable instance
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Flowable<T> concat(Iterable<? extends MaybeSource<? extends T>> sources) {
ObjectHelper.requireNonNull(sources, "sources is null");
return RxJavaPlugins.onAssembly(new MaybeConcatIterable<T>(sources));
}
/**
* Returns a Flowable that emits the items emitted by two MaybeSources, one after the other.
* <p>
* <img width="640" height="422" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concat.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T> the common value type
* @param source1
* a MaybeSource to be concatenated
* @param source2
* a MaybeSource to be concatenated
* @return a Flowable that emits items emitted by the two source MaybeSources, one after the other.
* @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a>
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
@SuppressWarnings("unchecked")
public static <T> Flowable<T> concat(MaybeSource<? extends T> source1, MaybeSource<? extends T> source2) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
return concatArray(source1, source2);
}
/**
* Returns a Flowable that emits the items emitted by three MaybeSources, one after the other.
* <p>
* <img width="640" height="422" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concat.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T> the common value type
* @param source1
* a MaybeSource to be concatenated
* @param source2
* a MaybeSource to be concatenated
* @param source3
* a MaybeSource to be concatenated
* @return a Flowable that emits items emitted by the three source MaybeSources, one after the other.
* @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a>
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
@SuppressWarnings("unchecked")
public static <T> Flowable<T> concat(
MaybeSource<? extends T> source1, MaybeSource<? extends T> source2, MaybeSource<? extends T> source3) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
ObjectHelper.requireNonNull(source3, "source3 is null");
return concatArray(source1, source2, source3);
}
/**
* Returns a Flowable that emits the items emitted by four MaybeSources, one after the other.
* <p>
* <img width="640" height="422" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concat.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T> the common value type
* @param source1
* a MaybeSource to be concatenated
* @param source2
* a MaybeSource to be concatenated
* @param source3
* a MaybeSource to be concatenated
* @param source4
* a MaybeSource to be concatenated
* @return a Flowable that emits items emitted by the four source MaybeSources, one after the other.
* @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a>
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
@SuppressWarnings("unchecked")
public static <T> Flowable<T> concat(
MaybeSource<? extends T> source1, MaybeSource<? extends T> source2, MaybeSource<? extends T> source3, MaybeSource<? extends T> source4) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
ObjectHelper.requireNonNull(source3, "source3 is null");
ObjectHelper.requireNonNull(source4, "source4 is null");
return concatArray(source1, source2, source3, source4);
}
/**
* Concatenate the single values, in a non-overlapping fashion, of the MaybeSource sources provided by
* a Publisher sequence.
* <p>
* <img width="640" height="416" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concat.p.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer and
* expects the {@code Publisher} to honor backpressure as well. If the sources {@code Publisher}
* violates this, a {@link io.reactivex.exceptions.MissingBackpressureException} is signalled.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <T> the value type
* @param sources the Publisher of MaybeSource instances
* @return the new Flowable instance
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Flowable<T> concat(Publisher<? extends MaybeSource<? extends T>> sources) {
return concat(sources, 2);
}
/**
* Concatenate the single values, in a non-overlapping fashion, of the MaybeSource sources provided by
* a Publisher sequence.
* <p>
* <img width="640" height="416" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concat.pn.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer and
* expects the {@code Publisher} to honor backpressure as well. If the sources {@code Publisher}
* violates this, a {@link io.reactivex.exceptions.MissingBackpressureException} is signalled.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <T> the value type
* @param sources the Publisher of MaybeSource instances
* @param prefetch the number of MaybeSources to prefetch from the Publisher
* @return the new Flowable instance
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> Flowable<T> concat(Publisher<? extends MaybeSource<? extends T>> sources, int prefetch) {
ObjectHelper.requireNonNull(sources, "sources is null");
ObjectHelper.verifyPositive(prefetch, "prefetch");
return RxJavaPlugins.onAssembly(new FlowableConcatMapPublisher(sources, MaybeToPublisher.instance(), prefetch, ErrorMode.IMMEDIATE));
}
/**
* Concatenate the single values, in a non-overlapping fashion, of the MaybeSource sources in the array.
* <p>
* <img width="640" height="526" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatArray.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code concatArray} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <T> the value type
* @param sources the array of MaybeSource instances
* @return the new Flowable instance
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
@SuppressWarnings("unchecked")
public static <T> Flowable<T> concatArray(MaybeSource<? extends T>... sources) {
ObjectHelper.requireNonNull(sources, "sources is null");
if (sources.length == 0) {
return Flowable.empty();
}
if (sources.length == 1) {
return RxJavaPlugins.onAssembly(new MaybeToFlowable<T>((MaybeSource<T>)sources[0]));
}
return RxJavaPlugins.onAssembly(new MaybeConcatArray<T>(sources));
}
/**
* Concatenates a variable number of MaybeSource sources and delays errors from any of them
* till all terminate.
* <p>
* <img width="640" height="425" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatArrayDelayError.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code concatArrayDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param sources the array of sources
* @param <T> the common base value type
* @return the new Flowable instance
* @throws NullPointerException if sources is null
*/
@SuppressWarnings("unchecked")
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Flowable<T> concatArrayDelayError(MaybeSource<? extends T>... sources) {
if (sources.length == 0) {
return Flowable.empty();
} else
if (sources.length == 1) {
return RxJavaPlugins.onAssembly(new MaybeToFlowable<T>((MaybeSource<T>)sources[0]));
}
return RxJavaPlugins.onAssembly(new MaybeConcatArrayDelayError<T>(sources));
}
/**
* Concatenates a sequence of MaybeSource eagerly into a single stream of values.
* <p>
* Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the
* source MaybeSources. The operator buffers the value emitted by these MaybeSources and then drains them
* in order, each one after the previous one completes.
* <p>
* <img width="640" height="489" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatArrayEager.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>This method does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <T> the value type
* @param sources a sequence of MaybeSources that need to be eagerly concatenated
* @return the new Flowable instance with the specified concatenation behavior
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Flowable<T> concatArrayEager(MaybeSource<? extends T>... sources) {
return Flowable.fromArray(sources).concatMapEager((Function)MaybeToPublisher.instance());
}
/**
* Concatenates the Iterable sequence of MaybeSources into a single sequence by subscribing to each MaybeSource,
* one after the other, one at a time and delays any errors till the all inner MaybeSources terminate.
* <p>
* <img width="640" height="469" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatDelayError.i.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code concatDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T> the common element base type
* @param sources the Iterable sequence of MaybeSources
* @return the new Flowable with the concatenating behavior
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Flowable<T> concatDelayError(Iterable<? extends MaybeSource<? extends T>> sources) {
ObjectHelper.requireNonNull(sources, "sources is null");
return Flowable.fromIterable(sources).concatMapDelayError((Function)MaybeToPublisher.instance());
}
/**
* Concatenates the Publisher sequence of Publishers into a single sequence by subscribing to each inner Publisher,
* one after the other, one at a time and delays any errors till the all inner and the outer Publishers terminate.
* <p>
* <img width="640" height="360" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatDelayError.p.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>{@code concatDelayError} fully supports backpressure.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code concatDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T> the common element base type
* @param sources the Publisher sequence of Publishers
* @return the new Publisher with the concatenating behavior
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Flowable<T> concatDelayError(Publisher<? extends MaybeSource<? extends T>> sources) {
return Flowable.fromPublisher(sources).concatMapDelayError((Function)MaybeToPublisher.instance());
}
/**
* Concatenates a sequence of MaybeSources eagerly into a single stream of values.
* <p>
* Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the
* source MaybeSources. The operator buffers the values emitted by these MaybeSources and then drains them
* in order, each one after the previous one completes.
* <p>
* <img width="640" height="526" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatEager.i.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>Backpressure is honored towards the downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>This method does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <T> the value type
* @param sources a sequence of MaybeSource that need to be eagerly concatenated
* @return the new Flowable instance with the specified concatenation behavior
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Flowable<T> concatEager(Iterable<? extends MaybeSource<? extends T>> sources) {
return Flowable.fromIterable(sources).concatMapEager((Function)MaybeToPublisher.instance());
}
/**
* Concatenates a Publisher sequence of MaybeSources eagerly into a single stream of values.
* <p>
* Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the
* emitted source Publishers as they are observed. The operator buffers the values emitted by these
* Publishers and then drains them in order, each one after the previous one completes.
* <p>
* <img width="640" height="511" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.concatEager.p.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>Backpressure is honored towards the downstream and the outer Publisher is
* expected to support backpressure. Violating this assumption, the operator will
* signal {@link io.reactivex.exceptions.MissingBackpressureException}.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>This method does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <T> the value type
* @param sources a sequence of Publishers that need to be eagerly concatenated
* @return the new Publisher instance with the specified concatenation behavior
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Flowable<T> concatEager(Publisher<? extends MaybeSource<? extends T>> sources) {
return Flowable.fromPublisher(sources).concatMapEager((Function)MaybeToPublisher.instance());
}
/**
* Provides an API (via a cold Maybe) that bridges the reactive world with the callback-style world.
* <p>
* Example:
* <pre><code>
* Maybe.<Event>create(emitter -> {
* Callback listener = new Callback() {
* @Override
* public void onEvent(Event e) {
* if (e.isNothing()) {
* emitter.onComplete();
* } else {
* emitter.onSuccess(e);
* }
* }
*
* @Override
* public void onFailure(Exception e) {
* emitter.onError(e);
* }
* };
*
* AutoCloseable c = api.someMethod(listener);
*
* emitter.setCancellable(c::close);
*
* });
* </code></pre>
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code create} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <T> the value type
* @param onSubscribe the emitter that is called when a MaybeObserver subscribes to the returned {@code Maybe}
* @return the new Maybe instance
* @see MaybeOnSubscribe
* @see Cancellable
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Maybe<T> create(MaybeOnSubscribe<T> onSubscribe) {
ObjectHelper.requireNonNull(onSubscribe, "onSubscribe is null");
return RxJavaPlugins.onAssembly(new MaybeCreate<T>(onSubscribe));
}
/**
* Calls a Callable for each individual MaybeObserver to return the actual MaybeSource source to
* be subscribed to.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code defer} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <T> the value type
* @param maybeSupplier the Callable that is called for each individual MaybeObserver and
* returns a MaybeSource instance to subscribe to
* @return the new Maybe instance
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Maybe<T> defer(final Callable<? extends MaybeSource<? extends T>> maybeSupplier) {
ObjectHelper.requireNonNull(maybeSupplier, "maybeSupplier is null");
return RxJavaPlugins.onAssembly(new MaybeDefer<T>(maybeSupplier));
}
/**
* Returns a (singleton) Maybe instance that calls {@link MaybeObserver#onComplete onComplete}
* immediately.
* <p>
* <img width="640" height="190" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/empty.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code empty} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <T> the value type
* @return the new Maybe instance
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
@SuppressWarnings("unchecked")
public static <T> Maybe<T> empty() {
return RxJavaPlugins.onAssembly((Maybe<T>)MaybeEmpty.INSTANCE);
}
/**
* Returns a Maybe that invokes a subscriber's {@link MaybeObserver#onError onError} method when the
* subscriber subscribes to it.
* <p>
* <img width="640" height="447" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.error.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code error} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param exception
* the particular Throwable to pass to {@link MaybeObserver#onError onError}
* @param <T>
* the type of the item (ostensibly) emitted by the Maybe
* @return a Maybe that invokes the subscriber's {@link MaybeObserver#onError onError} method when
* the subscriber subscribes to it
* @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Throw</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Maybe<T> error(Throwable exception) {
ObjectHelper.requireNonNull(exception, "exception is null");
return RxJavaPlugins.onAssembly(new MaybeError<T>(exception));
}
/**
* Returns a Maybe that invokes a {@link MaybeObserver}'s {@link MaybeObserver#onError onError} method when the
* MaybeObserver subscribes to it.
* <p>
* <img width="640" height="190" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/error.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code error} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param supplier
* a Callable factory to return a Throwable for each individual MaybeObserver
* @param <T>
* the type of the items (ostensibly) emitted by the Maybe
* @return a Maybe that invokes the {@link MaybeObserver}'s {@link MaybeObserver#onError onError} method when
* the MaybeObserver subscribes to it
* @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Throw</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Maybe<T> error(Callable<? extends Throwable> supplier) {
ObjectHelper.requireNonNull(supplier, "errorSupplier is null");
return RxJavaPlugins.onAssembly(new MaybeErrorCallable<T>(supplier));
}
/**
* Returns a Maybe instance that runs the given Action for each subscriber and
* emits either its exception or simply completes.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code fromAction} does not operate by default on a particular {@link Scheduler}.</dd>
* <dt><b>Error handling:</b></dt>
* <dd> If the {@link Action} throws an exception, the respective {@link Throwable} is
* delivered to the downstream via {@link MaybeObserver#onError(Throwable)},
* except when the downstream has disposed this {@code Maybe} source.
* In this latter case, the {@code Throwable} is delivered to the global error handler via
* {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}.
* </dd>
* </dl>
* @param <T> the target type
* @param run the runnable to run for each subscriber
* @return the new Maybe instance
* @throws NullPointerException if run is null
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Maybe<T> fromAction(final Action run) {
ObjectHelper.requireNonNull(run, "run is null");
return RxJavaPlugins.onAssembly(new MaybeFromAction<T>(run));
}
/**
* Wraps a CompletableSource into a Maybe.
*
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code fromCompletable} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <T> the target type
* @param completableSource the CompletableSource to convert from
* @return the new Maybe instance
* @throws NullPointerException if completable is null
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Maybe<T> fromCompletable(CompletableSource completableSource) {
ObjectHelper.requireNonNull(completableSource, "completableSource is null");
return RxJavaPlugins.onAssembly(new MaybeFromCompletable<T>(completableSource));
}
/**
* Wraps a SingleSource into a Maybe.
*
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code fromSingle} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <T> the target type
* @param singleSource the SingleSource to convert from
* @return the new Maybe instance
* @throws NullPointerException if single is null
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Maybe<T> fromSingle(SingleSource<T> singleSource) {
ObjectHelper.requireNonNull(singleSource, "singleSource is null");
return RxJavaPlugins.onAssembly(new MaybeFromSingle<T>(singleSource));
}
/**
* Returns a {@link Maybe} that invokes the given {@link Callable} for each individual {@link MaybeObserver} that
* subscribes and emits the resulting non-null item via {@code onSuccess} while
* considering a {@code null} result from the {@code Callable} as indication for valueless completion
* via {@code onComplete}.
* <p>
* This operator allows you to defer the execution of the given {@code Callable} until a {@code MaybeObserver}
* subscribes to the returned {@link Maybe}. In other terms, this source operator evaluates the given
* {@code Callable} "lazily".
* <p>
* Note that the {@code null} handling of this operator differs from the similar source operators in the other
* {@link io.reactivex base reactive classes}. Those operators signal a {@code NullPointerException} if the value returned by their
* {@code Callable} is {@code null} while this {@code fromCallable} considers it to indicate the
* returned {@code Maybe} is empty.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code fromCallable} does not operate by default on a particular {@link Scheduler}.</dd>
* <dt><b>Error handling:</b></dt>
* <dd>Any non-fatal exception thrown by {@link Callable#call()} will be forwarded to {@code onError},
* except if the {@code MaybeObserver} disposed the subscription in the meantime. In this latter case,
* the exception is forwarded to the global error handler via
* {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} wrapped into a
* {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}.
* Fatal exceptions are rethrown and usually will end up in the executing thread's
* {@link java.lang.Thread.UncaughtExceptionHandler#uncaughtException(Thread, Throwable)} handler.</dd>
* </dl>
*
* @param callable
* a {@link Callable} instance whose execution should be deferred and performed for each individual
* {@code MaybeObserver} that subscribes to the returned {@link Maybe}.
* @param <T>
* the type of the item emitted by the {@link Maybe}.
* @return a new Maybe instance
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Maybe<T> fromCallable(@NonNull final Callable<? extends T> callable) {
ObjectHelper.requireNonNull(callable, "callable is null");
return RxJavaPlugins.onAssembly(new MaybeFromCallable<T>(callable));
}
/**
* Converts a {@link Future} into a Maybe, treating a null result as an indication of emptiness.
* <p>
* <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/from.Future.png" alt="">
* <p>
* You can convert any object that supports the {@link Future} interface into a Maybe 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 Maybe is blocking; you cannot dispose it.
* <p>
* Unlike 1.x, disposing the Maybe won't cancel the future. If necessary, one can use composition to achieve the
* cancellation effect: {@code futureMaybe.doOnDispose(() -> future.cancel(true));}.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code fromFuture} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @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 Maybe
* @return a Maybe that emits the item from the source {@link Future}
* @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Maybe<T> fromFuture(Future<? extends T> future) {
ObjectHelper.requireNonNull(future, "future is null");
return RxJavaPlugins.onAssembly(new MaybeFromFuture<T>(future, 0L, null));
}
/**
* Converts a {@link Future} into a Maybe, with a timeout on the Future.
* <p>
* <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/from.Future.png" alt="">
* <p>
* You can convert any object that supports the {@link Future} interface into a Maybe that emits the
* return value of the {@link Future#get} method of that object, by passing the object into the {@code fromFuture}
* method.
* <p>
* Unlike 1.x, disposing the Maybe won't cancel the future. If necessary, one can use composition to achieve the
* cancellation effect: {@code futureMaybe.doOnCancel(() -> future.cancel(true));}.
* <p>
* <em>Important note:</em> This Maybe is blocking on the thread it gets subscribed on; you cannot dispose it.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code fromFuture} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @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 Maybe
* @return a Maybe that emits the item from the source {@link Future}
* @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Maybe<T> fromFuture(Future<? extends T> future, long timeout, TimeUnit unit) {
ObjectHelper.requireNonNull(future, "future is null");
ObjectHelper.requireNonNull(unit, "unit is null");
return RxJavaPlugins.onAssembly(new MaybeFromFuture<T>(future, timeout, unit));
}
/**
* Returns a Maybe instance that runs the given Action for each subscriber and
* emits either its exception or simply completes.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code fromRunnable} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <T> the target type
* @param run the runnable to run for each subscriber
* @return the new Maybe instance
* @throws NullPointerException if run is null
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Maybe<T> fromRunnable(final Runnable run) {
ObjectHelper.requireNonNull(run, "run is null");
return RxJavaPlugins.onAssembly(new MaybeFromRunnable<T>(run));
}
/**
* Returns a {@code Maybe} that emits a specified item.
* <p>
* <img width="640" height="485" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.just.png" alt="">
* <p>
* To convert any object into a {@code Maybe} that emits that object, pass that object into the
* {@code just} method.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param item
* the item to emit
* @param <T>
* the type of that item
* @return a {@code Maybe} that emits {@code item}
* @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Maybe<T> just(T item) {
ObjectHelper.requireNonNull(item, "item is null");
return RxJavaPlugins.onAssembly(new MaybeJust<T>(item));
}
/**
* Merges an Iterable sequence of MaybeSource instances into a single Flowable sequence,
* running all MaybeSources at once.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd>
* <dt><b>Error handling:</b></dt>
* <dd>If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting
* {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed.
* If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the
* first one's error or, depending on the concurrency of the sources, may terminate with a
* {@code CompositeException} containing two or more of the various error signals.
* {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via
* {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s
* signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a
* (composite) error will be sent to the same global error handler.
* Use {@link #mergeDelayError(Iterable)} to merge sources and terminate only when all source {@code MaybeSource}s
* have completed or failed with an error.
* </dd>
* </dl>
* @param <T> the common and resulting value type
* @param sources the Iterable sequence of MaybeSource sources
* @return the new Flowable instance
* @see #mergeDelayError(Iterable)
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Flowable<T> merge(Iterable<? extends MaybeSource<? extends T>> sources) {
return merge(Flowable.fromIterable(sources));
}
/**
* Merges a Flowable sequence of MaybeSource instances into a single Flowable sequence,
* running all MaybeSources at once.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd>
* <dt><b>Error handling:</b></dt>
* <dd>If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting
* {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed.
* If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the
* first one's error or, depending on the concurrency of the sources, may terminate with a
* {@code CompositeException} containing two or more of the various error signals.
* {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via
* {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s
* signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a
* (composite) error will be sent to the same global error handler.
* Use {@link #mergeDelayError(Publisher)} to merge sources and terminate only when all source {@code MaybeSource}s
* have completed or failed with an error.
* </dd>
* </dl>
* @param <T> the common and resulting value type
* @param sources the Flowable sequence of MaybeSource sources
* @return the new Flowable instance
* @see #mergeDelayError(Publisher)
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Flowable<T> merge(Publisher<? extends MaybeSource<? extends T>> sources) {
return merge(sources, Integer.MAX_VALUE);
}
/**
* Merges a Flowable sequence of MaybeSource instances into a single Flowable sequence,
* running at most maxConcurrency MaybeSources at once.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd>
* <dt><b>Error handling:</b></dt>
* <dd>If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting
* {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed.
* If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the
* first one's error or, depending on the concurrency of the sources, may terminate with a
* {@code CompositeException} containing two or more of the various error signals.
* {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via
* {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s
* signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a
* (composite) error will be sent to the same global error handler.
* Use {@link #mergeDelayError(Publisher, int)} to merge sources and terminate only when all source {@code MaybeSource}s
* have completed or failed with an error.
* </dd>
* </dl>
* @param <T> the common and resulting value type
* @param sources the Flowable sequence of MaybeSource sources
* @param maxConcurrency the maximum number of concurrently running MaybeSources
* @return the new Flowable instance
* @see #mergeDelayError(Publisher, int)
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> Flowable<T> merge(Publisher<? extends MaybeSource<? extends T>> sources, int maxConcurrency) {
ObjectHelper.requireNonNull(sources, "source is null");
ObjectHelper.verifyPositive(maxConcurrency, "maxConcurrency");
return RxJavaPlugins.onAssembly(new FlowableFlatMapPublisher(sources, MaybeToPublisher.instance(), false, maxConcurrency, 1));
}
/**
* Flattens a {@code MaybeSource} that emits a {@code MaybeSource} into a single {@code MaybeSource} that emits the item
* emitted by the nested {@code MaybeSource}, without any transformation.
* <p>
* <img width="640" height="393" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.merge.oo.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd>
* <dt><b>Error handling:</b></dt>
* <dd>The resulting {@code Maybe} emits the outer source's or the inner {@code MaybeSource}'s {@code Throwable} as is.
* Unlike the other {@code merge()} operators, this operator won't and can't produce a {@code CompositeException} because there is
* only one possibility for the outer or the inner {@code MaybeSource} to emit an {@code onError} signal.
* Therefore, there is no need for a {@code mergeDelayError(MaybeSource<MaybeSource<T>>)} operator.
* </dd>
* </dl>
*
* @param <T> the value type of the sources and the output
* @param source
* a {@code MaybeSource} that emits a {@code MaybeSource}
* @return a {@code Maybe} that emits the item that is the result of flattening the {@code MaybeSource} emitted
* by {@code source}
* @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> Maybe<T> merge(MaybeSource<? extends MaybeSource<? extends T>> source) {
ObjectHelper.requireNonNull(source, "source is null");
return RxJavaPlugins.onAssembly(new MaybeFlatten(source, Functions.identity()));
}
/**
* Flattens two MaybeSources into a single Flowable, without any transformation.
* <p>
* <img width="640" height="483" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.merge.png" alt="">
* <p>
* You can combine items emitted by multiple MaybeSources so that they appear as a single Flowable, by
* using the {@code merge} method.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd>
* <dt><b>Error handling:</b></dt>
* <dd>If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting
* {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed.
* If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the
* first one's error or, depending on the concurrency of the sources, may terminate with a
* {@code CompositeException} containing two or more of the various error signals.
* {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via
* {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s
* signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a
* (composite) error will be sent to the same global error handler.
* Use {@link #mergeDelayError(MaybeSource, MaybeSource)} to merge sources and terminate only when all source {@code MaybeSource}s
* have completed or failed with an error.
* </dd>
* </dl>
*
* @param <T> the common value type
* @param source1
* a MaybeSource to be merged
* @param source2
* a MaybeSource to be merged
* @return a Flowable that emits all of the items emitted by the source MaybeSources
* @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a>
* @see #mergeDelayError(MaybeSource, MaybeSource)
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
@SuppressWarnings("unchecked")
public static <T> Flowable<T> merge(
MaybeSource<? extends T> source1, MaybeSource<? extends T> source2
) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
return mergeArray(source1, source2);
}
/**
* Flattens three MaybeSources into a single Flowable, without any transformation.
* <p>
* <img width="640" height="483" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.merge.png" alt="">
* <p>
* You can combine items emitted by multiple MaybeSources so that they appear as a single Flowable, by using
* the {@code merge} method.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd>
* <dt><b>Error handling:</b></dt>
* <dd>If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting
* {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed.
* If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the
* first one's error or, depending on the concurrency of the sources, may terminate with a
* {@code CompositeException} containing two or more of the various error signals.
* {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via
* {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s
* signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a
* (composite) error will be sent to the same global error handler.
* Use {@link #mergeDelayError(MaybeSource, MaybeSource, MaybeSource)} to merge sources and terminate only when all source {@code MaybeSource}s
* have completed or failed with an error.
* </dd>
* </dl>
*
* @param <T> the common value type
* @param source1
* a MaybeSource to be merged
* @param source2
* a MaybeSource to be merged
* @param source3
* a MaybeSource to be merged
* @return a Flowable that emits all of the items emitted by the source MaybeSources
* @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a>
* @see #mergeDelayError(MaybeSource, MaybeSource, MaybeSource)
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
@SuppressWarnings("unchecked")
public static <T> Flowable<T> merge(
MaybeSource<? extends T> source1, MaybeSource<? extends T> source2,
MaybeSource<? extends T> source3
) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
ObjectHelper.requireNonNull(source3, "source3 is null");
return mergeArray(source1, source2, source3);
}
/**
* Flattens four MaybeSources into a single Flowable, without any transformation.
* <p>
* <img width="640" height="483" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.merge.png" alt="">
* <p>
* You can combine items emitted by multiple MaybeSources so that they appear as a single Flowable, by using
* the {@code merge} method.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd>
* <dt><b>Error handling:</b></dt>
* <dd>If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting
* {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed.
* If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the
* first one's error or, depending on the concurrency of the sources, may terminate with a
* {@code CompositeException} containing two or more of the various error signals.
* {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via
* {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s
* signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a
* (composite) error will be sent to the same global error handler.
* Use {@link #mergeDelayError(MaybeSource, MaybeSource, MaybeSource, MaybeSource)} to merge sources and terminate only when all source {@code MaybeSource}s
* have completed or failed with an error.
* </dd>
* </dl>
*
* @param <T> the common value type
* @param source1
* a MaybeSource to be merged
* @param source2
* a MaybeSource to be merged
* @param source3
* a MaybeSource to be merged
* @param source4
* a MaybeSource to be merged
* @return a Flowable that emits all of the items emitted by the source MaybeSources
* @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a>
* @see #mergeDelayError(MaybeSource, MaybeSource, MaybeSource, MaybeSource)
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
@SuppressWarnings("unchecked")
public static <T> Flowable<T> merge(
MaybeSource<? extends T> source1, MaybeSource<? extends T> source2,
MaybeSource<? extends T> source3, MaybeSource<? extends T> source4
) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
ObjectHelper.requireNonNull(source3, "source3 is null");
ObjectHelper.requireNonNull(source4, "source4 is null");
return mergeArray(source1, source2, source3, source4);
}
/**
* Merges an array sequence of MaybeSource instances into a single Flowable sequence,
* running all MaybeSources at once.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code mergeArray} does not operate by default on a particular {@link Scheduler}.</dd>
* <dt><b>Error handling:</b></dt>
* <dd>If any of the source {@code MaybeSource}s signal a {@code Throwable} via {@code onError}, the resulting
* {@code Flowable} terminates with that {@code Throwable} and all other source {@code MaybeSource}s are disposed.
* If more than one {@code MaybeSource} signals an error, the resulting {@code Flowable} may terminate with the
* first one's error or, depending on the concurrency of the sources, may terminate with a
* {@code CompositeException} containing two or more of the various error signals.
* {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via
* {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors. Similarly, {@code Throwable}s
* signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a
* (composite) error will be sent to the same global error handler.
* Use {@link #mergeArrayDelayError(MaybeSource...)} to merge sources and terminate only when all source {@code MaybeSource}s
* have completed or failed with an error.
* </dd>
* </dl>
* @param <T> the common and resulting value type
* @param sources the array sequence of MaybeSource sources
* @return the new Flowable instance
* @see #mergeArrayDelayError(MaybeSource...)
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
@SuppressWarnings("unchecked")
public static <T> Flowable<T> mergeArray(MaybeSource<? extends T>... sources) {
ObjectHelper.requireNonNull(sources, "sources is null");
if (sources.length == 0) {
return Flowable.empty();
}
if (sources.length == 1) {
return RxJavaPlugins.onAssembly(new MaybeToFlowable<T>((MaybeSource<T>)sources[0]));
}
return RxJavaPlugins.onAssembly(new MaybeMergeArray<T>(sources));
}
/**
* Flattens an array of MaybeSources into one Flowable, in a way that allows a Subscriber to receive all
* successfully emitted items from each of the source MaybeSources without being interrupted by an error
* notification from one of them.
* <p>
* This behaves like {@link #merge(Publisher)} except that if any of the merged MaybeSources notify of an
* error via {@link Subscriber#onError onError}, {@code mergeDelayError} will refrain from propagating that
* error notification until all of the merged MaybeSources have finished emitting items.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.png" alt="">
* <p>
* Even if multiple merged MaybeSources send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Subscribers once.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code mergeArrayDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T> the common element base type
* @param sources
* the Iterable of MaybeSources
* @return a Flowable that emits items that are the result of flattening the items emitted by the
* MaybeSources in the Iterable
* @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a>
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Flowable<T> mergeArrayDelayError(MaybeSource<? extends T>... sources) {
if (sources.length == 0) {
return Flowable.empty();
}
return Flowable.fromArray(sources).flatMap((Function)MaybeToPublisher.instance(), true, sources.length);
}
/**
* Flattens an Iterable of MaybeSources into one Flowable, in a way that allows a Subscriber to receive all
* successfully emitted items from each of the source MaybeSources without being interrupted by an error
* notification from one of them.
* <p>
* This behaves like {@link #merge(Publisher)} except that if any of the merged MaybeSources notify of an
* error via {@link Subscriber#onError onError}, {@code mergeDelayError} will refrain from propagating that
* error notification until all of the merged MaybeSources have finished emitting items.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.png" alt="">
* <p>
* Even if multiple merged MaybeSources send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Subscribers once.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T> the common element base type
* @param sources
* the Iterable of MaybeSources
* @return a Flowable that emits items that are the result of flattening the items emitted by the
* MaybeSources in the Iterable
* @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a>
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Flowable<T> mergeDelayError(Iterable<? extends MaybeSource<? extends T>> sources) {
return Flowable.fromIterable(sources).flatMap((Function)MaybeToPublisher.instance(), true);
}
/**
* Flattens a Publisher that emits MaybeSources into one Publisher, in a way that allows a Subscriber to
* receive all successfully emitted items from all of the source MaybeSources without being interrupted by
* an error notification from one of them or even the main Publisher.
* <p>
* This behaves like {@link #merge(Publisher)} except that if any of the merged MaybeSources notify of an
* error via {@link Subscriber#onError onError}, {@code mergeDelayError} will refrain from propagating that
* error notification until all of the merged MaybeSources and the main Publisher have finished emitting items.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.png" alt="">
* <p>
* Even if multiple merged Publishers send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Subscribers once.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream. The outer {@code Publisher} is consumed
* in unbounded mode (i.e., no backpressure is applied to it).</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T> the common element base type
* @param sources
* a Publisher that emits MaybeSources
* @return a Flowable that emits all of the items emitted by the Publishers emitted by the
* {@code source} Publisher
* @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a>
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Flowable<T> mergeDelayError(Publisher<? extends MaybeSource<? extends T>> sources) {
return mergeDelayError(sources, Integer.MAX_VALUE);
}
/**
* Flattens a Publisher that emits MaybeSources into one Publisher, in a way that allows a Subscriber to
* receive all successfully emitted items from all of the source MaybeSources without being interrupted by
* an error notification from one of them or even the main Publisher as well as limiting the total number of active MaybeSources.
* <p>
* This behaves like {@link #merge(Publisher, int)} except that if any of the merged MaybeSources notify of an
* error via {@link Subscriber#onError onError}, {@code mergeDelayError} will refrain from propagating that
* error notification until all of the merged MaybeSources and the main Publisher have finished emitting items.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.png" alt="">
* <p>
* Even if multiple merged Publishers send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Subscribers once.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream. The outer {@code Publisher} is consumed
* in unbounded mode (i.e., no backpressure is applied to it).</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* <p>History: 2.1.9 - experimental
* @param <T> the common element base type
* @param sources
* a Publisher that emits MaybeSources
* @param maxConcurrency the maximum number of active inner MaybeSources to be merged at a time
* @return a Flowable that emits all of the items emitted by the Publishers emitted by the
* {@code source} Publisher
* @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a>
* @since 2.2
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Flowable<T> mergeDelayError(Publisher<? extends MaybeSource<? extends T>> sources, int maxConcurrency) {
ObjectHelper.requireNonNull(sources, "source is null");
ObjectHelper.verifyPositive(maxConcurrency, "maxConcurrency");
return RxJavaPlugins.onAssembly(new FlowableFlatMapPublisher(sources, MaybeToPublisher.instance(), true, maxConcurrency, 1));
}
/**
* Flattens two MaybeSources into one Flowable, in a way that allows a Subscriber to receive all
* successfully emitted items from each of the source MaybeSources without being interrupted by an error
* notification from one of them.
* <p>
* This behaves like {@link #merge(MaybeSource, MaybeSource)} except that if any of the merged MaybeSources
* notify of an error via {@link Subscriber#onError onError}, {@code mergeDelayError} will refrain from
* propagating that error notification until all of the merged MaybeSources have finished emitting items.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.png" alt="">
* <p>
* Even if both merged MaybeSources send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Subscribers once.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T> the common element base type
* @param source1
* a MaybeSource to be merged
* @param source2
* a MaybeSource to be merged
* @return a Flowable that emits all of the items that are emitted by the two source MaybeSources
* @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a>
*/
@SuppressWarnings({ "unchecked" })
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Flowable<T> mergeDelayError(MaybeSource<? extends T> source1, MaybeSource<? extends T> source2) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
return mergeArrayDelayError(source1, source2);
}
/**
* Flattens three MaybeSource into one Flowable, in a way that allows a Subscriber to receive all
* successfully emitted items from all of the source MaybeSources without being interrupted by an error
* notification from one of them.
* <p>
* This behaves like {@link #merge(MaybeSource, MaybeSource, MaybeSource)} except that if any of the merged
* MaybeSources notify of an error via {@link Subscriber#onError onError}, {@code mergeDelayError} will refrain
* from propagating that error notification until all of the merged MaybeSources have finished emitting
* items.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.png" alt="">
* <p>
* Even if multiple merged MaybeSources send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Subscribers once.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T> the common element base type
* @param source1
* a MaybeSource to be merged
* @param source2
* a MaybeSource to be merged
* @param source3
* a MaybeSource to be merged
* @return a Flowable that emits all of the items that are emitted by the source MaybeSources
* @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a>
*/
@SuppressWarnings({ "unchecked" })
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Flowable<T> mergeDelayError(MaybeSource<? extends T> source1,
MaybeSource<? extends T> source2, MaybeSource<? extends T> source3) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
ObjectHelper.requireNonNull(source3, "source3 is null");
return mergeArrayDelayError(source1, source2, source3);
}
/**
* Flattens four MaybeSources into one Flowable, in a way that allows a Subscriber to receive all
* successfully emitted items from all of the source MaybeSources without being interrupted by an error
* notification from one of them.
* <p>
* This behaves like {@link #merge(MaybeSource, MaybeSource, MaybeSource, MaybeSource)} except that if any of
* the merged MaybeSources notify of an error via {@link Subscriber#onError onError}, {@code mergeDelayError}
* will refrain from propagating that error notification until all of the merged MaybeSources have finished
* emitting items.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.png" alt="">
* <p>
* Even if multiple merged MaybeSources send {@code onError} notifications, {@code mergeDelayError} will only
* invoke the {@code onError} method of its Subscribers once.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T> the common element base type
* @param source1
* a MaybeSource to be merged
* @param source2
* a MaybeSource to be merged
* @param source3
* a MaybeSource to be merged
* @param source4
* a MaybeSource to be merged
* @return a Flowable that emits all of the items that are emitted by the source MaybeSources
* @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a>
*/
@SuppressWarnings({ "unchecked" })
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Flowable<T> mergeDelayError(
MaybeSource<? extends T> source1, MaybeSource<? extends T> source2,
MaybeSource<? extends T> source3, MaybeSource<? extends T> source4) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
ObjectHelper.requireNonNull(source3, "source3 is null");
ObjectHelper.requireNonNull(source4, "source4 is null");
return mergeArrayDelayError(source1, source2, source3, source4);
}
/**
* Returns a Maybe that never sends any items or notifications to a {@link MaybeObserver}.
* <p>
* <img width="640" height="185" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/never.png" alt="">
* <p>
* This Maybe is useful primarily for testing purposes.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code never} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T>
* the type of items (not) emitted by the Maybe
* @return a Maybe that never emits any items or sends any notifications to a {@link MaybeObserver}
* @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Never</a>
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
@SuppressWarnings("unchecked")
public static <T> Maybe<T> never() {
return RxJavaPlugins.onAssembly((Maybe<T>)MaybeNever.INSTANCE);
}
/**
* Returns a Single that emits a Boolean value that indicates whether two MaybeSource sequences are the
* same by comparing the items emitted by each MaybeSource pairwise.
* <p>
* <img width="640" height="385" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sequenceEqual.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code sequenceEqual} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param source1
* the first MaybeSource to compare
* @param source2
* the second MaybeSource to compare
* @param <T>
* the type of items emitted by each MaybeSource
* @return a Single that emits a Boolean value that indicates whether the two sequences are the same
* @see <a href="http://reactivex.io/documentation/operators/sequenceequal.html">ReactiveX operators documentation: SequenceEqual</a>
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Single<Boolean> sequenceEqual(MaybeSource<? extends T> source1, MaybeSource<? extends T> source2) {
return sequenceEqual(source1, source2, ObjectHelper.equalsPredicate());
}
/**
* Returns a Single that emits a Boolean value that indicates whether two MaybeSources are the
* same by comparing the items emitted by each MaybeSource pairwise based on the results of a specified
* equality function.
* <p>
* <img width="640" height="385" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sequenceEqual.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code sequenceEqual} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param source1
* the first MaybeSource to compare
* @param source2
* the second MaybeSource to compare
* @param isEqual
* a function used to compare items emitted by each MaybeSource
* @param <T>
* the type of items emitted by each MaybeSource
* @return a Single that emits a Boolean value that indicates whether the two MaybeSource sequences
* are the same according to the specified function
* @see <a href="http://reactivex.io/documentation/operators/sequenceequal.html">ReactiveX operators documentation: SequenceEqual</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Single<Boolean> sequenceEqual(MaybeSource<? extends T> source1, MaybeSource<? extends T> source2,
BiPredicate<? super T, ? super T> isEqual) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
ObjectHelper.requireNonNull(isEqual, "isEqual is null");
return RxJavaPlugins.onAssembly(new MaybeEqualSingle<T>(source1, source2, isEqual));
}
/**
* Returns a Maybe that emits {@code 0L} after a specified delay.
* <p>
* <img width="640" height="200" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timer.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code timer} operates by default on the {@code computation} {@link Scheduler}.</dd>
* </dl>
*
* @param delay
* the initial delay before emitting a single {@code 0L}
* @param unit
* time units to use for {@code delay}
* @return a Maybe that emits {@code 0L} after a specified delay
* @see <a href="http://reactivex.io/documentation/operators/timer.html">ReactiveX operators documentation: Timer</a>
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.COMPUTATION)
public static Maybe<Long> timer(long delay, TimeUnit unit) {
return timer(delay, unit, Schedulers.computation());
}
/**
* Returns a Maybe that emits {@code 0L} after a specified delay on a specified Scheduler.
* <p>
* <img width="640" height="200" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timer.s.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>You specify which {@link Scheduler} this operator will use.</dd>
* </dl>
*
* @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 a Maybe that emits {@code 0L} after a specified delay, on a specified Scheduler
* @see <a href="http://reactivex.io/documentation/operators/timer.html">ReactiveX operators documentation: Timer</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.CUSTOM)
public static Maybe<Long> timer(long delay, TimeUnit unit, Scheduler scheduler) {
ObjectHelper.requireNonNull(unit, "unit is null");
ObjectHelper.requireNonNull(scheduler, "scheduler is null");
return RxJavaPlugins.onAssembly(new MaybeTimer(Math.max(0L, delay), unit, scheduler));
}
/**
* <strong>Advanced use only:</strong> creates a Maybe instance without
* any safeguards by using a callback that is called with a MaybeObserver.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code unsafeCreate} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <T> the value type
* @param onSubscribe the function that is called with the subscribing MaybeObserver
* @return the new Maybe instance
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Maybe<T> unsafeCreate(MaybeSource<T> onSubscribe) {
if (onSubscribe instanceof Maybe) {
throw new IllegalArgumentException("unsafeCreate(Maybe) should be upgraded");
}
ObjectHelper.requireNonNull(onSubscribe, "onSubscribe is null");
return RxJavaPlugins.onAssembly(new MaybeUnsafeCreate<T>(onSubscribe));
}
/**
* Constructs a Maybe that creates a dependent resource object which is disposed of when the
* upstream terminates or the downstream calls dispose().
* <p>
* <img width="640" height="400" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/using.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code using} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T> the element type of the generated MaybeSource
* @param <D> the type of the resource associated with the output sequence
* @param resourceSupplier
* the factory function to create a resource object that depends on the Maybe
* @param sourceSupplier
* the factory function to create a MaybeSource
* @param resourceDisposer
* the function that will dispose of the resource
* @return the Maybe whose lifetime controls the lifetime of the dependent resource object
* @see <a href="http://reactivex.io/documentation/operators/using.html">ReactiveX operators documentation: Using</a>
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public static <T, D> Maybe<T> using(Callable<? extends D> resourceSupplier,
Function<? super D, ? extends MaybeSource<? extends T>> sourceSupplier,
Consumer<? super D> resourceDisposer) {
return using(resourceSupplier, sourceSupplier, resourceDisposer, true);
}
/**
* Constructs a Maybe that creates a dependent resource object which is disposed of just before
* termination if you have set {@code disposeEagerly} to {@code true} and a downstream dispose() does not occur
* before termination. Otherwise resource disposal will occur on call to dispose(). Eager disposal is
* particularly appropriate for a synchronous Maybe that reuses resources. {@code disposeAction} will
* only be called once per subscription.
* <p>
* <img width="640" height="400" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/using.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code using} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T> the element type of the generated MaybeSource
* @param <D> the type of the resource associated with the output sequence
* @param resourceSupplier
* the factory function to create a resource object that depends on the Maybe
* @param sourceSupplier
* the factory function to create a MaybeSource
* @param resourceDisposer
* the function that will dispose of the resource
* @param eager
* if {@code true} then disposal will happen either on a dispose() call or just before emission of
* a terminal event ({@code onComplete} or {@code onError}).
* @return the Maybe whose lifetime controls the lifetime of the dependent resource object
* @see <a href="http://reactivex.io/documentation/operators/using.html">ReactiveX operators documentation: Using</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T, D> Maybe<T> using(Callable<? extends D> resourceSupplier,
Function<? super D, ? extends MaybeSource<? extends T>> sourceSupplier,
Consumer<? super D> resourceDisposer, boolean eager) {
ObjectHelper.requireNonNull(resourceSupplier, "resourceSupplier is null");
ObjectHelper.requireNonNull(sourceSupplier, "sourceSupplier is null");
ObjectHelper.requireNonNull(resourceDisposer, "disposer is null");
return RxJavaPlugins.onAssembly(new MaybeUsing<T, D>(resourceSupplier, sourceSupplier, resourceDisposer, eager));
}
/**
* Wraps a MaybeSource instance into a new Maybe instance if not already a Maybe
* instance.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code wrap} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <T> the value type
* @param source the source to wrap
* @return the Maybe wrapper or the source cast to Maybe (if possible)
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Maybe<T> wrap(MaybeSource<T> source) {
if (source instanceof Maybe) {
return RxJavaPlugins.onAssembly((Maybe<T>)source);
}
ObjectHelper.requireNonNull(source, "onSubscribe is null");
return RxJavaPlugins.onAssembly(new MaybeUnsafeCreate<T>(source));
}
/**
* Returns a Maybe that emits the results of a specified combiner function applied to combinations of
* items emitted, in sequence, by an Iterable of other MaybeSources.
* <p>
* Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the
* implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a
* {@code Function<Integer[], R>} passed to the method would trigger a {@code ClassCastException}.
*
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt="">
* <p>This operator terminates eagerly if any of the source MaybeSources signal an onError or onComplete. This
* also means it is possible some sources may not get subscribed to at all.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T> the common value type
* @param <R> the zipped result type
* @param sources
* an Iterable of source MaybeSources
* @param zipper
* a function that, when applied to an item emitted by each of the source MaybeSources, results in
* an item that will be emitted by the resulting Maybe
* @return a Maybe that emits the zipped results
* @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T, R> Maybe<R> zip(Iterable<? extends MaybeSource<? extends T>> sources, Function<? super Object[], ? extends R> zipper) {
ObjectHelper.requireNonNull(zipper, "zipper is null");
ObjectHelper.requireNonNull(sources, "sources is null");
return RxJavaPlugins.onAssembly(new MaybeZipIterable<T, R>(sources, zipper));
}
/**
* Returns a Maybe that emits the results of a specified combiner function applied to combinations of
* two items emitted, in sequence, by two other MaybeSources.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt="">
* <p>This operator terminates eagerly if any of the source MaybeSources signal an onError or onComplete. This
* also means it is possible some sources may not get subscribed to at all.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T1> the value type of the first source
* @param <T2> the value type of the second source
* @param <R> the zipped result type
* @param source1
* the first source MaybeSource
* @param source2
* a second source MaybeSource
* @param zipper
* a function that, when applied to an item emitted by each of the source MaybeSources, results
* in an item that will be emitted by the resulting Maybe
* @return a Maybe that emits the zipped results
* @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a>
*/
@SuppressWarnings("unchecked")
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T1, T2, R> Maybe<R> zip(
MaybeSource<? extends T1> source1, MaybeSource<? extends T2> source2,
BiFunction<? super T1, ? super T2, ? extends R> zipper) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
return zipArray(Functions.toFunction(zipper), source1, source2);
}
/**
* Returns a Maybe that emits the results of a specified combiner function applied to combinations of
* three items emitted, in sequence, by three other MaybeSources.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt="">
* <p>This operator terminates eagerly if any of the source MaybeSources signal an onError or onComplete. This
* also means it is possible some sources may not get subscribed to at all.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T1> the value type of the first source
* @param <T2> the value type of the second source
* @param <T3> the value type of the third source
* @param <R> the zipped result type
* @param source1
* the first source MaybeSource
* @param source2
* a second source MaybeSource
* @param source3
* a third source MaybeSource
* @param zipper
* a function that, when applied to an item emitted by each of the source MaybeSources, results in
* an item that will be emitted by the resulting Maybe
* @return a Maybe that emits the zipped results
* @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a>
*/
@SuppressWarnings("unchecked")
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T1, T2, T3, R> Maybe<R> zip(
MaybeSource<? extends T1> source1, MaybeSource<? extends T2> source2, MaybeSource<? extends T3> source3,
Function3<? super T1, ? super T2, ? super T3, ? extends R> zipper) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
ObjectHelper.requireNonNull(source3, "source3 is null");
return zipArray(Functions.toFunction(zipper), source1, source2, source3);
}
/**
* Returns a Maybe that emits the results of a specified combiner function applied to combinations of
* four items emitted, in sequence, by four other MaybeSources.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt="">
* <p>This operator terminates eagerly if any of the source MaybeSources signal an onError or onComplete. This
* also means it is possible some sources may not get subscribed to at all.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T1> the value type of the first source
* @param <T2> the value type of the second source
* @param <T3> the value type of the third source
* @param <T4> the value type of the fourth source
* @param <R> the zipped result type
* @param source1
* the first source MaybeSource
* @param source2
* a second source MaybeSource
* @param source3
* a third source MaybeSource
* @param source4
* a fourth source MaybeSource
* @param zipper
* a function that, when applied to an item emitted by each of the source MaybeSources, results in
* an item that will be emitted by the resulting Maybe
* @return a Maybe that emits the zipped results
* @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a>
*/
@SuppressWarnings("unchecked")
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T1, T2, T3, T4, R> Maybe<R> zip(
MaybeSource<? extends T1> source1, MaybeSource<? extends T2> source2, MaybeSource<? extends T3> source3,
MaybeSource<? extends T4> source4,
Function4<? super T1, ? super T2, ? super T3, ? super T4, ? extends R> zipper) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
ObjectHelper.requireNonNull(source3, "source3 is null");
ObjectHelper.requireNonNull(source4, "source4 is null");
return zipArray(Functions.toFunction(zipper), source1, source2, source3, source4);
}
/**
* Returns a Maybe that emits the results of a specified combiner function applied to combinations of
* five items emitted, in sequence, by five other MaybeSources.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt="">
* <p>This operator terminates eagerly if any of the source MaybeSources signal an onError or onComplete. This
* also means it is possible some sources may not get subscribed to at all.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T1> the value type of the first source
* @param <T2> the value type of the second source
* @param <T3> the value type of the third source
* @param <T4> the value type of the fourth source
* @param <T5> the value type of the fifth source
* @param <R> the zipped result type
* @param source1
* the first source MaybeSource
* @param source2
* a second source MaybeSource
* @param source3
* a third source MaybeSource
* @param source4
* a fourth source MaybeSource
* @param source5
* a fifth source MaybeSource
* @param zipper
* a function that, when applied to an item emitted by each of the source MaybeSources, results in
* an item that will be emitted by the resulting Maybe
* @return a Maybe that emits the zipped results
* @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a>
*/
@SuppressWarnings("unchecked")
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T1, T2, T3, T4, T5, R> Maybe<R> zip(
MaybeSource<? extends T1> source1, MaybeSource<? extends T2> source2, MaybeSource<? extends T3> source3,
MaybeSource<? extends T4> source4, MaybeSource<? extends T5> source5,
Function5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> zipper) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
ObjectHelper.requireNonNull(source3, "source3 is null");
ObjectHelper.requireNonNull(source4, "source4 is null");
ObjectHelper.requireNonNull(source5, "source5 is null");
return zipArray(Functions.toFunction(zipper), source1, source2, source3, source4, source5);
}
/**
* Returns a Maybe that emits the results of a specified combiner function applied to combinations of
* six items emitted, in sequence, by six other MaybeSources.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt="">
* <p>This operator terminates eagerly if any of the source MaybeSources signal an onError or onComplete. This
* also means it is possible some sources may not get subscribed to at all.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T1> the value type of the first source
* @param <T2> the value type of the second source
* @param <T3> the value type of the third source
* @param <T4> the value type of the fourth source
* @param <T5> the value type of the fifth source
* @param <T6> the value type of the sixth source
* @param <R> the zipped result type
* @param source1
* the first source MaybeSource
* @param source2
* a second source MaybeSource
* @param source3
* a third source MaybeSource
* @param source4
* a fourth source MaybeSource
* @param source5
* a fifth source MaybeSource
* @param source6
* a sixth source MaybeSource
* @param zipper
* a function that, when applied to an item emitted by each of the source MaybeSources, results in
* an item that will be emitted by the resulting Maybe
* @return a Maybe that emits the zipped results
* @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a>
*/
@SuppressWarnings("unchecked")
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T1, T2, T3, T4, T5, T6, R> Maybe<R> zip(
MaybeSource<? extends T1> source1, MaybeSource<? extends T2> source2, MaybeSource<? extends T3> source3,
MaybeSource<? extends T4> source4, MaybeSource<? extends T5> source5, MaybeSource<? extends T6> source6,
Function6<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? extends R> zipper) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
ObjectHelper.requireNonNull(source3, "source3 is null");
ObjectHelper.requireNonNull(source4, "source4 is null");
ObjectHelper.requireNonNull(source5, "source5 is null");
ObjectHelper.requireNonNull(source6, "source6 is null");
return zipArray(Functions.toFunction(zipper), source1, source2, source3, source4, source5, source6);
}
/**
* Returns a Maybe that emits the results of a specified combiner function applied to combinations of
* seven items emitted, in sequence, by seven other MaybeSources.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt="">
* <p>This operator terminates eagerly if any of the source MaybeSources signal an onError or onComplete. This
* also means it is possible some sources may not get subscribed to at all.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T1> the value type of the first source
* @param <T2> the value type of the second source
* @param <T3> the value type of the third source
* @param <T4> the value type of the fourth source
* @param <T5> the value type of the fifth source
* @param <T6> the value type of the sixth source
* @param <T7> the value type of the seventh source
* @param <R> the zipped result type
* @param source1
* the first source MaybeSource
* @param source2
* a second source MaybeSource
* @param source3
* a third source MaybeSource
* @param source4
* a fourth source MaybeSource
* @param source5
* a fifth source MaybeSource
* @param source6
* a sixth source MaybeSource
* @param source7
* a seventh source MaybeSource
* @param zipper
* a function that, when applied to an item emitted by each of the source MaybeSources, results in
* an item that will be emitted by the resulting Maybe
* @return a Maybe that emits the zipped results
* @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a>
*/
@SuppressWarnings("unchecked")
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T1, T2, T3, T4, T5, T6, T7, R> Maybe<R> zip(
MaybeSource<? extends T1> source1, MaybeSource<? extends T2> source2, MaybeSource<? extends T3> source3,
MaybeSource<? extends T4> source4, MaybeSource<? extends T5> source5, MaybeSource<? extends T6> source6,
MaybeSource<? extends T7> source7,
Function7<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? extends R> zipper) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
ObjectHelper.requireNonNull(source3, "source3 is null");
ObjectHelper.requireNonNull(source4, "source4 is null");
ObjectHelper.requireNonNull(source5, "source5 is null");
ObjectHelper.requireNonNull(source6, "source6 is null");
ObjectHelper.requireNonNull(source7, "source7 is null");
return zipArray(Functions.toFunction(zipper), source1, source2, source3, source4, source5, source6, source7);
}
/**
* Returns a Maybe that emits the results of a specified combiner function applied to combinations of
* eight items emitted, in sequence, by eight other MaybeSources.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt="">
* <p>This operator terminates eagerly if any of the source MaybeSources signal an onError or onComplete. This
* also means it is possible some sources may not get subscribed to at all.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T1> the value type of the first source
* @param <T2> the value type of the second source
* @param <T3> the value type of the third source
* @param <T4> the value type of the fourth source
* @param <T5> the value type of the fifth source
* @param <T6> the value type of the sixth source
* @param <T7> the value type of the seventh source
* @param <T8> the value type of the eighth source
* @param <R> the zipped result type
* @param source1
* the first source MaybeSource
* @param source2
* a second source MaybeSource
* @param source3
* a third source MaybeSource
* @param source4
* a fourth source MaybeSource
* @param source5
* a fifth source MaybeSource
* @param source6
* a sixth source MaybeSource
* @param source7
* a seventh source MaybeSource
* @param source8
* an eighth source MaybeSource
* @param zipper
* a function that, when applied to an item emitted by each of the source MaybeSources, results in
* an item that will be emitted by the resulting Maybe
* @return a Maybe that emits the zipped results
* @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a>
*/
@SuppressWarnings("unchecked")
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T1, T2, T3, T4, T5, T6, T7, T8, R> Maybe<R> zip(
MaybeSource<? extends T1> source1, MaybeSource<? extends T2> source2, MaybeSource<? extends T3> source3,
MaybeSource<? extends T4> source4, MaybeSource<? extends T5> source5, MaybeSource<? extends T6> source6,
MaybeSource<? extends T7> source7, MaybeSource<? extends T8> source8,
Function8<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? extends R> zipper) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
ObjectHelper.requireNonNull(source3, "source3 is null");
ObjectHelper.requireNonNull(source4, "source4 is null");
ObjectHelper.requireNonNull(source5, "source5 is null");
ObjectHelper.requireNonNull(source6, "source6 is null");
ObjectHelper.requireNonNull(source7, "source7 is null");
ObjectHelper.requireNonNull(source8, "source8 is null");
return zipArray(Functions.toFunction(zipper), source1, source2, source3, source4, source5, source6, source7, source8);
}
/**
* Returns a Maybe that emits the results of a specified combiner function applied to combinations of
* nine items emitted, in sequence, by nine other MaybeSources.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* <p>This operator terminates eagerly if any of the source MaybeSources signal an onError or onComplete. This
* also means it is possible some sources may not get subscribed to at all.
*
* @param <T1> the value type of the first source
* @param <T2> the value type of the second source
* @param <T3> the value type of the third source
* @param <T4> the value type of the fourth source
* @param <T5> the value type of the fifth source
* @param <T6> the value type of the sixth source
* @param <T7> the value type of the seventh source
* @param <T8> the value type of the eighth source
* @param <T9> the value type of the ninth source
* @param <R> the zipped result type
* @param source1
* the first source MaybeSource
* @param source2
* a second source MaybeSource
* @param source3
* a third source MaybeSource
* @param source4
* a fourth source MaybeSource
* @param source5
* a fifth source MaybeSource
* @param source6
* a sixth source MaybeSource
* @param source7
* a seventh source MaybeSource
* @param source8
* an eighth source MaybeSource
* @param source9
* a ninth source MaybeSource
* @param zipper
* a function that, when applied to an item emitted by each of the source MaybeSources, results in
* an item that will be emitted by the resulting MaybeSource
* @return a Maybe that emits the zipped results
* @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a>
*/
@SuppressWarnings("unchecked")
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Maybe<R> zip(
MaybeSource<? extends T1> source1, MaybeSource<? extends T2> source2, MaybeSource<? extends T3> source3,
MaybeSource<? extends T4> source4, MaybeSource<? extends T5> source5, MaybeSource<? extends T6> source6,
MaybeSource<? extends T7> source7, MaybeSource<? extends T8> source8, MaybeSource<? extends T9> source9,
Function9<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? super T9, ? extends R> zipper) {
ObjectHelper.requireNonNull(source1, "source1 is null");
ObjectHelper.requireNonNull(source2, "source2 is null");
ObjectHelper.requireNonNull(source3, "source3 is null");
ObjectHelper.requireNonNull(source4, "source4 is null");
ObjectHelper.requireNonNull(source5, "source5 is null");
ObjectHelper.requireNonNull(source6, "source6 is null");
ObjectHelper.requireNonNull(source7, "source7 is null");
ObjectHelper.requireNonNull(source8, "source8 is null");
ObjectHelper.requireNonNull(source9, "source9 is null");
return zipArray(Functions.toFunction(zipper), source1, source2, source3, source4, source5, source6, source7, source8, source9);
}
/**
* Returns a Maybe that emits the results of a specified combiner function applied to combinations of
* items emitted, in sequence, by an array of other MaybeSources.
* <p>
* Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the
* implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a
* {@code Function<Integer[], R>} passed to the method would trigger a {@code ClassCastException}.
*
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt="">
* <p>This operator terminates eagerly if any of the source MaybeSources signal an onError or onComplete. This
* also means it is possible some sources may not get subscribed to at all.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code zipArray} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <T> the common element type
* @param <R> the result type
* @param sources
* an array of source MaybeSources
* @param zipper
* a function that, when applied to an item emitted by each of the source MaybeSources, results in
* an item that will be emitted by the resulting MaybeSource
* @return a Maybe that emits the zipped results
* @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static <T, R> Maybe<R> zipArray(Function<? super Object[], ? extends R> zipper,
MaybeSource<? extends T>... sources) {
ObjectHelper.requireNonNull(sources, "sources is null");
if (sources.length == 0) {
return empty();
}
ObjectHelper.requireNonNull(zipper, "zipper is null");
return RxJavaPlugins.onAssembly(new MaybeZipArray<T, R>(sources, zipper));
}
// ------------------------------------------------------------------
// Instance methods
// ------------------------------------------------------------------
/**
* Mirrors the MaybeSource (current or provided) that first signals an event.
* <p>
* <img width="640" height="385" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/amb.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code ambWith} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param other
* a MaybeSource competing to react first. A subscription to this provided source will occur after
* subscribing to the current source.
* @return a Maybe that emits the same sequence as whichever of the source MaybeSources first
* signalled
* @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a>
*/
@SuppressWarnings("unchecked")
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> ambWith(MaybeSource<? extends T> other) {
ObjectHelper.requireNonNull(other, "other is null");
return ambArray(this, other);
}
/**
* Calls the specified converter function during assembly time and returns its resulting value.
* <p>
* This allows fluent conversion to any other type.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code as} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* <p>History: 2.1.7 - experimental
* @param <R> the resulting object type
* @param converter the function that receives the current Maybe instance and returns a value
* @return the converted value
* @throws NullPointerException if converter is null
* @since 2.2
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final <R> R as(@NonNull MaybeConverter<T, ? extends R> converter) {
return ObjectHelper.requireNonNull(converter, "converter is null").apply(this);
}
/**
* Waits in a blocking fashion until the current Maybe signals a success value (which is returned),
* null if completed or an exception (which is propagated).
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code blockingGet} does not operate by default on a particular {@link Scheduler}.</dd>
* <dt><b>Error handling:</b></dt>
* <dd>If the source signals an error, the operator wraps a checked {@link Exception}
* into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and
* {@link Error}s are rethrown as they are.</dd>
* </dl>
* @return the success value
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final T blockingGet() {
BlockingMultiObserver<T> observer = new BlockingMultiObserver<T>();
subscribe(observer);
return observer.blockingGet();
}
/**
* Waits in a blocking fashion until the current Maybe signals a success value (which is returned),
* defaultValue if completed or an exception (which is propagated).
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code blockingGet} does not operate by default on a particular {@link Scheduler}.</dd>
* <dt><b>Error handling:</b></dt>
* <dd>If the source signals an error, the operator wraps a checked {@link Exception}
* into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and
* {@link Error}s are rethrown as they are.</dd>
* </dl>
* @param defaultValue the default item to return if this Maybe is empty
* @return the success value
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final T blockingGet(T defaultValue) {
ObjectHelper.requireNonNull(defaultValue, "defaultValue is null");
BlockingMultiObserver<T> observer = new BlockingMultiObserver<T>();
subscribe(observer);
return observer.blockingGet(defaultValue);
}
/**
* Returns a Maybe that subscribes to this Maybe lazily, caches its event
* and replays it, to all the downstream subscribers.
* <p>
* <img width="640" height="410" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/cache.png" alt="">
* <p>
* The operator subscribes only when the first downstream subscriber subscribes and maintains
* a single subscription towards this Maybe.
* <p>
* <em>Note:</em> You sacrifice the ability to dispose the origin when you use the {@code cache}.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code cache} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @return a Maybe that, when first subscribed to, caches all of its items and notifications for the
* benefit of subsequent subscribers
* @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a>
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> cache() {
return RxJavaPlugins.onAssembly(new MaybeCache<T>(this));
}
/**
* Casts the success value of the current Maybe into the target type or signals a
* ClassCastException if not compatible.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code cast} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <U> the target type
* @param clazz the type token to use for casting the success result from the current Maybe
* @return the new Maybe instance
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <U> Maybe<U> cast(final Class<? extends U> clazz) {
ObjectHelper.requireNonNull(clazz, "clazz is null");
return map(Functions.castFunction(clazz));
}
/**
* Transform a Maybe by applying a particular Transformer function to it.
* <p>
* This method operates on the Maybe itself whereas {@link #lift} operates on the Maybe's MaybeObservers.
* <p>
* If the operator you are creating is designed to act on the individual item emitted by a Maybe, use
* {@link #lift}. If your operator is designed to transform the source Maybe as a whole (for instance, by
* applying a particular set of existing RxJava operators to it) use {@code compose}.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code compose} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <R> the value type of the Maybe returned by the transformer function
* @param transformer the transformer function, not null
* @return a Maybe, transformed by the transformer function
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Implementing-Your-Own-Operators">RxJava wiki: Implementing Your Own Operators</a>
*/
@SuppressWarnings("unchecked")
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final <R> Maybe<R> compose(MaybeTransformer<? super T, ? extends R> transformer) {
return wrap(((MaybeTransformer<T, R>) ObjectHelper.requireNonNull(transformer, "transformer is null")).apply(this));
}
/**
* Returns a Maybe that is based on applying a specified function to the item emitted by the source Maybe,
* where that function returns a MaybeSource.
* <p>
* <img width="640" height="356" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMap.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code concatMap} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* <p>Note that flatMap and concatMap for Maybe is the same operation.
* @param <R> the result value type
* @param mapper
* a function that, when applied to the item emitted by the source Maybe, returns a MaybeSource
* @return the Maybe returned from {@code func} when applied to the item emitted by the source Maybe
* @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <R> Maybe<R> concatMap(Function<? super T, ? extends MaybeSource<? extends R>> mapper) {
ObjectHelper.requireNonNull(mapper, "mapper is null");
return RxJavaPlugins.onAssembly(new MaybeFlatten<T, R>(this, mapper));
}
/**
* Returns a Flowable that emits the items emitted from the current MaybeSource, then the next, one after
* the other, without interleaving them.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concat.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code concatWith} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param other
* a MaybeSource to be concatenated after the current
* @return a Flowable that emits items emitted by the two source MaybeSources, one after the other,
* without interleaving them
* @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a>
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Flowable<T> concatWith(MaybeSource<? extends T> other) {
ObjectHelper.requireNonNull(other, "other is null");
return concat(this, other);
}
/**
* Returns a Single that emits a Boolean that indicates whether the source Maybe emitted a
* specified item.
* <p>
* <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/contains.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code contains} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param item
* the item to search for in the emissions from the source Maybe, not null
* @return a Single that emits {@code true} if the specified item is emitted by the source Maybe,
* or {@code false} if the source Maybe completes without emitting that item
* @see <a href="http://reactivex.io/documentation/operators/contains.html">ReactiveX operators documentation: Contains</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Single<Boolean> contains(final Object item) {
ObjectHelper.requireNonNull(item, "item is null");
return RxJavaPlugins.onAssembly(new MaybeContains<T>(this, item));
}
/**
* Returns a Single that counts the total number of items emitted (0 or 1) by the source Maybe and emits
* this count as a 64-bit Long.
* <p>
* <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/longCount.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code count} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @return a Single that emits a single item: the number of items emitted by the source Maybe as a
* 64-bit Long item
* @see <a href="http://reactivex.io/documentation/operators/count.html">ReactiveX operators documentation: Count</a>
* @see #count()
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Single<Long> count() {
return RxJavaPlugins.onAssembly(new MaybeCount<T>(this));
}
/**
* Returns a Maybe that emits the item emitted by the source Maybe or a specified default item
* if the source Maybe is empty.
* <p>
* Note that the result Maybe is semantically equivalent to a {@code Single}, since it's guaranteed
* to emit exactly one item or an error. See {@link #toSingle(Object)} for a method with equivalent
* behavior which returns a {@code Single}.
* <p>
* <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/defaultIfEmpty.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code defaultIfEmpty} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param defaultItem
* the item to emit if the source Maybe emits no items
* @return a Maybe that emits either the specified default item if the source Maybe emits no
* items, or the items emitted by the source Maybe
* @see <a href="http://reactivex.io/documentation/operators/defaultifempty.html">ReactiveX operators documentation: DefaultIfEmpty</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> defaultIfEmpty(T defaultItem) {
ObjectHelper.requireNonNull(defaultItem, "defaultItem is null");
return switchIfEmpty(just(defaultItem));
}
/**
* Returns a Maybe that signals the events emitted by the source Maybe shifted forward in time by a
* specified delay.
* <p>
* <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delay.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>This version of {@code delay} operates by default on the {@code computation} {@link Scheduler}.</dd>
* </dl>
*
* @param delay
* the delay to shift the source by
* @param unit
* the {@link TimeUnit} in which {@code period} is defined
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a>
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.COMPUTATION)
public final Maybe<T> delay(long delay, TimeUnit unit) {
return delay(delay, unit, Schedulers.computation());
}
/**
* Returns a Maybe that signals the events emitted by the source Maybe shifted forward in time by a
* specified delay running on the specified Scheduler.
* <p>
* <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delay.s.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>you specify which {@link Scheduler} this operator will use.</dd>
* </dl>
*
* @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 new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.CUSTOM)
public final Maybe<T> delay(long delay, TimeUnit unit, Scheduler scheduler) {
ObjectHelper.requireNonNull(unit, "unit is null");
ObjectHelper.requireNonNull(scheduler, "scheduler is null");
return RxJavaPlugins.onAssembly(new MaybeDelay<T>(this, Math.max(0L, delay), unit, scheduler));
}
/**
* Delays the emission of this Maybe until the given Publisher signals an item or completes.
* <p>
* <img width="640" height="450" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delay.oo.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The {@code delayIndicator} is consumed in an unbounded manner but is cancelled after
* the first item it produces.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>This version of {@code delay} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <U>
* the subscription delay value type (ignored)
* @param <V>
* the item delay value type (ignored)
* @param delayIndicator
* the Publisher that gets subscribed to when this Maybe signals an event and that
* signal is emitted when the Publisher signals an item or completes
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
@BackpressureSupport(BackpressureKind.UNBOUNDED_IN)
public final <U, V> Maybe<T> delay(Publisher<U> delayIndicator) {
ObjectHelper.requireNonNull(delayIndicator, "delayIndicator is null");
return RxJavaPlugins.onAssembly(new MaybeDelayOtherPublisher<T, U>(this, delayIndicator));
}
/**
* Returns a Maybe that delays the subscription to this Maybe
* until the other Publisher emits an element or completes normally.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The {@code Publisher} source is consumed in an unbounded fashion (without applying backpressure).</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>This method does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <U> the value type of the other Publisher, irrelevant
* @param subscriptionIndicator the other Publisher that should trigger the subscription
* to this Publisher.
* @return a Maybe that delays the subscription to this Maybe
* until the other Publisher emits an element or completes normally.
*/
@BackpressureSupport(BackpressureKind.UNBOUNDED_IN)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <U> Maybe<T> delaySubscription(Publisher<U> subscriptionIndicator) {
ObjectHelper.requireNonNull(subscriptionIndicator, "subscriptionIndicator is null");
return RxJavaPlugins.onAssembly(new MaybeDelaySubscriptionOtherPublisher<T, U>(this, subscriptionIndicator));
}
/**
* Returns a Maybe that delays the subscription to the source Maybe by a given amount of time.
* <p>
* <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delaySubscription.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>This version of {@code delaySubscription} operates by default on the {@code computation} {@link Scheduler}.</dd>
* </dl>
*
* @param delay
* the time to delay the subscription
* @param unit
* the time unit of {@code delay}
* @return a Maybe that delays the subscription to the source Maybe by the given amount
* @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a>
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.COMPUTATION)
public final Maybe<T> delaySubscription(long delay, TimeUnit unit) {
return delaySubscription(delay, unit, Schedulers.computation());
}
/**
* Returns a Maybe that delays the subscription to the source Maybe 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/ReactiveX/RxJava/images/rx-operators/delaySubscription.s.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>You specify which {@link Scheduler} this operator will use.</dd>
* </dl>
*
* @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 a Maybe that delays the subscription to the source Maybe by a given
* amount, waiting and subscribing on the given Scheduler
* @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a>
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.CUSTOM)
public final Maybe<T> delaySubscription(long delay, TimeUnit unit, Scheduler scheduler) {
return delaySubscription(Flowable.timer(delay, unit, scheduler));
}
/**
* Calls the specified consumer with the success item after this item has been emitted to the downstream.
* <p>Note that the {@code onAfterNext} action is shared between subscriptions and as such
* should be thread-safe.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code doAfterSuccess} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* <p>History: 2.0.1 - experimental
* @param onAfterSuccess the Consumer that will be called after emitting an item from upstream to the downstream
* @return the new Maybe instance
* @since 2.1
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> doAfterSuccess(Consumer<? super T> onAfterSuccess) {
ObjectHelper.requireNonNull(onAfterSuccess, "onAfterSuccess is null");
return RxJavaPlugins.onAssembly(new MaybeDoAfterSuccess<T>(this, onAfterSuccess));
}
/**
* Registers an {@link Action} to be called when this Maybe invokes either
* {@link MaybeObserver#onComplete onSuccess},
* {@link MaybeObserver#onComplete onComplete} or {@link MaybeObserver#onError onError}.
* <p>
* <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/finallyDo.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code doAfterTerminate} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param onAfterTerminate
* an {@link Action} to be invoked when the source Maybe finishes
* @return a Maybe that emits the same items as the source Maybe, then invokes the
* {@link Action}
* @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> doAfterTerminate(Action onAfterTerminate) {
return RxJavaPlugins.onAssembly(new MaybePeek<T>(this,
Functions.emptyConsumer(), // onSubscribe
Functions.emptyConsumer(), // onSuccess
Functions.emptyConsumer(), // onError
Functions.EMPTY_ACTION, // onComplete
ObjectHelper.requireNonNull(onAfterTerminate, "onAfterTerminate is null"),
Functions.EMPTY_ACTION // dispose
));
}
/**
* Calls the specified action after this Maybe signals onSuccess, onError or onComplete or gets disposed by
* the downstream.
* <p>In case of a race between a terminal event and a dispose call, the provided {@code onFinally} action
* is executed once per subscription.
* <p>Note that the {@code onFinally} action is shared between subscriptions and as such
* should be thread-safe.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code doFinally} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* <p>History: 2.0.1 - experimental
* @param onFinally the action called when this Maybe terminates or gets disposed
* @return the new Maybe instance
* @since 2.1
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> doFinally(Action onFinally) {
ObjectHelper.requireNonNull(onFinally, "onFinally is null");
return RxJavaPlugins.onAssembly(new MaybeDoFinally<T>(this, onFinally));
}
/**
* Calls the shared {@code Action} if a MaybeObserver subscribed to the current Maybe
* disposes the common Disposable it received via onSubscribe.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code doOnDispose} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param onDispose the action called when the subscription is disposed
* @throws NullPointerException if onDispose is null
* @return the new Maybe instance
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> doOnDispose(Action onDispose) {
return RxJavaPlugins.onAssembly(new MaybePeek<T>(this,
Functions.emptyConsumer(), // onSubscribe
Functions.emptyConsumer(), // onSuccess
Functions.emptyConsumer(), // onError
Functions.EMPTY_ACTION, // onComplete
Functions.EMPTY_ACTION, // (onSuccess | onError | onComplete) after
ObjectHelper.requireNonNull(onDispose, "onDispose is null")
));
}
/**
* Modifies the source Maybe so that it invokes an action when it calls {@code onComplete}.
* <p>
* <img width="640" height="358" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnComplete.m.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code doOnComplete} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param onComplete
* the action to invoke when the source Maybe calls {@code onComplete}
* @return the new Maybe with the side-effecting behavior applied
* @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> doOnComplete(Action onComplete) {
return RxJavaPlugins.onAssembly(new MaybePeek<T>(this,
Functions.emptyConsumer(), // onSubscribe
Functions.emptyConsumer(), // onSuccess
Functions.emptyConsumer(), // onError
ObjectHelper.requireNonNull(onComplete, "onComplete is null"),
Functions.EMPTY_ACTION, // (onSuccess | onError | onComplete)
Functions.EMPTY_ACTION // dispose
));
}
/**
* Calls the shared consumer with the error sent via onError for each
* MaybeObserver that subscribes to the current Maybe.
* <p>
* <img width="640" height="358" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnError.m.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code doOnError} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param onError the consumer called with the success value of onError
* @return the new Maybe instance
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> doOnError(Consumer<? super Throwable> onError) {
return RxJavaPlugins.onAssembly(new MaybePeek<T>(this,
Functions.emptyConsumer(), // onSubscribe
Functions.emptyConsumer(), // onSuccess
ObjectHelper.requireNonNull(onError, "onError is null"),
Functions.EMPTY_ACTION, // onComplete
Functions.EMPTY_ACTION, // (onSuccess | onError | onComplete)
Functions.EMPTY_ACTION // dispose
));
}
/**
* Calls the given onEvent callback with the (success value, null) for an onSuccess, (null, throwable) for
* an onError or (null, null) for an onComplete signal from this Maybe before delivering said
* signal to the downstream.
* <p>
* Exceptions thrown from the callback will override the event so the downstream receives the
* error instead of the original signal.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code doOnEvent} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param onEvent the callback to call with the terminal event tuple
* @return the new Maybe instance
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> doOnEvent(BiConsumer<? super T, ? super Throwable> onEvent) {
ObjectHelper.requireNonNull(onEvent, "onEvent is null");
return RxJavaPlugins.onAssembly(new MaybeDoOnEvent<T>(this, onEvent));
}
/**
* Calls the shared consumer with the Disposable sent through the onSubscribe for each
* MaybeObserver that subscribes to the current Maybe.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code doOnSubscribe} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param onSubscribe the consumer called with the Disposable sent via onSubscribe
* @return the new Maybe instance
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> doOnSubscribe(Consumer<? super Disposable> onSubscribe) {
return RxJavaPlugins.onAssembly(new MaybePeek<T>(this,
ObjectHelper.requireNonNull(onSubscribe, "onSubscribe is null"),
Functions.emptyConsumer(), // onSuccess
Functions.emptyConsumer(), // onError
Functions.EMPTY_ACTION, // onComplete
Functions.EMPTY_ACTION, // (onSuccess | onError | onComplete)
Functions.EMPTY_ACTION // dispose
));
}
/**
* Returns a Maybe instance that calls the given onTerminate callback
* just before this Maybe completes normally or with an exception.
* <p>
* <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnTerminate.png" alt="">
* <p>
* This differs from {@code doAfterTerminate} in that this happens <em>before</em> the {@code onComplete} or
* {@code onError} notification.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code doOnTerminate} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param onTerminate the action to invoke when the consumer calls {@code onComplete} or {@code onError}
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a>
* @see #doOnTerminate(Action)
* @since 2.2.7 - experimental
*/
@Experimental
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> doOnTerminate(final Action onTerminate) {
ObjectHelper.requireNonNull(onTerminate, "onTerminate is null");
return RxJavaPlugins.onAssembly(new MaybeDoOnTerminate<T>(this, onTerminate));
}
/**
* Calls the shared consumer with the success value sent via onSuccess for each
* MaybeObserver that subscribes to the current Maybe.
* <p>
* <img width="640" height="358" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnSuccess.m.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code doOnSuccess} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param onSuccess the consumer called with the success value of onSuccess
* @return the new Maybe instance
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> doOnSuccess(Consumer<? super T> onSuccess) {
return RxJavaPlugins.onAssembly(new MaybePeek<T>(this,
Functions.emptyConsumer(), // onSubscribe
ObjectHelper.requireNonNull(onSuccess, "onSuccess is null"),
Functions.emptyConsumer(), // onError
Functions.EMPTY_ACTION, // onComplete
Functions.EMPTY_ACTION, // (onSuccess | onError | onComplete)
Functions.EMPTY_ACTION // dispose
));
}
/**
* Filters the success item of the Maybe via a predicate function and emitting it if the predicate
* returns true, completing otherwise.
* <p>
* <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/filter.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code filter} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param predicate
* a function that evaluates the item emitted by the source Maybe, returning {@code true}
* if it passes the filter
* @return a Maybe that emit the item emitted by the source Maybe that the filter
* evaluates as {@code true}
* @see <a href="http://reactivex.io/documentation/operators/filter.html">ReactiveX operators documentation: Filter</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> filter(Predicate<? super T> predicate) {
ObjectHelper.requireNonNull(predicate, "predicate is null");
return RxJavaPlugins.onAssembly(new MaybeFilter<T>(this, predicate));
}
/**
* Returns a Maybe that is based on applying a specified function to the item emitted by the source Maybe,
* where that function returns a MaybeSource.
* <p>
* <img width="640" height="356" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMap.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* <p>Note that flatMap and concatMap for Maybe is the same operation.
*
* @param <R> the result value type
* @param mapper
* a function that, when applied to the item emitted by the source Maybe, returns a MaybeSource
* @return the Maybe returned from {@code func} when applied to the item emitted by the source Maybe
* @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <R> Maybe<R> flatMap(Function<? super T, ? extends MaybeSource<? extends R>> mapper) {
ObjectHelper.requireNonNull(mapper, "mapper is null");
return RxJavaPlugins.onAssembly(new MaybeFlatten<T, R>(this, mapper));
}
/**
* Maps the onSuccess, onError or onComplete signals of this Maybe into MaybeSource and emits that
* MaybeSource's signals.
* <p>
* <img width="640" height="354" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMap.mmm.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <R>
* the result type
* @param onSuccessMapper
* a function that returns a MaybeSource to merge for the onSuccess item emitted by this Maybe
* @param onErrorMapper
* a function that returns a MaybeSource to merge for an onError notification from this Maybe
* @param onCompleteSupplier
* a function that returns a MaybeSource to merge for an onComplete notification this Maybe
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <R> Maybe<R> flatMap(
Function<? super T, ? extends MaybeSource<? extends R>> onSuccessMapper,
Function<? super Throwable, ? extends MaybeSource<? extends R>> onErrorMapper,
Callable<? extends MaybeSource<? extends R>> onCompleteSupplier) {
ObjectHelper.requireNonNull(onSuccessMapper, "onSuccessMapper is null");
ObjectHelper.requireNonNull(onErrorMapper, "onErrorMapper is null");
ObjectHelper.requireNonNull(onCompleteSupplier, "onCompleteSupplier is null");
return RxJavaPlugins.onAssembly(new MaybeFlatMapNotification<T, R>(this, onSuccessMapper, onErrorMapper, onCompleteSupplier));
}
/**
* Returns a Maybe that emits the results of a specified function to the pair of values emitted by the
* source Maybe and a specified mapped MaybeSource.
* <p>
* <img width="640" height="390" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeMap.r.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <U>
* the type of items emitted by the MaybeSource returned by the {@code mapper} function
* @param <R>
* the type of items emitted by the resulting Maybe
* @param mapper
* a function that returns a MaybeSource for the item emitted by the source Maybe
* @param resultSelector
* a function that combines one item emitted by each of the source and collection MaybeSource and
* returns an item to be emitted by the resulting MaybeSource
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <U, R> Maybe<R> flatMap(Function<? super T, ? extends MaybeSource<? extends U>> mapper,
BiFunction<? super T, ? super U, ? extends R> resultSelector) {
ObjectHelper.requireNonNull(mapper, "mapper is null");
ObjectHelper.requireNonNull(resultSelector, "resultSelector is null");
return RxJavaPlugins.onAssembly(new MaybeFlatMapBiSelector<T, U, R>(this, mapper, resultSelector));
}
/**
* Maps the success value of the upstream {@link Maybe} into an {@link Iterable} and emits its items as a
* {@link Flowable} sequence.
* <p>
* <img width="640" height="373" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/flattenAsFlowable.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code flattenAsFlowable} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <U>
* the type of item emitted by the resulting Iterable
* @param mapper
* a function that returns an Iterable sequence of values for when given an item emitted by the
* source Maybe
* @return the new Flowable instance
* @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a>
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <U> Flowable<U> flattenAsFlowable(final Function<? super T, ? extends Iterable<? extends U>> mapper) {
ObjectHelper.requireNonNull(mapper, "mapper is null");
return RxJavaPlugins.onAssembly(new MaybeFlatMapIterableFlowable<T, U>(this, mapper));
}
/**
* Maps the success value of the upstream {@link Maybe} into an {@link Iterable} and emits its items as an
* {@link Observable} sequence.
* <p>
* <img width="640" height="373" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/flattenAsObservable.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code flattenAsObservable} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <U>
* the type of item emitted by the resulting Iterable
* @param mapper
* a function that returns an Iterable sequence of values for when given an item emitted by the
* source Maybe
* @return the new Observable instance
* @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <U> Observable<U> flattenAsObservable(final Function<? super T, ? extends Iterable<? extends U>> mapper) {
ObjectHelper.requireNonNull(mapper, "mapper is null");
return RxJavaPlugins.onAssembly(new MaybeFlatMapIterableObservable<T, U>(this, mapper));
}
/**
* Returns an Observable that is based on applying a specified function to the item emitted by the source Maybe,
* where that function returns an ObservableSource.
* <p>
* <img width="640" height="356" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMap.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code flatMapObservable} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <R> the result value type
* @param mapper
* a function that, when applied to the item emitted by the source Maybe, returns an ObservableSource
* @return the Observable returned from {@code func} when applied to the item emitted by the source Maybe
* @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <R> Observable<R> flatMapObservable(Function<? super T, ? extends ObservableSource<? extends R>> mapper) {
ObjectHelper.requireNonNull(mapper, "mapper is null");
return RxJavaPlugins.onAssembly(new MaybeFlatMapObservable<T, R>(this, mapper));
}
/**
* Returns a Flowable that emits items based on applying a specified function to the item emitted by the
* source Maybe, where that function returns a Publisher.
* <p>
* <img width="640" height="260" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMapPublisher.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The returned Flowable honors the downstream backpressure.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code flatMapPublisher} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <R> the result value type
* @param mapper
* a function that, when applied to the item emitted by the source Maybe, returns a
* Flowable
* @return the Flowable returned from {@code func} when applied to the item emitted by the source Maybe
* @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a>
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <R> Flowable<R> flatMapPublisher(Function<? super T, ? extends Publisher<? extends R>> mapper) {
ObjectHelper.requireNonNull(mapper, "mapper is null");
return RxJavaPlugins.onAssembly(new MaybeFlatMapPublisher<T, R>(this, mapper));
}
/**
* Returns a {@link Single} based on applying a specified function to the item emitted by the
* source {@link Maybe}, where that function returns a {@link Single}.
* When this Maybe completes a {@link NoSuchElementException} will be thrown.
* <p>
* <img width="640" height="356" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMapSingle.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code flatMapSingle} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <R> the result value type
* @param mapper
* a function that, when applied to the item emitted by the source Maybe, returns a
* Single
* @return the Single returned from {@code mapper} when applied to the item emitted by the source Maybe
* @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <R> Single<R> flatMapSingle(final Function<? super T, ? extends SingleSource<? extends R>> mapper) {
ObjectHelper.requireNonNull(mapper, "mapper is null");
return RxJavaPlugins.onAssembly(new MaybeFlatMapSingle<T, R>(this, mapper));
}
/**
* Returns a {@link Maybe} based on applying a specified function to the item emitted by the
* source {@link Maybe}, where that function returns a {@link Single}.
* When this Maybe just completes the resulting {@code Maybe} completes as well.
* <p>
* <img width="640" height="356" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMapSingle.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code flatMapSingleElement} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* <p>History: 2.0.2 - experimental
* @param <R> the result value type
* @param mapper
* a function that, when applied to the item emitted by the source Maybe, returns a
* Single
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a>
* @since 2.1
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <R> Maybe<R> flatMapSingleElement(final Function<? super T, ? extends SingleSource<? extends R>> mapper) {
ObjectHelper.requireNonNull(mapper, "mapper is null");
return RxJavaPlugins.onAssembly(new MaybeFlatMapSingleElement<T, R>(this, mapper));
}
/**
* Returns a {@link Completable} that completes based on applying a specified function to the item emitted by the
* source {@link Maybe}, where that function returns a {@link Completable}.
* <p>
* <img width="640" height="267" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMapCompletable.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code flatMapCompletable} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param mapper
* a function that, when applied to the item emitted by the source Maybe, returns a
* Completable
* @return the Completable returned from {@code mapper} when applied to the item emitted by the source Maybe
* @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Completable flatMapCompletable(final Function<? super T, ? extends CompletableSource> mapper) {
ObjectHelper.requireNonNull(mapper, "mapper is null");
return RxJavaPlugins.onAssembly(new MaybeFlatMapCompletable<T>(this, mapper));
}
/**
* Hides the identity of this Maybe and its Disposable.
* <p>
* <img width="640" height="300" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.hide.png" alt="">
* <p>Allows preventing certain identity-based
* optimizations (fusion).
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code hide} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @return the new Maybe instance
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> hide() {
return RxJavaPlugins.onAssembly(new MaybeHide<T>(this));
}
/**
* Ignores the item emitted by the source Maybe and only calls {@code onComplete} or {@code onError}.
* <p>
* <img width="640" height="389" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.ignoreElement.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code ignoreElement} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @return an empty Completable that only calls {@code onComplete} or {@code onError}, based on which one is
* called by the source Maybe
* @see <a href="http://reactivex.io/documentation/operators/ignoreelements.html">ReactiveX operators documentation: IgnoreElements</a>
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Completable ignoreElement() {
return RxJavaPlugins.onAssembly(new MaybeIgnoreElementCompletable<T>(this));
}
/**
* Returns a Single that emits {@code true} if the source Maybe is empty, otherwise {@code false}.
* <p>
* <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/isEmpty.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code isEmpty} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @return a Single that emits a Boolean
* @see <a href="http://reactivex.io/documentation/operators/contains.html">ReactiveX operators documentation: Contains</a>
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Single<Boolean> isEmpty() {
return RxJavaPlugins.onAssembly(new MaybeIsEmptySingle<T>(this));
}
/**
* <strong>This method requires advanced knowledge about building operators, please consider
* other standard composition methods first;</strong>
* Returns a {@code Maybe} which, when subscribed to, invokes the {@link MaybeOperator#apply(MaybeObserver) apply(MaybeObserver)} method
* of the provided {@link MaybeOperator} for each individual downstream {@link Maybe} and allows the
* insertion of a custom operator by accessing the downstream's {@link MaybeObserver} during this subscription phase
* and providing a new {@code MaybeObserver}, containing the custom operator's intended business logic, that will be
* used in the subscription process going further upstream.
* <p>
* Generally, such a new {@code MaybeObserver} will wrap the downstream's {@code MaybeObserver} and forwards the
* {@code onSuccess}, {@code onError} and {@code onComplete} events from the upstream directly or according to the
* emission pattern the custom operator's business logic requires. In addition, such operator can intercept the
* flow control calls of {@code dispose} and {@code isDisposed} that would have traveled upstream and perform
* additional actions depending on the same business logic requirements.
* <p>
* Example:
* <pre><code>
* // Step 1: Create the consumer type that will be returned by the MaybeOperator.apply():
*
* public final class CustomMaybeObserver<T> implements MaybeObserver<T>, Disposable {
*
* // The downstream's MaybeObserver that will receive the onXXX events
* final MaybeObserver<? super String> downstream;
*
* // The connection to the upstream source that will call this class' onXXX methods
* Disposable upstream;
*
* // The constructor takes the downstream subscriber and usually any other parameters
* public CustomMaybeObserver(MaybeObserver<? super String> downstream) {
* this.downstream = downstream;
* }
*
* // In the subscription phase, the upstream sends a Disposable to this class
* // and subsequently this class has to send a Disposable to the downstream.
* // Note that relaying the upstream's Disposable directly is not allowed in RxJava
* @Override
* public void onSubscribe(Disposable d) {
* if (upstream != null) {
* d.dispose();
* } else {
* upstream = d;
* downstream.onSubscribe(this);
* }
* }
*
* // The upstream calls this with the next item and the implementation's
* // responsibility is to emit an item to the downstream based on the intended
* // business logic, or if it can't do so for the particular item,
* // request more from the upstream
* @Override
* public void onSuccess(T item) {
* String str = item.toString();
* if (str.length() < 2) {
* downstream.onSuccess(str);
* } else {
* // Maybe is usually expected to produce one of the onXXX events
* downstream.onComplete();
* }
* }
*
* // Some operators may handle the upstream's error while others
* // could just forward it to the downstream.
* @Override
* public void onError(Throwable throwable) {
* downstream.onError(throwable);
* }
*
* // When the upstream completes, usually the downstream should complete as well.
* @Override
* public void onComplete() {
* downstream.onComplete();
* }
*
* // Some operators may use their own resources which should be cleaned up if
* // the downstream disposes the flow before it completed. Operators without
* // resources can simply forward the dispose to the upstream.
* // In some cases, a disposed flag may be set by this method so that other parts
* // of this class may detect the dispose and stop sending events
* // to the downstream.
* @Override
* public void dispose() {
* upstream.dispose();
* }
*
* // Some operators may simply forward the call to the upstream while others
* // can return the disposed flag set in dispose().
* @Override
* public boolean isDisposed() {
* return upstream.isDisposed();
* }
* }
*
* // Step 2: Create a class that implements the MaybeOperator interface and
* // returns the custom consumer type from above in its apply() method.
* // Such class may define additional parameters to be submitted to
* // the custom consumer type.
*
* final class CustomMaybeOperator<T> implements MaybeOperator<String> {
* @Override
* public MaybeObserver<? super String> apply(MaybeObserver<? super T> upstream) {
* return new CustomMaybeObserver<T>(upstream);
* }
* }
*
* // Step 3: Apply the custom operator via lift() in a flow by creating an instance of it
* // or reusing an existing one.
*
* Maybe.just(5)
* .lift(new CustomMaybeOperator<Integer>())
* .test()
* .assertResult("5");
*
* Maybe.just(15)
* .lift(new CustomMaybeOperator<Integer>())
* .test()
* .assertResult();
* </code></pre>
* <p>
* Creating custom operators can be complicated and it is recommended one consults the
* <a href="https://github.com/ReactiveX/RxJava/wiki/Writing-operators-for-2.0">RxJava wiki: Writing operators</a> page about
* the tools, requirements, rules, considerations and pitfalls of implementing them.
* <p>
* Note that implementing custom operators via this {@code lift()} method adds slightly more overhead by requiring
* an additional allocation and indirection per assembled flows. Instead, extending the abstract {@code Maybe}
* class and creating a {@link MaybeTransformer} with it is recommended.
* <p>
* Note also that it is not possible to stop the subscription phase in {@code lift()} as the {@code apply()} method
* requires a non-null {@code MaybeObserver} instance to be returned, which is then unconditionally subscribed to
* the upstream {@code Maybe}. For example, if the operator decided there is no reason to subscribe to the
* upstream source because of some optimization possibility or a failure to prepare the operator, it still has to
* return a {@code MaybeObserver} that should immediately dispose the upstream's {@code Disposable} in its
* {@code onSubscribe} method. Again, using a {@code MaybeTransformer} and extending the {@code Maybe} is
* a better option as {@link #subscribeActual} can decide to not subscribe to its upstream after all.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code lift} does not operate by default on a particular {@link Scheduler}, however, the
* {@link MaybeOperator} may use a {@code Scheduler} to support its own asynchronous behavior.</dd>
* </dl>
*
* @param <R> the output value type
* @param lift the {@link MaybeOperator} that receives the downstream's {@code MaybeObserver} and should return
* a {@code MaybeObserver} with custom behavior to be used as the consumer for the current
* {@code Maybe}.
* @return the new Maybe instance
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Writing-operators-for-2.0">RxJava wiki: Writing operators</a>
* @see #compose(MaybeTransformer)
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <R> Maybe<R> lift(final MaybeOperator<? extends R, ? super T> lift) {
ObjectHelper.requireNonNull(lift, "lift is null");
return RxJavaPlugins.onAssembly(new MaybeLift<T, R>(this, lift));
}
/**
* Returns a Maybe that applies a specified function to the item emitted by the source Maybe and
* emits the result of this function application.
* <p>
* <img width="640" height="515" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.map.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code map} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <R> the result value type
* @param mapper
* a function to apply to the item emitted by the Maybe
* @return a Maybe that emits the item from the source Maybe, transformed by the specified function
* @see <a href="http://reactivex.io/documentation/operators/map.html">ReactiveX operators documentation: Map</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <R> Maybe<R> map(Function<? super T, ? extends R> mapper) {
ObjectHelper.requireNonNull(mapper, "mapper is null");
return RxJavaPlugins.onAssembly(new MaybeMap<T, R>(this, mapper));
}
/**
* Maps the signal types of this Maybe into a {@link Notification} of the same kind
* and emits it as a single success value to downstream.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/materialize.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code materialize} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @return the new Single instance
* @since 2.2.4 - experimental
* @see Single#dematerialize(Function)
*/
@Experimental
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Single<Notification<T>> materialize() {
return RxJavaPlugins.onAssembly(new MaybeMaterialize<T>(this));
}
/**
* Flattens this and another Maybe into a single Flowable, without any transformation.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.png" alt="">
* <p>
* You can combine items emitted by multiple Maybes so that they appear as a single Flowable, by
* using the {@code mergeWith} method.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors backpressure from downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code mergeWith} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param other
* a MaybeSource to be merged
* @return a new Flowable instance
* @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a>
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Flowable<T> mergeWith(MaybeSource<? extends T> other) {
ObjectHelper.requireNonNull(other, "other is null");
return merge(this, other);
}
/**
* Wraps a Maybe to emit its item (or notify of its error) on a specified {@link Scheduler},
* asynchronously.
* <p>
* <img width="640" height="182" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.observeOn.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>you specify which {@link Scheduler} this operator will use.</dd>
* </dl>
*
* @param scheduler
* the {@link Scheduler} to notify subscribers on
* @return the new Maybe instance that its subscribers are notified on the specified
* {@link Scheduler}
* @see <a href="http://reactivex.io/documentation/operators/observeon.html">ReactiveX operators documentation: ObserveOn</a>
* @see <a href="http://www.grahamlea.com/2014/07/rxjava-threading-examples/">RxJava Threading Examples</a>
* @see #subscribeOn
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.CUSTOM)
public final Maybe<T> observeOn(final Scheduler scheduler) {
ObjectHelper.requireNonNull(scheduler, "scheduler is null");
return RxJavaPlugins.onAssembly(new MaybeObserveOn<T>(this, scheduler));
}
/**
* Filters the items emitted by a Maybe, only emitting its success value if that
* is an instance of the supplied Class.
* <p>
* <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ofClass.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code ofType} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <U> the output type
* @param clazz
* the class type to filter the items emitted by the source Maybe
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/filter.html">ReactiveX operators documentation: Filter</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <U> Maybe<U> ofType(final Class<U> clazz) {
ObjectHelper.requireNonNull(clazz, "clazz is null");
return filter(Functions.isInstanceOf(clazz)).cast(clazz);
}
/**
* Calls the specified converter function with the current Maybe instance
* during assembly time and returns its result.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code to} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <R> the result type
* @param convert the function that is called with the current Maybe instance during
* assembly time that should return some value to be the result
*
* @return the value returned by the convert function
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <R> R to(Function<? super Maybe<T>, R> convert) {
try {
return ObjectHelper.requireNonNull(convert, "convert is null").apply(this);
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
throw ExceptionHelper.wrapOrThrow(ex);
}
}
/**
* Converts this Maybe into a backpressure-aware Flowable instance composing cancellation
* through.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The returned Flowable honors the backpressure of the downstream.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code toFlowable} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @return the new Flowable instance
*/
@SuppressWarnings("unchecked")
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Flowable<T> toFlowable() {
if (this instanceof FuseToFlowable) {
return ((FuseToFlowable<T>)this).fuseToFlowable();
}
return RxJavaPlugins.onAssembly(new MaybeToFlowable<T>(this));
}
/**
* Converts this Maybe into an Observable instance composing disposal
* through.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code toObservable} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @return the new Observable instance
*/
@SuppressWarnings("unchecked")
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Observable<T> toObservable() {
if (this instanceof FuseToObservable) {
return ((FuseToObservable<T>)this).fuseToObservable();
}
return RxJavaPlugins.onAssembly(new MaybeToObservable<T>(this));
}
/**
* Converts this Maybe into a Single instance composing disposal
* through and turning an empty Maybe into a Single that emits the given
* value through onSuccess.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code toSingle} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param defaultValue the default item to signal in Single if this Maybe is empty
* @return the new Single instance
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Single<T> toSingle(T defaultValue) {
ObjectHelper.requireNonNull(defaultValue, "defaultValue is null");
return RxJavaPlugins.onAssembly(new MaybeToSingle<T>(this, defaultValue));
}
/**
* Converts this Maybe into a Single instance composing disposal
* through and turning an empty Maybe into a signal of NoSuchElementException.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code toSingle} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @return the new Single instance
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Single<T> toSingle() {
return RxJavaPlugins.onAssembly(new MaybeToSingle<T>(this, null));
}
/**
* Returns a Maybe instance that if this Maybe emits an error, it will emit an onComplete
* and swallow the throwable.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code onErrorComplete} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @return the new Maybe instance
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> onErrorComplete() {
return onErrorComplete(Functions.alwaysTrue());
}
/**
* Returns a Maybe instance that if this Maybe emits an error and the predicate returns
* true, it will emit an onComplete and swallow the throwable.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code onErrorComplete} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param predicate the predicate to call when an Throwable is emitted which should return true
* if the Throwable should be swallowed and replaced with an onComplete.
* @return the new Maybe instance
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> onErrorComplete(final Predicate<? super Throwable> predicate) {
ObjectHelper.requireNonNull(predicate, "predicate is null");
return RxJavaPlugins.onAssembly(new MaybeOnErrorComplete<T>(this, predicate));
}
/**
* Instructs a Maybe to pass control to another {@link MaybeSource} rather than invoking
* {@link MaybeObserver#onError onError} if it encounters an error.
* <p>
* <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/onErrorResumeNext.png" alt="">
* <p>
* You can use this to prevent errors from propagating or to supply fallback data should errors be
* encountered.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code onErrorResumeNext} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param next
* the next {@code MaybeSource} that will take over if the source Maybe encounters
* an error
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> onErrorResumeNext(final MaybeSource<? extends T> next) {
ObjectHelper.requireNonNull(next, "next is null");
return onErrorResumeNext(Functions.justFunction(next));
}
/**
* Instructs a Maybe to pass control to another Maybe rather than invoking
* {@link MaybeObserver#onError onError} if it encounters an error.
* <p>
* <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/onErrorResumeNext.png" alt="">
* <p>
* You can use this to prevent errors from propagating or to supply fallback data should errors be
* encountered.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code onErrorResumeNext} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param resumeFunction
* a function that returns a MaybeSource that will take over if the source Maybe encounters
* an error
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> onErrorResumeNext(Function<? super Throwable, ? extends MaybeSource<? extends T>> resumeFunction) {
ObjectHelper.requireNonNull(resumeFunction, "resumeFunction is null");
return RxJavaPlugins.onAssembly(new MaybeOnErrorNext<T>(this, resumeFunction, true));
}
/**
* Instructs a Maybe to emit an item (returned by a specified function) rather than invoking
* {@link MaybeObserver#onError onError} if it encounters an error.
* <p>
* <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/onErrorReturn.png" alt="">
* <p>
* You can use this to prevent errors from propagating or to supply fallback data should errors be
* encountered.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code onErrorReturn} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param valueSupplier
* a function that returns a single value that will be emitted as success value
* the current Maybe signals an onError event
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> onErrorReturn(Function<? super Throwable, ? extends T> valueSupplier) {
ObjectHelper.requireNonNull(valueSupplier, "valueSupplier is null");
return RxJavaPlugins.onAssembly(new MaybeOnErrorReturn<T>(this, valueSupplier));
}
/**
* Instructs a Maybe to emit an item (returned by a specified function) rather than invoking
* {@link MaybeObserver#onError onError} if it encounters an error.
* <p>
* <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/onErrorReturn.png" alt="">
* <p>
* You can use this to prevent errors from propagating or to supply fallback data should errors be
* encountered.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code onErrorReturnItem} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param item
* the value that is emitted as onSuccess in case this Maybe signals an onError
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> onErrorReturnItem(final T item) {
ObjectHelper.requireNonNull(item, "item is null");
return onErrorReturn(Functions.justFunction(item));
}
/**
* Instructs a Maybe to pass control to another MaybeSource rather than invoking
* {@link MaybeObserver#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="333" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/onExceptionResumeNextViaMaybe.png" alt="">
* <p>
* You can use this to prevent exceptions from propagating or to supply fallback data should exceptions be
* encountered.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code onExceptionResumeNext} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param next
* the next MaybeSource that will take over if the source Maybe encounters
* an exception
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> onExceptionResumeNext(final MaybeSource<? extends T> next) {
ObjectHelper.requireNonNull(next, "next is null");
return RxJavaPlugins.onAssembly(new MaybeOnErrorNext<T>(this, Functions.justFunction(next), false));
}
/**
* Nulls out references to the upstream producer and downstream MaybeObserver if
* the sequence is terminated or downstream calls dispose().
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @return a Maybe which nulls out references to the upstream producer and downstream MaybeObserver if
* the sequence is terminated or downstream calls dispose()
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> onTerminateDetach() {
return RxJavaPlugins.onAssembly(new MaybeDetach<T>(this));
}
/**
* Returns a Flowable that repeats the sequence of items emitted by the source Maybe indefinitely.
* <p>
* <img width="640" height="309" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/repeat.o.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors downstream backpressure.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code repeat} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @return a Flowable that emits the items emitted by the source Maybe repeatedly and in sequence
* @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a>
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Flowable<T> repeat() {
return repeat(Long.MAX_VALUE);
}
/**
* Returns a Flowable that repeats the sequence of items emitted by the source Maybe at most
* {@code count} times.
* <p>
* <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/repeat.on.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>This operator honors downstream backpressure.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code repeat} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param times
* the number of times the source Maybe items are repeated, a count of 0 will yield an empty
* sequence
* @return a Flowable that repeats the sequence of items emitted by the source Maybe at most
* {@code count} times
* @throws IllegalArgumentException
* if {@code count} is less than zero
* @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a>
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Flowable<T> repeat(long times) {
return toFlowable().repeat(times);
}
/**
* Returns a Flowable that repeats the sequence of items emitted by the source Maybe until
* the provided stop function returns true.
* <p>
* <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/repeat.on.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>This operator honors downstream backpressure.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code repeatUntil} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param stop
* a boolean supplier that is called when the current Flowable completes and unless it returns
* false, the current Flowable is resubscribed
* @return the new Flowable instance
* @throws NullPointerException
* if {@code stop} is null
* @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a>
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Flowable<T> repeatUntil(BooleanSupplier stop) {
return toFlowable().repeatUntil(stop);
}
/**
* Returns a Flowable that emits the same values as the source Publisher with the exception of an
* {@code onComplete}. An {@code onComplete} notification from the source will result in the emission of
* a {@code void} item to the Publisher provided as an argument to the {@code notificationHandler}
* function. If that Publisher calls {@code onComplete} or {@code onError} then {@code repeatWhen} will
* call {@code onComplete} or {@code onError} on the child subscription. Otherwise, this Publisher will
* resubscribe to the source Publisher.
* <p>
* <img width="640" height="430" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/repeatWhen.f.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator honors downstream backpressure and expects the source {@code Publisher} to honor backpressure as well.
* If this expectation is violated, the operator <em>may</em> throw an {@code IllegalStateException}.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code repeatWhen} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param handler
* receives a Publisher of notifications with which a user can complete or error, aborting the repeat.
* @return the source Publisher modified with repeat logic
* @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a>
*/
@BackpressureSupport(BackpressureKind.FULL)
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Flowable<T> repeatWhen(final Function<? super Flowable<Object>, ? extends Publisher<?>> handler) {
return toFlowable().repeatWhen(handler);
}
/**
* Returns a Maybe that mirrors the source Maybe, resubscribing to it if it calls {@code onError}
* (infinite retry count).
* <p>
* <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/retry.png" alt="">
* <p>
* If the source Maybe calls {@link MaybeObserver#onError}, this method will resubscribe to the source
* Maybe rather than propagating the {@code onError} call.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a>
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> retry() {
return retry(Long.MAX_VALUE, Functions.alwaysTrue());
}
/**
* Returns a Maybe that mirrors the source Maybe, 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/ReactiveX/RxJava/images/rx-operators/retry.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param predicate
* the predicate that determines if a resubscription may happen in case of a specific exception
* and retry count
* @return the new Maybe instance
* @see #retry()
* @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a>
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> retry(BiPredicate<? super Integer, ? super Throwable> predicate) {
return toFlowable().retry(predicate).singleElement();
}
/**
* Returns a Maybe that mirrors the source Maybe, 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/ReactiveX/RxJava/images/rx-operators/retry.png" alt="">
* <p>
* If the source Maybe calls {@link MaybeObserver#onError}, this method will resubscribe to the source
* Maybe for a maximum of {@code count} resubscriptions rather than propagating the
* {@code onError} call.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param count
* the number of times to resubscribe if the current Maybe fails
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a>
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> retry(long count) {
return retry(count, Functions.alwaysTrue());
}
/**
* Retries at most times or until the predicate returns false, whichever happens first.
*
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param times the number of times to resubscribe if the current Maybe fails
* @param predicate the predicate called with the failure Throwable and should return true to trigger a retry.
* @return the new Maybe instance
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> retry(long times, Predicate<? super Throwable> predicate) {
return toFlowable().retry(times, predicate).singleElement();
}
/**
* Retries the current Maybe if it fails and the predicate returns true.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param predicate the predicate that receives the failure Throwable and should return true to trigger a retry.
* @return the new Maybe instance
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> retry(Predicate<? super Throwable> predicate) {
return retry(Long.MAX_VALUE, predicate);
}
/**
* Retries until the given stop function returns true.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code retryUntil} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param stop the function that should return true to stop retrying
* @return the new Maybe instance
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> retryUntil(final BooleanSupplier stop) {
ObjectHelper.requireNonNull(stop, "stop is null");
return retry(Long.MAX_VALUE, Functions.predicateReverseFor(stop));
}
/**
* Returns a Maybe that emits the same values as the source Maybe with the exception of an
* {@code onError}. An {@code onError} notification from the source will result in the emission of a
* {@link Throwable} item to the Publisher provided as an argument to the {@code notificationHandler}
* function. If that Publisher calls {@code onComplete} or {@code onError} then {@code retry} will call
* {@code onComplete} or {@code onError} on the child subscription. Otherwise, this Publisher will
* resubscribe to the source Publisher.
* <p>
* <img width="640" height="430" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/retryWhen.f.png" alt="">
* <p>
* Example:
*
* This retries 3 times, each time incrementing the number of seconds it waits.
*
* <pre><code>
* Maybe.create((MaybeEmitter<? super String> s) -> {
* System.out.println("subscribing");
* s.onError(new RuntimeException("always fails"));
* }, BackpressureStrategy.BUFFER).retryWhen(attempts -> {
* return attempts.zipWith(Publisher.range(1, 3), (n, i) -> i).flatMap(i -> {
* System.out.println("delay retry by " + i + " second(s)");
* return Flowable.timer(i, TimeUnit.SECONDS);
* });
* }).blockingForEach(System.out::println);
* </code></pre>
*
* Output is:
*
* <pre> {@code
* subscribing
* delay retry by 1 second(s)
* subscribing
* delay retry by 2 second(s)
* subscribing
* delay retry by 3 second(s)
* subscribing
* } </pre>
* <p>
* Note that the inner {@code Publisher} returned by the handler function should signal
* either {@code onNext}, {@code onError} or {@code onComplete} in response to the received
* {@code Throwable} to indicate the operator should retry or terminate. If the upstream to
* the operator is asynchronous, signalling onNext followed by onComplete immediately may
* result in the sequence to be completed immediately. Similarly, if this inner
* {@code Publisher} signals {@code onError} or {@code onComplete} while the upstream is
* active, the sequence is terminated with the same signal immediately.
* <p>
* The following example demonstrates how to retry an asynchronous source with a delay:
* <pre><code>
* Maybe.timer(1, TimeUnit.SECONDS)
* .doOnSubscribe(s -> System.out.println("subscribing"))
* .map(v -> { throw new RuntimeException(); })
* .retryWhen(errors -> {
* AtomicInteger counter = new AtomicInteger();
* return errors
* .takeWhile(e -> counter.getAndIncrement() != 3)
* .flatMap(e -> {
* System.out.println("delay retry by " + counter.get() + " second(s)");
* return Flowable.timer(counter.get(), TimeUnit.SECONDS);
* });
* })
* .blockingGet();
* </code></pre>
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code retryWhen} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param handler
* receives a Publisher of notifications with which a user can complete or error, aborting the
* retry
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a>
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> retryWhen(
final Function<? super Flowable<Throwable>, ? extends Publisher<?>> handler) {
return toFlowable().retryWhen(handler).singleElement();
}
/**
* Subscribes to a Maybe and ignores {@code onSuccess} and {@code onComplete} emissions.
* <p>
* If the Maybe emits an error, it is wrapped into an
* {@link io.reactivex.exceptions.OnErrorNotImplementedException OnErrorNotImplementedException}
* and routed to the RxJavaPlugins.onError handler.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @return a {@link Disposable} reference with which the caller can stop receiving items before
* the Maybe has finished sending them
* @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a>
*/
@SchedulerSupport(SchedulerSupport.NONE)
public final Disposable subscribe() {
return subscribe(Functions.emptyConsumer(), Functions.ON_ERROR_MISSING, Functions.EMPTY_ACTION);
}
/**
* Subscribes to a Maybe and provides a callback to handle the items it emits.
* <p>
* If the Maybe emits an error, it is wrapped into an
* {@link io.reactivex.exceptions.OnErrorNotImplementedException OnErrorNotImplementedException}
* and routed to the RxJavaPlugins.onError handler.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param onSuccess
* the {@code Consumer<T>} you have designed to accept a success value from the Maybe
* @return a {@link Disposable} reference with which the caller can stop receiving items before
* the Maybe has finished sending them
* @throws NullPointerException
* if {@code onSuccess} is null
* @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a>
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Disposable subscribe(Consumer<? super T> onSuccess) {
return subscribe(onSuccess, Functions.ON_ERROR_MISSING, Functions.EMPTY_ACTION);
}
/**
* Subscribes to a Maybe and provides callbacks to handle the items it emits and any error
* notification it issues.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param onSuccess
* the {@code Consumer<T>} you have designed to accept a success value from the Maybe
* @param onError
* the {@code Consumer<Throwable>} you have designed to accept any error notification from the
* Maybe
* @return a {@link Disposable} reference with which the caller can stop receiving items before
* the Maybe has finished sending them
* @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a>
* @throws NullPointerException
* if {@code onSuccess} is null, or
* if {@code onError} is null
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Disposable subscribe(Consumer<? super T> onSuccess, Consumer<? super Throwable> onError) {
return subscribe(onSuccess, onError, Functions.EMPTY_ACTION);
}
/**
* Subscribes to a Maybe and provides callbacks to handle the items it emits and any error or
* completion notification it issues.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param onSuccess
* the {@code Consumer<T>} you have designed to accept a success value from the Maybe
* @param onError
* the {@code Consumer<Throwable>} you have designed to accept any error notification from the
* Maybe
* @param onComplete
* the {@code Action} you have designed to accept a completion notification from the
* Maybe
* @return a {@link Disposable} reference with which the caller can stop receiving items before
* the Maybe has finished sending them
* @throws NullPointerException
* if {@code onSuccess} is null, or
* if {@code onError} is null, or
* if {@code onComplete} is null
* @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Disposable subscribe(Consumer<? super T> onSuccess, Consumer<? super Throwable> onError,
Action onComplete) {
ObjectHelper.requireNonNull(onSuccess, "onSuccess is null");
ObjectHelper.requireNonNull(onError, "onError is null");
ObjectHelper.requireNonNull(onComplete, "onComplete is null");
return subscribeWith(new MaybeCallbackObserver<T>(onSuccess, onError, onComplete));
}
@SchedulerSupport(SchedulerSupport.NONE)
@Override
public final void subscribe(MaybeObserver<? super T> observer) {
ObjectHelper.requireNonNull(observer, "observer is null");
observer = RxJavaPlugins.onSubscribe(this, observer);
ObjectHelper.requireNonNull(observer, "The RxJavaPlugins.onSubscribe hook returned a null MaybeObserver. Please check the handler provided to RxJavaPlugins.setOnMaybeSubscribe for invalid null returns. Further reading: https://github.com/ReactiveX/RxJava/wiki/Plugins");
try {
subscribeActual(observer);
} catch (NullPointerException ex) {
throw ex;
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
NullPointerException npe = new NullPointerException("subscribeActual failed");
npe.initCause(ex);
throw npe;
}
}
/**
* Implement this method in subclasses to handle the incoming {@link MaybeObserver}s.
* <p>There is no need to call any of the plugin hooks on the current {@code Maybe} instance or
* the {@code MaybeObserver}; all hooks and basic safeguards have been
* applied by {@link #subscribe(MaybeObserver)} before this method gets called.
* @param observer the MaybeObserver to handle, not null
*/
protected abstract void subscribeActual(MaybeObserver<? super T> observer);
/**
* Asynchronously subscribes subscribers to this Maybe on the specified {@link Scheduler}.
* <p>
* <img width="640" height="752" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.subscribeOn.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>you specify which {@link Scheduler} this operator will use.</dd>
* </dl>
*
* @param scheduler
* the {@link Scheduler} to perform subscription actions on
* @return the new Maybe instance that its subscriptions happen on the specified {@link Scheduler}
* @see <a href="http://reactivex.io/documentation/operators/subscribeon.html">ReactiveX operators documentation: SubscribeOn</a>
* @see <a href="http://www.grahamlea.com/2014/07/rxjava-threading-examples/">RxJava Threading Examples</a>
* @see #observeOn
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.CUSTOM)
public final Maybe<T> subscribeOn(Scheduler scheduler) {
ObjectHelper.requireNonNull(scheduler, "scheduler is null");
return RxJavaPlugins.onAssembly(new MaybeSubscribeOn<T>(this, scheduler));
}
/**
* Subscribes a given MaybeObserver (subclass) to this Maybe and returns the given
* MaybeObserver as is.
* <p>Usage example:
* <pre><code>
* Maybe<Integer> source = Maybe.just(1);
* CompositeDisposable composite = new CompositeDisposable();
*
* DisposableMaybeObserver<Integer> ds = new DisposableMaybeObserver<>() {
* // ...
* };
*
* composite.add(source.subscribeWith(ds));
* </code></pre>
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code subscribeWith} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <E> the type of the MaybeObserver to use and return
* @param observer the MaybeObserver (subclass) to use and return, not null
* @return the input {@code subscriber}
* @throws NullPointerException if {@code subscriber} is null
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final <E extends MaybeObserver<? super T>> E subscribeWith(E observer) {
subscribe(observer);
return observer;
}
/**
* Returns a Maybe that emits the items emitted by the source Maybe or the items of an alternate
* MaybeSource if the current Maybe is empty.
* <p>
* <img width="640" height="445" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/switchifempty.m.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code switchIfEmpty} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param other
* the alternate MaybeSource to subscribe to if the main does not emit any items
* @return a Maybe that emits the items emitted by the source Maybe or the items of an
* alternate MaybeSource if the source Maybe is empty.
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> switchIfEmpty(MaybeSource<? extends T> other) {
ObjectHelper.requireNonNull(other, "other is null");
return RxJavaPlugins.onAssembly(new MaybeSwitchIfEmpty<T>(this, other));
}
/**
* Returns a Single that emits the items emitted by the source Maybe or the item of an alternate
* SingleSource if the current Maybe is empty.
* <p>
* <img width="640" height="445" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/switchifempty.m.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code switchIfEmpty} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* <p>History: 2.1.4 - experimental
* @param other
* the alternate SingleSource to subscribe to if the main does not emit any items
* @return a Single that emits the items emitted by the source Maybe or the item of an
* alternate SingleSource if the source Maybe is empty.
* @since 2.2
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final Single<T> switchIfEmpty(SingleSource<? extends T> other) {
ObjectHelper.requireNonNull(other, "other is null");
return RxJavaPlugins.onAssembly(new MaybeSwitchIfEmptySingle<T>(this, other));
}
/**
* Returns a Maybe that emits the items emitted by the source Maybe until a second MaybeSource
* emits an item.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeUntil.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code takeUntil} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param other
* the MaybeSource whose first emitted item will cause {@code takeUntil} to stop emitting items
* from the source Maybe
* @param <U>
* the type of items emitted by {@code other}
* @return a Maybe that emits the items emitted by the source Maybe until such time as {@code other} emits its first item
* @see <a href="http://reactivex.io/documentation/operators/takeuntil.html">ReactiveX operators documentation: TakeUntil</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <U> Maybe<T> takeUntil(MaybeSource<U> other) {
ObjectHelper.requireNonNull(other, "other is null");
return RxJavaPlugins.onAssembly(new MaybeTakeUntilMaybe<T, U>(this, other));
}
/**
* Returns a Maybe that emits the item emitted by the source Maybe until a second Publisher
* emits an item.
* <p>
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeUntil.png" alt="">
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The {@code Publisher} is consumed in an unbounded fashion and is cancelled after the first item
* emitted.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code takeUntil} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param other
* the Publisher whose first emitted item will cause {@code takeUntil} to stop emitting items
* from the source Publisher
* @param <U>
* the type of items emitted by {@code other}
* @return a Maybe that emits the items emitted by the source Maybe until such time as {@code other} emits its first item
* @see <a href="http://reactivex.io/documentation/operators/takeuntil.html">ReactiveX operators documentation: TakeUntil</a>
*/
@BackpressureSupport(BackpressureKind.UNBOUNDED_IN)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <U> Maybe<T> takeUntil(Publisher<U> other) {
ObjectHelper.requireNonNull(other, "other is null");
return RxJavaPlugins.onAssembly(new MaybeTakeUntilPublisher<T, U>(this, other));
}
/**
* Returns a Maybe that mirrors the source Maybe 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 Maybe terminates and notifies MaybeObservers of a {@code TimeoutException}.
* <p>
* <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout.1.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>This version of {@code timeout} operates by default on the {@code computation} {@link Scheduler}.</dd>
* </dl>
*
* @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 new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a>
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.COMPUTATION)
public final Maybe<T> timeout(long timeout, TimeUnit timeUnit) {
return timeout(timeout, timeUnit, Schedulers.computation());
}
/**
* Returns a Maybe that mirrors the source Maybe 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 source MaybeSource is disposed and resulting Maybe begins instead to mirror a fallback MaybeSource.
* <p>
* <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout.2.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>This version of {@code timeout} operates by default on the {@code computation} {@link Scheduler}.</dd>
* </dl>
*
* @param timeout
* maximum duration between items before a timeout occurs
* @param timeUnit
* the unit of time that applies to the {@code timeout} argument
* @param fallback
* the fallback MaybeSource to use in case of a timeout
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.COMPUTATION)
public final Maybe<T> timeout(long timeout, TimeUnit timeUnit, MaybeSource<? extends T> fallback) {
ObjectHelper.requireNonNull(fallback, "fallback is null");
return timeout(timeout, timeUnit, Schedulers.computation(), fallback);
}
/**
* Returns a Maybe that mirrors the source Maybe 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 source MaybeSource is disposed and resulting Maybe begins instead
* to mirror a fallback MaybeSource.
* <p>
* <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout.2s.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>You specify which {@link Scheduler} this operator will use.</dd>
* </dl>
*
* @param timeout
* maximum duration between items before a timeout occurs
* @param timeUnit
* the unit of time that applies to the {@code timeout} argument
* @param fallback
* the MaybeSource to use as the fallback in case of a timeout
* @param scheduler
* the {@link Scheduler} to run the timeout timers on
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.CUSTOM)
public final Maybe<T> timeout(long timeout, TimeUnit timeUnit, Scheduler scheduler, MaybeSource<? extends T> fallback) {
ObjectHelper.requireNonNull(fallback, "fallback is null");
return timeout(timer(timeout, timeUnit, scheduler), fallback);
}
/**
* Returns a Maybe that mirrors the source Maybe 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 Maybe terminates and
* notifies MaybeObservers of a {@code TimeoutException}.
* <p>
* <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout.1s.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>You specify which {@link Scheduler} this operator will use.</dd>
* </dl>
*
* @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 new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a>
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.CUSTOM)
public final Maybe<T> timeout(long timeout, TimeUnit timeUnit, Scheduler scheduler) {
return timeout(timer(timeout, timeUnit, scheduler));
}
/**
* If the current {@code Maybe} didn't signal an event before the {@code timeoutIndicator} {@link MaybeSource} signals, a
* {@link TimeoutException} is signaled instead.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code timeout} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <U> the value type of the
* @param timeoutIndicator the {@code MaybeSource} that indicates the timeout by signaling onSuccess
* or onComplete.
* @return the new Maybe instance
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <U> Maybe<T> timeout(MaybeSource<U> timeoutIndicator) {
ObjectHelper.requireNonNull(timeoutIndicator, "timeoutIndicator is null");
return RxJavaPlugins.onAssembly(new MaybeTimeoutMaybe<T, U>(this, timeoutIndicator, null));
}
/**
* If the current {@code Maybe} didn't signal an event before the {@code timeoutIndicator} {@link MaybeSource} signals,
* the current {@code Maybe} is disposed and the {@code fallback} {@code MaybeSource} subscribed to
* as a continuation.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code timeout} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <U> the value type of the
* @param timeoutIndicator the {@code MaybeSource} that indicates the timeout by signaling {@code onSuccess}
* or {@code onComplete}.
* @param fallback the {@code MaybeSource} that is subscribed to if the current {@code Maybe} times out
* @return the new Maybe instance
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <U> Maybe<T> timeout(MaybeSource<U> timeoutIndicator, MaybeSource<? extends T> fallback) {
ObjectHelper.requireNonNull(timeoutIndicator, "timeoutIndicator is null");
ObjectHelper.requireNonNull(fallback, "fallback is null");
return RxJavaPlugins.onAssembly(new MaybeTimeoutMaybe<T, U>(this, timeoutIndicator, fallback));
}
/**
* If the current {@code Maybe} source didn't signal an event before the {@code timeoutIndicator} {@link Publisher} signals, a
* {@link TimeoutException} is signaled instead.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The {@code timeoutIndicator} {@link Publisher} is consumed in an unbounded manner and
* is cancelled after its first item.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code timeout} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <U> the value type of the
* @param timeoutIndicator the {@code MaybeSource} that indicates the timeout by signaling {@code onSuccess}
* or {@code onComplete}.
* @return the new Maybe instance
*/
@BackpressureSupport(BackpressureKind.UNBOUNDED_IN)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <U> Maybe<T> timeout(Publisher<U> timeoutIndicator) {
ObjectHelper.requireNonNull(timeoutIndicator, "timeoutIndicator is null");
return RxJavaPlugins.onAssembly(new MaybeTimeoutPublisher<T, U>(this, timeoutIndicator, null));
}
/**
* If the current {@code Maybe} didn't signal an event before the {@code timeoutIndicator} {@link Publisher} signals,
* the current {@code Maybe} is disposed and the {@code fallback} {@code MaybeSource} subscribed to
* as a continuation.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The {@code timeoutIndicator} {@link Publisher} is consumed in an unbounded manner and
* is cancelled after its first item.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code timeout} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param <U> the value type of the
* @param timeoutIndicator the {@code MaybeSource} that indicates the timeout by signaling {@code onSuccess}
* or {@code onComplete}
* @param fallback the {@code MaybeSource} that is subscribed to if the current {@code Maybe} times out
* @return the new Maybe instance
*/
@BackpressureSupport(BackpressureKind.UNBOUNDED_IN)
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <U> Maybe<T> timeout(Publisher<U> timeoutIndicator, MaybeSource<? extends T> fallback) {
ObjectHelper.requireNonNull(timeoutIndicator, "timeoutIndicator is null");
ObjectHelper.requireNonNull(fallback, "fallback is null");
return RxJavaPlugins.onAssembly(new MaybeTimeoutPublisher<T, U>(this, timeoutIndicator, fallback));
}
/**
* Returns a Maybe which makes sure when a MaybeObserver disposes the Disposable,
* that call is propagated up on the specified scheduler.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code unsubscribeOn} calls dispose() of the upstream on the {@link Scheduler} you specify.</dd>
* </dl>
* @param scheduler the target scheduler where to execute the disposal
* @return the new Maybe instance
* @throws NullPointerException if scheduler is null
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.CUSTOM)
public final Maybe<T> unsubscribeOn(final Scheduler scheduler) {
ObjectHelper.requireNonNull(scheduler, "scheduler is null");
return RxJavaPlugins.onAssembly(new MaybeUnsubscribeOn<T>(this, scheduler));
}
/**
* Waits until this and the other MaybeSource signal a success value then applies the given BiFunction
* to those values and emits the BiFunction's resulting value to downstream.
*
* <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt="">
*
* <p>If either this or the other MaybeSource is empty or signals an error, the resulting Maybe will
* terminate immediately and dispose the other source.
*
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code zipWith} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param <U>
* the type of items emitted by the {@code other} MaybeSource
* @param <R>
* the type of items emitted by the resulting Maybe
* @param other
* the other MaybeSource
* @param zipper
* a function that combines the pairs of items from the two MaybeSources to generate the items to
* be emitted by the resulting Maybe
* @return the new Maybe instance
* @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a>
*/
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public final <U, R> Maybe<R> zipWith(MaybeSource<? extends U> other, BiFunction<? super T, ? super U, ? extends R> zipper) {
ObjectHelper.requireNonNull(other, "other is null");
return zip(this, other, zipper);
}
// ------------------------------------------------------------------
// Test helper
// ------------------------------------------------------------------
/**
* Creates a TestObserver and subscribes
* it to this Maybe.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code test} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @return the new TestObserver instance
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final TestObserver<T> test() {
TestObserver<T> to = new TestObserver<T>();
subscribe(to);
return to;
}
/**
* Creates a TestObserver optionally in cancelled state, then subscribes it to this Maybe.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code test} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
* @param cancelled if true, the TestObserver will be cancelled before subscribing to this
* Maybe.
* @return the new TestObserver instance
*/
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final TestObserver<T> test(boolean cancelled) {
TestObserver<T> to = new TestObserver<T>();
if (cancelled) {
to.cancel();
}
subscribe(to);
return to;
}
}
|
artem-zinnatullin/RxJava
|
src/main/java/io/reactivex/Maybe.java
|
Java
|
apache-2.0
| 233,229 |
# Copyright 2010 Jacob Kaplan-Moss
#
# 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.
"""
Flavor interface.
"""
from oslo_utils import strutils
from six.moves.urllib import parse
from novaclient import base
from novaclient import exceptions
from novaclient.openstack.common.gettextutils import _
from novaclient import utils
class Flavor(base.Resource):
"""
A flavor is an available hardware configuration for a server.
"""
HUMAN_ID = True
def __repr__(self):
return "<Flavor: %s>" % self.name
@property
def ephemeral(self):
"""
Provide a user-friendly accessor to OS-FLV-EXT-DATA:ephemeral
"""
return self._info.get("OS-FLV-EXT-DATA:ephemeral", 'N/A')
@property
def is_public(self):
"""
Provide a user-friendly accessor to os-flavor-access:is_public
"""
return self._info.get("os-flavor-access:is_public", 'N/A')
def get_keys(self):
"""
Get extra specs from a flavor.
:param flavor: The :class:`Flavor` to get extra specs from
"""
_resp, body = self.manager.api.client.get(
"/flavors/%s/os-extra_specs" %
base.getid(self))
return body["extra_specs"]
def set_keys(self, metadata):
"""
Set extra specs on a flavor.
:param flavor: The :class:`Flavor` to set extra spec on
:param metadata: A dict of key/value pairs to be set
"""
utils.validate_flavor_metadata_keys(metadata.keys())
body = {'extra_specs': metadata}
return self.manager._create(
"/flavors/%s/os-extra_specs" % base.getid(self),
body,
"extra_specs",
return_raw=True)
def unset_keys(self, keys):
"""
Unset extra specs on a flavor.
:param flavor: The :class:`Flavor` to unset extra spec on
:param keys: A list of keys to be unset
"""
for k in keys:
self.manager._delete(
"/flavors/%s/os-extra_specs/%s" % (base.getid(self), k))
def delete(self):
"""
Delete this flavor.
"""
self.manager.delete(self)
class FlavorManager(base.ManagerWithFind):
"""
Manage :class:`Flavor` resources.
"""
resource_class = Flavor
is_alphanum_id_allowed = True
def list(self, detailed=True, is_public=True):
"""
Get a list of all flavors.
:rtype: list of :class:`Flavor`.
"""
qparams = {}
# is_public is ternary - None means give all flavors.
# By default Nova assumes True and gives admins public flavors
# and flavors from their own projects only.
if not is_public:
qparams['is_public'] = is_public
query_string = "?%s" % parse.urlencode(qparams) if qparams else ""
detail = ""
if detailed:
detail = "/detail"
return self._list("/flavors%s%s" % (detail, query_string), "flavors")
def get(self, flavor):
"""
Get a specific flavor.
:param flavor: The ID of the :class:`Flavor` to get.
:rtype: :class:`Flavor`
"""
return self._get("/flavors/%s" % base.getid(flavor), "flavor")
def delete(self, flavor):
"""
Delete a specific flavor.
:param flavor: The ID of the :class:`Flavor` to get.
"""
self._delete("/flavors/%s" % base.getid(flavor))
def _build_body(self, name, ram, vcpus, disk, id, swap,
ephemeral, rxtx_factor, is_public):
return {
"flavor": {
"name": name,
"ram": ram,
"vcpus": vcpus,
"disk": disk,
"id": id,
"swap": swap,
"OS-FLV-EXT-DATA:ephemeral": ephemeral,
"rxtx_factor": rxtx_factor,
"os-flavor-access:is_public": is_public,
}
}
def create(self, name, ram, vcpus, disk, flavorid="auto",
ephemeral=0, swap=0, rxtx_factor=1.0, is_public=True):
"""
Create a flavor.
:param name: Descriptive name of the flavor
:param ram: Memory in MB for the flavor
:param vcpus: Number of VCPUs for the flavor
:param disk: Size of local disk in GB
:param flavorid: ID for the flavor (optional). You can use the reserved
value ``"auto"`` to have Nova generate a UUID for the
flavor in cases where you cannot simply pass ``None``.
:param swap: Swap space in MB
:param rxtx_factor: RX/TX factor
:rtype: :class:`Flavor`
"""
try:
ram = int(ram)
except (TypeError, ValueError):
raise exceptions.CommandError(_("Ram must be an integer."))
try:
vcpus = int(vcpus)
except (TypeError, ValueError):
raise exceptions.CommandError(_("VCPUs must be an integer."))
try:
disk = int(disk)
except (TypeError, ValueError):
raise exceptions.CommandError(_("Disk must be an integer."))
if flavorid == "auto":
flavorid = None
try:
swap = int(swap)
except (TypeError, ValueError):
raise exceptions.CommandError(_("Swap must be an integer."))
try:
ephemeral = int(ephemeral)
except (TypeError, ValueError):
raise exceptions.CommandError(_("Ephemeral must be an integer."))
try:
rxtx_factor = float(rxtx_factor)
except (TypeError, ValueError):
raise exceptions.CommandError(_("rxtx_factor must be a float."))
try:
is_public = strutils.bool_from_string(is_public, True)
except Exception:
raise exceptions.CommandError(_("is_public must be a boolean."))
body = self._build_body(name, ram, vcpus, disk, flavorid, swap,
ephemeral, rxtx_factor, is_public)
return self._create("/flavors", body, "flavor")
|
akash1808/python-novaclient
|
novaclient/v1_1/flavors.py
|
Python
|
apache-2.0
| 6,740 |
package main
import (
"fmt"
"os"
"github.com/codegangsta/cli"
"github.com/heartbeatsjp/check_happo/command"
"github.com/heartbeatsjp/happo-agent/halib"
)
// GlobalFlags are global level options
var GlobalFlags = []cli.Flag{}
// Commands is list of subcommand
var Commands = []cli.Command{
{
Name: "monitor",
Usage: "",
Action: command.CmdMonitor,
Flags: []cli.Flag{
cli.StringFlag{
Name: "host, H",
Usage: "hostname or IP address",
},
cli.IntFlag{
Name: "port, P",
Value: halib.DefaultAgentPort,
Usage: "Port number",
},
cli.StringSliceFlag{
Name: "proxy, X",
Value: &cli.StringSlice{},
Usage: "Proxy hostname[:port] (You can multiple define.)",
},
cli.StringFlag{
Name: "plugin_name, p",
Usage: "Plugin Name",
},
cli.StringFlag{
Name: "plugin_option, o",
Usage: "Plugin Option",
},
cli.StringFlag{
Name: "timeout, t",
Usage: "Connect Timeout",
},
cli.BoolFlag{
Name: "verbose, v",
Usage: "verbose output",
},
},
},
{
Name: "check_happo",
Usage: "",
Action: command.CmdTest,
Flags: []cli.Flag{},
},
}
// CommandNotFound implements action when subcommand not found
func CommandNotFound(c *cli.Context, command string) {
fmt.Fprintf(os.Stderr, "%s: '%s' is not a %s command. See '%s --help'.", c.App.Name, command, c.App.Name, c.App.Name)
os.Exit(2)
}
|
heartbeatsjp/check_happo
|
commands.go
|
GO
|
apache-2.0
| 1,406 |
//! \file
/*
** Copyright (C) - Triton
**
** This program is under the terms of the Apache License 2.0.
*/
#ifndef TRITON_LIFTINGTOLLVM_HPP
#define TRITON_LIFTINGTOLLVM_HPP
#include <map>
#include <memory>
#include <ostream>
#include <triton/ast.hpp>
#include <triton/dllexport.hpp>
#include <triton/symbolicExpression.hpp>
//! The Triton namespace
namespace triton {
/*!
* \addtogroup triton
* @{
*/
//! The Engines namespace
namespace engines {
/*!
* \ingroup triton
* \addtogroup engines
* @{
*/
//! The Lifters namespace
namespace lifters {
/*!
* \ingroup engines
* \addtogroup lifters
* @{
*/
//! \class LiftingToLLVM
/*! \brief The lifting to LLVM class. */
class LiftingToLLVM {
public:
//! Constructor.
TRITON_EXPORT LiftingToLLVM();
//! Lifts a symbolic expression and all its references to LLVM format. `fname` represents the name of the LLVM function.
TRITON_EXPORT std::ostream& liftToLLVM(std::ostream& stream, const triton::engines::symbolic::SharedSymbolicExpression& expr, const char* fname="__triton", bool optimize=false);
//! Lifts a abstract node and all its references to LLVM format. `fname` represents the name of the LLVM function.
TRITON_EXPORT std::ostream& liftToLLVM(std::ostream& stream, const triton::ast::SharedAbstractNode& node, const char* fname="__triton", bool optimize=false);
//! Lifts and simplify an AST using LLVM
TRITON_EXPORT triton::ast::SharedAbstractNode simplifyAstViaLLVM(const triton::ast::SharedAbstractNode& node) const;
};
/*! @} End of lifters namespace */
};
/*! @} End of engines namespace */
};
/*! @} End of triton namespace */
};
#endif /* TRITON_LIFTINGTOLLVM_HPP */
|
JonathanSalwan/Triton
|
src/libtriton/includes/triton/liftingToLLVM.hpp
|
C++
|
apache-2.0
| 1,827 |
/*
* Copyright 1999-2010 University of Chicago
*
* 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.globus.gsi.stores;
import org.globus.gsi.provider.SigningPolicyStore;
import org.globus.gsi.provider.SigningPolicyStoreException;
import org.globus.gsi.provider.SigningPolicyStoreParameters;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import java.io.IOException;
import java.net.URI;
import java.security.InvalidAlgorithmParameterException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.security.auth.x500.X500Principal;
import org.globus.gsi.SigningPolicy;
import org.globus.gsi.util.CertificateIOUtil;
import org.globus.util.GlobusResource;
import org.globus.util.GlobusPathMatchingResourcePatternResolver;
/**
* FILL ME
*
* @author ranantha@mcs.anl.gov
*/
public class ResourceSigningPolicyStore implements SigningPolicyStore {
private GlobusPathMatchingResourcePatternResolver globusResolver = new GlobusPathMatchingResourcePatternResolver();
private Map<URI, ResourceSigningPolicy> signingPolicyFileMap = new HashMap<URI, ResourceSigningPolicy>();
private Map<String, SigningPolicy> policyMap = new HashMap<String, SigningPolicy>();
private ResourceSigningPolicyStoreParameters parameters;
private Log logger = LogFactory.getLog(ResourceSigningPolicyStore.class.getCanonicalName());
private final Map<String, Long> invalidPoliciesCache = new HashMap<String, Long>();
private final Map<String, Long> validPoliciesCache = new HashMap<String, Long>();
private final static long CACHE_TIME_MILLIS = 3600*1000;
private long lastUpdate = 0;
/**
* Please use the {@link Stores} class to generate Key/Cert stores
*/
public ResourceSigningPolicyStore(SigningPolicyStoreParameters param) throws InvalidAlgorithmParameterException {
if (param == null) {
throw new IllegalArgumentException();
}
if (!(param instanceof ResourceSigningPolicyStoreParameters)) {
throw new InvalidAlgorithmParameterException();
}
this.parameters = (ResourceSigningPolicyStoreParameters) param;
}
public synchronized SigningPolicy getSigningPolicy(X500Principal caPrincipal) throws SigningPolicyStoreException {
if (caPrincipal == null) {
return null;
}
String name = caPrincipal.getName();
long now = System.currentTimeMillis();
String hash = CertificateIOUtil.nameHash(caPrincipal);
Long validCacheTime = validPoliciesCache.get(hash);
Long invalidCacheTime = invalidPoliciesCache.get(hash);
if ((invalidCacheTime != null) && (now - invalidCacheTime < 10*CACHE_TIME_MILLIS)) {
return null;
}
if ((validCacheTime == null) || (now - validCacheTime >= CACHE_TIME_MILLIS) || !this.policyMap.containsKey(name)) {
loadPolicy(hash);
}
return this.policyMap.get(name);
}
private synchronized void loadPolicy(String hash) throws SigningPolicyStoreException {
String locations = this.parameters.getTrustRootLocations();
GlobusResource[] resources;
resources = globusResolver.getResources(locations);
long now = System.currentTimeMillis();
boolean found_policy = false;
// Optimization: If we find a hash for this CA, only process that.
// Otherwise, we will process all policies.
for (GlobusResource resource : resources) {
String filename = resource.getFilename();
// Note invalidPoliciesCache contains both filenames and hashes!
Long invalidCacheTime = invalidPoliciesCache.get(filename);
if ((invalidCacheTime != null) && (now - invalidCacheTime < 10*CACHE_TIME_MILLIS)) {
continue;
}
if (!filename.startsWith(hash)) {
continue;
}
if (!resource.isReadable()) {
logger.debug("Cannot read: " + resource.getFilename());
continue;
}
try {
loadSigningPolicy(resource, policyMap, signingPolicyFileMap);
} catch (Exception e) {
invalidCacheTime = invalidPoliciesCache.get(filename);
if ((invalidCacheTime == null) || (now - invalidCacheTime >= 10*CACHE_TIME_MILLIS)) {
logger.warn("Failed to load signing policy: " + filename);
logger.debug("Failed to load signing policy: " + filename, e);
invalidPoliciesCache.put(filename, now);
invalidPoliciesCache.put(hash, now);
}
continue;
}
found_policy = true;
}
if (found_policy) {
if (!validPoliciesCache.containsKey(hash)) {
invalidPoliciesCache.put(hash, now);
}
return;
}
// Poor-man's implementation. Note it is much more expensive than a hashed directory
for (GlobusResource resource : resources) {
String filename = resource.getFilename();
Long invalidCacheTime = invalidPoliciesCache.get(filename);
if ((invalidCacheTime != null) && (now - invalidCacheTime < 10*CACHE_TIME_MILLIS)) {
continue;
}
try {
loadSigningPolicy(resource, policyMap, signingPolicyFileMap);
} catch (Exception e) {
invalidCacheTime = invalidPoliciesCache.get(filename);
if ((invalidCacheTime == null) || (now - invalidCacheTime >= 10*CACHE_TIME_MILLIS)) {
logger.warn("Failed to load signing policy: " + filename);
logger.debug("Failed to load signing policy: " + filename, e);
invalidPoliciesCache.put(filename, now);
invalidPoliciesCache.put(hash, now);
}
continue;
}
}
if (!validPoliciesCache.containsKey(hash)) {
invalidPoliciesCache.put(hash, now);
}
}
private void loadSigningPolicy(
GlobusResource policyResource, Map<String, SigningPolicy> policyMapToLoad,
Map<URI, ResourceSigningPolicy> currentPolicyFileMap) throws SigningPolicyStoreException {
URI uri;
if (!policyResource.isReadable()) {
throw new SigningPolicyStoreException("Cannot read file");
}
try {
uri = policyResource.getURI();
} catch (IOException e) {
throw new SigningPolicyStoreException(e);
}
ResourceSigningPolicy filePolicy = this.signingPolicyFileMap.get(uri);
if (filePolicy == null) {
try {
filePolicy = new ResourceSigningPolicy(policyResource);
} catch (ResourceStoreException e) {
throw new SigningPolicyStoreException(e);
}
}
Collection<SigningPolicy> policies = filePolicy.getSigningPolicies();
currentPolicyFileMap.put(uri, filePolicy);
if (policies != null) {
long now = System.currentTimeMillis();
for (SigningPolicy policy : policies) {
X500Principal caPrincipal = policy.getCASubjectDN();
policyMapToLoad.put(caPrincipal.getName(), policy);
String hash = CertificateIOUtil.nameHash(caPrincipal);
validPoliciesCache.put(hash, now);
}
}
}
}
|
gbehrmann/JGlobus
|
ssl-proxies/src/main/java/org/globus/gsi/stores/ResourceSigningPolicyStore.java
|
Java
|
apache-2.0
| 8,094 |
/*
* 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 io.prestosql.plugin.iceberg;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.airlift.slice.Slice;
import io.prestosql.orc.OrcDataSink;
import io.prestosql.orc.OrcDataSource;
import io.prestosql.orc.OrcWriteValidation;
import io.prestosql.orc.OrcWriterOptions;
import io.prestosql.orc.OrcWriterStats;
import io.prestosql.orc.metadata.ColumnMetadata;
import io.prestosql.orc.metadata.CompressionKind;
import io.prestosql.orc.metadata.OrcColumnId;
import io.prestosql.orc.metadata.OrcType;
import io.prestosql.orc.metadata.statistics.ColumnStatistics;
import io.prestosql.orc.metadata.statistics.DateStatistics;
import io.prestosql.orc.metadata.statistics.DecimalStatistics;
import io.prestosql.orc.metadata.statistics.DoubleStatistics;
import io.prestosql.orc.metadata.statistics.IntegerStatistics;
import io.prestosql.orc.metadata.statistics.StringStatistics;
import io.prestosql.plugin.hive.orc.OrcFileWriter;
import io.prestosql.spi.type.Type;
import org.apache.iceberg.Metrics;
import org.apache.iceberg.Schema;
import org.apache.iceberg.types.Conversions;
import org.apache.iceberg.types.Types;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.function.Supplier;
import static com.google.common.base.Verify.verify;
import static io.prestosql.orc.metadata.OrcColumnId.ROOT_COLUMN;
import static io.prestosql.plugin.hive.acid.AcidTransaction.NO_ACID_TRANSACTION;
import static io.prestosql.plugin.iceberg.TypeConverter.ORC_ICEBERG_ID_KEY;
import static java.lang.Math.toIntExact;
import static java.util.Objects.requireNonNull;
public class IcebergOrcFileWriter
extends OrcFileWriter
implements IcebergFileWriter
{
private final Schema icebergSchema;
private final ColumnMetadata<OrcType> orcColumns;
public IcebergOrcFileWriter(
Schema icebergSchema,
OrcDataSink orcDataSink,
Callable<Void> rollbackAction,
List<String> columnNames,
List<Type> fileColumnTypes,
ColumnMetadata<OrcType> fileColumnOrcTypes,
CompressionKind compression,
OrcWriterOptions options,
boolean writeLegacyVersion,
int[] fileInputColumnIndexes,
Map<String, String> metadata,
Optional<Supplier<OrcDataSource>> validationInputFactory,
OrcWriteValidation.OrcWriteValidationMode validationMode,
OrcWriterStats stats)
{
super(orcDataSink, NO_ACID_TRANSACTION, false, OptionalInt.empty(), rollbackAction, columnNames, fileColumnTypes, fileColumnOrcTypes, compression, options, writeLegacyVersion, fileInputColumnIndexes, metadata, validationInputFactory, validationMode, stats);
this.icebergSchema = requireNonNull(icebergSchema, "icebergSchema is null");
orcColumns = fileColumnOrcTypes;
}
@Override
public Metrics getMetrics()
{
return computeMetrics(icebergSchema, orcColumns, orcWriter.getFileRowCount(), orcWriter.getFileStats());
}
private static Metrics computeMetrics(Schema icebergSchema, ColumnMetadata<OrcType> orcColumns, long fileRowCount, Optional<ColumnMetadata<ColumnStatistics>> columnStatistics)
{
if (columnStatistics.isEmpty()) {
return new Metrics(fileRowCount, null, null, null, null, null);
}
// Columns that are descendants of LIST or MAP types are excluded because:
// 1. Their stats are not used by Apache Iceberg to filter out data files
// 2. Their record count can be larger than table-level row count. There's no good way to calculate nullCounts for them.
// See https://github.com/apache/iceberg/pull/199#discussion_r429443627
Set<OrcColumnId> excludedColumns = getExcludedColumns(orcColumns);
ImmutableMap.Builder<Integer, Long> valueCountsBuilder = ImmutableMap.builder();
ImmutableMap.Builder<Integer, Long> nullCountsBuilder = ImmutableMap.builder();
ImmutableMap.Builder<Integer, ByteBuffer> lowerBoundsBuilder = ImmutableMap.builder();
ImmutableMap.Builder<Integer, ByteBuffer> upperBoundsBuilder = ImmutableMap.builder();
// OrcColumnId(0) is the root column that represents file-level schema
for (int i = 1; i < orcColumns.size(); i++) {
OrcColumnId orcColumnId = new OrcColumnId(i);
if (excludedColumns.contains(orcColumnId)) {
continue;
}
OrcType orcColumn = orcColumns.get(orcColumnId);
ColumnStatistics orcColumnStats = columnStatistics.get().get(orcColumnId);
int icebergId = getIcebergId(orcColumn);
Types.NestedField icebergField = icebergSchema.findField(icebergId);
verify(icebergField != null, "Cannot find Iceberg column with ID %s in schema %s", icebergId, icebergSchema);
valueCountsBuilder.put(icebergId, fileRowCount);
if (orcColumnStats.hasNumberOfValues()) {
nullCountsBuilder.put(icebergId, fileRowCount - orcColumnStats.getNumberOfValues());
}
toIcebergMinMax(orcColumnStats, icebergField.type()).ifPresent(minMax -> {
lowerBoundsBuilder.put(icebergId, minMax.getMin());
upperBoundsBuilder.put(icebergId, minMax.getMax());
});
}
Map<Integer, Long> valueCounts = valueCountsBuilder.build();
Map<Integer, Long> nullCounts = nullCountsBuilder.build();
Map<Integer, ByteBuffer> lowerBounds = lowerBoundsBuilder.build();
Map<Integer, ByteBuffer> upperBounds = upperBoundsBuilder.build();
return new Metrics(
fileRowCount,
null, // TODO: Add column size accounting to ORC column writers
valueCounts.isEmpty() ? null : valueCounts,
nullCounts.isEmpty() ? null : nullCounts,
lowerBounds.isEmpty() ? null : lowerBounds,
upperBounds.isEmpty() ? null : upperBounds);
}
private static Set<OrcColumnId> getExcludedColumns(ColumnMetadata<OrcType> orcColumns)
{
ImmutableSet.Builder<OrcColumnId> excludedColumns = ImmutableSet.builder();
populateExcludedColumns(orcColumns, ROOT_COLUMN, false, excludedColumns);
return excludedColumns.build();
}
private static void populateExcludedColumns(ColumnMetadata<OrcType> orcColumns, OrcColumnId orcColumnId, boolean exclude, ImmutableSet.Builder<OrcColumnId> excludedColumns)
{
if (exclude) {
excludedColumns.add(orcColumnId);
}
OrcType orcColumn = orcColumns.get(orcColumnId);
switch (orcColumn.getOrcTypeKind()) {
case LIST:
case MAP:
for (OrcColumnId child : orcColumn.getFieldTypeIndexes()) {
populateExcludedColumns(orcColumns, child, true, excludedColumns);
}
return;
case STRUCT:
for (OrcColumnId child : orcColumn.getFieldTypeIndexes()) {
populateExcludedColumns(orcColumns, child, exclude, excludedColumns);
}
return;
}
}
private static int getIcebergId(OrcType orcColumn)
{
String icebergId = orcColumn.getAttributes().get(ORC_ICEBERG_ID_KEY);
verify(icebergId != null, "ORC column %s doesn't have an associated Iceberg ID", orcColumn);
return Integer.parseInt(icebergId);
}
private static Optional<IcebergMinMax> toIcebergMinMax(ColumnStatistics orcColumnStats, org.apache.iceberg.types.Type icebergType)
{
IntegerStatistics integerStatistics = orcColumnStats.getIntegerStatistics();
if (integerStatistics != null) {
Object min = integerStatistics.getMin();
Object max = integerStatistics.getMax();
if (min == null || max == null) {
return Optional.empty();
}
if (icebergType.typeId() == org.apache.iceberg.types.Type.TypeID.INTEGER) {
min = toIntExact((Long) min);
max = toIntExact((Long) max);
}
return Optional.of(new IcebergMinMax(icebergType, min, max));
}
DoubleStatistics doubleStatistics = orcColumnStats.getDoubleStatistics();
if (doubleStatistics != null) {
Object min = doubleStatistics.getMin();
Object max = doubleStatistics.getMax();
if (min == null || max == null) {
return Optional.empty();
}
if (icebergType.typeId() == org.apache.iceberg.types.Type.TypeID.FLOAT) {
min = ((Double) min).floatValue();
max = ((Double) max).floatValue();
}
return Optional.of(new IcebergMinMax(icebergType, min, max));
}
StringStatistics stringStatistics = orcColumnStats.getStringStatistics();
if (stringStatistics != null) {
Slice min = stringStatistics.getMin();
Slice max = stringStatistics.getMax();
if (min == null || max == null) {
return Optional.empty();
}
return Optional.of(new IcebergMinMax(icebergType, min.toStringUtf8(), max.toStringUtf8()));
}
DateStatistics dateStatistics = orcColumnStats.getDateStatistics();
if (dateStatistics != null) {
Integer min = dateStatistics.getMin();
Integer max = dateStatistics.getMax();
if (min == null || max == null) {
return Optional.empty();
}
return Optional.of(new IcebergMinMax(icebergType, min, max));
}
DecimalStatistics decimalStatistics = orcColumnStats.getDecimalStatistics();
if (decimalStatistics != null) {
BigDecimal min = decimalStatistics.getMin();
BigDecimal max = decimalStatistics.getMax();
if (min == null || max == null) {
return Optional.empty();
}
min = min.setScale(((Types.DecimalType) icebergType).scale());
max = max.setScale(((Types.DecimalType) icebergType).scale());
return Optional.of(new IcebergMinMax(icebergType, min, max));
}
return Optional.empty();
}
private static class IcebergMinMax
{
private ByteBuffer min;
private ByteBuffer max;
private IcebergMinMax(org.apache.iceberg.types.Type type, Object min, Object max)
{
this.min = Conversions.toByteBuffer(type, min);
this.max = Conversions.toByteBuffer(type, max);
}
public ByteBuffer getMin()
{
return min;
}
public ByteBuffer getMax()
{
return max;
}
}
}
|
erichwang/presto
|
presto-iceberg/src/main/java/io/prestosql/plugin/iceberg/IcebergOrcFileWriter.java
|
Java
|
apache-2.0
| 11,546 |