repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
EngineerBetter/concourse-up
|
util/bincache/bincache.go
|
1871
|
package bincache
import (
"archive/zip"
"bytes"
"crypto/sha256"
"encoding/hex"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
)
// Download a file from url and check with a sha1
func Download(url string) (string, error) {
path, err := os.UserCacheDir()
if err != nil {
return "", err
}
path = filepath.Join(path, "concourse-up", "bin")
err = os.MkdirAll(path, 0700)
if err != nil {
return "", err
}
path = filepath.Join(path, hash(url))
if _, err = os.Stat(path); !os.IsNotExist(err) {
return path, nil
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0700)
if err != nil {
return "", err
}
defer f.Close()
resp, err := http.Get(url)
if err != nil {
os.Remove(path)
return "", err
}
defer resp.Body.Close()
var closer io.ReadCloser
// if strings.HasSuffix(url, ".zip") {
// closer, err = handleZipFile(resp)
// if err != nil {
// return "", nil
// }
// } else {
// closer = resp.Body
// }
if isZip(url, resp) {
closer, err = handleZipFile(resp)
if err != nil {
return "", nil
}
} else {
closer = resp.Body
}
_, err = io.Copy(f, closer)
if err != nil {
os.Remove(path)
return "", err
}
return path, nil
}
func handleZipFile(resp *http.Response) (io.ReadCloser, error) {
body, errz := ioutil.ReadAll(resp.Body)
if errz != nil {
return nil, errz
}
r, errz := zip.NewReader(bytes.NewReader(body), resp.ContentLength)
if errz != nil {
return nil, errz
}
firstFile, errz := r.File[0].Open()
if errz != nil {
return nil, errz
}
return firstFile, nil
}
func isZip(url string, resp *http.Response) bool {
if strings.HasSuffix(url, ".zip") {
return true
}
if resp.Header.Get("Content-Type") == "application/zip" {
return true
}
return false
}
func hash(s string) string {
sum := sha256.Sum256([]byte(s))
return hex.EncodeToString(sum[:])
}
|
apache-2.0
|
STRiDGE/dozer
|
core/src/test/java/org/dozer/DozerInitializerTest.java
|
2608
|
/*
* Copyright 2005-2017 Dozer 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 org.dozer;
import org.dozer.config.GlobalSettings;
import org.dozer.util.DozerConstants;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DozerInitializerTest extends AbstractDozerTest {
private DozerInitializer instance;
@Before
public void setUp() throws Exception {
instance = DozerInitializer.getInstance();
instance.destroy();
}
@After
public void tearDown() throws Exception {
instance.destroy();
}
@Test
public void testIsInitialized() {
assertFalse(instance.isInitialized());
instance.init();
assertTrue(instance.isInitialized());
instance.destroy();
assertFalse(instance.isInitialized());
}
@Test
public void testDoubleCalls() {
instance.destroy();
assertFalse(instance.isInitialized());
instance.init();
instance.init();
assertTrue(instance.isInitialized());
instance.destroy();
instance.destroy();
assertFalse(instance.isInitialized());
}
@Test(expected = MappingException.class)
public void testBeanIsMissing() {
GlobalSettings settings = mock(GlobalSettings.class);
when(settings.getClassLoaderName()).thenReturn(DozerConstants.DEFAULT_CLASS_LOADER_BEAN);
when(settings.getProxyResolverName()).thenReturn("no.such.class.Found");
instance.initialize(settings, getClass().getClassLoader());
fail();
}
@Test(expected = MappingException.class)
public void testBeanIsNotAssignable() {
GlobalSettings settings = mock(GlobalSettings.class);
when(settings.getClassLoaderName()).thenReturn("java.lang.String");
when(settings.getProxyResolverName()).thenReturn(DozerConstants.DEFAULT_PROXY_RESOLVER_BEAN);
instance.initialize(settings, getClass().getClassLoader());
fail();
}
}
|
apache-2.0
|
songshu198907/LeetPractise
|
src/main/java/algorithm/leet_76_90/Subsets_78.java
|
1032
|
package algorithm.leet_76_90;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by songheng on 4/18/16.
*/
public class Subsets_78 {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
if(nums == null || nums.length ==0){
return res;
}
for(int i = 1 ; i <= nums.length ; i ++ ){
helper(res,new ArrayList<>(),0,nums.length - 1, i , nums);
}
res.add(new ArrayList<>());
return res ;
}
private void helper(List<List<Integer>> res , List<Integer> prev, int start ,int end , int remaining, int arr[]){
if(remaining == 0 ){
res.add(prev);
return;
}
for(int i = start ; i <= end - remaining + 1 ; i++){
List<Integer> curr = new ArrayList<>(prev);
curr.add(arr[i]);
helper(res,curr,i+1,end,remaining-1,arr);
}
prev = null;
}
}
|
apache-2.0
|
OpeningDesign/SketchSpace
|
etherpad/src/plugins/openingDesign/main.js
|
437
|
import("etherpad.log");
import("plugins.openingDesign.hooks");
function openingDesignInit() {
this.hooks = ['modals', 'docbarItemsPad'];
this.description = 'openingDesign';
this.docbarItemsPad = hooks.docbarItemsPad;
this.modals = hooks.modals;
this.install = install;
this.uninstall = uninstall;
}
function install() {
log.info("Installing openingDesign");
}
function uninstall() {
log.info("Uninstalling openingDesign");
}
|
apache-2.0
|
lordelph/phrekyll
|
Phrekyll/Processor/Markdown.php
|
4255
|
<?php
/**
* 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.
*
* @category Phrekyll
* @package Phrekyll\Processor
* @author Victor Farazdagi
* @license http://www.apache.org/licenses/LICENSE-2.0
*/
namespace Phrekyll\Processor;
use Michelf\MarkdownExtra as MarkdownParser;
use Phrekyll\Autoloader as Loader;
/**
* Markdown markup processor
*
* @category Phrekyll
* @package Phrekyll\Processor
* @author Victor Farazdagi
*/
class Markdown
extends Base
implements \Phrekyll\Processor
{
/**
* List of permitted Markdown configuration variables
*
* Taken from https://michelf.ca/projects/php-markdown/configuration/
* @var array
*/
private static $markdownConfigVars=array(
'empty_element_suffix',
'tab_width',
'no_markup',
'no_entities',
'predef_urls',
'predef_titles',
'fn_id_prefix',
'fn_link_title',
'fn_backlink_title',
'fn_link_class',
'fn_backlink_class',
'code_class_prefix',
'code_attr_on_pre',
'predef_abbr',
'code_class_prefix',
'code_attr_on_pre'
);
/**
* Reference to procesor class
* @var MarkdownParser
*/
protected $markdown;
/**
* Processor can be setup at initialization time
*
* @param array $options Processor options
*
* @return void
*/
public function __construct($options = array())
{
$this->markdown = new MarkdownParser;
}
/**
* Helper for setting markdown configuration values
*
* @param string $name name of config variable
* @param string $value value of config variable
* @return void
*/
protected function setMarkdownConfig($name, $value)
{
$this->markdown->$name = $value;
}
/**
* Configure Markdown with options from the page and config.yml
*
* You can add markdown: entry to your config.yml or page front
* matter which contains values for any of the Markdown Extra
* configuration options.
*
* See https://michelf.ca/projects/php-markdown/configuration/ for
* a complete list of options. An example to support marking up
* code blocks for the Google Prettify script would be this:
*
* <code>
* markdown:
* code_class_prefix: "prettyprint "
* code_attr_on_pre: true
* </code>
*
* The space in the prefix is important in the case of prettyprint,
* as you can specify extra styles on markdown fenced code blocks,
* allowing you to specify the language, for example:
*
* <code>
* ~~~~~~~~~ .lang-js
* {"foo":"bar"}
* ~~~~~~~~~
* </code>
*
* @param array $vars List of variables passed to template engine
*/
protected function configureMarkdown($vars)
{
foreach (self::$markdownConfigVars as $name) {
//if variable set in front matter, use that, but if not present
//use site-wide configuration from config.yml
if (isset($vars['page']['markdown'][$name])) {
$this->setMarkdownConfig($name, $vars['page']['markdown'][$name]);
} elseif (isset($vars['site']['markdown'][$name])) {
$this->setMarkdownConfig($name, $vars['site']['markdown'][$name]);
}
}
}
/**
* Parse the incoming template
*
* @param string $tpl Source template content
* @param array $vars List of variables passed to template engine
*
* @return string Processed template
*/
public function render($tpl, $vars = array())
{
$this->configureMarkdown($vars);
return $this->markdown->transform($tpl);
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Hieracium/Hieracium amplexicaule/ Syn. Hieracium speluncarum/README.md
|
189
|
# Hieracium speluncarum Arv.-Touv. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
stdlib-js/stdlib
|
lib/node_modules/@stdlib/stats/incr/mmpe/lib/main.js
|
2139
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
var incrmmean = require( '@stdlib/stats/incr/mmean' );
// MAIN //
/**
* Returns an accumulator function which incrementally computes a moving mean percentage error.
*
* @param {PositiveInteger} W - window size
* @throws {TypeError} must provide a positive integer
* @returns {Function} accumulator function
*
* @example
* var accumulator = incrmmpe( 3 );
*
* var m = accumulator();
* // returns null
*
* m = accumulator( 2.0, 3.0 );
* // returns ~33.33
*
* m = accumulator( 5.0, 2.0 );
* // returns ~-58.33
*
* m = accumulator( 3.0, 2.0 );
* // returns ~-55.56
*
* m = accumulator( 2.0, 5.0 );
* // returns ~-46.67
*
* m = accumulator();
* // returns ~-46.67
*/
function incrmmpe( W ) {
var mean;
if ( !isPositiveInteger( W ) ) {
throw new TypeError( 'invalid argument. Must provide a positive integer. Value: `' + W + '`.' );
}
mean = incrmmean( W );
return accumulator;
/**
* If provided input values, the accumulator function returns an updated mean percentage error. If not provided input values, the accumulator function returns the current mean percentage error.
*
* @private
* @param {number} [f] - input value
* @param {number} [a] - input value
* @returns {(number|null)} mean percentage error or null
*/
function accumulator( f, a ) {
if ( arguments.length === 0 ) {
return mean();
}
return mean( 100.0 * ((a-f)/a) );
}
}
// EXPORTS //
module.exports = incrmmpe;
|
apache-2.0
|
hingstarne/origin
|
pkg/project/api/v1/types.go
|
1629
|
package v1
import (
kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api/v1"
)
// ProjectList is a list of Project objects.
type ProjectList struct {
kapi.TypeMeta `json:",inline"`
kapi.ListMeta `json:"metadata,omitempty"`
Items []Project `json:"items"`
}
// These are internal finalizer values to Origin
const (
FinalizerOrigin kapi.FinalizerName = "openshift.io/origin"
)
// ProjectSpec describes the attributes on a Project
type ProjectSpec struct {
// Finalizers is an opaque list of values that must be empty to permanently remove object from storage
Finalizers []kapi.FinalizerName `json:"finalizers,omitempty" description:"an opaque list of values that must be empty to permanently remove object from storage"`
}
// ProjectStatus is information about the current status of a Project
type ProjectStatus struct {
Phase kapi.NamespacePhase `json:"phase,omitempty" description:"phase is the current lifecycle phase of the project"`
}
// Project is a logical top-level container for a set of origin resources
type Project struct {
kapi.TypeMeta `json:",inline"`
kapi.ObjectMeta `json:"metadata,omitempty"`
// Spec defines the behavior of the Namespace.
Spec ProjectSpec `json:"spec,omitempty" description:"spec defines the behavior of the Project"`
// Status describes the current status of a Namespace
Status ProjectStatus `json:"status,omitempty" description:"status describes the current status of a Project; read-only"`
}
type ProjectRequest struct {
kapi.TypeMeta `json:",inline"`
kapi.ObjectMeta `json:"metadata,omitempty"`
DisplayName string `json:"displayName,omitempty"`
}
|
apache-2.0
|
MBoustani/climate
|
ocw/esgf/main.py
|
3986
|
#
# 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.
#
'''
Example main program for ESGF-RCMES integration.
'''
# constant parameters
DATA_DIRECTORY = "/tmp"
from ocw.esgf.logon import logon
from ocw.esgf.search import SearchClient
from ocw.esgf.download import download
def main():
'''Example driver program'''
username = raw_input('Enter your ESGF Username:\n')
password = raw_input('Enter your ESGF Password:\n')
# step 1: obtain short-term certificate
print 'Retrieving ESGF certificate...'
# logon using client-side MyProxy libraries
if logon(username, password):
print "...done."
# step 2: execute faceted search for files
urls = main_obs4mips()
#urls = main_cmip5()
# step 3: download file(s)
for i, url in enumerate(urls):
if i>=1:
break
download(url, toDirectory=DATA_DIRECTORY)
def main_cmip5():
'''
Example workflow to search for CMIP5 files
'''
searchClient = SearchClient(searchServiceUrl="http://pcmdi9.llnl.gov/esg-search/search", distrib=False)
print '\nAvailable projects=%s' % searchClient.getFacets('project')
searchClient.setConstraint(project='CMIP5')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
print '\nAvailable models=%s' % searchClient.getFacets('model')
searchClient.setConstraint(model='INM-CM4')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
print '\nAvailable experiments=%s' % searchClient.getFacets('experiment')
searchClient.setConstraint(experiment='historical')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
print '\nAvailable time frequencies=%s' % searchClient.getFacets('time_frequency')
searchClient.setConstraint(time_frequency='mon')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
print '\nAvailable CF standard names=%s' % searchClient.getFacets('cf_standard_name')
searchClient.setConstraint(cf_standard_name='air_temperature')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
urls = searchClient.getFiles()
return urls
def main_obs4mips():
'''
Example workflow to search for obs4MIPs files.
'''
searchClient = SearchClient(distrib=False)
# obs4MIPs
print '\nAvailable projects=%s' % searchClient.getFacets('project')
searchClient.setConstraint(project='obs4MIPs')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
print '\nAvailable variables=%s' % searchClient.getFacets('variable')
searchClient.setConstraint(variable='hus')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
print '\nAvailable time frequencies=%s' % searchClient.getFacets('time_frequency')
searchClient.setConstraint(time_frequency='mon')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
print '\nAvailable models=%s' % searchClient.getFacets('model')
searchClient.setConstraint(model='Obs-MLS')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
urls = searchClient.getFiles()
return urls
if __name__ == '__main__':
main()
|
apache-2.0
|
omindra/schema_org_java_api
|
core_with_extensions/src/main/java/org/schema/api/model/thing/creativeWork/article/newsArticle/ReviewNewsArticle.java
|
124
|
package org.schema.api.model.thing.creativeWork.article.newsArticle;
public class ReviewNewsArticle extends NewsArticle
{
}
|
apache-2.0
|
DarkRebel/myrobotlab
|
src/org/myrobotlab/control/ProxyGUI.java
|
2022
|
/**
*
* @author greg (at) myrobotlab.org
*
* This file is part of MyRobotLab (http://myrobotlab.org).
*
* MyRobotLab is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version (subject to the "Classpath" exception
* as provided in the LICENSE.txt file that accompanied this code).
*
* MyRobotLab is distributed in the hope that it will be useful or fun,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* All libraries in thirdParty bundle are subject to their own license
* requirements - please refer to http://myrobotlab.org/libraries for
* details.
*
* Enjoy !
*
* */
package org.myrobotlab.control;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.myrobotlab.logging.LoggerFactory;
import javax.swing.JTabbedPane;
import org.myrobotlab.service.Proxy;
import org.myrobotlab.service.GUIService;
import org.slf4j.Logger;
public class ProxyGUI extends ServiceGUI implements ActionListener {
static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(ProxyGUI.class.getCanonicalName());
public ProxyGUI(final String boundServiceName, final GUIService myService, final JTabbedPane tabs) {
super(boundServiceName, myService, tabs);
}
public void init() {
}
public void getState(Proxy template) {
}
@Override
public void attachGUI() {
//subscribe("publishState", "getState", _TemplateServiceGUI.class);
myService.send(boundServiceName, "publishState");
}
@Override
public void detachGUI() {
//unsubscribe("publishState", "getState", _TemplateServiceGUI.class);
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
|
apache-2.0
|
masukomi/mobtvse
|
vendor/bundle/gems/timecop-0.4.5/lib/timecop/time_stack_item.rb
|
3600
|
class Timecop
# A data class for carrying around "time movement" objects. Makes it easy to keep track of the time
# movements on a simple stack.
class TimeStackItem #:nodoc:
attr_reader :mock_type
def initialize(mock_type, *args)
raise "Unknown mock_type #{mock_type}" unless [:freeze, :travel].include?(mock_type)
@mock_type = mock_type
@time = parse_time(*args)
@travel_offset = compute_travel_offset
@dst_adjustment = compute_dst_adjustment(@time)
end
def year
time.year
end
def month
time.month
end
def day
time.day
end
def hour
time.hour
end
def min
time.min
end
def sec
time.sec
end
def utc_offset
time.utc_offset
end
def travel_offset
@travel_offset
end
def time(time_klass=Time) #:nodoc:
if travel_offset.nil?
time_klass.at( @time.to_f )
else
time_klass.at( ( Time.now_without_mock_time + travel_offset ).to_f )
end
end
def date(date_klass=Date)
date_klass.jd( time.to_date.jd )
end
def datetime(datetime_klass=DateTime)
# DateTime doesn't know about DST, so let's remove its presence
our_offset = utc_offset + dst_adjustment
fractions_of_a_second = time.to_f % 1
datetime_klass.new(year, month, day, hour, min, sec + fractions_of_a_second,
utc_offset_to_rational(our_offset))
end
def dst_adjustment
@dst_adjustment
end
private
def rational_to_utc_offset(rational)
((24.0 / rational.denominator) * rational.numerator) * (60 * 60)
end
def utc_offset_to_rational(utc_offset)
Rational(utc_offset, 24 * 60 * 60)
end
def parse_time(*args)
time_klass = Time
time_klass = Time.zone if Time.respond_to? :zone
arg = args.shift
if arg.is_a?(Time)
if Timecop.active_support != false && arg.respond_to?(:in_time_zone)
arg.in_time_zone
else
arg.getlocal
end
elsif Object.const_defined?(:DateTime) && arg.is_a?(DateTime)
expected_time = time_klass.local(arg.year, arg.month, arg.day, arg.hour, arg.min, arg.sec)
expected_time += expected_time.utc_offset - rational_to_utc_offset(arg.offset)
expected_time + compute_dst_adjustment(expected_time)
elsif Object.const_defined?(:Date) && arg.is_a?(Date)
time_klass.local(arg.year, arg.month, arg.day, 0, 0, 0)
elsif args.empty? && arg.kind_of?(Integer)
Time.now + arg
elsif arg.nil?
Time.now
else
if arg.is_a?(String) && Timecop.active_support != false && Time.respond_to?(:parse)
Time.parse(arg)
else
# we'll just assume it's a list of y/m/d/h/m/s
year = arg || 2000
month = args.shift || 1
day = args.shift || 1
hour = args.shift || 0
minute = args.shift || 0
second = args.shift || 0
time_klass.local(year, month, day, hour, minute, second)
end
end
end
def compute_dst_adjustment(time)
return 0 if !(time.dst? ^ Time.now.dst?)
return -1 * 60 * 60 if time.dst?
return 60 * 60
end
def compute_travel_offset
return nil if mock_type == :freeze
time - Time.now_without_mock_time
end
end
end
|
apache-2.0
|
cackharot/fbeazt
|
src/foodbeazt/service/SettingsService.py
|
491
|
from datetime import datetime
from bson import ObjectId
class SettingsService(object):
def __init__(self, db):
self.db = db
self.settings = db.settings_collection
self._id = ObjectId("5bbbaee7bacf833c1203d7b3")
def save(self, item):
item['_id'] = self._id
item['created_at'] = datetime.now()
item['status'] = True
return self.settings.save(item)
def get(self):
return self.settings.find_one({'_id': self._id})
|
apache-2.0
|
gureronder/midpoint
|
gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/PageAdminResources.java
|
7479
|
/*
* Copyright (c) 2010-2015 Evolveum
*
* 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.evolveum.midpoint.web.page.admin.resources;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.PrismProperty;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.delta.PropertyDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.query.*;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.security.api.AuthorizationConstants;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.page.admin.PageAdmin;
import com.evolveum.midpoint.web.page.admin.resources.dto.ResourceDto;
import com.evolveum.midpoint.web.util.OnePageParameterEncoder;
import com.evolveum.midpoint.web.util.WebMiscUtil;
import com.evolveum.midpoint.web.util.WebModelUtils;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.model.IModel;
import org.apache.wicket.util.string.StringValue;
import java.util.Collection;
import java.util.List;
/**
* @author lazyman
*/
public class PageAdminResources extends PageAdmin {
private static final String DOT_CLASS = PageAdminResources.class.getName() + ".";
private static final String OPERATION_LOAD_RESOURCE = DOT_CLASS + "loadResource";
private static final String OPERATION_DELETE_SYNC_TOKEN = DOT_CLASS + "deleteSyncToken";
private static final String OPERATION_SAVE_SYNC_TASK = DOT_CLASS + "saveSyncTask";
protected static final Trace LOGGER = TraceManager.getTrace(PageAdminResources.class);
public static final String AUTH_RESOURCE_ALL = AuthorizationConstants.AUTZ_UI_RESOURCES_ALL_URL;
public static final String AUTH_RESOURCE_ALL_LABEL = "PageAdminResources.auth.resourcesAll.label";
public static final String AUTH_RESOURCE_ALL_DESCRIPTION = "PageAdminResources.auth.resourcesAll.description";
protected boolean isResourceOidAvailable() {
StringValue resourceOid = getPageParameters().get(OnePageParameterEncoder.PARAMETER);
return resourceOid != null && StringUtils.isNotEmpty(resourceOid.toString());
}
protected String getResourceOid() {
StringValue resourceOid = getPageParameters().get(OnePageParameterEncoder.PARAMETER);
return resourceOid != null ? resourceOid.toString() : null;
}
protected PrismObject<ResourceType> loadResource(Collection<SelectorOptions<GetOperationOptions>> options) {
OperationResult result = new OperationResult(OPERATION_LOAD_RESOURCE);
PrismObject<ResourceType> resource = null;
try {
Task task = createSimpleTask(OPERATION_LOAD_RESOURCE);
LOGGER.trace("getObject(resource) oid={}, options={}", getResourceOid(), options);
resource = getModelService().getObject(ResourceType.class, getResourceOid(), options, task, result);
result.recomputeStatus();
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("getObject(resource) result\n:{}", result.debugDump());
}
} catch (Exception ex) {
LoggingUtils.logException(LOGGER, "Couldn't get resource", ex);
result.recordFatalError("Couldn't get resource, reason: " + ex.getMessage(), ex);
}
if (!WebMiscUtil.isSuccessOrHandledError(result)) {
if (resource != null) {
showResult(result);
} else {
getSession().error(getString("pageAdminResources.message.cantLoadResource"));
throw new RestartResponseException(PageResources.class);
}
}
return resource;
}
protected void deleteSyncTokenPerformed(AjaxRequestTarget target, IModel<ResourceDto> model){
ResourceDto dto = model.getObject();
String resourceOid = dto.getOid();
String handlerUri = "http://midpoint.evolveum.com/xml/ns/public/model/synchronization/task/live-sync/handler-3";
ObjectReferenceType resourceRef = new ObjectReferenceType();
resourceRef.setOid(resourceOid);
PrismObject<TaskType> oldTask;
OperationResult result = new OperationResult(OPERATION_DELETE_SYNC_TOKEN);
ObjectQuery query;
ObjectFilter refFilter = RefFilter.createReferenceEqual(TaskType.F_OBJECT_REF, TaskType.class,
getPrismContext(), resourceOid);
ObjectFilter filterHandleUri = EqualFilter.createEqual(TaskType.F_HANDLER_URI, TaskType.class,
getPrismContext(), null, handlerUri);
query = new ObjectQuery();
query.setFilter(AndFilter.createAnd(refFilter, filterHandleUri));
List<PrismObject<TaskType>> taskList = WebModelUtils.searchObjects(TaskType.class, query,
result, this);
if(taskList.size() != 1){
error(getString("pageResource.message.invalidTaskSearch"));
} else {
oldTask = taskList.get(0);
saveTask(oldTask, result);
}
result.recomputeStatus();
showResult(result);
target.add(getFeedbackPanel());
}
private void saveTask(PrismObject<TaskType> oldTask, OperationResult result){
Task task = createSimpleTask(OPERATION_SAVE_SYNC_TASK);
PrismProperty property = oldTask.findProperty(new ItemPath(TaskType.F_EXTENSION, SchemaConstants.SYNC_TOKEN));
if(property == null){
return;
}
Object value = property.getRealValue();
ObjectDelta<TaskType> delta = ObjectDelta.createModifyDelta(oldTask.getOid(),
PropertyDelta.createModificationDeleteProperty(new ItemPath(TaskType.F_EXTENSION, SchemaConstants.SYNC_TOKEN), property.getDefinition(), value),
TaskType.class, getPrismContext());
if(LOGGER.isTraceEnabled()){
LOGGER.trace(delta.debugDump());
}
try {
getModelService().executeChanges(WebMiscUtil.createDeltaCollection(delta), null, task, result);
} catch (Exception e){
LoggingUtils.logException(LOGGER, "Couldn't save task.", e);
result.recordFatalError("Couldn't save task.", e);
}
result.recomputeStatus();
}
}
|
apache-2.0
|
BVier/Taskana
|
web/src/app/guards/domain.guard.ts
|
907
|
import { of } from 'rxjs';
import { CanActivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { DomainService } from 'app/services/domain/domain.service';
import { GeneralModalService } from 'app/services/general-modal/general-modal.service';
import { MessageModal } from 'app/models/message-modal';
import { map, catchError } from 'rxjs/operators';
@Injectable()
export class DomainGuard implements CanActivate {
constructor(private domainService: DomainService, private generalModalService: GeneralModalService) { }
canActivate() {
return this.domainService.getDomains().pipe(
map(domain => true),
catchError(() => {
this.generalModalService.triggerMessage(new MessageModal(
'There was an error, please contact with your administrator', 'There was an error getting Domains'
));
return of(false);
})
);
}
}
|
apache-2.0
|
UniversalDependencies/universaldependencies.github.io
|
treebanks/eu_bdt/eu_bdt-pos-INTJ.html
|
15006
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-GB" xml:lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Statistics of INTJ in UD_Basque-BDT</title>
<link rel="root" href=""/> <!-- for JS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style.css"/>
<link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
<link rel="stylesheet" type="text/css" href="../../css/hint.css"/>
<script type="text/javascript" src="../../lib/ext/head.load.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.2.2/anchor.min.js"></script>
<script>document.addEventListener("DOMContentLoaded", function(event) {anchors.add();});</script>
<!-- Set up this custom Google search at https://cse.google.com/cse/business/settings?cx=001145188882102106025:dl1mehhcgbo -->
<!-- DZ 2021-01-22: I am temporarily hiding the search field to find out whether it slows down loading of the title page.
<script>
(function() {
var cx = '001145188882102106025:dl1mehhcgbo';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script> -->
<!-- <link rel="shortcut icon" href="favicon.ico"/> -->
</head>
<body>
<div id="main" class="center">
<div id="hp-header">
<table width="100%"><tr><td width="50%">
<span class="header-text"><a href="http://universaldependencies.org/#language-">home</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/edit/pages-source/treebanks/eu_bdt/eu_bdt-pos-INTJ.md" target="#">edit page</a></span>
<span class="header-text"><a href="https://github.com/universaldependencies/docs/issues">issue tracker</a></span>
</td><td>
<gcse:search></gcse:search>
</td></tr></table>
</div>
<hr/>
<div class="v2complete">
This page pertains to UD version 2.
</div>
<div id="content">
<noscript>
<div id="noscript">
It appears that you have Javascript disabled.
Please consider enabling Javascript for this page to see the visualizations.
</div>
</noscript>
<!-- The content may include scripts and styles, hence we must load the shared libraries before the content. -->
<script type="text/javascript">
console.time('loading libraries');
var root = '../../'; // filled in by jekyll
head.js(
// External libraries
// DZ: Copied from embedding.html. I don't know which one is needed for what, so I'm currently keeping them all.
root + 'lib/ext/jquery.min.js',
root + 'lib/ext/jquery.svg.min.js',
root + 'lib/ext/jquery.svgdom.min.js',
root + 'lib/ext/jquery.timeago.js',
root + 'lib/ext/jquery-ui.min.js',
root + 'lib/ext/waypoints.min.js',
root + 'lib/ext/jquery.address.min.js'
);
</script>
<h2 id="treebank-statistics-ud_basque-bdt-pos-tags-intj">Treebank Statistics: UD_Basque-BDT: POS Tags: <code class="language-plaintext highlighter-rouge">INTJ</code></h2>
<p>There are 21 <code class="language-plaintext highlighter-rouge">INTJ</code> lemmas (0%), 21 <code class="language-plaintext highlighter-rouge">INTJ</code> types (0%) and 36 <code class="language-plaintext highlighter-rouge">INTJ</code> tokens (0%).
Out of 16 observed tags, the rank of <code class="language-plaintext highlighter-rouge">INTJ</code> is: 11 in number of lemmas, 12 in number of types and 15 in number of tokens.</p>
<p>The 10 most frequent <code class="language-plaintext highlighter-rouge">INTJ</code> lemmas: <em>beno, alde, a, dzast, ea, hara, kaixo, tira, ahalena, ai</em></p>
<p>The 10 most frequent <code class="language-plaintext highlighter-rouge">INTJ</code> types: <em>beno, alde, Kaixo, Tira, a, dzast, ea, hara, Bof, Eskerrak</em></p>
<p>The 10 most frequent ambiguous lemmas: <em>alde</em> (<tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt> 104, <tt><a href="eu_bdt-pos-ADP.html">ADP</a></tt> 70, <tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 4), <em>a</em> (<tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt> 5, <tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 2), <em>ea</em> (<tt><a href="eu_bdt-pos-X.html">X</a></tt> 8, <tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 2), <em>hara</em> (<tt><a href="eu_bdt-pos-ADV.html">ADV</a></tt> 7, <tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 2), <em>tira</em> (<tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 2, <tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt> 2), <em>arren</em> (<tt><a href="eu_bdt-pos-CCONJ.html">CCONJ</a></tt> 90, <tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 1, <tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt> 1), <em>tik-tak</em> (<tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 1, <tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt> 1)</p>
<p>The 10 most frequent ambiguous types: <em>alde</em> (<tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt> 27, <tt><a href="eu_bdt-pos-ADP.html">ADP</a></tt> 24, <tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 4), <em>ea</em> (<tt><a href="eu_bdt-pos-X.html">X</a></tt> 8, <tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 2, <tt><a href="eu_bdt-pos-CCONJ.html">CCONJ</a></tt> 1), <em>hara</em> (<tt><a href="eu_bdt-pos-ADV.html">ADV</a></tt> 6, <tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 1), <em>Jesus</em> (<tt><a href="eu_bdt-pos-PROPN.html">PROPN</a></tt> 5, <tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 1), <em>arren</em> (<tt><a href="eu_bdt-pos-CCONJ.html">CCONJ</a></tt> 90, <tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 1, <tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt> 1), <em>ene</em> (<tt><a href="eu_bdt-pos-PRON.html">PRON</a></tt> 2, <tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 1)</p>
<ul>
<li><em>alde</em>
<ul>
<li><tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt> 27: <em>Zeintzuk dira bi taldeen <b>alde</b> indartsuenak ?</em></li>
<li><tt><a href="eu_bdt-pos-ADP.html">ADP</a></tt> 24: <em>Batzuetan zortedunak dira eta bezeroek dirua jokatzen dute haien <b>alde</b> .</em></li>
<li><tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 4: <em>Eztabaidak <b>alde</b> batera utzita , etapa garaipena esprintean erabaki zen .</em></li>
</ul>
</li>
<li><em>ea</em>
<ul>
<li><tt><a href="eu_bdt-pos-X.html">X</a></tt> 8: <em>Orain erlojupekoa dator , <b>ea</b> denbora ateratzerik dudan “ .</em></li>
<li><tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 2: <em>- Piztu zinta , <b>ea</b> zer gertatu den bigarren saioan .</em></li>
<li><tt><a href="eu_bdt-pos-CCONJ.html">CCONJ</a></tt> 1: <em>Mutriku , Portugalete , Lutxana-Deustu eta Zierbena aterako dira lehenengo txandan ; Ondarroa , Santurtzi , Santander <b>ea</b> Algorta bigarrengoan eta Isuntza , Arkote , Castro eta Urdaibai hirugarrengoan .</em></li>
</ul>
</li>
<li><em>hara</em>
<ul>
<li><tt><a href="eu_bdt-pos-ADV.html">ADV</a></tt> 6: <em>Honelaxe ikusmiran nenbilela , <b>hara</b> non irakurtzen dudan erdi aldeko kale batean :</em></li>
<li><tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 1: <em>Baina , <b>hara</b> , Kalifornian , eskola-liburuetatik marrubi-pastelak ezabatzea proposatu omen dute bertako hezkuntza-arduradunek , marrubi-pastelak ez direlako politikoki zuzenak .</em></li>
</ul>
</li>
<li><em>Jesus</em>
<ul>
<li><tt><a href="eu_bdt-pos-PROPN.html">PROPN</a></tt> 5: <em><b>Jesus</b> Sanchez autobus gidaria koman dago .</em></li>
<li><tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 1: <em>- <b>Jesus</b> ene , nirekin akabatuko du mutiko honek !</em></li>
</ul>
</li>
<li><em>arren</em>
<ul>
<li><tt><a href="eu_bdt-pos-CCONJ.html">CCONJ</a></tt> 90: <em>Aurten hasi da jokatzen , iaztik den <b>arren</b> .</em></li>
<li><tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 1: <em>hari buruzkoak jakiteko , egon , <b>arren</b> , adi .</em></li>
<li><tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt> 1: <em>Markagailua txukundu <b>arren</b> , ordea , galiziarrek ez zuten partiduan eskainitako itxura kaskarra hobetu .</em></li>
</ul>
</li>
<li><em>ene</em>
<ul>
<li><tt><a href="eu_bdt-pos-PRON.html">PRON</a></tt> 2: <em>Arin , buelta erdia eman eta sabela zulatu diot <b>ene</b> atzeko guardari .</em></li>
<li><tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> 1: <em>- Jesus <b>ene</b> , nirekin akabatuko du mutiko honek !</em></li>
</ul>
</li>
</ul>
<h2 id="morphology">Morphology</h2>
<p>The form / lemma ratio of <code class="language-plaintext highlighter-rouge">INTJ</code> is 1.000000 (the average of all parts of speech is 2.172787).</p>
<p>The 1st highest number of forms (1) was observed with the lemma “a”: <em>a</em>.</p>
<p>The 2nd highest number of forms (1) was observed with the lemma “ahalena”: <em>ahalena</em>.</p>
<p>The 3rd highest number of forms (1) was observed with the lemma “ai”: <em>ai</em>.</p>
<p><code class="language-plaintext highlighter-rouge">INTJ</code> does not occur with any features.</p>
<h2 id="relations">Relations</h2>
<p><code class="language-plaintext highlighter-rouge">INTJ</code> nodes are attached to their parents using 9 different relations: <tt><a href="eu_bdt-dep-discourse.html">discourse</a></tt> (21; 58% instances), <tt><a href="eu_bdt-dep-advcl.html">advcl</a></tt> (4; 11% instances), <tt><a href="eu_bdt-dep-nmod.html">nmod</a></tt> (3; 8% instances), <tt><a href="eu_bdt-dep-advmod.html">advmod</a></tt> (2; 6% instances), <tt><a href="eu_bdt-dep-conj.html">conj</a></tt> (2; 6% instances), <tt><a href="eu_bdt-dep-mark.html">mark</a></tt> (1; 3% instances), <tt><a href="eu_bdt-dep-obl.html">obl</a></tt> (1; 3% instances), <tt><a href="eu_bdt-dep-root.html">root</a></tt> (1; 3% instances), <tt><a href="eu_bdt-dep-xcomp.html">xcomp</a></tt> (1; 3% instances)</p>
<p>Parents of <code class="language-plaintext highlighter-rouge">INTJ</code> nodes belong to 7 different parts of speech: <tt><a href="eu_bdt-pos-VERB.html">VERB</a></tt> (21; 58% instances), <tt><a href="eu_bdt-pos-AUX.html">AUX</a></tt> (8; 22% instances), <tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt> (3; 8% instances), <tt><a href="eu_bdt-pos-ADJ.html">ADJ</a></tt> (1; 3% instances), <tt><a href="eu_bdt-pos-CCONJ.html">CCONJ</a></tt> (1; 3% instances), <tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> (1; 3% instances), (1; 3% instances)</p>
<p>27 (75%) <code class="language-plaintext highlighter-rouge">INTJ</code> nodes are leaves.</p>
<p>2 (6%) <code class="language-plaintext highlighter-rouge">INTJ</code> nodes have one child.</p>
<p>7 (19%) <code class="language-plaintext highlighter-rouge">INTJ</code> nodes have two children.</p>
<p>The highest child degree of a <code class="language-plaintext highlighter-rouge">INTJ</code> node is 2.</p>
<p>Children of <code class="language-plaintext highlighter-rouge">INTJ</code> nodes are attached using 5 different relations: <tt><a href="eu_bdt-dep-dep.html">dep</a></tt> (10; 63% instances), <tt><a href="eu_bdt-dep-punct.html">punct</a></tt> (3; 19% instances), <tt><a href="eu_bdt-dep-cc.html">cc</a></tt> (1; 6% instances), <tt><a href="eu_bdt-dep-csubj.html">csubj</a></tt> (1; 6% instances), <tt><a href="eu_bdt-dep-nmod.html">nmod</a></tt> (1; 6% instances)</p>
<p>Children of <code class="language-plaintext highlighter-rouge">INTJ</code> nodes belong to 6 different parts of speech: <tt><a href="eu_bdt-pos-VERB.html">VERB</a></tt> (6; 38% instances), <tt><a href="eu_bdt-pos-NUM.html">NUM</a></tt> (4; 25% instances), <tt><a href="eu_bdt-pos-PUNCT.html">PUNCT</a></tt> (3; 19% instances), <tt><a href="eu_bdt-pos-CCONJ.html">CCONJ</a></tt> (1; 6% instances), <tt><a href="eu_bdt-pos-INTJ.html">INTJ</a></tt> (1; 6% instances), <tt><a href="eu_bdt-pos-NOUN.html">NOUN</a></tt> (1; 6% instances)</p>
</div>
<!-- support for embedded visualizations -->
<script type="text/javascript">
var root = '../../'; // filled in by jekyll
head.js(
// We assume that external libraries such as jquery.min.js have already been loaded outside!
// (See _layouts/base.html.)
// brat helper modules
root + 'lib/brat/configuration.js',
root + 'lib/brat/util.js',
root + 'lib/brat/annotation_log.js',
root + 'lib/ext/webfont.js',
// brat modules
root + 'lib/brat/dispatcher.js',
root + 'lib/brat/url_monitor.js',
root + 'lib/brat/visualizer.js',
// embedding configuration
root + 'lib/local/config.js',
// project-specific collection data
root + 'lib/local/collections.js',
// Annodoc
root + 'lib/annodoc/annodoc.js',
// NOTE: non-local libraries
'https://spyysalo.github.io/conllu.js/conllu.js'
);
var webFontURLs = [
// root + 'static/fonts/Astloch-Bold.ttf',
root + 'static/fonts/PT_Sans-Caption-Web-Regular.ttf',
root + 'static/fonts/Liberation_Sans-Regular.ttf'
];
var setupTimeago = function() {
jQuery("time.timeago").timeago();
};
head.ready(function() {
setupTimeago();
// mark current collection (filled in by Jekyll)
Collections.listing['_current'] = '';
// perform all embedding and support functions
Annodoc.activate(Config.bratCollData, Collections.listing);
});
</script>
<!-- google analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-55233688-1', 'auto');
ga('send', 'pageview');
</script>
<div id="footer">
<p class="footer-text">© 2014–2021
<a href="http://universaldependencies.org/introduction.html#contributors" style="color:gray">Universal Dependencies contributors</a>.
Site powered by <a href="http://spyysalo.github.io/annodoc" style="color:gray">Annodoc</a> and <a href="http://brat.nlplab.org/" style="color:gray">brat</a></p>.
</div>
</div>
</body>
</html>
|
apache-2.0
|
giorno/tui
|
src/model/float.rb
|
656
|
# vim: et
require_relative 'base'
module Tui module Model
# Model for floating point number objects.
class Float < Base
# Constructor.
public
def initialize ( label, value = 0.0, ro = false )
super( label, value, ro )
if not ro
self.value = value # validation step
end
end # initialize
# Check if the provided value is indeed a floating point number.
# @override
public
def valid? ( value )
return value.is_a? ::Float
end # valid?
# @overriden
public
def from_s ( value )
self.value= Float( value )
end # from_s
end # Float
end # ::Model
end # ::Tui
|
apache-2.0
|
jeffyu/blogging
|
ims-web/src/main/java/net/java/dev/blog/action/BlogManagerController.java
|
2522
|
/**
*
*/
package net.java.dev.blog.action;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.java.dev.blog.security.ui.SecurityContextUtil;
import net.java.dev.blog.service.Blog;
import net.java.dev.blog.service.BlogService;
import net.java.dev.blog.service.Label;
import net.java.dev.blog.service.ManagerService;
import net.java.dev.blog.service.User;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
/**
* @author Jeff.Yu
*
*/
public class BlogManagerController extends MultiActionController {
private BlogService blogService;
private ManagerService managerService;
public ModelAndView getBlog(HttpServletRequest request, HttpServletResponse response) throws Exception {
String blogId = request.getParameter("blogID");
if (blogId == null || "".equals(blogId)) {
Map<String, Object> data = new HashMap<String, Object>();
data.put("allLabels", blogService.getLabels());
return new ModelAndView("manager/blog", data);
} else {
Blog blog = blogService.getBlog(Long.valueOf(blogId));
StringBuffer blogLabels = new StringBuffer();
for(Label label : blog.getLabels()) {
blogLabels.append(label.getLabelName());
blogLabels.append(",");
}
Map<String, Object> data = new HashMap<String, Object>();
data.put("blog", blog);
data.put("blogLabels", blogLabels.toString());
data.put("allLabels", blogService.getLabels());
return new ModelAndView("manager/blog", data);
}
}
public ModelAndView removeBlog(HttpServletRequest request, HttpServletResponse response) throws Exception {
String blogId = request.getParameter("blogID");
User currentUser = SecurityContextUtil.getBloggingUser();
managerService.removeBlog(Long.valueOf(blogId), currentUser);
return new ModelAndView("redirect:index.do");
}
public ModelAndView removeComment(HttpServletRequest request, HttpServletResponse response) throws Exception {
String blogId = request.getParameter("blogID");
String commentId = request.getParameter("commentID");
managerService.removeComment(Long.valueOf(commentId));
return new ModelAndView("redirect:editBlog.do?blogID=" + blogId);
}
public void setBlogService(BlogService blogService) {
this.blogService = blogService;
}
public void setManagerService(ManagerService managerService) {
this.managerService = managerService;
}
}
|
apache-2.0
|
nghiant2710/base-images
|
balena-base-images/python/beaglebone-green-gateway/alpine/3.13/3.6.12/run/Dockerfile
|
4146
|
# AUTOGENERATED FILE
FROM balenalib/beaglebone-green-gateway-alpine:3.13-run
# remove several traces of python
RUN apk del python*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# install python dependencies
RUN apk add --no-cache ca-certificates libffi \
&& apk add --no-cache libssl1.0 || apk add --no-cache libssl1.1
# key 63C7CC90: public key "Simon McVittie <[email protected]>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <[email protected]>" imported
RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
# point Python at a system-provided certificate database. Otherwise, we might hit CERTIFICATE_VERIFY_FAILED.
# https://www.python.org/dev/peps/pep-0476/#trust-database
ENV SSL_CERT_FILE /etc/ssl/certs/ca-certificates.crt
ENV PYTHON_VERSION 3.6.12
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.0.1
ENV SETUPTOOLS_VERSION 56.0.0
RUN set -x \
&& buildDeps=' \
curl \
gnupg \
' \
&& apk add --no-cache --virtual .build-deps $buildDeps \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-alpine-armv7hf-openssl1.1.tar.gz" \
&& echo "9ea800721595b573ee89cb20f4c28fa0273cf726a509bc7fcd21772bd4adefda Python-$PYTHON_VERSION.linux-alpine-armv7hf-openssl1.1.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-alpine-armv7hf-openssl1.1.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-alpine-armv7hf-openssl1.1.tar.gz" \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@python" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Alpine Linux 3.13 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.6.12, Pip v21.0.1, Setuptools v56.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh
|
apache-2.0
|
nghiant2710/base-images
|
balena-base-images/node/beaglebone-green-gateway/debian/jessie/14.16.1/build/Dockerfile
|
2801
|
# AUTOGENERATED FILE
FROM balenalib/beaglebone-green-gateway-debian:jessie-build
ENV NODE_VERSION 14.16.1
ENV YARN_VERSION 1.22.4
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --batch --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& echo "54efe997dbeff971b1e39c8eb910566ecb68cfd6140a6b5c738265d4b5842d24 node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@node" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Jessie \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v14.16.1, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
apache-2.0
|
mareklibra/userportal
|
src/components/VmDialog/index.js
|
28260
|
import React from 'react'
import PropTypes from 'prop-types'
import Immutable from 'immutable'
import { connect } from 'react-redux'
import { Link } from 'react-router-dom'
import NavigationPrompt from 'react-router-navigation-prompt'
import Switch from 'react-bootstrap-switch'
import {
generateUnique,
templateNameRenderer,
filterOsByArchitecture,
findOsByName,
isWindows,
} from '_/helpers'
import { isRunning, getVmIconId, isValidOsIcon, isVmNameValid } from '../utils'
import style from './style.css'
import sharedStyle from '../sharedStyle.css'
import CloudInitEditor from '../CloudInitEditor'
import DetailContainer from '../DetailContainer'
import IconUpload from './IconUpload'
import ErrorAlert from '../ErrorAlert'
import FieldHelp from '../FieldHelp'
import NavigationConfirmationModal from '../NavigationConfirmationModal'
import SelectBox from '../SelectBox'
import VmIcon from '../VmIcon'
import timezones from '_/components/utils/timezones.json'
import { createVm, editVm } from '_/actions'
import { MAX_VM_MEMORY_FACTOR } from '_/constants'
import { msg } from '_/intl'
const zeroUID = '00000000-0000-0000-0000-000000000000'
const FIRST_DEVICE = 0
const SECOND_DEVICE = 1
const defaultDevices = ['hd', null]
class VmDialog extends React.Component {
constructor (props) {
super(props)
this.state = {
correlationId: '',
id: undefined,
name: '',
description: '',
cpus: 1,
memory: 1024 * 1024 * 1024,
cdrom: {
fileId: '',
},
clusterId: undefined,
templateId: undefined,
osId: undefined,
bootDevices: defaultDevices,
saved: false,
isChanged: false,
bootMenuEnabled: false,
cloudInit: {
enabled: false,
hostName: '',
sshAuthorizedKeys: '',
},
icon: {
id: undefined,
mediaType: undefined,
data: undefined,
},
uiErrors: {
icon: undefined,
},
timeZone: null,
}
this.submitHandler = this.submitHandler.bind(this)
this.initDefaults = this.initDefaults.bind(this)
this.onIntegerChanged = this.onIntegerChanged.bind(this)
this.getMemoryPolicy = this.getMemoryPolicy.bind(this)
this.getCluster = this.getCluster.bind(this)
this.getTemplate = this.getTemplate.bind(this)
this.getOS = this.getOS.bind(this)
this.getOsIdFromType = this.getOsIdFromType.bind(this)
this.checkTimeZone = this.checkTimeZone.bind(this)
this.onChangeCluster = this.onChangeCluster.bind(this)
this.onChangeTemplate = this.onChangeTemplate.bind(this)
this.doChangeTemplateIdTo = this.doChangeTemplateIdTo.bind(this)
this.onChangeOperatingSystem = this.onChangeOperatingSystem.bind(this)
this.doChangeOsIdTo = this.doChangeOsIdTo.bind(this)
this.onChangeVmName = this.onChangeVmName.bind(this)
this.onChangeVmDescription = this.onChangeVmDescription.bind(this)
this.onChangeVmMemory = this.onChangeVmMemory.bind(this)
this.onChangeVmCpu = this.onChangeVmCpu.bind(this)
this.onChangeCD = this.onChangeCD.bind(this)
this.onChangeBootMenuEnabled = this.onChangeBootMenuEnabled.bind(this)
this.onChangeBootDevice = this.onChangeBootDevice.bind(this)
this.handleCloudInitChange = this.handleCloudInitChange.bind(this)
this.onIconChange = this.onIconChange.bind(this)
this.setUiError = this.setUiError.bind(this)
}
componentDidMount () {
const vm = this.props.vm
if (vm) { // 'edit' mode
const bootDevices = vm.getIn(['os', 'bootDevices']).toJS()
const resultDevices = []
for (let i = 0; i < defaultDevices.length; i++) {
resultDevices.push(bootDevices[i] ? bootDevices[i] : defaultDevices[i])
}
this.setState({
id: vm.get('id'),
name: vm.get('name'),
description: vm.get('description'),
cpus: vm.getIn(['cpu', 'vCPUs']),
memory: vm.getIn(['memory', 'total']),
clusterId: vm.getIn(['cluster', 'id']),
templateId: vm.getIn(['template', 'id']),
osId: this.getOsIdFromType(vm.getIn(['os', 'type'])),
bootDevices: resultDevices,
cdrom: {
fileId: null,
},
bootMenuEnabled: vm.get('bootMenuEnabled'),
cloudInit: vm.get('cloudInit').toJS(),
icon: {
id: getVmIconId(this.props.operatingSystems, vm),
mediaType: undefined,
data: undefined,
},
timeZone: null,
})
}
setTimeout(() => this.initDefaults(), 0)
}
static getDerivedStateFromProps (props, state) {
// If a user message correlating to the correlationId exists, the add/edit failed and
// the state should still be marked as isChanged to prevent page navigation.
if (props.userMessages.get('records').find(record => record.getIn([ 'failedAction', 'meta', 'correlationId' ]) === state.correlationId)) {
return { isChanged: true }
}
return null
}
setUiError (name, error) {
this.setState((prevState) => ({
uiErrors: Object.assign({}, prevState.uiErrors, {
[name]: error,
}),
}))
}
submitHandler (e) {
e.preventDefault()
const correlationId = generateUnique('vm-dialog-')
const template = this.getTemplate(this.state.templateId)
const clone = !!(template && template.get('type') === 'server')
this.props.vm
? this.props.updateVm(this.composeVm(), correlationId)
: this.props.addVm(this.composeVm(), correlationId, clone)
this.setState({
saved: true,
isChanged: false,
correlationId,
})
}
getLatestUserMessage () {
const { correlationId } = this.state
const filtered = this.props.userMessages
.get('records')
.filter(record => record.getIn([ 'failedAction', 'meta', 'correlationId' ]) === correlationId)
const last = filtered.last()
return last && last.get('message')
}
getMemoryPolicy () {
const cluster = this.getCluster()
const overCommitPercent = cluster && cluster.getIn(['memoryPolicy', 'overCommitPercent'])
let guaranteed = overCommitPercent ? (this.state.memory * (100 / overCommitPercent)) : this.state.memory
const memoryPolicy = {
'max': this.state.memory * MAX_VM_MEMORY_FACTOR,
'guaranteed': Math.round(guaranteed),
}
console.log('getMemoryPolicy() resulting memory_policy: ', memoryPolicy)
return memoryPolicy
}
/**
* Compose vm object from entered values
*
* Structure conforms vmToInternal()
*/
composeVm () {
// TODO: Here is the old compose!!
const os = this.props.operatingSystems.get(this.state.osId)
return {
'id': this.state.id,
'name': this.state.name,
'description': this.state.description,
'template': { 'id': this.state.templateId },
'cluster': { 'id': this.state.clusterId },
'memory': this.state.memory || 0,
'memory_policy': this.getMemoryPolicy(),
'cdrom': {
'fileId': this.state.cdrom.fileId === null ? '' : this.state.cdrom.fileId,
},
'os': {
'type': os ? os.get('name') : null,
'bootDevices': this.state.bootDevices || [],
},
'cpu': {
'topology': {
'cores': '1', // TODO: fix to conform topology in template!
'sockets': this.state.cpus || 1,
'threads': '1',
},
},
bootMenuEnabled: this.state.bootMenuEnabled,
cloudInit: this.state.cloudInit,
'status': this.props.vm ? this.props.vm.get('status') : '',
icons: {
large: {
id: this.state.icon.id,
media_type: this.state.icon.id ? undefined : this.state.icon.mediaType,
data: this.state.icon.id ? undefined : this.state.icon.data,
},
},
timeZone: this.state.timeZone,
}
}
onChangeVmName (event) {
const newName = event.target.value
const vmNameErrorText = isVmNameValid(newName)
? null
: msg.pleaseEnterValidVmName()
this.setState({ name: newName, isChanged: true, vmNameErrorText })
const template = this.getTemplate()
if (!template) {
return
}
const templateHostName = template.getIn(['cloudInit', 'hostName'])
if (templateHostName) {
return
}
this.setState(state => { state.cloudInit.hostName = newName })
}
onChangeVmDescription (event) {
this.setState({ description: event.target.value, isChanged: true })
}
onChangeVmMemory (event) {
this.onIntegerChanged({ stateProp: 'memory', value: event.target.value, factor: 1024 * 1024, isChanged: true })
}
onChangeVmCpu (event) {
this.onIntegerChanged({ stateProp: 'cpus', value: event.target.value })
}
onChangeCD (fileId) {
this.setState({ cdrom: { fileId }, isChanged: true })
}
onIntegerChanged ({ value, stateProp, factor = 1 }) {
let intVal = parseInt(value)
if (!isNaN(intVal)) {
value = intVal * factor
} else {
console.log('not an integer: ', value)
value = ''
}
const stateChange = {}
stateChange[stateProp] = value
stateChange['isChanged'] = true
this.setState(stateChange)
}
onChangeOperatingSystem (osId) {
this.doChangeOsIdTo(osId)
}
doChangeOsIdTo (osId) {
const os = this.props.operatingSystems.get(osId)
if (os) {
this.onChangeOsIconId(os.getIn(['icons', 'large', 'id']))
this.checkTimeZone({ osType: os.get('name') })
}
this.setState({
osId,
isChanged: true,
})
}
onChangeOsIconId (iconId) {
if (this.state.icon.id && isValidOsIcon(this.props.operatingSystems, this.state.icon.id)) { // change unless custom icon is selected
this.doChangeIconId(iconId)
}
}
checkTimeZone ({ osType }) {
const { config } = this.props
let timeZone = this.state.timeZone
const template = this.getTemplate()
if (template && template.getIn(['timeZone', 'name'])) {
timeZone = timeZone || template.get('timeZone').toJS()
}
const isWindowsTimeZone = timeZone && timezones.find(timezone => timezone.id === timeZone.name)
const isWindowsVm = isWindows(osType)
if (isWindowsVm && !isWindowsTimeZone) {
timeZone = {
name: config.get('defaultWindowsTimezone'),
}
}
if (!isWindowsVm && isWindowsTimeZone) {
timeZone = {
name: config.get('defaultGeneralTimezone'),
}
}
if (timeZone) {
this.setState({
timeZone,
})
}
}
doChangeIconId (iconId) {
this.setUiError('icon')
this.setState({
icon: {
id: iconId,
},
isChanged: true,
})
}
onIconChange (icon) {
if (icon) {
this.setUiError('icon')
this.setState({
icon,
isChanged: true,
})
} else {
// set default os icon
const os = this.getOS()
if (os) {
this.doChangeIconId(os.getIn(['icons', 'large', 'id']))
}
}
}
getOsIdFromType (type) {
const os = findOsByName(this.props.operatingSystems, type)
return os ? os.get('id') : undefined
}
/**
* @returns OperatingSystem object conforming this.state.osId
*/
getOS () {
const osId = this.state.osId
if (osId) {
const os = this.props.operatingSystems.get(osId)
if (os) {
return os
}
}
return undefined
}
/**
* User selected different template.
*/
onChangeTemplate (templateId) {
this.doChangeTemplateIdTo(templateId)
}
doChangeTemplateIdTo (templateId) {
const template = this.getTemplate(templateId)
let { memory, cpus, osId, cloudInit, bootMenuEnabled } = this.state
if (template) {
memory = template.get('memory')
cpus = template.getIn(['cpu', 'topology', 'cores'], 1) * template.getIn(['cpu', 'topology', 'sockets'], 1) * template.getIn(['cpu', 'topology', 'threads'], 1)
osId = this.getOsIdFromType(template.getIn(['os', 'type'], 'Blank'))
cloudInit = template.get('cloudInit').toJS()
bootMenuEnabled = template.get('bootMenuEnabled')
}
this.setState({
templateId,
memory,
cpus,
isChanged: true,
cloudInit,
bootMenuEnabled,
})
const osType = this.props.operatingSystems.getIn([ osId, 'name' ])
this.checkTimeZone({ osType })
if (this.state.osId !== osId) {
this.doChangeOsIdTo(osId)
}
// fire external data retrieval here if needed after Template change
}
/**
* @returns template object conforming this.state.templateId
*/
getTemplate (templateId) {
templateId = templateId || this.state.templateId
if (templateId) {
const template = this.props.templates.get(templateId)
if (template) {
return template
}
}
return undefined
}
/**
* User selected different cluster.
*/
onChangeCluster (clusterId) {
this.setState({
clusterId,
})
const template = this.getTemplate(this.state.templateId)
if (template && template.get('clusterId') && template.get('clusterId') !== clusterId) {
this.doChangeTemplateIdTo(zeroUID) // Careful: this.state.clusterId still contains previous clusterId, call setTimeout(function, 0) if needed otherwise
}
// fire external data retrieval here if needed after Cluster change
}
onChangeBootMenuEnabled (switchComponent, value) {
this.setState({ bootMenuEnabled: value })
}
/**
* @returns cluster object conforming this.state.clusterId
*/
getCluster () {
const clusterId = this.state.clusterId
if (clusterId) {
const cluster = this.props.clusters.get(clusterId)
if (cluster) {
return cluster
}
}
return undefined
}
getCDRomFileId () {
if (this.state.cdrom.fileId !== null) {
return this.state.cdrom.fileId
} else {
return this.props.vm.getIn(['cdrom', 'fileId']) || ''
}
}
initDefaults () {
const { clusters, templates, operatingSystems } = this.props
const stateChange = {}
const defaultClusterName = 'Default'
if (!this.getCluster()) {
const clustersList = clusters.toList()
const def = (clustersList.filter(item => item.get('name') === defaultClusterName).first()) || clustersList.first()
stateChange.clusterId = def ? def.get('id') : undefined
console.log(`VmDialog initDefaults(): Setting initial value for clusterId = ${this.state.clusterId} to ${stateChange.clusterId}`)
}
if (!this.getTemplate()) {
const def = templates.get(zeroUID) || this.props.templates.toList().first()
stateChange.templateId = def ? def.get('id') : undefined
console.log(`VmDialog initDefaults(): Setting initial value for templateId = ${this.state.templateId} to ${stateChange.templateId}`)
}
if (!this.getOS()) {
const osList = operatingSystems.toList()
const os = osList.sort((a, b) => a.get('id').localeCompare(b.get('id'))).first()
if (os) {
stateChange.osId = os.get('id')
stateChange.icon = {
id: os.getIn(['icons', 'large', 'id']),
}
}
console.log(`VmDialog initDefaults(): Setting initial value for osId = ${this.state.osId} to ${stateChange.osId}`)
}
if (this.getTemplate(stateChange.templateId).get('timeZone')) {
stateChange.timeZone = this.getTemplate(stateChange.templateId).get('timeZone').toJS()
console.log(`VmDialog initDefaults(): Setting initial value for timeZone = ${JSON.stringify(this.state.timeZone)} to ${JSON.stringify(stateChange.timeZone)}`)
}
this.setState(stateChange)
}
handleCloudInitChange (key) {
return (value) => {
this.setState((prevState) => {
return { cloudInit: Object.assign({}, prevState.cloudInit, { [key]: value }) }
})
}
}
onChangeBootDevice (id) {
return (device) => {
this.setState((prevState) => {
const copiedDevices = prevState.bootDevices.slice()
copiedDevices[id] = device
for (let i = id + 1; i < copiedDevices.length; i++) {
copiedDevices[i] = copiedDevices[i] === device ? null : copiedDevices[i]
}
return { bootDevices: copiedDevices }
})
}
}
render () {
const {
icons,
templates,
clusters,
storages,
previousPath,
operatingSystems,
} = this.props
const { bootDevices } = this.state
const vm = this.props.vm
const idPrefix = `vmdialog-${vm ? vm.get('name') : '_new'}`
const files = [{ id: '', value: '[Eject]' }]
storages.toList().forEach(storageDomain => {
const fileList = storageDomain.get('files')
if (fileList) {
files.push(...fileList.map(item => (
{ id: item['id'], value: item['name'] }
)))
}
})
const isEdit = !!vm
const isUp = (isEdit && isRunning(vm.get('status')))
const filteredTemplates = templates
.filter(template => template.get('clusterId') === this.state.clusterId || !template.get('clusterId'))
const cluster = this.getCluster()
const architecture = cluster && cluster.get('architecture')
const osMap = filterOsByArchitecture(operatingSystems, architecture)
const os = this.getOS()
const template = this.getTemplate()
const cdromFileId = this.getCDRomFileId()
const submitText = isEdit ? msg.updateVm() : msg.createVm()
const allowedBootDevices = ['hd', 'network', 'cdrom']
const dialogHeader = isEdit ? `${vm.get('name')} - ${msg.edit()}` : msg.createANewVm()
const icon = this.state.icon.id ? icons.get(this.state.icon.id) : Immutable.fromJS(this.state.icon)
const bootMenuHint = isUp
? (<React.Fragment>
{msg.bootMenuTooltip()}
<br />
<span className='pficon pficon-warning-triangle-o' />
{msg.bootMenuWarning()}
</React.Fragment>)
: msg.bootMenuTooltip()
const vmNameError = this.state.vmNameErrorText
? (<span className={`help-block ${style['error-text']}`}>{this.state.vmNameErrorText}</span>)
: null
return (
<div className='detail-container'><DetailContainer>
<h1 className={style['header']} id={`${idPrefix}-${isEdit ? 'edit' : 'create'}-title`}>
<VmIcon icon={icon} missingIconClassName='pficon pficon-virtual-machine' />
{dialogHeader}
</h1>
{this.getLatestUserMessage() && (<ErrorAlert message={this.getLatestUserMessage()} id={`${idPrefix}-erroralert`} />)}
<br />
<form>
<NavigationPrompt when={this.state.isChanged}>
{({ isActive, onConfirm, onCancel }) => (
<NavigationConfirmationModal show={isActive} onYes={onConfirm} onNo={onCancel} />
)}
</NavigationPrompt>
<div className={style['vm-dialog-container']}>
<dl className={sharedStyle['vm-properties']}>
<dt>
<FieldHelp content={msg.uniqueNameOfTheVirtualMachine()} text={msg.name()} />
</dt>
<dd className={this.state.vmNameErrorText ? 'has-error' : ''}>
<input
type='text'
className='form-control'
id='vmName'
placeholder={msg.enterVmName()}
onChange={this.onChangeVmName}
value={this.state.name || ''} />
{vmNameError}
</dd>
<dt>
<FieldHelp content={msg.optionalUserDescriptionOfVm()} text={msg.description()} />
</dt>
<dd>
<input
type='text'
className='form-control'
id='vmDescription'
placeholder={msg.enterVmDescription()}
onChange={this.onChangeVmDescription}
value={this.state.description || ''} />
</dd>
<dt>
<FieldHelp content={msg.groupOfHostsVmCanBeRunningOn()} text={msg.cluster()} />
</dt>
<dd className={style['field-overflow-visible']}>
<SelectBox
onChange={this.onChangeCluster}
selected={cluster ? cluster.get('id') : ''}
idPrefix='select-cluster'
sort
items={clusters.toList().map(item => (
{ id: item.get('id'), value: item.get('name') }
)).toJS()}
/>
</dd>
<dt>
<FieldHelp content={msg.containsConfigurationAndDisksWhichWillBeUsedToCreateThisVm()} text={msg.template()} />
</dt>
<dd className={style['field-overflow-visible']}>
<SelectBox
onChange={this.onChangeTemplate}
selected={template ? template.get('id') : ''}
idPrefix='select-template'
sort
items={filteredTemplates.toList().map(item => (
{ id: item.get('id'), value: templateNameRenderer(item) }
)).toJS()}
/>
</dd>
<dt>
<FieldHelp content={msg.operatingSystemInstalledOnVm()} text={msg.operatingSystem()} />
</dt>
<dd className={style['field-overflow-visible']}>
<SelectBox
onChange={this.onChangeOperatingSystem}
selected={os ? os.get('id') : ''}
idPrefix='select-os'
sort
items={osMap.toList().map(item => (
{ id: item.get('id'), value: item.get('description') }
)).toJS()}
/>
</dd>
<dt>
<span className='pficon pficon-memory' />
<FieldHelp content={msg.totalMemoryVmWillBeEquippedWith()} text={msg.definedMemory()} />
</dt>
<dd>
<input
type='number'
className='form-control'
id='vmMemory'
placeholder={msg.vmMemory()}
onChange={this.onChangeVmMemory}
value={this.state.memory / 1024 / 1024 || ''}
min={0}
step={256} />
</dd>
<dt>
<span className='pficon pficon-cpu' />
<FieldHelp content={msg.totalCountOfVirtualProcessorsVmWillBeEquippedWith()} text={msg.cpus()} />
</dt>
<dd>
<input
type='number'
className='form-control'
id='vmCpus'
placeholder={msg.cpus()}
onChange={this.onChangeVmCpu}
value={this.state.cpus || ''}
min={1}
step={1} />
</dd>
{ isEdit && (
<div> {/* this <div> is ugly anti-pattern and should be replaced by React.Fragment as soon as upgraded to React 16 */}
<dt>
<span className='pficon pficon-storage-domain' />
<FieldHelp content={msg.changeCd()} text={msg.cd()} />
</dt>
<dd className={style['field-overflow-visible']}>
<SelectBox
onChange={this.onChangeCD}
idPrefix='select-changecd'
selected={cdromFileId}
sort
items={files}
/>
</dd>
</div>
)}
<dt>
{
(isUp && vm.get('bootMenuEnabled') !== this.state.bootMenuEnabled) &&
<span className={'pficon pficon-warning-triangle-o ' + style['space-right']} />
}
<FieldHelp content={bootMenuHint} text={msg.bootMenu()} />
</dt>
<dd>
<Switch
animate
bsSize='mini'
value={!!this.state.bootMenuEnabled}
onChange={this.onChangeBootMenuEnabled}
/>
</dd>
<dt>
<FieldHelp content={msg.bootSequenceTooltip()} text={msg.bootSequence()} />
</dt>
<dd />
<div>
<dt className={style['field-shifted']}>
<FieldHelp content={msg.firstDeviceTooltip()} text={msg.firstDevice()} />
</dt>
<dd className={style['field-overflow-visible']}>
<SelectBox
onChange={this.onChangeBootDevice(FIRST_DEVICE)}
selected={bootDevices[FIRST_DEVICE]}
idPrefix='select-first-device'
items={allowedBootDevices.map(item => (
{ id: item, value: msg[`${item}Boot`]() }
))}
/>
</dd>
<dt className={style['field-shifted']}>
<FieldHelp content={msg.secondDeviceTooltip()} text={msg.secondDevice()} />
</dt>
<dd className={style['field-overflow-visible']}>
<SelectBox
onChange={this.onChangeBootDevice(SECOND_DEVICE)}
selected={bootDevices[SECOND_DEVICE]}
idPrefix='select-second-device'
items={[{ id: null, value: '[None]' }, ...allowedBootDevices.filter(item => (
item !== bootDevices[FIRST_DEVICE]
)).map(item => (
{ id: item, value: msg[`${item}Boot`]() }
))]}
/>
</dd>
</div>
<CloudInitEditor
enabled={this.state.cloudInit.enabled}
hostName={this.state.cloudInit.hostName}
sshAuthorizedKeys={this.state.cloudInit.sshAuthorizedKeys}
onEnabledChange={this.handleCloudInitChange('enabled')}
onHostNameChange={this.handleCloudInitChange('hostName')}
onSshAuthorizedKeysChange={this.handleCloudInitChange('sshAuthorizedKeys')}
/>
<IconUpload
onIconChange={this.onIconChange}
onErrorChange={(error) => this.setUiError('icon', error)}
error={this.state.uiErrors.icon} />
</dl>
</div>
<div className={style['vm-dialog-buttons']}>
<Link id='button-close' className='btn btn-default' to={previousPath}>{msg.close()}</Link>
<button id='button-submit' className='btn btn-primary' type='button' onClick={this.submitHandler}>{submitText}</button>
</div>
</form>
</DetailContainer></div>
)
}
}
VmDialog.propTypes = {
vm: PropTypes.object, // optional, VM object to edit
clusters: PropTypes.object.isRequired, // deep immutable, {[id: string]: Cluster}
templates: PropTypes.object.isRequired, // deep immutable, {[id: string]: Template}
operatingSystems: PropTypes.object.isRequired, // deep immutable, {[id: string]: OperatingSystem}
userMessages: PropTypes.object.isRequired,
icons: PropTypes.object.isRequired,
config: PropTypes.object.isRequired,
storages: PropTypes.object.isRequired, // deep immutable, {[id: string]: StorageDomain}
previousPath: PropTypes.string.isRequired,
addVm: PropTypes.func.isRequired,
updateVm: PropTypes.func.isRequired,
}
export default connect(
(state) => ({
clusters: state.clusters.filter(cluster => cluster.get('canUserUseCluster')),
templates: state.templates.filter(cluster => cluster.get('canUserUseTemplate')),
operatingSystems: state.operatingSystems,
userMessages: state.userMessages,
icons: state.icons,
storages: state.storageDomains,
config: state.config,
}),
(dispatch) => ({
addVm: (vm, correlationId, clone) => dispatch(createVm({ vm, pushToDetailsOnSuccess: true, clone }, { correlationId })),
updateVm: (vm, correlationId) => dispatch(editVm({ vm }, { correlationId })),
})
)(VmDialog)
|
apache-2.0
|
vdmeer/skb-java-interfaces
|
src/main/java/de/vandermeer/skb/interfaces/coin/TailsErrorWithErrors.java
|
2493
|
/* Copyright 2016 Sven van der Meer <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.vandermeer.skb.interfaces.coin;
import java.util.LinkedHashSet;
import java.util.Set;
import org.apache.commons.lang3.text.StrBuilder;
import de.vandermeer.skb.interfaces.messagesets.IsErrorSet;
import de.vandermeer.skb.interfaces.render.DoesRender;
/**
* A tails (error) coin with a value and errors.
*
* @author Sven van der Meer <[email protected]>
* @version v0.0.2 build 170502 (02-May-17) for Java 1.8
* @since v0.0.1
*/
public interface TailsErrorWithErrors<R, M> extends TailsError<R>, IsErrorSet<M> {
@Override
default boolean reportsErrors(){
return true;
}
@Override
default boolean hasErrorReports(){
return this.hasErrors();
}
/**
* Renders the error set.
* The method uses {@link DoesRender} or simple toString to render errors.
* Each element in the error set is rendered in a single line, preceded by the type (error).
* @return rendered object
*/
@Override
default String render() {
StrBuilder ret = new StrBuilder(100);
for(M m : this.getErrorMessages()){
ret.append("errors: ");
if(m instanceof DoesRender){
ret.append(((DoesRender)m).render());
}
else{
ret.append(m);
}
ret.appendNewLine();
}
return ret.toString();
}
/**
* Creates a new error coin with given value and errors.
* @param <R> type of the return value
* @param <M> the message type for the set
* @param value the actual return value
* @return new error coin
*/
static <R, M> TailsErrorWithErrors<R, M> create(final R value){
return new TailsErrorWithErrors<R, M>() {
final Set<M> errorSet = new LinkedHashSet<>();
@Override
public Set<M> getErrorMessages() {
return this.errorSet;
}
@Override
public R getReturn() {
return value;
}
};
}
}
|
apache-2.0
|
cliffroot/prom.by
|
project/src/com/prom/by/model/Order.java
|
6736
|
package com.prom.by.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import android.os.Parcel;
import android.os.Parcelable;
@Element(name = "order")
public class Order implements Parcelable{
@Attribute (name = "id", required = false)
Long id;
@Attribute (name = "state", required = false)
String state;
@Element(name = "name", required = false)
String name;
@Element(name = "phone", required = false)
String phone;
@Element(name = "company", required = false)
String company;
@Element(name = "email", required = false)
String email;
@Element(name = "date", required = false)
String date;
@Element(name = "address", required = false)
String address;
@Element(name = "index", required = false)
String index;
@Element(name = "payercomment", required = false)
String payerComment;
@Element(name = "salescomment", required = false)
String salesComment;
@Element(name = "paymentType", required = false)
String paymentType;
@Element(name = "deliveryType", required = false)
String deliveryType;
@Element(name = "deliveryCost", required = false)
Double deliveryCost;
@Element(name = "priceBYR", required = false)
Double price;
@ElementList(name = "items", required = false)
List<Item> items;
public String getName() {
return name==null?"":name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPaymentType() {
return paymentType;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public String getDeliveryType() {
return deliveryType;
}
public void setDeliveryType(String deliveryType) {
this.deliveryType = deliveryType;
}
public Double getDeliveryCost() {
return deliveryCost;
}
public void setDeliveryCost(Double deliveryCost) {
this.deliveryCost = deliveryCost;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public String getPayerComment() {
return payerComment;
}
public void setPayerComment(String payerComment) {
this.payerComment = payerComment;
}
public String getSalesComment() {
return salesComment;
}
public void setSalesComment(String salesComment) {
this.salesComment = salesComment;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Double getItemsTotalPrice () {
Double price = 0.0;
for (Item item: items) {
price += item.getPrice()==null?0.d:item.getPrice();
}
return price;
}
public String getAllItems () {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
builder.append(items.get(i).getName());
if (i != items.size() - 1) {
builder.append("; ");
}
}
return builder.toString();
}
public boolean itemSKUStartsWith (String prefix) {
for (Item item: items) {
if (item.getSku().toString().startsWith(prefix)) {
return true;
}
}
return false;
}
public boolean itemNameContains (String str) {
Locale locale = new Locale ("ru");
for (Item item: items) {
if (item.getName().toLowerCase(locale).contains(str)) {
return true;
}
}
return false;
}
@Override
public String toString () {
StringBuilder builder = new StringBuilder();
builder.append("{Name:");
builder.append(name);
builder.append(", Email : ");
builder.append(email);
builder.append(", Phone : ");
builder.append(phone);
for (Item item: items) {
builder.append("Item: ");
builder.append(item.toString());
}
builder.append("}\n");
return builder.toString();
}
@Override
public int describeContents() {
return id.hashCode();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
//have to write this way, as values can be null.
dest.writeValue(id);
dest.writeValue(state);
dest.writeValue(name);
dest.writeValue(phone);
dest.writeValue(company);
dest.writeValue(email);
dest.writeValue(date);
dest.writeValue(address);
dest.writeValue(index);
dest.writeValue(payerComment);
dest.writeValue(salesComment);
dest.writeValue(paymentType);
dest.writeValue(deliveryType);
dest.writeValue(deliveryCost);
dest.writeValue(price);
dest.writeList(items);
}
public static final Parcelable.Creator<Order> CREATOR = new Parcelable.Creator<Order>() {
@Override
public Order createFromParcel(Parcel in) {
return new Order(in);
}
@Override
public Order[] newArray(int size) {
return new Order[size];
}
};
public Order () {
}
public Order (Parcel parcel) {
id = (Long) parcel.readValue(Long.class.getClassLoader());
state =(String) parcel.readValue(String.class.getClassLoader());
name = (String)parcel.readValue(String.class.getClassLoader());
phone =(String) parcel.readValue(String.class.getClassLoader());
company =(String) parcel.readValue(String.class.getClassLoader());
email = (String)parcel.readValue(String.class.getClassLoader());
date = (String)parcel.readValue(String.class.getClassLoader());
address = (String)parcel.readValue(String.class.getClassLoader());
index = (String)parcel.readValue(String.class.getClassLoader());
payerComment = (String)parcel.readValue(String.class.getClassLoader());
salesComment = (String)parcel.readValue(String.class.getClassLoader());
paymentType = (String)parcel.readValue(String.class.getClassLoader());
deliveryType = (String)parcel.readValue(String.class.getClassLoader());
deliveryCost = (Double)parcel.readValue(Double.class.getClassLoader());
price = (Double) parcel.readValue(Double.class.getClassLoader());
items = new ArrayList<Item>();
parcel.readList(items, Item.class.getClassLoader());
}
}
|
apache-2.0
|
lijunguan/AlbumSelector
|
imageseletor/src/main/java/io/github/lijunguan/imgselector/model/entity/AlbumFolder.java
|
2209
|
package io.github.lijunguan.imgselector.model.entity;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.List;
/**
* Created by lijunguan on 2016/4/8
* email: [email protected]
* blog : https://lijunguan.github.io
*/
public class AlbumFolder implements Parcelable {
/**
* 相册目录的路径
*/
private String mPath;
/**
* 相册目录名
*/
private String mFloderName;
/**
* 目录下的所有图片集合
*/
private List<ImageInfo> mImgInfos;
/**
* 目录封面
*/
private ImageInfo mCover;
public String getPath() {
return mPath;
}
public void setPath(String mPath) {
this.mPath = mPath;
}
public String getFloderName() {
return mFloderName;
}
public void setFloderName(String mFloderName) {
this.mFloderName = mFloderName;
}
public List<ImageInfo> getImgInfos() {
return mImgInfos;
}
public void setImgInfos(List<ImageInfo> mImgInfos) {
this.mImgInfos = mImgInfos;
}
public ImageInfo getCover() {
return mCover;
}
public void setCover(ImageInfo mCover) {
this.mCover = mCover;
}
public AlbumFolder() {
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.mPath);
dest.writeString(this.mFloderName);
dest.writeTypedList(mImgInfos);
dest.writeParcelable(this.mCover, flags);
}
protected AlbumFolder(Parcel in) {
this.mPath = in.readString();
this.mFloderName = in.readString();
this.mImgInfos = in.createTypedArrayList(ImageInfo.CREATOR);
this.mCover = in.readParcelable(ImageInfo.class.getClassLoader());
}
public static final Creator<AlbumFolder> CREATOR = new Creator<AlbumFolder>() {
@Override
public AlbumFolder createFromParcel(Parcel source) {
return new AlbumFolder(source);
}
@Override
public AlbumFolder[] newArray(int size) {
return new AlbumFolder[size];
}
};
}
|
apache-2.0
|
src-code/amphtml
|
extensions/amp-analytics/0.1/analytics-root.js
|
15094
|
/**
* Copyright 2017 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {HostServices} from '../../../src/inabox/host-services';
import {ScrollManager} from './scroll-manager';
import {Services} from '../../../src/services';
import {VisibilityManagerForMApp} from './visibility-manager-for-mapp';
import {
closestAncestorElementBySelector,
matches,
scopedQuerySelector,
} from '../../../src/dom';
import {dev, user, userAssert} from '../../../src/log';
import {getMode} from '../../../src/mode';
import {layoutRectLtwh} from '../../../src/layout-rect';
import {map} from '../../../src/utils/object';
import {provideVisibilityManager} from './visibility-manager';
import {tryResolve} from '../../../src/utils/promise';
import {whenContentIniLoad} from '../../../src/ini-load';
const TAG = 'amp-analytics/analytics-root';
/**
* An analytics root. Analytics can be scoped to either ampdoc, embed or
* an arbitrary AMP element.
*
* TODO(#22733): merge analytics root properties into ampdoc.
*
* @implements {../../../src/service.Disposable}
* @abstract
*/
export class AnalyticsRoot {
/**
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
*/
constructor(ampdoc) {
/** @const */
this.ampdoc = ampdoc;
/** @const */
this.trackers_ = map();
/** @private {?./visibility-manager.VisibilityManager} */
this.visibilityManager_ = null;
/** @private {?./scroll-manager.ScrollManager} */
this.scrollManager_ = null;
/** @private {?Promise} */
this.usingHostAPIPromise_ = null;
/** @private {?../../../src/inabox/host-services.VisibilityInterface} */
this.hostVisibilityService_ = null;
}
/**
* @return {!Promise<boolean>}
*/
isUsingHostAPI() {
if (this.usingHostAPIPromise_) {
return this.usingHostAPIPromise_;
}
if (!HostServices.isAvailable(this.ampdoc)) {
this.usingHostAPIPromise_ = Promise.resolve(false);
} else {
// TODO: Using the visibility service and apply it for all tracking types
const promise = HostServices.visibilityForDoc(this.ampdoc);
this.usingHostAPIPromise_ = promise
.then(visibilityService => {
this.hostVisibilityService_ = visibilityService;
return true;
})
.catch(error => {
dev().fine(
TAG,
'VisibilityServiceError - fallback=' + error.fallback
);
if (error.fallback) {
// Do not use HostAPI, fallback to original implementation.
return false;
}
// Cannot fallback, service error. Throw user error.
throw user().createError('Host Visibility Service Error');
});
}
return this.usingHostAPIPromise_;
}
/** @override */
dispose() {
for (const k in this.trackers_) {
this.trackers_[k].dispose();
delete this.trackers_[k];
}
if (this.visibilityManager_) {
this.visibilityManager_.dispose();
}
if (this.scrollManager_) {
this.scrollManager_.dispose();
}
}
/**
* Returns the type of the tracker.
* @return {string}
* @abstract
*/
getType() {}
/**
* The root node the analytics is scoped to.
*
* @return {!Document|!ShadowRoot}
* @abstract
*/
getRoot() {}
/**
* The viewer of analytics root
* @return {!../../../src/service/viewer-interface.ViewerInterface}
*/
getViewer() {
return Services.viewerForDoc(this.ampdoc);
}
/**
* The root element within the analytics root.
*
* @return {!Element}
*/
getRootElement() {
const root = this.getRoot();
return dev().assertElement(root.documentElement || root.body || root);
}
/**
* The host element of the analytics root.
*
* @return {?Element}
* @abstract
*/
getHostElement() {}
/**
* The signals for the root.
*
* @return {!../../../src/utils/signals.Signals}
* @abstract
*/
signals() {}
/**
* Whether this analytics root contains the specified node.
*
* @param {!Node} node
* @return {boolean}
*/
contains(node) {
return this.getRoot().contains(node);
}
/**
* Returns the element with the specified ID in the scope of this root.
*
* @param {string} unusedId
* @return {?Element}
* @abstract
*/
getElementById(unusedId) {}
/**
* Returns the tracker for the specified name and list of allowed types.
*
* @param {string} name
* @param {!Object<string, typeof ./events.EventTracker>} whitelist
* @return {?./events.EventTracker}
*/
getTrackerForWhitelist(name, whitelist) {
const trackerProfile = whitelist[name];
if (trackerProfile) {
return this.getTracker(name, trackerProfile);
}
return null;
}
/**
* Returns the tracker for the specified name and type. If the tracker
* has not been requested before, it will be created.
*
* @param {string} name
* @param {typeof ./events.CustomEventTracker|typeof ./events.ClickEventTracker|typeof ./events.ScrollEventTracker|typeof ./events.SignalTracker|typeof ./events.IniLoadTracker|typeof ./events.VideoEventTracker|typeof ./events.VideoEventTracker|typeof ./events.VisibilityTracker|typeof ./events.AmpStoryEventTracker} klass
* @return {!./events.EventTracker}
*/
getTracker(name, klass) {
let tracker = this.trackers_[name];
if (!tracker) {
tracker = new klass(this);
this.trackers_[name] = tracker;
}
return tracker;
}
/**
* Returns the tracker for the specified name or `null`.
* @param {string} name
* @return {?./events.EventTracker}
*/
getTrackerOptional(name) {
return this.trackers_[name] || null;
}
/**
* Searches the element that matches the selector within the scope of the
* analytics root in relationship to the specified context node.
*
* @param {!Element} context
* @param {string} selector DOM query selector.
* @param {?string=} selectionMethod Allowed values are `null`,
* `'closest'` and `'scope'`.
* @return {!Promise<!Element>} Element corresponding to the selector.
*/
getElement(context, selector, selectionMethod = null) {
// Special case selectors. The selection method is irrelavant.
// And no need to wait for document ready.
if (selector == ':root') {
return tryResolve(() => this.getRootElement());
}
if (selector == ':host') {
return new Promise(resolve => {
resolve(
user().assertElement(
this.getHostElement(),
`Element "${selector}" not found`
)
);
});
}
// Wait for document-ready to avoid false missed searches
return this.ampdoc.whenReady().then(() => {
let found;
let result = null;
// Query search based on the selection method.
try {
if (selectionMethod == 'scope') {
found = scopedQuerySelector(context, selector);
} else if (selectionMethod == 'closest') {
found = closestAncestorElementBySelector(context, selector);
} else {
found = this.getRoot().querySelector(selector);
}
} catch (e) {
userAssert(false, `Invalid query selector ${selector}`);
}
// DOM search can "look" outside the boundaries of the root, thus make
// sure the result is contained.
if (found && this.contains(found)) {
result = found;
}
return user().assertElement(result, `Element "${selector}" not found`);
});
}
/**
* Searches the AMP element that matches the selector within the scope of the
* analytics root in relationship to the specified context node.
*
* @param {!Element} context
* @param {string} selector DOM query selector.
* @param {?string=} selectionMethod Allowed values are `null`,
* `'closest'` and `'scope'`.
* @return {!Promise<!AmpElement>} AMP element corresponding to the selector if found.
*/
getAmpElement(context, selector, selectionMethod) {
return this.getElement(context, selector, selectionMethod).then(element => {
userAssert(
element.classList.contains('i-amphtml-element'),
'Element "%s" is required to be an AMP element',
selector
);
return element;
});
}
/**
* Creates listener-filter for DOM events to check against the specified
* selector. If the node (or its ancestors) match the selector the listener
* will be called.
*
* @param {function(!Element, !Event)} listener The first argument is the
* matched target node and the second is the original event.
* @param {!Element} context
* @param {string} selector DOM query selector.
* @param {?string=} selectionMethod Allowed values are `null`,
* `'closest'` and `'scope'`.
* @return {function(!Event)}
*/
createSelectiveListener(listener, context, selector, selectionMethod = null) {
return event => {
if (selector == ':host') {
// `:host` is not reachable via selective listener b/c event path
// cannot be retargeted across the boundary of the embed.
return;
}
// Navigate up the DOM tree to find the actual target.
const rootElement = this.getRootElement();
const isSelectAny = selector == '*';
const isSelectRoot = selector == ':root';
let {target} = event;
while (target) {
// Target must be contained by this root.
if (!this.contains(target)) {
break;
}
// `:scope` context must contain the target.
if (
selectionMethod == 'scope' &&
!isSelectRoot &&
!context.contains(target)
) {
break;
}
// `closest()` target must contain the conext.
if (selectionMethod == 'closest' && !target.contains(context)) {
// However, the search must continue!
target = target.parentElement;
continue;
}
// Check if the target matches the selector.
if (
isSelectAny ||
(isSelectRoot && target == rootElement) ||
tryMatches_(target, selector)
) {
listener(target, event);
// Don't fire the event multiple times even if the more than one
// ancestor matches the selector.
break;
}
target = target.parentElement;
}
};
}
/**
* Returns the promise that will be resolved as soon as the elements within
* the root have been loaded inside the first viewport of the root.
* @return {!Promise}
* @abstract
*/
whenIniLoaded() {}
/**
* Returns the visibility root corresponding to this analytics root (ampdoc
* or embed). The visibility root is created lazily as needed and takes
* care of all visibility tracking functions.
*
* The caller needs to make sure to call getVisibilityManager after
* usingHostAPIPromise has resolved
* @return {!./visibility-manager.VisibilityManager}
*/
getVisibilityManager() {
if (!this.visibilityManager_) {
if (this.hostVisibilityService_) {
// If there is hostAPI (hostAPI never exist with the FIE case)
this.visibilityManager_ = new VisibilityManagerForMApp(
this.ampdoc,
this.hostVisibilityService_
);
} else {
this.visibilityManager_ = provideVisibilityManager(this.getRoot());
}
}
return this.visibilityManager_;
}
/**
* Returns the Scroll Managet corresponding to this analytics root.
* The Scroll Manager is created lazily as needed, and will handle
* calling all handlers for a scroll event.
* @return {!./scroll-manager.ScrollManager}
*/
getScrollManager() {
// TODO (zhouyx@): Disallow scroll trigger with host API
if (!this.scrollManager_) {
this.scrollManager_ = new ScrollManager(this.ampdoc);
}
return this.scrollManager_;
}
}
/**
* The implementation of the analytics root for an ampdoc.
*/
export class AmpdocAnalyticsRoot extends AnalyticsRoot {
/**
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
*/
constructor(ampdoc) {
super(ampdoc);
}
/** @override */
getType() {
return 'ampdoc';
}
/** @override */
getRoot() {
return this.ampdoc.getRootNode();
}
/** @override */
getHostElement() {
// ampdoc is always the root of everything - no host.
return null;
}
/** @override */
signals() {
return this.ampdoc.signals();
}
/** @override */
getElementById(id) {
return this.ampdoc.getElementById(id);
}
/** @override */
whenIniLoaded() {
const viewport = Services.viewportForDoc(this.ampdoc);
let rect;
if (getMode(this.ampdoc.win).runtime == 'inabox') {
// TODO(dvoytenko, #7971): This is currently addresses incorrect position
// calculations in a in-a-box viewport where all elements are offset
// to the bottom of the embed. The current approach, even if fixed, still
// creates a significant probability of risk condition.
// Once address, we can simply switch to the 0/0 approach in the `else`
// clause.
rect = viewport.getLayoutRect(this.getRootElement());
} else {
const size = viewport.getSize();
rect = layoutRectLtwh(0, 0, size.width, size.height);
}
return whenContentIniLoad(this.ampdoc, this.ampdoc.win, rect);
}
}
/**
* The implementation of the analytics root for FIE.
* TODO(#22733): merge into AnalyticsRoot once ampdoc-fie is launched.
*/
export class EmbedAnalyticsRoot extends AnalyticsRoot {
/**
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @param {!../../../src/friendly-iframe-embed.FriendlyIframeEmbed} embed
*/
constructor(ampdoc, embed) {
super(ampdoc);
/** @const */
this.embed = embed;
}
/** @override */
getType() {
return 'embed';
}
/** @override */
getRoot() {
return this.embed.win.document;
}
/** @override */
getHostElement() {
return this.embed.iframe;
}
/** @override */
signals() {
return this.embed.signals();
}
/** @override */
getElementById(id) {
return this.embed.win.document.getElementById(id);
}
/** @override */
whenIniLoaded() {
return this.embed.whenIniLoaded();
}
}
/**
* @param {!Element} el
* @param {string} selector
* @return {boolean}
* @noinline
*/
function tryMatches_(el, selector) {
try {
return matches(el, selector);
} catch (e) {
user().error(TAG, 'Bad query selector.', selector, e);
return false;
}
}
|
apache-2.0
|
gudnam/bringluck
|
bringluck/src/com/gudnam/bringluck/common/BLFragmentActivity.java
|
282
|
package com.gudnam.bringluck.common;
import java.util.ArrayList;
import android.support.v4.app.FragmentActivity;
public class BLFragmentActivity extends FragmentActivity{
public static ArrayList<FragmentActivity> frgActList = new ArrayList<FragmentActivity>();
}
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Vicia/Vicia bicolor/README.md
|
170
|
# Vicia bicolor Willd. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Viruses/Baculoviridae/Nucleopolyhedrovirus/Euproctis bipunctapex/README.md
|
191
|
# Euproctis bipunctapex Npv SPECIES
#### Status
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Lachemilla/Lachemilla rupestris/README.md
|
185
|
# Lachemilla rupestris (Kunth) Rothm. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Ayapana turbacensis/ Syn. Eupatorium turbacense/README.md
|
186
|
# Eupatorium turbacense Hieron. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Violaceae/Viola/Viola suavis/Viola suavis catalonica/README.md
|
219
|
# Viola suavis var. catalonica (W.Becker) M.Espeut VARIETY
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Viola catalonica W.Becker
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Chlorophyta/Charophyceae/Charales/Clavatoraceae/Dictyoclavator/README.md
|
176
|
# Dictyoclavator L.J.Grambast GENUS
#### Status
ACCEPTED
#### According to
World Register of Marine Species
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Moraceae/Pharmacosycea/Pharmacosycea hernandezii/README.md
|
182
|
# Pharmacosycea hernandezii Liebm. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Spiraea/Spiraea bodinieri/Spiraea bodinieri concolor/README.md
|
189
|
# Spiraea bodinieri var. concolor VARIETY
#### Status
DOUBTFUL
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
coderFun/RadarView
|
library/src/androidTest/java/com/coderfun/library/ApplicationTest.java
|
351
|
package com.coderfun.library;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
|
apache-2.0
|
xiviwo/config_track
|
db/migrate/20111013080753_addindex.rb
|
260
|
class Addindex < ActiveRecord::Migration
def self.up
add_index :assignments, [:assign_date,:status]
add_index :assignments, :title
end
def self.down
remove_index :assignments, [:assign_date,:status]
remove_index :assignments, :title
end
end
|
apache-2.0
|
dudochkin-victor/handset-video
|
src/xdgpath.cpp
|
1217
|
/*
* Meego-handset-video is an video player for MeeGo handset.
* Copyright (C) 2010, Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Apache License, version 2.0. The full text of the Apache License is at
* http://www.apache.org/licenses/LICENSE-2.0
*
*/
#include <QProcess>
#include <QtDebug>
#include <QDir>
#include "xdgpath.h"
XDGPath::XDGPath()
{
m_p = new QProcess();
m_xdgPath.clear();
m_usedProcess = false;
connect(m_p, SIGNAL(readyReadStandardOutput()), this, SLOT(readProcessOutput()));
}
XDGPath::~XDGPath()
{
delete m_p;
}
void XDGPath::readProcessOutput()
{
QByteArray b = m_p->readAllStandardOutput();
m_xdgPath = QString(b).simplified();
qDebug() << "XDG result is " << m_xdgPath;
}
QString XDGPath::getXDGVideosPath()
{
if (!m_usedProcess) {
m_usedProcess = true;
QString command = "xdg-user-dir";
QStringList args;
args << "VIDEOS";
m_p->start(command, args);
m_p->waitForFinished(2000);
if (m_xdgPath.isEmpty())
m_xdgPath = (QDir::homePath() + QString("/Videos"));
return m_xdgPath;
} else {
return m_xdgPath;
}
}
|
apache-2.0
|
alefherrera/sisalud
|
SiSaludSRL/src/main/java/ar/edu/ungs/commons/exception/JdbcBatchException.java
|
2039
|
package ar.edu.ungs.commons.exception;
public class JdbcBatchException extends Exception {
private static final long serialVersionUID = 1;
private String codigoDeError;
/**
* Constructor sin Argumentos
*/
public JdbcBatchException() {
super();
}
/**
* Contructor con el Mensaje de Error
*
* @param message Mensaje de Error
*/
public JdbcBatchException(String message) {
super(message);
}
/**
* Contructor con la Causa de la Excepción
*
* @param cause Causa de la Excepción
*/
public JdbcBatchException(Throwable cause) {
super(cause);
}
/**
* Contructor con el Mensaje de Error y la Causa de la Excepción
*
* @param message Mensaje de Error
* @param cause Causa de la Excepción
*/
public JdbcBatchException(String message, Throwable cause) {
super(message, cause);
}
/**
* Contructor con la Causa de la Excepción y el Código de Error
*
* @param cause Causa de la Excepción
* @param codigoDeError Código de Error
*/
public JdbcBatchException(Throwable cause, String codigoDeError) {
super(cause);
this.codigoDeError = codigoDeError;
}
/**
* Contructor con el Mensaje de Error y el Código de Error
*
* @param message Mensaje de Error
* @param codigoDeError Código de Error
*/
public JdbcBatchException(String message, String codigoDeError) {
super(message);
this.codigoDeError = codigoDeError;
}
/**
* Devuelve el Código de Error
*
* @return Devuelve el Código de Error
*/
public String getCodigoDeError() {
return codigoDeError;
}
/**
* Setea el Código de Error
*
* @param codigoDeError Código de Error
*/
public void setCodigoDeError(String codigoDeError) {
this.codigoDeError = codigoDeError;
}
}
|
apache-2.0
|
Esri/InteractiveFilter
|
js/nls/zh-CN/resources.js
|
1195
|
define({
"map": {
"error": "无法创建地图",
"licenseError": {
"message": "您的帐户无权使用非公共的可配置应用程序。 请联系您的组织管理员为您分配包含基本应用程序或附加基本应用程序许可的用户类型。",
"title": "未经许可"
}
},
"viewer": {
"content_title": "过滤器",
"button_text": "应用",
"filterInstructions": "通过指定值来过滤图层。",
"filterOr": "以下任意表达式必须为 true。",
"filterAnd": "以下表达式必须全部为 true。",
"filterNo": "此 Web 地图不包含任何交互式过滤器。要启用交互式过滤器表达式,请选中 Web 地图过滤器对话框中的“请求值”。<br><br>更多有关帮助,请查看 ${link} 帮助主题了解有关如何在 web 地图中创建交互式过滤器表达式的详细信息。",
"filterLink": "http://doc.arcgis.com/en/arcgis-online/use-maps/apply-filters.htm",
"errors": {
"message": "创建过滤器应用时出现问题"
}
},
"tools": {
"toggle": "切换面板",
"clear": "清除",
"zoom": "缩放"
},
"legend": {
"title": "图例"
}
});
|
apache-2.0
|
lhong375/aura
|
auradocs-integration-test/src/test/java/org/auraframework/components/auradocs/AuradocsExampleUITest.java
|
8515
|
/*
* Copyright (C) 2013 salesforce.com, 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.auraframework.components.auradocs;
import java.util.List;
import org.auraframework.system.AuraContext.Mode;
import org.auraframework.test.WebDriverTestCase;
import org.auraframework.util.AuraUITestingUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebElement;
/**
* A webdriver test for auradoc examples.
*/
public class AuradocsExampleUITest extends WebDriverTestCase {
public AuradocsExampleUITest(String name) {
super(name);
}
public void testAddClassTopicExampleProd() throws Exception {
doHelloWorldExample(Mode.PROD);
}
public void testAddClassTopicExampleDev() throws Exception {
doHelloWorldExample(Mode.DEV);
}
private long doHelloWorldExample(Mode mode) throws Exception {
long start = System.currentTimeMillis();
open("/auradocs#help?topic=helloWorld", mode);
AuraUITestingUtil util = new AuraUITestingUtil(getDriver());
WebElement exampleElement = util.findDomElement(By.cssSelector(".auradocsExample"));
assertNotNull(exampleElement);
assertTrue(exampleElement.isDisplayed());
// Check we get two sane tabs:
List<WebElement> tabs = exampleElement.findElements(By.className("uiTab"));
assertEquals(2, tabs.size());
List<WebElement> tabBodies = exampleElement.findElements(By.className("tabBody"));
assertEquals(2, tabBodies.size());
assertSaneTabState(0, tabs, tabBodies);
// Check we get two appropriate displays. This will require switching
// between the various iframes and returning to the top window.
String topWindow = getDriver().getWindowHandle();
WebElement element = tabBodies.get(0).findElement(By.tagName("iframe"));
assertTrue("Example frame should be displayed initially", element.isDisplayed());
try {
getDriver().switchTo().frame(element);
String bodyText = getDriver().findElement(By.tagName("body")).getText();
assertTrue("Couldn't find Hello world! displayed (visible text of iframe is " + bodyText + ")",
bodyText.contains("Hello world!"));
} finally {
getDriver().switchTo().window(topWindow);
}
element = tabBodies.get(1).findElement(By.cssSelector(".CodeMirror-line-numbers"));
assertNotNull("Can't find CodeMirror numbers", element);
assertFalse("Source numbers should not be displayed initially", element.isDisplayed());
element = tabBodies.get(1).findElement(By.tagName("iframe"));
assertFalse("Source frame should not be displayed initially", element.isDisplayed());
try {
getDriver().switchTo().frame(element);
String text = getDriver().findElement(By.cssSelector(".xml-tagname")).getText();
assertTrue("Couldn't find aura:component in codemirror (visible text of span is " + text + ")",
text.contains("aura:component"));
text = getDriver().findElement(By.cssSelector(".xml-text")).getText();
assertTrue("Couldn't find Hello world! in codemirror (visible text of span is " + text + ")",
text.contains("Hello world!"));
} finally {
getDriver().switchTo().window(topWindow);
}
// Confirm that if we switch tabs, the right visibility happens:
tabs.get(1).click();
assertSaneTabState(1, tabs, tabBodies);
assertFalse("Example frame should not be displayed after click",
tabBodies.get(0).findElement(By.tagName("iframe")).isDisplayed());
assertTrue("CodeMirror numbers should display after click",
tabBodies.get(1).findElement(By.cssSelector(".CodeMirror-line-numbers")).isDisplayed());
assertTrue("CodeMirror source should display after click", tabBodies.get(1).findElement(By.tagName("iframe"))
.isDisplayed());
return System.currentTimeMillis() - start;
}
public void testEventsNotifierExampleProd() throws Exception {
doEventDemoExample(Mode.PROD);
}
public void testEventsNotifierExampleDev() throws Exception {
doEventDemoExample(Mode.DEV);
}
private long doEventDemoExample(Mode mode) throws Exception {
long start = System.currentTimeMillis();
open("/auradocs#help?topic=eventsDemo", Mode.PROD);
AuraUITestingUtil util = new AuraUITestingUtil(getDriver());
WebElement exampleElement = util.findDomElement(By.cssSelector(".auradocsExample"));
assertNotNull(exampleElement);
assertTrue(exampleElement.isDisplayed());
// Check we get four sane tabs:
List<WebElement> tabs = exampleElement.findElements(By.className("uiTab"));
assertEquals(4, tabs.size());
List<WebElement> tabBodies = exampleElement.findElements(By.className("tabBody"));
assertEquals(4, tabBodies.size());
assertSaneTabState(0, tabs, tabBodies);
tabs.get(2).click();
assertSaneTabState(2, tabs, tabBodies);
String topWindow = getDriver().getWindowHandle();
WebElement element = tabBodies.get(2).findElement(By.tagName("iframe"));
// We'll check height relations, as a poor proxy for "is scrollbar visible"
Dimension tabBodySize = tabBodies.get(2).getSize();
assertTrue("JS Controller frame should be displayed after click", element.isDisplayed());
try {
getDriver().switchTo().frame(element);
WebElement frameBody = getDriver().findElement(By.tagName("body"));
String bodyText = frameBody.getText();
assertTrue("Couldn't find fireComponentEvent displayed (visible text of iframe is " + bodyText + ")",
bodyText.contains(" fireComponentEvent : function(cmp, event) {"));
Dimension frameBodySize = frameBody.getSize();
assertTrue(String.format("Sizes suggest scrollbar may not be visible (frame=%s, tabbody=%s)",
frameBodySize, tabBodySize), frameBodySize.getHeight() > tabBodySize.getHeight());
// Oh, and let's check that codemirror did its spanning right:
assertEquals("Didn't tag fireCompenentEvent as a js variable", "fireComponentEvent", getDriver()
.findElement(By.cssSelector(".js-variable")).getText());
} finally {
getDriver().switchTo().window(topWindow);
}
return System.currentTimeMillis() - start;
}
/**
* Asserts various sanity checks on example rendering.
*
* @param selected which tab index should be selected
* @param tabs list of .uiTab elements, paired index-to-index with {@code tabBodies}
* @param tabBodies list of .tabBody elements, paired index-to-index with {@code tabs}
*/
private void assertSaneTabState(int selected, List<WebElement> tabs, List<WebElement> tabBodies) {
assertEquals("Tabs and TabBodies should have same size", tabs.size(), tabBodies.size());
assertTrue("Selection index should be between 0 and tabs.size(), but is " + selected + " of " + tabs.size(),
selected >= 0 && selected < tabs.size());
for (int i = 0; i < tabs.size(); i++) {
if (i == selected) {
assertTrue("Selected tab doesn't have 'active' class (" + tabs.get(i).getAttribute("class") + ")",
hasCssClass(tabs.get(i), "active"));
assertEquals("block", tabBodies.get(i).getCssValue("display"));
} else {
assertFalse("Unselected tab has 'active' class (" + tabs.get(i).getAttribute("class") + ")",
hasCssClass(tabs.get(i), "active"));
assertEquals("none", tabBodies.get(i).getCssValue("display"));
}
}
}
}
|
apache-2.0
|
litsec/eidas-opensaml
|
docs/javadoc/opensaml3/1.4.0/se/litsec/eidas/opensaml/metadata/class-use/MetadataServiceListSignatureValidator.html
|
5074
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_191) on Wed Jun 05 15:47:25 CEST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class se.litsec.eidas.opensaml.metadata.MetadataServiceListSignatureValidator (eIDAS extension for OpenSAML 3.x - 1.4.0)</title>
<meta name="date" content="2019-06-05">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class se.litsec.eidas.opensaml.metadata.MetadataServiceListSignatureValidator (eIDAS extension for OpenSAML 3.x - 1.4.0)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../se/litsec/eidas/opensaml/metadata/MetadataServiceListSignatureValidator.html" title="class in se.litsec.eidas.opensaml.metadata">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?se/litsec/eidas/opensaml/metadata/class-use/MetadataServiceListSignatureValidator.html" target="_top">Frames</a></li>
<li><a href="MetadataServiceListSignatureValidator.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class se.litsec.eidas.opensaml.metadata.MetadataServiceListSignatureValidator" class="title">Uses of Class<br>se.litsec.eidas.opensaml.metadata.MetadataServiceListSignatureValidator</h2>
</div>
<div class="classUseContainer">No usage of se.litsec.eidas.opensaml.metadata.MetadataServiceListSignatureValidator</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../se/litsec/eidas/opensaml/metadata/MetadataServiceListSignatureValidator.html" title="class in se.litsec.eidas.opensaml.metadata">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?se/litsec/eidas/opensaml/metadata/class-use/MetadataServiceListSignatureValidator.html" target="_top">Frames</a></li>
<li><a href="MetadataServiceListSignatureValidator.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2019 <a href="http://www.litsec.se">Litsec AB</a>. All rights reserved.</small></p>
</body>
</html>
|
apache-2.0
|
yaolihui129/Xinda
|
Apps/Report/Controller/ApiController.class.php
|
1723
|
<?php
/**
* Created by PhpStorm.
* User: yaolihui
* Date: 2018/2/11
* Time: 10:46
*/
namespace Report\Controller;
class ApiController extends WebInfoController {
public function index(){
//定义可以查的平台
$branch=['全部','保险服务','安鑫保','车险APP','易鑫车服','微信','第三方'];
//接收传递参数
$_SESSION['branch']=I('branch');
$search=trim(I('search'));
// dump($_POST);
$this->assign('branch',$branch);
$this->assign('search',$search);
if($_SESSION['branch']=='全部'){
$_SESSION['branch']='';
}else{
if($_SESSION['branch']){
$where['branch']=$_SESSION['branch'];
}
}
$where['client|apiName|adress|author']=array('like','%'.$search.'%');
$where['deleted']='0';
$m=M("tp_apitest");
$data=$m->where($where)->order('branch,adress')->select();
$this->assign('data',$data);
$count=$m->where($where)->count();
$this->assign('count',$count);
$this->display();
}
public function details(){
$id=I(id);
$data=M("tp_apitest")->find($id);
$this->assign('data',$data);
$where=array('api'=>$id,'deleted'=>'0');
$version=M('tp_apiversion')->where($where)->order('atime desc')->select();
$this->assign('version',$version);
$parameter=M('tp_api_parameter')->where($where)->order('sn,id')->select();
$this->assign('parameter',$parameter);
$scene=M('tp_api_scene')->where($where)->order('sn,id')->select();
$this->assign('scene',$scene);
// dump($scene);
$this->display();
}
}
|
apache-2.0
|
BigBlueHat/atmailopen
|
html/japanese/help/newmbox.html
|
1677
|
<title>ウェブメールヘルプガイド</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<LINK href="javascript/stylehelp.css" rel=stylesheet type=text/css>
<font face="Verdana, Arial" size="+1">
メールボックスオプション</font> [ <a href="parse.php?file=html/$this->Language/help/file.html">ヘルプインデックス</a> ]
<hr noshade>
<font class="sw">
<p>ここではご使用のメールボックスやフォルダのオプション設定が可能です。</p>
<p><b>アクティブメールボックス</b>では、ご使用のメールボックス内のフォルダのリストや、総メール数、各フォルダの容量の表示、フォルダの削除が可能です。</p>
<p><b>新規フォルダ作成</b>ではメールボックスフォルダの追加が可能です。</p>
<!-- if($pref['allow_BlockEmailAddress']) { -->
<p><b>受信拒否</b>オプションは特定のメールアドレスから送られてくるメールの受信を拒否することができます。受信したくないメールのアドレスを選択し、<b>追加</b>ボタンを押してください。</p>
<!-- } -->
<!-- if($domains[$this->pop3host]) { -->
<p><b>自動返信</b>オプションでは、受け取ったメールのすべてに対し自動的に返信することができます。自動返信に使用するメールを入力してください。</p>
<!-- } -->
<!-- if($pref['allow_EmailToFolderRules']) { -->
<p><b>メール振り分け</b>オプションでは、受信したメールを自動的に受信箱の特定のフォルダに振り分けることができます。</p>
<!-- } -->
</font>
|
apache-2.0
|
Zlate87/sample-transport-app
|
app/src/androidTest/java/com/zlate87/sample_transport_app/CustomMatchers.java
|
5643
|
package com.zlate87.sample_transport_app;
import android.annotation.TargetApi;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
/**
* Class containing custom matchers.
*/
public class CustomMatchers {
/**
* Matcher that matches ImageView drawable with a drawable from resources.
*
* @param resourceId the resource id for the drawable.
* @return {@code true} if the drawable matches, {@code false} if not
*/
public static Matcher<View> withDrawable(final int resourceId) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText(String.format("with drawable from resource id: [%s]", resourceId));
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean matchesSafely(View view) {
final Drawable resourcesDrawable = getDrawable(view, resourceId);
final ImageView imageView = (ImageView) view;
if (imageView.getDrawable() == null) {
return resourcesDrawable == null;
}
return areDrawablesIdentical(imageView.getDrawable(), resourcesDrawable);
}
};
}
/**
* Matcher that matches view with a given id at given position in a recycler view.
*
* @param recyclerViewId the recycler view id
* @param position element position where the view is at recycler view
* @param viewId the view id
* @return {@code true} if the view matches, {@code false} if not
*/
public static Matcher<View> viewAtPositionInRecyclerView(final int recyclerViewId, final int position,
final int viewId) {
return new TypeSafeMatcher<View>() {
Resources resources = null;
View childView;
public void describeTo(Description description) {
String idDescription = Integer.toString(recyclerViewId);
if (resources != null) {
try {
idDescription = this.resources.getResourceName(recyclerViewId);
} catch (Resources.NotFoundException var4) {
idDescription = String.format("%d (resource name not found)", recyclerViewId);
}
}
description.appendText("with id: " + idDescription);
}
public boolean matchesSafely(View view) {
resources = view.getResources();
if (childView == null) {
RecyclerView recyclerView = (RecyclerView) view.getRootView().findViewById(recyclerViewId);
if (recyclerView != null && recyclerView.getId() == recyclerViewId) {
childView = recyclerView.getChildAt(position);
} else {
return false;
}
}
if (viewId == -1) {
return view == childView;
} else {
View targetView = childView.findViewById(viewId);
return view == targetView;
}
}
};
}
/**
* Matches dynamic view in a linear layout within a recycler view for a given:
*
* @param recyclerViewId the id of the recycler view
* @param viewPosition the position index of the route preview view in the recycler view
* @param iconsLayout the id of the layout for the icon attributes
* @param iconPosition the icon position inside the icons layout
* @return the matcher
*/
public static Matcher<View> dynamicView(final int recyclerViewId,
final int viewPosition,
final int iconsLayout,
final int iconPosition) {
return new TypeSafeMatcher<View>() {
Resources resources = null;
View routePreviewView;
public void describeTo(Description description) {
String idDescription = Integer.toString(recyclerViewId);
if (resources != null) {
try {
idDescription = this.resources.getResourceName(recyclerViewId);
} catch (Resources.NotFoundException var4) {
idDescription = String.format("%d (resource name not found)", recyclerViewId);
}
}
description.appendText("with id: " + idDescription);
}
public boolean matchesSafely(View view) {
resources = view.getResources();
if (routePreviewView == null) {
RecyclerView recyclerView = (RecyclerView) view.getRootView().findViewById(recyclerViewId);
if (recyclerView != null && recyclerView.getId() == recyclerViewId) {
routePreviewView = recyclerView.getChildAt(viewPosition);
} else {
return false;
}
}
LinearLayout iconsLinearLayout = (LinearLayout) routePreviewView.findViewById(iconsLayout);
View targetView = iconsLinearLayout.getChildAt(iconPosition);
return view == targetView;
}
};
}
private static Drawable getDrawable(View view, int resourceId) {
final Drawable resourcesDrawable;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
resourcesDrawable = view.getResources().getDrawable(resourceId);
} else {
resourcesDrawable = view.getContext().getDrawable(resourceId);
}
return resourcesDrawable;
}
private static boolean areDrawablesIdentical(Drawable drawableA, Drawable drawableB) {
Drawable.ConstantState constantStateA = drawableA.getConstantState();
Drawable.ConstantState constantStateB = drawableB.getConstantState();
return (constantStateA != null && constantStateB != null && constantStateA.equals(constantStateB))
|| getBitmap(drawableA).sameAs(getBitmap(drawableB));
}
private static Bitmap getBitmap(Drawable drawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
}
|
apache-2.0
|
bowenli86/flink
|
flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/utils/AggregateUtil.scala
|
29858
|
/*
* 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.flink.table.planner.plan.utils
import org.apache.flink.api.common.typeinfo.Types
import org.apache.flink.table.api.config.ExecutionConfigOptions
import org.apache.flink.table.api.{DataTypes, TableConfig, TableException}
import org.apache.flink.table.dataformat.{BaseRow, BinaryString, Decimal, SqlTimestamp}
import org.apache.flink.table.dataview.MapViewTypeInfo
import org.apache.flink.table.expressions.ExpressionUtils.extractValue
import org.apache.flink.table.expressions._
import org.apache.flink.table.functions.{AggregateFunction, TableAggregateFunction, UserDefinedAggregateFunction, UserDefinedFunction}
import org.apache.flink.table.planner.JLong
import org.apache.flink.table.planner.calcite.FlinkRelBuilder.PlannerNamedWindowProperty
import org.apache.flink.table.planner.calcite.{FlinkTypeFactory, FlinkTypeSystem}
import org.apache.flink.table.planner.dataview.DataViewUtils.useNullSerializerForStateViewFieldsFromAccType
import org.apache.flink.table.planner.dataview.{DataViewSpec, MapViewSpec}
import org.apache.flink.table.planner.expressions.{PlannerProctimeAttribute, PlannerRowtimeAttribute, PlannerWindowEnd, PlannerWindowStart}
import org.apache.flink.table.planner.functions.aggfunctions.DeclarativeAggregateFunction
import org.apache.flink.table.planner.functions.sql.{FlinkSqlOperatorTable, SqlFirstLastValueAggFunction, SqlListAggFunction}
import org.apache.flink.table.planner.functions.utils.AggSqlFunction
import org.apache.flink.table.planner.functions.utils.UserDefinedFunctionUtils._
import org.apache.flink.table.planner.plan.`trait`.{ModifyKindSetTraitDef, RelModifiedMonotonicity}
import org.apache.flink.table.runtime.operators.bundle.trigger.CountBundleTrigger
import org.apache.flink.table.runtime.types.LogicalTypeDataTypeConverter.{fromDataTypeToLogicalType, fromLogicalTypeToDataType}
import org.apache.flink.table.runtime.types.TypeInfoDataTypeConverter.fromDataTypeToTypeInfo
import org.apache.flink.table.types.DataType
import org.apache.flink.table.types.logical.LogicalTypeRoot._
import org.apache.flink.table.types.logical.utils.LogicalTypeChecks
import org.apache.flink.table.types.logical.utils.LogicalTypeChecks.hasRoot
import org.apache.flink.table.types.logical.{LogicalTypeRoot, _}
import org.apache.flink.table.types.utils.TypeConversions.fromLegacyInfoToDataType
import org.apache.calcite.rel.`type`._
import org.apache.calcite.rel.core.{Aggregate, AggregateCall}
import org.apache.calcite.sql.fun._
import org.apache.calcite.sql.validate.SqlMonotonicity
import org.apache.calcite.sql.{SqlKind, SqlRankFunction}
import org.apache.calcite.tools.RelBuilder
import org.apache.flink.table.planner.plan.metadata.FlinkRelMetadataQuery
import org.apache.flink.table.planner.plan.nodes.physical.stream.StreamPhysicalRel
import java.time.Duration
import java.util
import scala.collection.JavaConversions._
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
object AggregateUtil extends Enumeration {
/**
* Returns whether any of the aggregates are accurate DISTINCT.
*
* @return Whether any of the aggregates are accurate DISTINCT
*/
def containsAccurateDistinctCall(aggCalls: util.List[AggregateCall]): Boolean = {
aggCalls.exists(call => call.isDistinct && !call.isApproximate)
}
/**
* Returns whether any of the aggregates are approximate DISTINCT.
*
* @return Whether any of the aggregates are approximate DISTINCT
*/
def containsApproximateDistinctCall(aggCalls: util.List[AggregateCall]): Boolean = {
aggCalls.exists(call => call.isDistinct && call.isApproximate)
}
/**
* Returns indices of group functions.
*/
def getGroupIdExprIndexes(aggCalls: Seq[AggregateCall]): Seq[Int] = {
aggCalls.zipWithIndex.filter { case (call, _) =>
call.getAggregation.getKind match {
case SqlKind.GROUP_ID | SqlKind.GROUPING | SqlKind.GROUPING_ID => true
case _ => false
}
}.map { case (_, idx) => idx }
}
/**
* Check whether AUXILIARY_GROUP aggCalls is in the front of the given agg's aggCallList,
* and whether aggCallList contain AUXILIARY_GROUP when the given agg's groupSet is empty
* or the indicator is true.
* Returns AUXILIARY_GROUP aggCalls' args and other aggCalls.
*
* @param agg aggregate
* @return returns AUXILIARY_GROUP aggCalls' args and other aggCalls
*/
def checkAndSplitAggCalls(agg: Aggregate): (Array[Int], Seq[AggregateCall]) = {
var nonAuxGroupCallsStartIdx = -1
val aggCalls = agg.getAggCallList
aggCalls.zipWithIndex.foreach {
case (call, idx) =>
if (call.getAggregation == FlinkSqlOperatorTable.AUXILIARY_GROUP) {
require(call.getArgList.size == 1)
}
if (nonAuxGroupCallsStartIdx >= 0) {
// the left aggCalls should not be AUXILIARY_GROUP
require(call.getAggregation != FlinkSqlOperatorTable.AUXILIARY_GROUP,
"AUXILIARY_GROUP should be in the front of aggCall list")
}
if (nonAuxGroupCallsStartIdx < 0 &&
call.getAggregation != FlinkSqlOperatorTable.AUXILIARY_GROUP) {
nonAuxGroupCallsStartIdx = idx
}
}
if (nonAuxGroupCallsStartIdx < 0) {
nonAuxGroupCallsStartIdx = aggCalls.length
}
val (auxGroupCalls, otherAggCalls) = aggCalls.splitAt(nonAuxGroupCallsStartIdx)
if (agg.getGroupCount == 0) {
require(auxGroupCalls.isEmpty,
"AUXILIARY_GROUP aggCalls should be empty when groupSet is empty")
}
val auxGrouping = auxGroupCalls.map(_.getArgList.head.toInt).toArray
require(auxGrouping.length + otherAggCalls.length == aggCalls.length)
(auxGrouping, otherAggCalls)
}
def checkAndGetFullGroupSet(agg: Aggregate): Array[Int] = {
val (auxGroupSet, _) = checkAndSplitAggCalls(agg)
agg.getGroupSet.toArray ++ auxGroupSet
}
def getOutputIndexToAggCallIndexMap(
aggregateCalls: Seq[AggregateCall],
inputType: RelDataType,
orderKeyIdx: Array[Int] = null): util.Map[Integer, Integer] = {
val aggInfos = transformToAggregateInfoList(
aggregateCalls,
inputType,
orderKeyIdx,
Array.fill(aggregateCalls.size)(false),
needInputCount = false,
isStateBackedDataViews = false,
needDistinctInfo = false).aggInfos
val map = new util.HashMap[Integer, Integer]()
var outputIndex = 0
aggregateCalls.indices.foreach {
aggCallIndex =>
val aggInfo = aggInfos(aggCallIndex)
val aggBuffers = aggInfo.externalAccTypes
aggBuffers.indices.foreach { bufferIndex =>
map.put(outputIndex + bufferIndex, aggCallIndex)
}
outputIndex += aggBuffers.length
}
map
}
def deriveAggregateInfoList(
aggNode: StreamPhysicalRel,
aggCalls: Seq[AggregateCall],
grouping: Array[Int]): AggregateInfoList = {
val input = aggNode.getInput(0)
// need to call `retract()` if input contains update or delete
val modifyKindSetTrait = input.getTraitSet.getTrait(ModifyKindSetTraitDef.INSTANCE)
val needRetraction = if (modifyKindSetTrait == null) {
// FlinkChangelogModeInferenceProgram is not applied yet, false as default
false
} else {
!modifyKindSetTrait.modifyKindSet.isInsertOnly
}
val fmq = FlinkRelMetadataQuery.reuseOrCreate(aggNode.getCluster.getMetadataQuery)
val monotonicity = fmq.getRelModifiedMonotonicity(aggNode)
val needRetractionArray = AggregateUtil.getNeedRetractions(
grouping.length, needRetraction, monotonicity, aggCalls)
AggregateUtil.transformToStreamAggregateInfoList(
aggCalls,
input.getRowType,
needRetractionArray,
needInputCount = needRetraction,
isStateBackendDataViews = true)
}
def transformToBatchAggregateFunctions(
aggregateCalls: Seq[AggregateCall],
inputRowType: RelDataType,
orderKeyIdx: Array[Int] = null)
: (Array[Array[Int]], Array[Array[DataType]], Array[UserDefinedFunction]) = {
val aggInfos = transformToAggregateInfoList(
aggregateCalls,
inputRowType,
orderKeyIdx,
Array.fill(aggregateCalls.size)(false),
needInputCount = false,
isStateBackedDataViews = false,
needDistinctInfo = false).aggInfos
val aggFields = aggInfos.map(_.argIndexes)
val bufferTypes = aggInfos.map(_.externalAccTypes)
val functions = aggInfos.map(_.function)
(aggFields, bufferTypes, functions)
}
def transformToBatchAggregateInfoList(
aggregateCalls: Seq[AggregateCall],
inputRowType: RelDataType,
orderKeyIdx: Array[Int] = null,
needRetractions: Array[Boolean] = null): AggregateInfoList = {
val needRetractionArray = if (needRetractions == null) {
Array.fill(aggregateCalls.size)(false)
} else {
needRetractions
}
transformToAggregateInfoList(
aggregateCalls,
inputRowType,
orderKeyIdx,
needRetractionArray,
needInputCount = false,
isStateBackedDataViews = false,
needDistinctInfo = false)
}
def transformToStreamAggregateInfoList(
aggregateCalls: Seq[AggregateCall],
inputRowType: RelDataType,
needRetraction: Array[Boolean],
needInputCount: Boolean,
isStateBackendDataViews: Boolean,
needDistinctInfo: Boolean = true): AggregateInfoList = {
transformToAggregateInfoList(
aggregateCalls,
inputRowType,
orderKeyIdx = null,
needRetraction ++ Array(needInputCount), // for additional count(*)
needInputCount,
isStateBackendDataViews,
needDistinctInfo)
}
/**
* Transforms calcite aggregate calls to AggregateInfos.
*
* @param aggregateCalls the calcite aggregate calls
* @param inputRowType the input rel data type
* @param orderKeyIdx the index of order by field in the input, null if not over agg
* @param needRetraction whether the aggregate function need retract method
* @param needInputCount whether need to calculate the input counts, which is used in
* aggregation with retraction input.If needed,
* insert a count(1) aggregate into the agg list.
* @param isStateBackedDataViews whether the dataview in accumulator use state or heap
* @param needDistinctInfo whether need to extract distinct information
*/
private def transformToAggregateInfoList(
aggregateCalls: Seq[AggregateCall],
inputRowType: RelDataType,
orderKeyIdx: Array[Int],
needRetraction: Array[Boolean],
needInputCount: Boolean,
isStateBackedDataViews: Boolean,
needDistinctInfo: Boolean): AggregateInfoList = {
// Step-1:
// if need inputCount, find count1 in the existed aggregate calls first,
// if not exist, insert a new count1 and remember the index
val (indexOfCountStar, countStarInserted, aggCalls) = insertCountStarAggCall(
needInputCount,
aggregateCalls)
// Step-2:
// extract distinct information from aggregate calls
val (distinctInfos, newAggCalls) = extractDistinctInformation(
needDistinctInfo,
aggCalls,
inputRowType,
isStateBackedDataViews,
needInputCount) // needInputCount means whether the aggregate consume retractions
// Step-3:
// create aggregate information
val factory = new AggFunctionFactory(inputRowType, orderKeyIdx, needRetraction)
val aggInfos = newAggCalls.zipWithIndex.map { case (call, index) =>
val argIndexes = call.getAggregation match {
case _: SqlRankFunction => orderKeyIdx
case _ => call.getArgList.map(_.intValue()).toArray
}
val function = factory.createAggFunction(call, index)
val (externalAccTypes, viewSpecs, externalResultType) = function match {
case a: DeclarativeAggregateFunction =>
val bufferTypes: Array[LogicalType] = a.getAggBufferTypes.map(_.getLogicalType)
val bufferTypeInfos = bufferTypes.map(fromLogicalTypeToDataType)
(bufferTypeInfos, Array.empty[DataViewSpec],
fromLogicalTypeToDataType(a.getResultType.getLogicalType))
case a: UserDefinedAggregateFunction[_, _] =>
val (implicitAccType, implicitResultType) = call.getAggregation match {
case aggSqlFun: AggSqlFunction =>
(aggSqlFun.externalAccType, aggSqlFun.externalResultType)
case _ => (null, null)
}
val externalAccType = getAccumulatorTypeOfAggregateFunction(a, implicitAccType)
val (newExternalAccType, specs) = useNullSerializerForStateViewFieldsFromAccType(
index,
a,
externalAccType,
isStateBackedDataViews)
(Array(newExternalAccType), specs,
getResultTypeOfAggregateFunction(a, implicitResultType))
case _ => throw new TableException(s"Unsupported function: $function")
}
AggregateInfo(
call,
function,
index,
argIndexes,
externalAccTypes,
viewSpecs,
externalResultType,
needRetraction(index))
}.toArray
AggregateInfoList(aggInfos, indexOfCountStar, countStarInserted, distinctInfos)
}
/**
* Inserts an COUNT(*) aggregate call if needed. The COUNT(*) aggregate call is used
* to count the number of added and retracted input records.
* @param needInputCount whether to insert an InputCount aggregate
* @param aggregateCalls original aggregate calls
* @return (indexOfCountStar, countStarInserted, newAggCalls)
*/
private def insertCountStarAggCall(
needInputCount: Boolean,
aggregateCalls: Seq[AggregateCall]): (Option[Int], Boolean, Seq[AggregateCall]) = {
var indexOfCountStar: Option[Int] = None
var countStarInserted: Boolean = false
if (!needInputCount) {
return (indexOfCountStar, countStarInserted, aggregateCalls)
}
// if need inputCount, find count(*) in the existed aggregate calls first,
// if not exist, insert a new count(*) and remember the index
var newAggCalls = aggregateCalls
aggregateCalls.zipWithIndex.foreach { case (call, index) =>
if (call.getAggregation.isInstanceOf[SqlCountAggFunction] &&
call.filterArg < 0 &&
call.getArgList.isEmpty &&
!call.isApproximate &&
!call.isDistinct) {
indexOfCountStar = Some(index)
}
}
// count(*) not exist in aggregateCalls, insert a count(*) in it.
val typeFactory = new FlinkTypeFactory(new FlinkTypeSystem)
if (indexOfCountStar.isEmpty) {
val count1 = AggregateCall.create(
SqlStdOperatorTable.COUNT,
false,
false,
new util.ArrayList[Integer](),
-1,
typeFactory.createFieldTypeFromLogicalType(new BigIntType()),
"_$count1$_")
indexOfCountStar = Some(aggregateCalls.length)
countStarInserted = true
newAggCalls = aggregateCalls ++ Seq(count1)
}
(indexOfCountStar, countStarInserted, newAggCalls)
}
/**
* Extracts DistinctInfo array from the aggregate calls,
* and change the distinct aggregate to non-distinct aggregate.
*
* @param needDistinctInfo whether to extract distinct information
* @param aggCalls the original aggregate calls
* @param inputType the input rel data type
* @param isStateBackedDataViews whether the dataview in accumulator use state or heap
* @param consumeRetraction whether the distinct aggregate consumes retraction messages
* @return (distinctInfoArray, newAggCalls)
*/
private def extractDistinctInformation(
needDistinctInfo: Boolean,
aggCalls: Seq[AggregateCall],
inputType: RelDataType,
isStateBackedDataViews: Boolean,
consumeRetraction: Boolean): (Array[DistinctInfo], Seq[AggregateCall]) = {
if (!needDistinctInfo) {
return (Array(), aggCalls)
}
val distinctMap = mutable.LinkedHashMap.empty[String, DistinctInfo]
val newAggCalls = aggCalls.zipWithIndex.map { case (call, index) =>
val argIndexes = call.getArgList.map(_.intValue()).toArray
// extract distinct information and replace a new call
if (call.isDistinct && !call.isApproximate && argIndexes.length > 0) {
val argTypes: Array[LogicalType] = call
.getArgList
.map(inputType.getFieldList.get(_).getType)
.map(FlinkTypeFactory.toLogicalType)
.toArray
val keyType = createDistinctKeyType(argTypes)
val distinctInfo = distinctMap.getOrElseUpdate(
argIndexes.mkString(","),
DistinctInfo(
argIndexes,
keyType,
null, // later fill in
excludeAcc = false,
null, // later fill in
consumeRetraction,
ArrayBuffer.empty[Int],
ArrayBuffer.empty[Int]))
// add current agg to the distinct agg list
distinctInfo.filterArgs += call.filterArg
distinctInfo.aggIndexes += index
AggregateCall.create(
call.getAggregation,
false,
false,
call.getArgList,
-1, // remove filterArg
call.getType,
call.getName)
} else {
call
}
}
// fill in the acc type and dataview spec
val distinctInfos = distinctMap.values.zipWithIndex.map { case (d, index) =>
val valueType = if (consumeRetraction) {
if (d.filterArgs.length <= 1) {
Types.LONG
} else {
Types.PRIMITIVE_ARRAY(Types.LONG)
}
} else {
if (d.filterArgs.length <= 64) {
Types.LONG
} else {
Types.PRIMITIVE_ARRAY(Types.LONG)
}
}
val accTypeInfo = new MapViewTypeInfo(
// distinct is internal code gen, use internal type serializer.
fromDataTypeToTypeInfo(d.keyType),
valueType,
isStateBackedDataViews,
// the mapview serializer should handle null keys
true)
val accDataType = fromLegacyInfoToDataType(accTypeInfo)
val distinctMapViewSpec = if (isStateBackedDataViews) {
Some(MapViewSpec(
s"distinctAcc_$index",
-1, // the field index will not be used
accTypeInfo))
} else {
None
}
DistinctInfo(
d.argIndexes,
d.keyType,
accDataType,
excludeAcc = false,
distinctMapViewSpec,
consumeRetraction,
d.filterArgs,
d.aggIndexes)
}
(distinctInfos.toArray, newAggCalls)
}
def createDistinctKeyType(argTypes: Array[LogicalType]): DataType = {
if (argTypes.length == 1) {
argTypes(0).getTypeRoot match {
case INTEGER => DataTypes.INT
case BIGINT => DataTypes.BIGINT
case SMALLINT => DataTypes.SMALLINT
case TINYINT => DataTypes.TINYINT
case FLOAT => DataTypes.FLOAT
case DOUBLE => DataTypes.DOUBLE
case BOOLEAN => DataTypes.BOOLEAN
case DATE => DataTypes.INT
case TIME_WITHOUT_TIME_ZONE => DataTypes.INT
case TIMESTAMP_WITHOUT_TIME_ZONE =>
val dt = argTypes(0).asInstanceOf[TimestampType]
DataTypes.TIMESTAMP(dt.getPrecision).bridgedTo(classOf[SqlTimestamp])
case TIMESTAMP_WITH_LOCAL_TIME_ZONE =>
val dt = argTypes(0).asInstanceOf[LocalZonedTimestampType]
DataTypes.TIMESTAMP_WITH_LOCAL_TIME_ZONE(dt.getPrecision).bridgedTo(classOf[SqlTimestamp])
case INTERVAL_YEAR_MONTH => DataTypes.INT
case INTERVAL_DAY_TIME => DataTypes.BIGINT
case VARCHAR =>
val dt = argTypes(0).asInstanceOf[VarCharType]
DataTypes.VARCHAR(dt.getLength).bridgedTo(classOf[BinaryString])
case CHAR =>
val dt = argTypes(0).asInstanceOf[CharType]
DataTypes.CHAR(dt.getLength).bridgedTo(classOf[BinaryString])
case DECIMAL =>
val dt = argTypes(0).asInstanceOf[DecimalType]
DataTypes.DECIMAL(dt.getPrecision, dt.getScale).bridgedTo(classOf[Decimal])
case t =>
throw new TableException(s"Distinct aggregate function does not support type: $t.\n" +
s"Please re-check the data type.")
}
} else {
fromLogicalTypeToDataType(RowType.of(argTypes: _*)).bridgedTo(classOf[BaseRow])
}
}
/**
* Return true if all aggregates can be partially merged. False otherwise.
*/
def doAllSupportPartialMerge(aggInfos: Array[AggregateInfo]): Boolean = {
val supportMerge = aggInfos.map(_.function).forall {
case _: DeclarativeAggregateFunction => true
case a => ifMethodExistInFunction("merge", a)
}
//it means grouping without aggregate functions
aggInfos.isEmpty || supportMerge
}
/**
* Return true if all aggregates can be split. False otherwise.
*/
def doAllAggSupportSplit(aggCalls: util.List[AggregateCall]): Boolean = {
aggCalls.forall { aggCall =>
aggCall.getAggregation match {
case _: SqlCountAggFunction |
_: SqlAvgAggFunction |
_: SqlMinMaxAggFunction |
_: SqlSumAggFunction |
_: SqlSumEmptyIsZeroAggFunction |
_: SqlSingleValueAggFunction |
_: SqlListAggFunction => true
case _: SqlFirstLastValueAggFunction => aggCall.getArgList.size() == 1
case _ => false
}
}
}
/**
* Derives output row type from stream local aggregate
*/
def inferStreamLocalAggRowType(
aggInfoList: AggregateInfoList,
inputType: RelDataType,
groupSet: Array[Int],
typeFactory: FlinkTypeFactory): RelDataType = {
val accTypes = aggInfoList.getAccTypes
val groupingTypes = groupSet
.map(inputType.getFieldList.get(_).getType)
.map(FlinkTypeFactory.toLogicalType)
val groupingNames = groupSet.map(inputType.getFieldNames.get(_))
val accFieldNames = inferStreamAggAccumulatorNames(aggInfoList)
typeFactory.buildRelNodeRowType(
groupingNames ++ accFieldNames,
groupingTypes ++ accTypes.map(fromDataTypeToLogicalType))
}
/**
* Derives accumulators names from stream aggregate
*/
def inferStreamAggAccumulatorNames(aggInfoList: AggregateInfoList): Array[String] = {
var index = -1
val aggBufferNames = aggInfoList.aggInfos.indices.flatMap { i =>
aggInfoList.aggInfos(i).function match {
case _: AggregateFunction[_, _] =>
val name = aggInfoList.aggInfos(i).agg.getAggregation.getName.toLowerCase
index += 1
Array(s"$name$$$index")
case daf: DeclarativeAggregateFunction =>
daf.aggBufferAttributes.map { a =>
index += 1
s"${a.getName}$$$index"
}
}
}
val distinctBufferNames = aggInfoList.distinctInfos.indices.map { i =>
s"distinct$$$i"
}
(aggBufferNames ++ distinctBufferNames).toArray
}
/**
* Optimize max or min with retraction agg. MaxWithRetract can be optimized to Max if input is
* update increasing.
*/
def getNeedRetractions(
groupCount: Int,
needRetraction: Boolean,
monotonicity: RelModifiedMonotonicity,
aggCalls: Seq[AggregateCall]): Array[Boolean] = {
val needRetractionArray = Array.fill(aggCalls.size)(needRetraction)
if (monotonicity != null && needRetraction) {
aggCalls.zipWithIndex.foreach { case (aggCall, idx) =>
aggCall.getAggregation match {
// if monotonicity is decreasing and aggCall is min with retract,
// set needRetraction to false
case a: SqlMinMaxAggFunction
if a.getKind == SqlKind.MIN &&
monotonicity.fieldMonotonicities(groupCount + idx) == SqlMonotonicity.DECREASING =>
needRetractionArray(idx) = false
// if monotonicity is increasing and aggCall is max with retract,
// set needRetraction to false
case a: SqlMinMaxAggFunction
if a.getKind == SqlKind.MAX &&
monotonicity.fieldMonotonicities(groupCount + idx) == SqlMonotonicity.INCREASING =>
needRetractionArray(idx) = false
case _ => // do nothing
}
}
}
needRetractionArray
}
/**
* Derives output row type from local aggregate
*/
def inferLocalAggRowType(
aggInfoList: AggregateInfoList,
inputRowType: RelDataType,
groupSet: Array[Int],
typeFactory: FlinkTypeFactory): RelDataType = {
val accTypes = aggInfoList.getAccTypes
val groupingTypes = groupSet
.map(inputRowType.getFieldList.get(_).getType)
.map(FlinkTypeFactory.toLogicalType)
val groupingNames = groupSet.map(inputRowType.getFieldNames.get(_))
val accFieldNames = inferAggAccumulatorNames(aggInfoList)
typeFactory.buildRelNodeRowType(
groupingNames ++ accFieldNames,
groupingTypes ++ accTypes.map(fromDataTypeToLogicalType))
}
/**
* Derives accumulators names from aggregate
*/
def inferAggAccumulatorNames(aggInfoList: AggregateInfoList): Array[String] = {
var index = -1
val aggBufferNames = aggInfoList.aggInfos.indices.flatMap { i =>
aggInfoList.aggInfos(i).function match {
case _: AggregateFunction[_, _] =>
val name = aggInfoList.aggInfos(i).agg.getAggregation.getName.toLowerCase
index += 1
Array(s"$name$$$index")
case daf: DeclarativeAggregateFunction =>
daf.aggBufferAttributes.map { a =>
index += 1
s"${a.getName}$$$index"
}
}
}
val distinctBufferNames = aggInfoList.distinctInfos.indices.map { i =>
s"distinct$$$i"
}
(aggBufferNames ++ distinctBufferNames).toArray
}
/**
* Creates a MiniBatch trigger depends on the config.
*/
def createMiniBatchTrigger(tableConfig: TableConfig): CountBundleTrigger[BaseRow] = {
val size = tableConfig.getConfiguration.getLong(
ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_SIZE)
if (size <= 0 ) {
throw new IllegalArgumentException(
ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_SIZE + " must be > 0.")
}
new CountBundleTrigger[BaseRow](size)
}
/**
* Compute field index of given timeField expression.
*/
def timeFieldIndex(
inputType: RelDataType, relBuilder: RelBuilder, timeField: FieldReferenceExpression): Int = {
relBuilder.values(inputType).field(timeField.getName).getIndex
}
/**
* Computes the positions of (window start, window end, row time).
*/
private[flink] def computeWindowPropertyPos(
properties: Seq[PlannerNamedWindowProperty]): (Option[Int], Option[Int], Option[Int]) = {
val propPos = properties.foldRight(
(None: Option[Int], None: Option[Int], None: Option[Int], 0)) {
case (p, (s, e, rt, i)) => p match {
case PlannerNamedWindowProperty(_, prop) =>
prop match {
case PlannerWindowStart(_) if s.isDefined =>
throw new TableException(
"Duplicate window start property encountered. This is a bug.")
case PlannerWindowStart(_) =>
(Some(i), e, rt, i - 1)
case PlannerWindowEnd(_) if e.isDefined =>
throw new TableException("Duplicate window end property encountered. This is a bug.")
case PlannerWindowEnd(_) =>
(s, Some(i), rt, i - 1)
case PlannerRowtimeAttribute(_) if rt.isDefined =>
throw new TableException(
"Duplicate window rowtime property encountered. This is a bug.")
case PlannerRowtimeAttribute(_) =>
(s, e, Some(i), i - 1)
case PlannerProctimeAttribute(_) =>
// ignore this property, it will be null at the position later
(s, e, rt, i - 1)
}
}
}
(propPos._1, propPos._2, propPos._3)
}
def isRowtimeAttribute(field: FieldReferenceExpression): Boolean = {
LogicalTypeChecks.isRowtimeAttribute(field.getOutputDataType.getLogicalType)
}
def isProctimeAttribute(field: FieldReferenceExpression): Boolean = {
LogicalTypeChecks.isProctimeAttribute(field.getOutputDataType.getLogicalType)
}
def hasTimeIntervalType(intervalType: ValueLiteralExpression): Boolean = {
hasRoot(intervalType.getOutputDataType.getLogicalType, LogicalTypeRoot.INTERVAL_DAY_TIME)
}
def hasRowIntervalType(intervalType: ValueLiteralExpression): Boolean = {
hasRoot(intervalType.getOutputDataType.getLogicalType, LogicalTypeRoot.BIGINT)
}
def toLong(literalExpr: ValueLiteralExpression): JLong =
extractValue(literalExpr, classOf[JLong]).get()
def toDuration(literalExpr: ValueLiteralExpression): Duration =
extractValue(literalExpr, classOf[Duration]).get()
private[flink] def isTableAggregate(aggCalls: util.List[AggregateCall]): Boolean = {
aggCalls
.filter(e => e.getAggregation.isInstanceOf[AggSqlFunction])
.map(e => e.getAggregation.asInstanceOf[AggSqlFunction].aggregateFunction)
.exists(_.isInstanceOf[TableAggregateFunction[_, _]])
}
}
|
apache-2.0
|
JoyIfBam5/aws-sdk-cpp
|
aws-cpp-sdk-ssm/include/aws/ssm/model/GetMaintenanceWindowTaskResult.h
|
29007
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/ssm/SSM_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/ssm/model/MaintenanceWindowTaskType.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <aws/ssm/model/MaintenanceWindowTaskInvocationParameters.h>
#include <aws/ssm/model/LoggingInfo.h>
#include <aws/ssm/model/Target.h>
#include <aws/ssm/model/MaintenanceWindowTaskParameterValueExpression.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace SSM
{
namespace Model
{
class AWS_SSM_API GetMaintenanceWindowTaskResult
{
public:
GetMaintenanceWindowTaskResult();
GetMaintenanceWindowTaskResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
GetMaintenanceWindowTaskResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The retrieved Maintenance Window ID.</p>
*/
inline const Aws::String& GetWindowId() const{ return m_windowId; }
/**
* <p>The retrieved Maintenance Window ID.</p>
*/
inline void SetWindowId(const Aws::String& value) { m_windowId = value; }
/**
* <p>The retrieved Maintenance Window ID.</p>
*/
inline void SetWindowId(Aws::String&& value) { m_windowId = std::move(value); }
/**
* <p>The retrieved Maintenance Window ID.</p>
*/
inline void SetWindowId(const char* value) { m_windowId.assign(value); }
/**
* <p>The retrieved Maintenance Window ID.</p>
*/
inline GetMaintenanceWindowTaskResult& WithWindowId(const Aws::String& value) { SetWindowId(value); return *this;}
/**
* <p>The retrieved Maintenance Window ID.</p>
*/
inline GetMaintenanceWindowTaskResult& WithWindowId(Aws::String&& value) { SetWindowId(std::move(value)); return *this;}
/**
* <p>The retrieved Maintenance Window ID.</p>
*/
inline GetMaintenanceWindowTaskResult& WithWindowId(const char* value) { SetWindowId(value); return *this;}
/**
* <p>The retrieved Maintenance Window task ID.</p>
*/
inline const Aws::String& GetWindowTaskId() const{ return m_windowTaskId; }
/**
* <p>The retrieved Maintenance Window task ID.</p>
*/
inline void SetWindowTaskId(const Aws::String& value) { m_windowTaskId = value; }
/**
* <p>The retrieved Maintenance Window task ID.</p>
*/
inline void SetWindowTaskId(Aws::String&& value) { m_windowTaskId = std::move(value); }
/**
* <p>The retrieved Maintenance Window task ID.</p>
*/
inline void SetWindowTaskId(const char* value) { m_windowTaskId.assign(value); }
/**
* <p>The retrieved Maintenance Window task ID.</p>
*/
inline GetMaintenanceWindowTaskResult& WithWindowTaskId(const Aws::String& value) { SetWindowTaskId(value); return *this;}
/**
* <p>The retrieved Maintenance Window task ID.</p>
*/
inline GetMaintenanceWindowTaskResult& WithWindowTaskId(Aws::String&& value) { SetWindowTaskId(std::move(value)); return *this;}
/**
* <p>The retrieved Maintenance Window task ID.</p>
*/
inline GetMaintenanceWindowTaskResult& WithWindowTaskId(const char* value) { SetWindowTaskId(value); return *this;}
/**
* <p>The targets where the task should execute.</p>
*/
inline const Aws::Vector<Target>& GetTargets() const{ return m_targets; }
/**
* <p>The targets where the task should execute.</p>
*/
inline void SetTargets(const Aws::Vector<Target>& value) { m_targets = value; }
/**
* <p>The targets where the task should execute.</p>
*/
inline void SetTargets(Aws::Vector<Target>&& value) { m_targets = std::move(value); }
/**
* <p>The targets where the task should execute.</p>
*/
inline GetMaintenanceWindowTaskResult& WithTargets(const Aws::Vector<Target>& value) { SetTargets(value); return *this;}
/**
* <p>The targets where the task should execute.</p>
*/
inline GetMaintenanceWindowTaskResult& WithTargets(Aws::Vector<Target>&& value) { SetTargets(std::move(value)); return *this;}
/**
* <p>The targets where the task should execute.</p>
*/
inline GetMaintenanceWindowTaskResult& AddTargets(const Target& value) { m_targets.push_back(value); return *this; }
/**
* <p>The targets where the task should execute.</p>
*/
inline GetMaintenanceWindowTaskResult& AddTargets(Target&& value) { m_targets.push_back(std::move(value)); return *this; }
/**
* <p>The resource that the task used during execution. For RUN_COMMAND and
* AUTOMATION task types, the TaskArn is the Systems Manager Document name/ARN. For
* LAMBDA tasks, the value is the function name/ARN. For STEP_FUNCTION tasks, the
* value is the state machine ARN.</p>
*/
inline const Aws::String& GetTaskArn() const{ return m_taskArn; }
/**
* <p>The resource that the task used during execution. For RUN_COMMAND and
* AUTOMATION task types, the TaskArn is the Systems Manager Document name/ARN. For
* LAMBDA tasks, the value is the function name/ARN. For STEP_FUNCTION tasks, the
* value is the state machine ARN.</p>
*/
inline void SetTaskArn(const Aws::String& value) { m_taskArn = value; }
/**
* <p>The resource that the task used during execution. For RUN_COMMAND and
* AUTOMATION task types, the TaskArn is the Systems Manager Document name/ARN. For
* LAMBDA tasks, the value is the function name/ARN. For STEP_FUNCTION tasks, the
* value is the state machine ARN.</p>
*/
inline void SetTaskArn(Aws::String&& value) { m_taskArn = std::move(value); }
/**
* <p>The resource that the task used during execution. For RUN_COMMAND and
* AUTOMATION task types, the TaskArn is the Systems Manager Document name/ARN. For
* LAMBDA tasks, the value is the function name/ARN. For STEP_FUNCTION tasks, the
* value is the state machine ARN.</p>
*/
inline void SetTaskArn(const char* value) { m_taskArn.assign(value); }
/**
* <p>The resource that the task used during execution. For RUN_COMMAND and
* AUTOMATION task types, the TaskArn is the Systems Manager Document name/ARN. For
* LAMBDA tasks, the value is the function name/ARN. For STEP_FUNCTION tasks, the
* value is the state machine ARN.</p>
*/
inline GetMaintenanceWindowTaskResult& WithTaskArn(const Aws::String& value) { SetTaskArn(value); return *this;}
/**
* <p>The resource that the task used during execution. For RUN_COMMAND and
* AUTOMATION task types, the TaskArn is the Systems Manager Document name/ARN. For
* LAMBDA tasks, the value is the function name/ARN. For STEP_FUNCTION tasks, the
* value is the state machine ARN.</p>
*/
inline GetMaintenanceWindowTaskResult& WithTaskArn(Aws::String&& value) { SetTaskArn(std::move(value)); return *this;}
/**
* <p>The resource that the task used during execution. For RUN_COMMAND and
* AUTOMATION task types, the TaskArn is the Systems Manager Document name/ARN. For
* LAMBDA tasks, the value is the function name/ARN. For STEP_FUNCTION tasks, the
* value is the state machine ARN.</p>
*/
inline GetMaintenanceWindowTaskResult& WithTaskArn(const char* value) { SetTaskArn(value); return *this;}
/**
* <p>The IAM service role to assume during task execution.</p>
*/
inline const Aws::String& GetServiceRoleArn() const{ return m_serviceRoleArn; }
/**
* <p>The IAM service role to assume during task execution.</p>
*/
inline void SetServiceRoleArn(const Aws::String& value) { m_serviceRoleArn = value; }
/**
* <p>The IAM service role to assume during task execution.</p>
*/
inline void SetServiceRoleArn(Aws::String&& value) { m_serviceRoleArn = std::move(value); }
/**
* <p>The IAM service role to assume during task execution.</p>
*/
inline void SetServiceRoleArn(const char* value) { m_serviceRoleArn.assign(value); }
/**
* <p>The IAM service role to assume during task execution.</p>
*/
inline GetMaintenanceWindowTaskResult& WithServiceRoleArn(const Aws::String& value) { SetServiceRoleArn(value); return *this;}
/**
* <p>The IAM service role to assume during task execution.</p>
*/
inline GetMaintenanceWindowTaskResult& WithServiceRoleArn(Aws::String&& value) { SetServiceRoleArn(std::move(value)); return *this;}
/**
* <p>The IAM service role to assume during task execution.</p>
*/
inline GetMaintenanceWindowTaskResult& WithServiceRoleArn(const char* value) { SetServiceRoleArn(value); return *this;}
/**
* <p>The type of task to execute.</p>
*/
inline const MaintenanceWindowTaskType& GetTaskType() const{ return m_taskType; }
/**
* <p>The type of task to execute.</p>
*/
inline void SetTaskType(const MaintenanceWindowTaskType& value) { m_taskType = value; }
/**
* <p>The type of task to execute.</p>
*/
inline void SetTaskType(MaintenanceWindowTaskType&& value) { m_taskType = std::move(value); }
/**
* <p>The type of task to execute.</p>
*/
inline GetMaintenanceWindowTaskResult& WithTaskType(const MaintenanceWindowTaskType& value) { SetTaskType(value); return *this;}
/**
* <p>The type of task to execute.</p>
*/
inline GetMaintenanceWindowTaskResult& WithTaskType(MaintenanceWindowTaskType&& value) { SetTaskType(std::move(value)); return *this;}
/**
* <p>The parameters to pass to the task when it executes.</p> <note> <p>
* <code>TaskParameters</code> has been deprecated. To specify parameters to pass
* to a task when it runs, instead use the <code>Parameters</code> option in the
* <code>TaskInvocationParameters</code> structure. For information about how
* Systems Manager handles these options for the supported Maintenance Window task
* types, see <a>MaintenanceWindowTaskInvocationParameters</a>.</p> </note>
*/
inline const Aws::Map<Aws::String, MaintenanceWindowTaskParameterValueExpression>& GetTaskParameters() const{ return m_taskParameters; }
/**
* <p>The parameters to pass to the task when it executes.</p> <note> <p>
* <code>TaskParameters</code> has been deprecated. To specify parameters to pass
* to a task when it runs, instead use the <code>Parameters</code> option in the
* <code>TaskInvocationParameters</code> structure. For information about how
* Systems Manager handles these options for the supported Maintenance Window task
* types, see <a>MaintenanceWindowTaskInvocationParameters</a>.</p> </note>
*/
inline void SetTaskParameters(const Aws::Map<Aws::String, MaintenanceWindowTaskParameterValueExpression>& value) { m_taskParameters = value; }
/**
* <p>The parameters to pass to the task when it executes.</p> <note> <p>
* <code>TaskParameters</code> has been deprecated. To specify parameters to pass
* to a task when it runs, instead use the <code>Parameters</code> option in the
* <code>TaskInvocationParameters</code> structure. For information about how
* Systems Manager handles these options for the supported Maintenance Window task
* types, see <a>MaintenanceWindowTaskInvocationParameters</a>.</p> </note>
*/
inline void SetTaskParameters(Aws::Map<Aws::String, MaintenanceWindowTaskParameterValueExpression>&& value) { m_taskParameters = std::move(value); }
/**
* <p>The parameters to pass to the task when it executes.</p> <note> <p>
* <code>TaskParameters</code> has been deprecated. To specify parameters to pass
* to a task when it runs, instead use the <code>Parameters</code> option in the
* <code>TaskInvocationParameters</code> structure. For information about how
* Systems Manager handles these options for the supported Maintenance Window task
* types, see <a>MaintenanceWindowTaskInvocationParameters</a>.</p> </note>
*/
inline GetMaintenanceWindowTaskResult& WithTaskParameters(const Aws::Map<Aws::String, MaintenanceWindowTaskParameterValueExpression>& value) { SetTaskParameters(value); return *this;}
/**
* <p>The parameters to pass to the task when it executes.</p> <note> <p>
* <code>TaskParameters</code> has been deprecated. To specify parameters to pass
* to a task when it runs, instead use the <code>Parameters</code> option in the
* <code>TaskInvocationParameters</code> structure. For information about how
* Systems Manager handles these options for the supported Maintenance Window task
* types, see <a>MaintenanceWindowTaskInvocationParameters</a>.</p> </note>
*/
inline GetMaintenanceWindowTaskResult& WithTaskParameters(Aws::Map<Aws::String, MaintenanceWindowTaskParameterValueExpression>&& value) { SetTaskParameters(std::move(value)); return *this;}
/**
* <p>The parameters to pass to the task when it executes.</p> <note> <p>
* <code>TaskParameters</code> has been deprecated. To specify parameters to pass
* to a task when it runs, instead use the <code>Parameters</code> option in the
* <code>TaskInvocationParameters</code> structure. For information about how
* Systems Manager handles these options for the supported Maintenance Window task
* types, see <a>MaintenanceWindowTaskInvocationParameters</a>.</p> </note>
*/
inline GetMaintenanceWindowTaskResult& AddTaskParameters(const Aws::String& key, const MaintenanceWindowTaskParameterValueExpression& value) { m_taskParameters.emplace(key, value); return *this; }
/**
* <p>The parameters to pass to the task when it executes.</p> <note> <p>
* <code>TaskParameters</code> has been deprecated. To specify parameters to pass
* to a task when it runs, instead use the <code>Parameters</code> option in the
* <code>TaskInvocationParameters</code> structure. For information about how
* Systems Manager handles these options for the supported Maintenance Window task
* types, see <a>MaintenanceWindowTaskInvocationParameters</a>.</p> </note>
*/
inline GetMaintenanceWindowTaskResult& AddTaskParameters(Aws::String&& key, const MaintenanceWindowTaskParameterValueExpression& value) { m_taskParameters.emplace(std::move(key), value); return *this; }
/**
* <p>The parameters to pass to the task when it executes.</p> <note> <p>
* <code>TaskParameters</code> has been deprecated. To specify parameters to pass
* to a task when it runs, instead use the <code>Parameters</code> option in the
* <code>TaskInvocationParameters</code> structure. For information about how
* Systems Manager handles these options for the supported Maintenance Window task
* types, see <a>MaintenanceWindowTaskInvocationParameters</a>.</p> </note>
*/
inline GetMaintenanceWindowTaskResult& AddTaskParameters(const Aws::String& key, MaintenanceWindowTaskParameterValueExpression&& value) { m_taskParameters.emplace(key, std::move(value)); return *this; }
/**
* <p>The parameters to pass to the task when it executes.</p> <note> <p>
* <code>TaskParameters</code> has been deprecated. To specify parameters to pass
* to a task when it runs, instead use the <code>Parameters</code> option in the
* <code>TaskInvocationParameters</code> structure. For information about how
* Systems Manager handles these options for the supported Maintenance Window task
* types, see <a>MaintenanceWindowTaskInvocationParameters</a>.</p> </note>
*/
inline GetMaintenanceWindowTaskResult& AddTaskParameters(Aws::String&& key, MaintenanceWindowTaskParameterValueExpression&& value) { m_taskParameters.emplace(std::move(key), std::move(value)); return *this; }
/**
* <p>The parameters to pass to the task when it executes.</p> <note> <p>
* <code>TaskParameters</code> has been deprecated. To specify parameters to pass
* to a task when it runs, instead use the <code>Parameters</code> option in the
* <code>TaskInvocationParameters</code> structure. For information about how
* Systems Manager handles these options for the supported Maintenance Window task
* types, see <a>MaintenanceWindowTaskInvocationParameters</a>.</p> </note>
*/
inline GetMaintenanceWindowTaskResult& AddTaskParameters(const char* key, MaintenanceWindowTaskParameterValueExpression&& value) { m_taskParameters.emplace(key, std::move(value)); return *this; }
/**
* <p>The parameters to pass to the task when it executes.</p> <note> <p>
* <code>TaskParameters</code> has been deprecated. To specify parameters to pass
* to a task when it runs, instead use the <code>Parameters</code> option in the
* <code>TaskInvocationParameters</code> structure. For information about how
* Systems Manager handles these options for the supported Maintenance Window task
* types, see <a>MaintenanceWindowTaskInvocationParameters</a>.</p> </note>
*/
inline GetMaintenanceWindowTaskResult& AddTaskParameters(const char* key, const MaintenanceWindowTaskParameterValueExpression& value) { m_taskParameters.emplace(key, value); return *this; }
/**
* <p>The parameters to pass to the task when it executes.</p>
*/
inline const MaintenanceWindowTaskInvocationParameters& GetTaskInvocationParameters() const{ return m_taskInvocationParameters; }
/**
* <p>The parameters to pass to the task when it executes.</p>
*/
inline void SetTaskInvocationParameters(const MaintenanceWindowTaskInvocationParameters& value) { m_taskInvocationParameters = value; }
/**
* <p>The parameters to pass to the task when it executes.</p>
*/
inline void SetTaskInvocationParameters(MaintenanceWindowTaskInvocationParameters&& value) { m_taskInvocationParameters = std::move(value); }
/**
* <p>The parameters to pass to the task when it executes.</p>
*/
inline GetMaintenanceWindowTaskResult& WithTaskInvocationParameters(const MaintenanceWindowTaskInvocationParameters& value) { SetTaskInvocationParameters(value); return *this;}
/**
* <p>The parameters to pass to the task when it executes.</p>
*/
inline GetMaintenanceWindowTaskResult& WithTaskInvocationParameters(MaintenanceWindowTaskInvocationParameters&& value) { SetTaskInvocationParameters(std::move(value)); return *this;}
/**
* <p>The priority of the task when it executes. The lower the number, the higher
* the priority. Tasks that have the same priority are scheduled in parallel.</p>
*/
inline int GetPriority() const{ return m_priority; }
/**
* <p>The priority of the task when it executes. The lower the number, the higher
* the priority. Tasks that have the same priority are scheduled in parallel.</p>
*/
inline void SetPriority(int value) { m_priority = value; }
/**
* <p>The priority of the task when it executes. The lower the number, the higher
* the priority. Tasks that have the same priority are scheduled in parallel.</p>
*/
inline GetMaintenanceWindowTaskResult& WithPriority(int value) { SetPriority(value); return *this;}
/**
* <p>The maximum number of targets allowed to run this task in parallel.</p>
*/
inline const Aws::String& GetMaxConcurrency() const{ return m_maxConcurrency; }
/**
* <p>The maximum number of targets allowed to run this task in parallel.</p>
*/
inline void SetMaxConcurrency(const Aws::String& value) { m_maxConcurrency = value; }
/**
* <p>The maximum number of targets allowed to run this task in parallel.</p>
*/
inline void SetMaxConcurrency(Aws::String&& value) { m_maxConcurrency = std::move(value); }
/**
* <p>The maximum number of targets allowed to run this task in parallel.</p>
*/
inline void SetMaxConcurrency(const char* value) { m_maxConcurrency.assign(value); }
/**
* <p>The maximum number of targets allowed to run this task in parallel.</p>
*/
inline GetMaintenanceWindowTaskResult& WithMaxConcurrency(const Aws::String& value) { SetMaxConcurrency(value); return *this;}
/**
* <p>The maximum number of targets allowed to run this task in parallel.</p>
*/
inline GetMaintenanceWindowTaskResult& WithMaxConcurrency(Aws::String&& value) { SetMaxConcurrency(std::move(value)); return *this;}
/**
* <p>The maximum number of targets allowed to run this task in parallel.</p>
*/
inline GetMaintenanceWindowTaskResult& WithMaxConcurrency(const char* value) { SetMaxConcurrency(value); return *this;}
/**
* <p>The maximum number of errors allowed before the task stops being
* scheduled.</p>
*/
inline const Aws::String& GetMaxErrors() const{ return m_maxErrors; }
/**
* <p>The maximum number of errors allowed before the task stops being
* scheduled.</p>
*/
inline void SetMaxErrors(const Aws::String& value) { m_maxErrors = value; }
/**
* <p>The maximum number of errors allowed before the task stops being
* scheduled.</p>
*/
inline void SetMaxErrors(Aws::String&& value) { m_maxErrors = std::move(value); }
/**
* <p>The maximum number of errors allowed before the task stops being
* scheduled.</p>
*/
inline void SetMaxErrors(const char* value) { m_maxErrors.assign(value); }
/**
* <p>The maximum number of errors allowed before the task stops being
* scheduled.</p>
*/
inline GetMaintenanceWindowTaskResult& WithMaxErrors(const Aws::String& value) { SetMaxErrors(value); return *this;}
/**
* <p>The maximum number of errors allowed before the task stops being
* scheduled.</p>
*/
inline GetMaintenanceWindowTaskResult& WithMaxErrors(Aws::String&& value) { SetMaxErrors(std::move(value)); return *this;}
/**
* <p>The maximum number of errors allowed before the task stops being
* scheduled.</p>
*/
inline GetMaintenanceWindowTaskResult& WithMaxErrors(const char* value) { SetMaxErrors(value); return *this;}
/**
* <p>The location in Amazon S3 where the task results are logged.</p> <note> <p>
* <code>LoggingInfo</code> has been deprecated. To specify an S3 bucket to contain
* logs, instead use the <code>OutputS3BucketName</code> and
* <code>OutputS3KeyPrefix</code> options in the
* <code>TaskInvocationParameters</code> structure. For information about how
* Systems Manager handles these options for the supported Maintenance Window task
* types, see <a>MaintenanceWindowTaskInvocationParameters</a>.</p> </note>
*/
inline const LoggingInfo& GetLoggingInfo() const{ return m_loggingInfo; }
/**
* <p>The location in Amazon S3 where the task results are logged.</p> <note> <p>
* <code>LoggingInfo</code> has been deprecated. To specify an S3 bucket to contain
* logs, instead use the <code>OutputS3BucketName</code> and
* <code>OutputS3KeyPrefix</code> options in the
* <code>TaskInvocationParameters</code> structure. For information about how
* Systems Manager handles these options for the supported Maintenance Window task
* types, see <a>MaintenanceWindowTaskInvocationParameters</a>.</p> </note>
*/
inline void SetLoggingInfo(const LoggingInfo& value) { m_loggingInfo = value; }
/**
* <p>The location in Amazon S3 where the task results are logged.</p> <note> <p>
* <code>LoggingInfo</code> has been deprecated. To specify an S3 bucket to contain
* logs, instead use the <code>OutputS3BucketName</code> and
* <code>OutputS3KeyPrefix</code> options in the
* <code>TaskInvocationParameters</code> structure. For information about how
* Systems Manager handles these options for the supported Maintenance Window task
* types, see <a>MaintenanceWindowTaskInvocationParameters</a>.</p> </note>
*/
inline void SetLoggingInfo(LoggingInfo&& value) { m_loggingInfo = std::move(value); }
/**
* <p>The location in Amazon S3 where the task results are logged.</p> <note> <p>
* <code>LoggingInfo</code> has been deprecated. To specify an S3 bucket to contain
* logs, instead use the <code>OutputS3BucketName</code> and
* <code>OutputS3KeyPrefix</code> options in the
* <code>TaskInvocationParameters</code> structure. For information about how
* Systems Manager handles these options for the supported Maintenance Window task
* types, see <a>MaintenanceWindowTaskInvocationParameters</a>.</p> </note>
*/
inline GetMaintenanceWindowTaskResult& WithLoggingInfo(const LoggingInfo& value) { SetLoggingInfo(value); return *this;}
/**
* <p>The location in Amazon S3 where the task results are logged.</p> <note> <p>
* <code>LoggingInfo</code> has been deprecated. To specify an S3 bucket to contain
* logs, instead use the <code>OutputS3BucketName</code> and
* <code>OutputS3KeyPrefix</code> options in the
* <code>TaskInvocationParameters</code> structure. For information about how
* Systems Manager handles these options for the supported Maintenance Window task
* types, see <a>MaintenanceWindowTaskInvocationParameters</a>.</p> </note>
*/
inline GetMaintenanceWindowTaskResult& WithLoggingInfo(LoggingInfo&& value) { SetLoggingInfo(std::move(value)); return *this;}
/**
* <p>The retrieved task name.</p>
*/
inline const Aws::String& GetName() const{ return m_name; }
/**
* <p>The retrieved task name.</p>
*/
inline void SetName(const Aws::String& value) { m_name = value; }
/**
* <p>The retrieved task name.</p>
*/
inline void SetName(Aws::String&& value) { m_name = std::move(value); }
/**
* <p>The retrieved task name.</p>
*/
inline void SetName(const char* value) { m_name.assign(value); }
/**
* <p>The retrieved task name.</p>
*/
inline GetMaintenanceWindowTaskResult& WithName(const Aws::String& value) { SetName(value); return *this;}
/**
* <p>The retrieved task name.</p>
*/
inline GetMaintenanceWindowTaskResult& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}
/**
* <p>The retrieved task name.</p>
*/
inline GetMaintenanceWindowTaskResult& WithName(const char* value) { SetName(value); return *this;}
/**
* <p>The retrieved task description.</p>
*/
inline const Aws::String& GetDescription() const{ return m_description; }
/**
* <p>The retrieved task description.</p>
*/
inline void SetDescription(const Aws::String& value) { m_description = value; }
/**
* <p>The retrieved task description.</p>
*/
inline void SetDescription(Aws::String&& value) { m_description = std::move(value); }
/**
* <p>The retrieved task description.</p>
*/
inline void SetDescription(const char* value) { m_description.assign(value); }
/**
* <p>The retrieved task description.</p>
*/
inline GetMaintenanceWindowTaskResult& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}
/**
* <p>The retrieved task description.</p>
*/
inline GetMaintenanceWindowTaskResult& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}
/**
* <p>The retrieved task description.</p>
*/
inline GetMaintenanceWindowTaskResult& WithDescription(const char* value) { SetDescription(value); return *this;}
private:
Aws::String m_windowId;
Aws::String m_windowTaskId;
Aws::Vector<Target> m_targets;
Aws::String m_taskArn;
Aws::String m_serviceRoleArn;
MaintenanceWindowTaskType m_taskType;
Aws::Map<Aws::String, MaintenanceWindowTaskParameterValueExpression> m_taskParameters;
MaintenanceWindowTaskInvocationParameters m_taskInvocationParameters;
int m_priority;
Aws::String m_maxConcurrency;
Aws::String m_maxErrors;
LoggingInfo m_loggingInfo;
Aws::String m_name;
Aws::String m_description;
};
} // namespace Model
} // namespace SSM
} // namespace Aws
|
apache-2.0
|
gosu-lang/old-gosu-repo
|
gosu-test-api/src/main/java/gw/test/servlet/RemoteTestServlet.java
|
20725
|
/*
* Copyright 2013 Guidewire Software, Inc.
*/
package gw.test.servlet;
import gw.config.CommonServices;
import gw.lang.reflect.IConstructorInfo;
import gw.lang.reflect.IParameterInfo;
import gw.lang.reflect.IType;
import gw.lang.reflect.ITypeInfo;
import gw.lang.reflect.TypeSystem;
import gw.lang.reflect.gs.IGosuClass;
import gw.lang.reflect.java.IJavaType;
import gw.test.TestClass;
import gw.lang.reflect.IParameterInfo;
import gw.lang.reflect.java.JavaTypes;
import gw.test.TestEnvironment;
import gw.test.TestMetadata;
import gw.test.TestSpec;
import gw.test.remote.ForwardingTestEnvironment;
import gw.test.remote.RemoteTestResult;
import gw.util.GosuStringUtil;
import gw.lang.reflect.java.JavaTypes;
import gw.test.TestClass;
import gw.test.remote.RemoteTestResult;
import gw.xml.simple.SimpleXmlNode;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Collection;
public class RemoteTestServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
handleRequest(request, response);
}
public static String TEST_INFO_COMMAND = "testInfo";
public static String RUN_TEST_METHOD_COMMAND = "runTestMethod";
public static String BEFORE_TEST_CLASS_COMMAND = "beforeTestClass";
public static String AFTER_TEST_CLASS_COMMAND = "afterTestClass";
public static String REFRESH_TYPES_COMMAND = "refreshTypes";
public static String PING = "ping";
public static String REDIRECT_SYSTEM_OUT_COMMAND = "redirectSystemOut";
public static String REDIRECT_SYSTEM_ERR_COMMAND = "redirectSystemErr";
public static String STOP_REDIRECTING_OUTPUT_COMMAND = "stopRedirectingOutput";
public static final String SET_UP_TEST_ENVIRONMENT_COMMAND = "setUpTestEnvironment";
public static final String TEAR_DOWN_TEST_ENVIRONMENT_COMMAND = "tearDownTestEnvironment";
protected void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
_originalOut.println("Incoming request for " + request.getPathInfo());
String[] pathComponents = GosuStringUtil.split(request.getPathInfo(), "/");
if (!handleRequest(pathComponents, response)) {
throw new IllegalArgumentException("Unrecognized path " + request.getContextPath());
}
}
protected boolean handleRequest(String[] pathComponents, HttpServletResponse response) {
String lastComponent = pathComponents[pathComponents.length - 1];
if (lastComponent.equals(TEST_INFO_COMMAND)) {
handleTestInfoRequest(pathComponents, response);
} else if (lastComponent.equals(RUN_TEST_METHOD_COMMAND)) {
handleRunTestMethodRequest(pathComponents, response);
} else if (lastComponent.equals(BEFORE_TEST_CLASS_COMMAND)) {
handleBeforeTestClassRequest(pathComponents, response);
} else if (lastComponent.equals(AFTER_TEST_CLASS_COMMAND)) {
handleAfterTestClassRequest(pathComponents, response);
} else if (lastComponent.equals(REFRESH_TYPES_COMMAND)) {
handleRefreshTypesRequest(response);
} else if (lastComponent.equals(PING)) {
handlePingRequest(response);
} else if (lastComponent.equals(REDIRECT_SYSTEM_OUT_COMMAND)) {
handleRedirectSystemOutRequest(response);
} else if (lastComponent.equals(REDIRECT_SYSTEM_ERR_COMMAND)) {
handleRedirectSystemErrRequest(response);
} else if (lastComponent.equals(STOP_REDIRECTING_OUTPUT_COMMAND)) {
handleStopRedirectingOutputRequest(response);
} else if (lastComponent.equals(SET_UP_TEST_ENVIRONMENT_COMMAND)) {
handleSetUpTestEnvironmentRequest(pathComponents, response);
} else if (lastComponent.equals(TEAR_DOWN_TEST_ENVIRONMENT_COMMAND)) {
handleTearDownTestEnvironmentRequest(pathComponents, response);
} else {
// Return false if the request falls through and isn't handled
return false;
}
// Return true if any other branch was taken, meaning that something handled it
return true;
}
private void handleTestInfoRequest(String[] pathComponents, HttpServletResponse response) {
String typeName = constructTypeName(pathComponents, 0, pathComponents.length - 1);
String testInfoResults;
try {
testInfoResults = constructTestInfo(typeName);
} catch (Throwable t) {
t.printStackTrace();
// If there's an error, return an empty test info with no methods, rather than just nothing at all
// TODO - AHK - Return additional error information back
SimpleXmlNode classInfoNode = new SimpleXmlNode("TestClassInfo");
classInfoNode.getAttributes().put("name", typeName);
testInfoResults = classInfoNode.toXmlString();
}
try {
response.setContentType("text/html; charset=UTF8");
PrintWriter out = response.getWriter();
out.print(testInfoResults);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String constructTestInfo(String typeName) {
IType testType = TypeSystem.getByFullName(typeName);
// If the type doesn't parse, then we need to bail out
if (!testType.isValid()) {
if (testType instanceof IGosuClass) {
throw new RuntimeException(((IGosuClass)testType).getParseResultsException());
} else {
throw new IllegalStateException("Test type " + testType + " is not valid.");
}
}
String[] methodNames = TestSpec.extractTestMethods(testType);
// TODO - AHK - Should be consolidated with code in TestClassWrapper
ITypeInfo typeInfo = testType.getTypeInfo();
IConstructorInfo noArgCons = typeInfo.getConstructor();
TestClass test;
if (noArgCons != null) {
test = (TestClass) noArgCons.getConstructor().newInstance();
test.createClassMetadata();
} else {
IConstructorInfo oneArgCons = typeInfo.getConstructor(JavaTypes.STRING());
if (oneArgCons != null) {
test = (TestClass) oneArgCons.getConstructor().newInstance("dummy");
test.createClassMetadata();
} else {
throw new IllegalStateException("Test type " + testType + " does not have either a no-arg constructor or a one-arg constructor taking a String");
}
}
SimpleXmlNode classInfoNode = new SimpleXmlNode("TestClassInfo");
classInfoNode.getAttributes().put("name", typeName);
Collection<TestMetadata> classMetadata = test.createClassMetadata();
for (String methodName : methodNames) {
SimpleXmlNode methodInfoNode = new SimpleXmlNode("TestMethodInfo");
methodInfoNode.getAttributes().put("name", methodName);
classInfoNode.getChildren().add(methodInfoNode);
for (TestMetadata md : classMetadata) {
methodInfoNode.getChildren().add(md.serializeToXml());
}
Collection<TestMetadata> methodMetadata = test.createMethodMetadata(methodName);
for (TestMetadata md : methodMetadata) {
methodInfoNode.getChildren().add(md.serializeToXml());
}
}
return classInfoNode.toXmlString();
}
private void handleBeforeTestClassRequest(String[] pathComponents, HttpServletResponse response) {
handleTestClassMethod(pathComponents, pathComponents.length - 1, response, new TestClassCallback() {
@Override
public void invoke(TestClass testClass) {
testClass.beforeTestClass();
}
});
}
private void handleAfterTestClassRequest(String[] pathComponents, HttpServletResponse response) {
handleTestClassMethod(pathComponents, pathComponents.length - 1, response, new TestClassCallback() {
@Override
public void invoke(TestClass testClass) {
testClass.afterTestClass();
}
});
}
private void handleRunTestMethodRequest(final String[] pathComponents, HttpServletResponse response) {
handleTestClassMethod(pathComponents, pathComponents.length - 2, response, new TestClassCallback() {
@Override
public void invoke(TestClass testClass) throws Throwable {
// TODO - AHK - This should reuse more of the code from TestClassWrapper
String methodName = pathComponents[pathComponents.length - 2];
testClass.setName(methodName);
testClass.initMetadata(methodName);
callTestMethod(testClass);
}
});
}
private void callTestMethod(TestClass testClass) throws Throwable {
// TODO - AHK - This should probably just work through the TestExecutionManager
testClass.beforeTestMethod();
try {
testClass.reallyRunBare();
} catch (Throwable e) {
testClass.afterTestMethod(e);
throw e;
}
testClass.afterTestMethod(null);
}
private interface TestClassCallback {
void invoke(TestClass testClass) throws Throwable;
}
private void handleTestClassMethod(String[] pathComponents, int lastNameIndex, HttpServletResponse response, TestClassCallback callback) {
RemoteTestResult testResult = new RemoteTestResult();
try {
String typeName = constructTypeName(pathComponents, 0, lastNameIndex);
TestClass testClass = createTestClassInstance(typeName);
callback.invoke(testClass);
} catch (Throwable t) {
testResult.setException(t);
}
sendRemoteTestResult(response, testResult);
}
private String constructTypeName(String[] components, int start, int end) {
StringBuilder typeName = new StringBuilder();
for (int i = start; i < end; i++) {
if (i > start) {
typeName.append(".");
}
typeName.append(components[i]);
}
return typeName.toString();
}
private TestClass createTestClassInstance(String typeName) {
IType testType = TypeSystem.getByFullName(typeName);
if( !(testType instanceof IJavaType) ){
try {
if( !(testType instanceof IGosuClass) ||
((IGosuClass)testType).getBackingClass() != getTestClass( typeName, testType ) ) {
// So we have a java class and an non-java class. Go boom
throw(new IllegalStateException("Type " + typeName + " exists as both a java type and a non-java type."));
}
} catch (ClassNotFoundException e) {
// This is fine
}
}
return TestClass.createTestClass(testType);
}
private Class<?> getTestClass( String typeName, IType testType ) throws ClassNotFoundException {
return Class.forName( typeName, false, testType.getTypeLoader().getModule().getModuleTypeLoader().getDefaultTypeLoader().getGosuClassLoader().getActualLoader() );
}
private void sendRemoteTestResult(HttpServletResponse response, RemoteTestResult testResult) {
try {
response.setContentType("text/html; charset=UTF8");
PrintWriter out = response.getWriter();
out.print(testResult.toXML());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void handleRefreshTypesRequest(HttpServletResponse response) {
try {
ChangedTypesRefresher.getInstance().reloadChangedTypes();
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
} catch (Throwable t) {
t.printStackTrace();
}
}
private void handlePingRequest(HttpServletResponse response) {
try {
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void handleSetUpTestEnvironmentRequest(String[] pathComponents, HttpServletResponse response) {
TestEnvironment testEnvironment = createTestEnvironment(pathComponents);
boolean success;
try {
testEnvironment.beforeRemoteExecution();
success = true;
} catch (Exception e) {
e.printStackTrace();
success = false;
}
try {
response.setContentType("text/html; charset=UTF8");
PrintWriter out = response.getWriter();
out.print(success);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void handleTearDownTestEnvironmentRequest(String[] pathComponents, HttpServletResponse response) {
TestEnvironment testEnvironment = createTestEnvironment(pathComponents);
boolean success;
try {
testEnvironment.afterRemoteExecution();
success = true;
} catch (Exception e) {
e.printStackTrace();
success = false;
}
try {
response.setContentType("text/html; charset=UTF8");
PrintWriter out = response.getWriter();
out.print(success);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private TestEnvironment createTestEnvironment(String[] pathComponents) {
// TODO - AHK - Error handling
// TODO - AHK - Validate that it's actually a TestEnvironment
// TODO - AHK - Handle the case where there's no appropriate constructor
String typeName = constructTypeName(pathComponents, 0, pathComponents.length - 2);
String[] constructorArgs = splitArgs(pathComponents[pathComponents.length - 2]);
IType testEnvironmentType = TypeSystem.getByFullName(typeName);
TestEnvironment testEnvironment = null;
for (IConstructorInfo cons : testEnvironmentType.getTypeInfo().getConstructors()) {
if (cons.getParameters().length == constructorArgs.length) {
Object[] convertedArgs = convertConstructorArgs(constructorArgs, cons.getParameters());
testEnvironment = (TestEnvironment) cons.getConstructor().newInstance(convertedArgs);
break;
}
}
return testEnvironment;
}
private String[] splitArgs(String constructorArgs) {
if (constructorArgs.equals(ForwardingTestEnvironment.NO_ARGS_STRING)) {
return new String[0];
} else {
return GosuStringUtil.split(constructorArgs, ",");
}
}
private Object[] convertConstructorArgs(String[] constructorArgs, IParameterInfo[] params) {
Object[] results = new Object[constructorArgs.length];
for (int i = 0; i < constructorArgs.length; i++) {
results[i] = convertConstructorArg(constructorArgs[i], params[i].getFeatureType());
}
return results;
}
private Object convertConstructorArg(String arg, IType targetType) {
if (targetType.equals(JavaTypes.BOOLEAN()) || targetType.equals(JavaTypes.pBOOLEAN())) {
return Boolean.valueOf(arg);
} else {
throw new IllegalArgumentException("Unhandled type TestEnvironment constructor argument type " + targetType);
}
}
private static PrintStream _originalOut = System.out;
private static PrintStream _originalErr = System.err;
protected void handleRedirectSystemOutRequest(HttpServletResponse response) {
redirectOutput(response, new SystemOutInfo());
}
private void handleRedirectSystemErrRequest(HttpServletResponse response) {
redirectOutput(response, new SystemErrInfo());
}
private void handleStopRedirectingOutputRequest(HttpServletResponse response) {
stopRedirectingOutput(new SystemOutInfo());
stopRedirectingOutput(new SystemErrInfo());
try {
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void stopRedirectingOutput(StreamInfo streamInfo) {
if (!streamInfo.isCurrentStream(streamInfo.getOriginalStream())) {
streamInfo.setStream(streamInfo.getOriginalStream());
afterStreamRedirected(streamInfo);
}
}
protected static abstract class StreamInfo {
public abstract PrintStream getOriginalStream();
public abstract void setStream(PrintStream newStream);
public abstract boolean isCurrentStream(PrintStream stream);
}
protected static class SystemOutInfo extends StreamInfo {
@Override
public PrintStream getOriginalStream() {
return _originalOut;
}
@Override
public void setStream(PrintStream newStream) {
System.setOut(newStream);
}
@Override
public boolean isCurrentStream(PrintStream stream) {
return System.out == stream;
}
}
protected static class SystemErrInfo extends StreamInfo {
@Override
public PrintStream getOriginalStream() {
return _originalErr;
}
@Override
public void setStream(PrintStream newStream) {
System.setErr(newStream);
}
@Override
public boolean isCurrentStream(PrintStream stream) {
return System.err == stream;
}
}
private void redirectOutput(HttpServletResponse response, StreamInfo streamInfo) {
// TODO - AHK - Soooo . . . this is a total hack to keep the thread handling this alive. Is there some
// better way to do this? How does this ever get closed?
try {
RedirectingPrintStream redirectingStream = new RedirectingPrintStream(response.getOutputStream(), streamInfo.getOriginalStream());
streamInfo.setStream(redirectingStream);
afterStreamRedirected(streamInfo);
while (true) {
try {
Thread.sleep(500);
// We want this thread to die if either A) the system output has been directed elsewhere or B)
// there's been an error in the redirected stream, which generally means that the socket has closed
// on the other end. If we're exiting while the output is still redirected, we want to change it back
if (!streamInfo.isCurrentStream(redirectingStream) || redirectingStream.hasOutputStreamError()) {
if (streamInfo.isCurrentStream(redirectingStream)) {
streamInfo.setStream(streamInfo.getOriginalStream());
afterStreamRedirected(streamInfo);
}
break;
}
} catch (InterruptedException e) {
// Ignore
}
}
} catch (IOException e) {
// TODO - Handle this better somehow?
e.printStackTrace();
}
}
protected void afterStreamRedirected(StreamInfo streamInfo) {
}
private static class RedirectingPrintStream extends PrintStream {
private PrintStream _s1;
private PrintStream _s2;
private RedirectingPrintStream(OutputStream out, PrintStream originalStream) {
super(out, true);
_s1 = new PrintStream(out, true);
_s2 = originalStream;
}
public boolean hasOutputStreamError() {
return _s1.checkError();
}
@Override
public void flush() {
_s1.flush();
_s2.flush();
}
@Override
public void close() {
_s1.close();
_s2.close();
}
@Override
public void write(int b) {
_s1.write(b);
_s2.write(b);
}
@Override
public void write(byte[] buf, int off, int len) {
_s1.write(buf, off, len);
_s2.write(buf, off, len);
}
@Override
public void print(boolean b) {
_s1.print(b);
_s2.print(b);
}
@Override
public void print(char c) {
_s1.print(c);
_s2.print(c);
}
@Override
public void print(int i) {
_s1.print(i);
_s2.print(i);
}
@Override
public void print(long l) {
_s1.print(l);
_s2.print(l);
}
@Override
public void print(float f) {
_s1.print(f);
_s2.print(f);
}
@Override
public void print(double d) {
_s1.print(d);
_s2.print(d);
}
@Override
public void print(char[] s) {
_s1.print(s);
_s2.print(s);
}
@Override
public void print(String s) {
_s1.print(s);
_s2.print(s);
}
@Override
public void print(Object obj) {
_s1.print(obj);
_s2.print(obj);
}
@Override
public void println() {
_s1.println();
_s2.println();
}
@Override
public void println(boolean x) {
_s1.println(x);
_s2.println(x);
}
@Override
public void println(char x) {
_s1.println(x);
_s2.println(x);
}
@Override
public void println(int x) {
_s1.println(x);
_s2.println(x);
}
@Override
public void println(long x) {
_s1.println(x);
_s2.println(x);
}
@Override
public void println(float x) {
_s1.println(x);
_s2.println(x);
}
@Override
public void println(double x) {
_s1.println(x);
_s2.println(x);
}
@Override
public void println(char[] x) {
_s1.println(x);
_s2.println(x);
}
@Override
public void println(String x) {
_s1.println(x);
_s2.println(x);
}
@Override
public void println(Object x) {
_s1.println(x);
_s2.println(x);
}
@Override
public void write(byte[] b) throws IOException {
_s1.write(b);
_s2.write(b);
}
}
}
|
apache-2.0
|
adammurdoch/native-platform
|
native-platform/src/main/java/net/rubygrapefruit/platform/terminal/TerminalInputListener.java
|
723
|
package net.rubygrapefruit.platform.terminal;
/**
* Receives terminal input.
*/
public interface TerminalInputListener {
enum Key {
// Order is significant, used by Windows native code
Enter,
UpArrow,
DownArrow,
LeftArrow,
RightArrow,
Home,
End,
EraseBack,
EraseForward,
BackTab,
PageUp,
PageDown
}
/**
* Called when a character is typed. Note that this method is not called for the 'enter' key.
*/
void character(char ch);
/**
* Called when a control key is typed.
*/
void controlKey(Key key);
/**
* Called on the end of input.
*/
void endInput();
}
|
apache-2.0
|
filip26/api-machine
|
src/test/java/org/sprintapi/api/http/servlet/todo/action/TodoReadItemAction.java
|
1529
|
/*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sprintapi.api.http.servlet.todo.action;
import org.sprintapi.api.Context;
import org.sprintapi.api.action.Action;
import org.sprintapi.api.content.ContentBuilder;
import org.sprintapi.api.error.ApiErrorException;
import org.sprintapi.api.http.servlet.todo.TodoItem;
import org.sprintapi.api.meta.type.Language;
import org.sprintapi.api.request.Request;
import org.sprintapi.api.response.Response;
public class TodoReadItemAction implements Action<Void, TodoItem> {
@Override
public void invoke(Request<Void> request, Response<TodoItem> response, Context<Void, TodoItem> ctx) throws ApiErrorException {
TodoItem item1 = new TodoItem();
item1.setDescription("Todo Item 1");
response.setContent(
(new ContentBuilder<TodoItem>())
.language(Language.EN_US)
.body(item1)
);
}
@Override
public TodoReadItemAction getThreadSafeInstance() {
return this;
}
}
|
apache-2.0
|
miguelaferreira/ratpoison
|
recipes/default.rb
|
702
|
#
# Cookbook Name:: ratpoison
# Recipe:: default
#
# Copyright 2014, Shuberg Philis B.V.
#
# 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_recipe 'xvfb'
include_recipe 'ratpoison::windowmanager'
|
apache-2.0
|
jonny-novikov/google-gdata
|
src/contentforshopping/managedaccountsquery.cs
|
1341
|
using System.Text;
using Google.GData.Client;
namespace Google.GData.ContentForShopping
{
/// <summary>
/// A subclass of FeedQuery, to create a ContentForShopping managedaccounts
/// query URI. Provides public properties that describe the different
/// aspects of the URI, as well as a composite URI.
/// </summary>
public class ManagedAccountsQuery : FeedQuery
{
/// <summary>
/// Constructor
/// </summary>
public ManagedAccountsQuery()
: base(ContentForShoppingNameTable.AllFeedsBaseUri)
{
}
/// <summary>
/// Constructor
/// </summary>
public ManagedAccountsQuery(string accountId)
: base(ContentForShoppingNameTable.AllFeedsBaseUri)
{
AccountId = accountId;
}
/// <summary>
/// Accessor method for AccountId.
/// </summary>
public string AccountId { get; set; }
/// <summary>
/// Returns the base Uri for the feed.
/// </summary>
protected override string GetBaseUri()
{
StringBuilder sb = new StringBuilder(baseUri, 2048);
sb.Append("/");
sb.Append(AccountId);
sb.Append("/managedaccounts/");
return sb.ToString();
}
}
}
|
apache-2.0
|
marcus-nl/flowable-engine
|
modules/flowable-cmmn-json-converter/src/main/java/org/flowable/cmmn/editor/json/converter/CaseTaskJsonConverter.java
|
3292
|
/* 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.flowable.cmmn.editor.json.converter;
import java.util.Map;
import org.flowable.cmmn.editor.constants.CmmnStencilConstants;
import org.flowable.cmmn.editor.json.converter.CmmnJsonConverter.CmmnModelIdHelper;
import org.flowable.cmmn.model.BaseElement;
import org.flowable.cmmn.model.CaseTask;
import org.flowable.cmmn.model.CmmnModel;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* @author Tijs Rademakers
*/
public class CaseTaskJsonConverter extends BaseCmmnJsonConverter implements CaseModelAwareConverter {
protected Map<String, String> caseModelMap;
public static void fillTypes(Map<String, Class<? extends BaseCmmnJsonConverter>> convertersToCmmnMap,
Map<Class<? extends BaseElement>, Class<? extends BaseCmmnJsonConverter>> convertersToJsonMap) {
fillJsonTypes(convertersToCmmnMap);
fillCmmnTypes(convertersToJsonMap);
}
public static void fillJsonTypes(Map<String, Class<? extends BaseCmmnJsonConverter>> convertersToBpmnMap) {
convertersToBpmnMap.put(STENCIL_TASK_CASE, CaseTaskJsonConverter.class);
}
public static void fillCmmnTypes(Map<Class<? extends BaseElement>, Class<? extends BaseCmmnJsonConverter>> convertersToJsonMap) {
convertersToJsonMap.put(CaseTask.class, CaseTaskJsonConverter.class);
}
@Override
protected String getStencilId(BaseElement baseElement) {
return CmmnStencilConstants.STENCIL_TASK_CASE;
}
@Override
protected void convertElementToJson(ObjectNode elementNode, ObjectNode propertiesNode, ActivityProcessor processor,
BaseElement baseElement, CmmnModel cmmnModel) {
// todo
}
@Override
protected BaseElement convertJsonToElement(JsonNode elementNode, JsonNode modelNode, ActivityProcessor processor,
BaseElement parentElement, Map<String, JsonNode> shapeMap, CmmnModel cmmnModel, CmmnModelIdHelper cmmnModelIdHelper) {
CaseTask task = new CaseTask();
JsonNode caseModelReferenceNode = CmmnJsonConverterUtil.getProperty(PROPERTY_CASE_REFERENCE, elementNode);
if (caseModelReferenceNode != null && caseModelReferenceNode.has("id") && !caseModelReferenceNode.get("id").isNull()) {
String caseModelId = caseModelReferenceNode.get("id").asText();
if (caseModelMap != null) {
String caseModelKey = caseModelMap.get(caseModelId);
task.setCaseRef(caseModelKey);
}
}
return task;
}
@Override
public void setCaseModelMap(Map<String, String> caseModelMap) {
this.caseModelMap = caseModelMap;
}
}
|
apache-2.0
|
GPUOpen-Drivers/llvm
|
lib/CodeGen/MIRVRegNamerUtils.cpp
|
11427
|
//===---------- MIRVRegNamerUtils.cpp - MIR VReg Renaming Utilities -------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "MIRVRegNamerUtils.h"
using namespace llvm;
#define DEBUG_TYPE "mir-vregnamer-utils"
namespace {
// TypedVReg and VRType are used to tell the renamer what to do at points in a
// sequence of values to be renamed. A TypedVReg can either contain
// an actual VReg, a FrameIndex, or it could just be a barrier for the next
// candidate (side-effecting instruction). This tells the renamer to increment
// to the next vreg name, or to skip modulo some skip-gap value.
enum VRType { RSE_Reg = 0, RSE_FrameIndex, RSE_NewCandidate };
class TypedVReg {
VRType Type;
Register Reg;
public:
TypedVReg(Register Reg) : Type(RSE_Reg), Reg(Reg) {}
TypedVReg(VRType Type) : Type(Type), Reg(~0U) {
assert(Type != RSE_Reg && "Expected a non-Register Type.");
}
bool isReg() const { return Type == RSE_Reg; }
bool isFrameIndex() const { return Type == RSE_FrameIndex; }
bool isCandidate() const { return Type == RSE_NewCandidate; }
VRType getType() const { return Type; }
Register getReg() const {
assert(this->isReg() && "Expected a virtual or physical Register.");
return Reg;
}
};
/// Here we find our candidates. What makes an interesting candidate?
/// A candidate for a canonicalization tree root is normally any kind of
/// instruction that causes side effects such as a store to memory or a copy to
/// a physical register or a return instruction. We use these as an expression
/// tree root that we walk in order to build a canonical walk which should
/// result in canonical vreg renaming.
std::vector<MachineInstr *> populateCandidates(MachineBasicBlock *MBB) {
std::vector<MachineInstr *> Candidates;
MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
for (auto II = MBB->begin(), IE = MBB->end(); II != IE; ++II) {
MachineInstr *MI = &*II;
bool DoesMISideEffect = false;
if (MI->getNumOperands() > 0 && MI->getOperand(0).isReg()) {
const Register Dst = MI->getOperand(0).getReg();
DoesMISideEffect |= !Register::isVirtualRegister(Dst);
for (auto UI = MRI.use_begin(Dst); UI != MRI.use_end(); ++UI) {
if (DoesMISideEffect)
break;
DoesMISideEffect |= (UI->getParent()->getParent() != MI->getParent());
}
}
if (!MI->mayStore() && !MI->isBranch() && !DoesMISideEffect)
continue;
LLVM_DEBUG(dbgs() << "Found Candidate: "; MI->dump(););
Candidates.push_back(MI);
}
return Candidates;
}
void doCandidateWalk(std::vector<TypedVReg> &VRegs,
std::queue<TypedVReg> &RegQueue,
std::vector<MachineInstr *> &VisitedMIs,
const MachineBasicBlock *MBB) {
const MachineFunction &MF = *MBB->getParent();
const MachineRegisterInfo &MRI = MF.getRegInfo();
while (!RegQueue.empty()) {
auto TReg = RegQueue.front();
RegQueue.pop();
if (TReg.isFrameIndex()) {
LLVM_DEBUG(dbgs() << "Popping frame index.\n";);
VRegs.push_back(TypedVReg(RSE_FrameIndex));
continue;
}
assert(TReg.isReg() && "Expected vreg or physreg.");
Register Reg = TReg.getReg();
if (Register::isVirtualRegister(Reg)) {
LLVM_DEBUG({
dbgs() << "Popping vreg ";
MRI.def_begin(Reg)->dump();
dbgs() << "\n";
});
if (!llvm::any_of(VRegs, [&](const TypedVReg &TR) {
return TR.isReg() && TR.getReg() == Reg;
})) {
VRegs.push_back(TypedVReg(Reg));
}
} else {
LLVM_DEBUG(dbgs() << "Popping physreg.\n";);
VRegs.push_back(TypedVReg(Reg));
continue;
}
for (auto RI = MRI.def_begin(Reg), RE = MRI.def_end(); RI != RE; ++RI) {
MachineInstr *Def = RI->getParent();
if (Def->getParent() != MBB)
continue;
if (llvm::any_of(VisitedMIs,
[&](const MachineInstr *VMI) { return Def == VMI; })) {
break;
}
LLVM_DEBUG({
dbgs() << "\n========================\n";
dbgs() << "Visited MI: ";
Def->dump();
dbgs() << "BB Name: " << Def->getParent()->getName() << "\n";
dbgs() << "\n========================\n";
});
VisitedMIs.push_back(Def);
for (unsigned I = 1, E = Def->getNumOperands(); I != E; ++I) {
MachineOperand &MO = Def->getOperand(I);
if (MO.isFI()) {
LLVM_DEBUG(dbgs() << "Pushing frame index.\n";);
RegQueue.push(TypedVReg(RSE_FrameIndex));
}
if (!MO.isReg())
continue;
RegQueue.push(TypedVReg(MO.getReg()));
}
}
}
}
std::map<unsigned, unsigned>
getVRegRenameMap(const std::vector<TypedVReg> &VRegs,
const std::vector<Register> &renamedInOtherBB,
MachineRegisterInfo &MRI, NamedVRegCursor &NVC) {
std::map<unsigned, unsigned> VRegRenameMap;
bool FirstCandidate = true;
for (auto &vreg : VRegs) {
if (vreg.isFrameIndex()) {
// We skip one vreg for any frame index because there is a good chance
// (especially when comparing SelectionDAG to GlobalISel generated MIR)
// that in the other file we are just getting an incoming vreg that comes
// from a copy from a frame index. So it's safe to skip by one.
unsigned LastRenameReg = NVC.incrementVirtualVReg();
(void)LastRenameReg;
LLVM_DEBUG(dbgs() << "Skipping rename for FI " << LastRenameReg << "\n";);
continue;
} else if (vreg.isCandidate()) {
// After the first candidate, for every subsequent candidate, we skip mod
// 10 registers so that the candidates are more likely to start at the
// same vreg number making it more likely that the canonical walk from the
// candidate insruction. We don't need to skip from the first candidate of
// the BasicBlock because we already skip ahead several vregs for each BB.
unsigned LastRenameReg = NVC.getVirtualVReg();
if (FirstCandidate)
NVC.incrementVirtualVReg(LastRenameReg % 10);
FirstCandidate = false;
continue;
} else if (!Register::isVirtualRegister(vreg.getReg())) {
unsigned LastRenameReg = NVC.incrementVirtualVReg();
(void)LastRenameReg;
LLVM_DEBUG({
dbgs() << "Skipping rename for Phys Reg " << LastRenameReg << "\n";
});
continue;
}
auto Reg = vreg.getReg();
if (llvm::find(renamedInOtherBB, Reg) != renamedInOtherBB.end()) {
LLVM_DEBUG(dbgs() << "Vreg " << Reg
<< " already renamed in other BB.\n";);
continue;
}
auto Rename = NVC.createVirtualRegister(Reg);
if (VRegRenameMap.find(Reg) == VRegRenameMap.end()) {
LLVM_DEBUG(dbgs() << "Mapping vreg ";);
if (MRI.reg_begin(Reg) != MRI.reg_end()) {
LLVM_DEBUG(auto foo = &*MRI.reg_begin(Reg); foo->dump(););
} else {
LLVM_DEBUG(dbgs() << Reg;);
}
LLVM_DEBUG(dbgs() << " to ";);
if (MRI.reg_begin(Rename) != MRI.reg_end()) {
LLVM_DEBUG(auto foo = &*MRI.reg_begin(Rename); foo->dump(););
} else {
LLVM_DEBUG(dbgs() << Rename;);
}
LLVM_DEBUG(dbgs() << "\n";);
VRegRenameMap.insert(std::pair<unsigned, unsigned>(Reg, Rename));
}
}
return VRegRenameMap;
}
bool doVRegRenaming(std::vector<Register> &renamedInOtherBB,
const std::map<unsigned, unsigned> &VRegRenameMap,
MachineRegisterInfo &MRI) {
bool Changed = false;
for (auto I = VRegRenameMap.begin(), E = VRegRenameMap.end(); I != E; ++I) {
auto VReg = I->first;
auto Rename = I->second;
renamedInOtherBB.push_back(Rename);
std::vector<MachineOperand *> RenameMOs;
for (auto &MO : MRI.reg_operands(VReg)) {
RenameMOs.push_back(&MO);
}
for (auto *MO : RenameMOs) {
Changed = true;
MO->setReg(Rename);
if (!MO->isDef())
MO->setIsKill(false);
}
}
return Changed;
}
bool renameVRegs(MachineBasicBlock *MBB,
std::vector<Register> &renamedInOtherBB,
NamedVRegCursor &NVC) {
bool Changed = false;
MachineFunction &MF = *MBB->getParent();
MachineRegisterInfo &MRI = MF.getRegInfo();
std::vector<MachineInstr *> Candidates = populateCandidates(MBB);
std::vector<MachineInstr *> VisitedMIs;
llvm::copy(Candidates, std::back_inserter(VisitedMIs));
std::vector<TypedVReg> VRegs;
for (auto candidate : Candidates) {
VRegs.push_back(TypedVReg(RSE_NewCandidate));
std::queue<TypedVReg> RegQueue;
// Here we walk the vreg operands of a non-root node along our walk.
// The root nodes are the original candidates (stores normally).
// These are normally not the root nodes (except for the case of copies to
// physical registers).
for (unsigned i = 1; i < candidate->getNumOperands(); i++) {
if (candidate->mayStore() || candidate->isBranch())
break;
MachineOperand &MO = candidate->getOperand(i);
if (!(MO.isReg() && Register::isVirtualRegister(MO.getReg())))
continue;
LLVM_DEBUG(dbgs() << "Enqueue register"; MO.dump(); dbgs() << "\n";);
RegQueue.push(TypedVReg(MO.getReg()));
}
// Here we walk the root candidates. We start from the 0th operand because
// the root is normally a store to a vreg.
for (unsigned i = 0; i < candidate->getNumOperands(); i++) {
if (!candidate->mayStore() && !candidate->isBranch())
break;
MachineOperand &MO = candidate->getOperand(i);
// TODO: Do we want to only add vregs here?
if (!MO.isReg() && !MO.isFI())
continue;
LLVM_DEBUG(dbgs() << "Enqueue Reg/FI"; MO.dump(); dbgs() << "\n";);
RegQueue.push(MO.isReg() ? TypedVReg(MO.getReg())
: TypedVReg(RSE_FrameIndex));
}
doCandidateWalk(VRegs, RegQueue, VisitedMIs, MBB);
}
// If we have populated no vregs to rename then bail.
// The rest of this function does the vreg remaping.
if (VRegs.size() == 0)
return Changed;
auto VRegRenameMap = getVRegRenameMap(VRegs, renamedInOtherBB, MRI, NVC);
Changed |= doVRegRenaming(renamedInOtherBB, VRegRenameMap, MRI);
return Changed;
}
} // anonymous namespace
void NamedVRegCursor::skipVRegs() {
unsigned VRegGapIndex = 1;
if (!virtualVRegNumber) {
VRegGapIndex = 0;
virtualVRegNumber = MRI.createIncompleteVirtualRegister();
}
const unsigned VR_GAP = (++VRegGapIndex * SkipGapSize);
unsigned I = virtualVRegNumber;
const unsigned E = (((I + VR_GAP) / VR_GAP) + 1) * VR_GAP;
virtualVRegNumber = E;
}
unsigned NamedVRegCursor::createVirtualRegister(unsigned VReg) {
if (!virtualVRegNumber)
skipVRegs();
std::string S;
raw_string_ostream OS(S);
OS << "namedVReg" << (virtualVRegNumber & ~0x80000000);
OS.flush();
virtualVRegNumber++;
if (auto RC = MRI.getRegClassOrNull(VReg))
return MRI.createVirtualRegister(RC, OS.str());
return MRI.createGenericVirtualRegister(MRI.getType(VReg), OS.str());
}
bool NamedVRegCursor::renameVRegs(MachineBasicBlock *MBB) {
return ::renameVRegs(MBB, RenamedInOtherBB, *this);
}
|
apache-2.0
|
gudnam/bringluck
|
google_play_services/docs/reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.Builder.html
|
48054
|
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />
<link rel="shortcut icon" type="image/x-icon" href="../../../../../../../favicon.ico" />
<title>StreetViewPanoramaOrientation.Builder | Android Developers</title>
<!-- STYLESHEETS -->
<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto+Condensed">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:light,regular,medium,thin,italic,mediumitalic,bold"
title="roboto">
<link href="../../../../../../../assets/css/default.css?v=2" rel="stylesheet" type="text/css">
<!-- FULLSCREEN STYLESHEET -->
<link href="../../../../../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen"
type="text/css">
<!-- JAVASCRIPT -->
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script src="../../../../../../../assets/js/android_3p-bundle.js" type="text/javascript"></script>
<script type="text/javascript">
var toRoot = "../../../../../../../";
var metaTags = [];
var devsite = false;
</script>
<script src="../../../../../../../assets/js/docs.js?v=2" type="text/javascript"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-5831155-1', 'android.com');
ga('create', 'UA-49880327-2', 'android.com', {'name': 'universal'}); // New tracker);
ga('send', 'pageview');
ga('universal.send', 'pageview'); // Send page view for new tracker.
</script>
</head>
<body class="gc-documentation
develop" itemscope itemtype="http://schema.org/Article">
<div id="doc-api-level" class="" style="display:none"></div>
<a name="top"></a>
<a name="top"></a>
<!-- Header -->
<div id="header-wrapper">
<div id="header">
<div class="wrap" id="header-wrap">
<div class="col-3 logo">
<a href="../../../../../../../index.html">
<img src="../../../../../../../assets/images/dac_logo.png"
srcset="../../../../../../../assets/images/[email protected] 2x"
width="123" height="25" alt="Android Developers" />
</a>
<div class="btn-quicknav" id="btn-quicknav">
<a href="#" class="arrow-inactive">Quicknav</a>
<a href="#" class="arrow-active">Quicknav</a>
</div>
</div>
<ul class="nav-x col-9">
<li class="design">
<a href="../../../../../../../design/index.html"
zh-tw-lang="設計"
zh-cn-lang="设计"
ru-lang="Проектирование"
ko-lang="디자인"
ja-lang="設計"
es-lang="Diseñar"
>Design</a></li>
<li class="develop"><a href="../../../../../../../develop/index.html"
zh-tw-lang="開發"
zh-cn-lang="开发"
ru-lang="Разработка"
ko-lang="개발"
ja-lang="開発"
es-lang="Desarrollar"
>Develop</a></li>
<li class="distribute last"><a href="../../../../../../../distribute/googleplay/index.html"
zh-tw-lang="發佈"
zh-cn-lang="分发"
ru-lang="Распространение"
ko-lang="배포"
ja-lang="配布"
es-lang="Distribuir"
>Distribute</a></li>
</ul>
<div class="menu-container">
<div class="moremenu">
<div id="more-btn"></div>
</div>
<div class="morehover" id="moremenu">
<div class="top"></div>
<div class="mid">
<div class="header">Links</div>
<ul>
<li><a href="https://play.google.com/apps/publish/" target="_googleplay">Google Play Developer Console</a></li>
<li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li>
<li><a href="../../../../../../../about/index.html">About Android</a></li>
</ul>
<div class="header">Android Sites</div>
<ul>
<li><a href="http://www.android.com">Android.com</a></li>
<li class="active"><a>Android Developers</a></li>
<li><a href="http://source.android.com">Android Open Source Project</a></li>
</ul>
<br class="clearfix" />
</div><!-- end 'mid' -->
<div class="bottom"></div>
</div><!-- end 'moremenu' -->
<div class="search" id="search-container">
<div class="search-inner">
<div id="search-btn"></div>
<div class="left"></div>
<form onsubmit="return submit_search()">
<input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../../../../../')"
onkeyup="return search_changed(event, false, '../../../../../../../')" />
</form>
<div class="right"></div>
<a class="close hide">close</a>
<div class="left"></div>
<div class="right"></div>
</div><!-- end search-inner -->
</div><!-- end search-container -->
<div class="search_filtered_wrapper reference">
<div class="suggest-card reference no-display">
<ul class="search_filtered">
</ul>
</div>
</div>
<div class="search_filtered_wrapper docs">
<div class="suggest-card dummy no-display"> </div>
<div class="suggest-card develop no-display">
<ul class="search_filtered">
</ul>
<div class="child-card guides no-display">
</div>
<div class="child-card training no-display">
</div>
<div class="child-card samples no-display">
</div>
</div>
<div class="suggest-card design no-display">
<ul class="search_filtered">
</ul>
</div>
<div class="suggest-card distribute no-display">
<ul class="search_filtered">
</ul>
</div>
</div>
</div><!-- end menu-container (search and menu widget) -->
<!-- Expanded quicknav -->
<div id="quicknav" class="col-13">
<ul>
<li class="about">
<ul>
<li><a href="../../../../../../../about/index.html">About</a></li>
<li><a href="../../../../../../../wear/index.html">Wear</a></li>
<li><a href="../../../../../../../tv/index.html">TV</a></li>
<li><a href="../../../../../../../auto/index.html">Auto</a></li>
</ul>
</li>
<li class="design">
<ul>
<li><a href="../../../../../../../design/index.html">Get Started</a></li>
<li><a href="../../../../../../../design/devices.html">Devices</a></li>
<li><a href="../../../../../../../design/style/index.html">Style</a></li>
<li><a href="../../../../../../../design/patterns/index.html">Patterns</a></li>
<li><a href="../../../../../../../design/building-blocks/index.html">Building Blocks</a></li>
<li><a href="../../../../../../../design/downloads/index.html">Downloads</a></li>
<li><a href="../../../../../../../design/videos/index.html">Videos</a></li>
</ul>
</li>
<li class="develop">
<ul>
<li><a href="../../../../../../../training/index.html"
zh-tw-lang="訓練課程"
zh-cn-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li><a href="../../../../../../../guide/index.html"
zh-tw-lang="API 指南"
zh-cn-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li><a href="../../../../../../../reference/packages.html"
zh-tw-lang="參考資源"
zh-cn-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li><a href="../../../../../../../sdk/index.html"
zh-tw-lang="相關工具"
zh-cn-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a>
</li>
<li><a href="../../../../../../../google/index.html">Google Services</a>
</li>
</ul>
</li>
<li class="distribute last">
<ul>
<li><a href="../../../../../../../distribute/googleplay/index.html">Google Play</a></li>
<li><a href="../../../../../../../distribute/essentials/index.html">Essentials</a></li>
<li><a href="../../../../../../../distribute/users/index.html">Get Users</a></li>
<li><a href="../../../../../../../distribute/engage/index.html">Engage & Retain</a></li>
<li><a href="../../../../../../../distribute/monetize/index.html">Monetize</a></li>
<li><a href="../../../../../../../distribute/tools/index.html">Tools & Reference</a></li>
<li><a href="../../../../../../../distribute/stories/index.html">Developer Stories</a></li>
</ul>
</li>
</ul>
</div><!-- /Expanded quicknav -->
</div><!-- end header-wrap.wrap -->
</div><!-- end header -->
<!-- Secondary x-nav -->
<div id="nav-x">
<div class="wrap">
<ul class="nav-x col-9 develop" style="width:100%">
<li class="training"><a href="../../../../../../../training/index.html"
zh-tw-lang="訓練課程"
zh-cn-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li class="guide"><a href="../../../../../../../guide/index.html"
zh-tw-lang="API 指南"
zh-cn-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li class="reference"><a href="../../../../../../../reference/packages.html"
zh-tw-lang="參考資源"
zh-cn-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li class="tools"><a href="../../../../../../../sdk/index.html"
zh-tw-lang="相關工具"
zh-cn-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a></li>
<li class="google"><a href="../../../../../../../google/index.html"
>Google Services</a>
</li>
</ul>
</div>
</div>
<!-- /Sendondary x-nav DEVELOP -->
<div id="searchResults" class="wrap" style="display:none;">
<h2 id="searchTitle">Results</h2>
<div id="leftSearchControl" class="search-control">Loading...</div>
</div>
</div> <!--end header-wrapper -->
<div id="sticky-header">
<div>
<a class="logo" href="#top"></a>
<a class="top" href="#top"></a>
<ul class="breadcrumb">
<li class="current">StreetViewPanoramaOrientation.Builder</li>
</ul>
</div>
</div>
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav">
<div id="api-nav-header">
<div id="api-level-toggle">
<label for="apiLevelCheckbox" class="disabled"
title="Select your target API level to dim unavailable APIs">API level: </label>
<div class="select-wrapper">
<select id="apiLevelSelector">
<!-- option elements added by buildApiLevelSelector() -->
</select>
</div>
</div><!-- end toggle -->
<div id="api-nav-title">Android APIs</div>
</div><!-- end nav header -->
<script>
var SINCE_DATA = [ ];
buildApiLevelSelector();
</script>
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav" class="scroll-pane">
<ul>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/package-summary.html">com.google.android.gms</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/actions/package-summary.html">com.google.android.gms.actions</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/package-summary.html">com.google.android.gms.ads</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/doubleclick/package-summary.html">com.google.android.gms.ads.doubleclick</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/identifier/package-summary.html">com.google.android.gms.ads.identifier</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/package-summary.html">com.google.android.gms.ads.mediation</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/admob/package-summary.html">com.google.android.gms.ads.mediation.admob</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/customevent/package-summary.html">com.google.android.gms.ads.mediation.customevent</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/purchase/package-summary.html">com.google.android.gms.ads.purchase</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/search/package-summary.html">com.google.android.gms.ads.search</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/analytics/package-summary.html">com.google.android.gms.analytics</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/analytics/ecommerce/package-summary.html">com.google.android.gms.analytics.ecommerce</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/appindexing/package-summary.html">com.google.android.gms.appindexing</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/appstate/package-summary.html">com.google.android.gms.appstate</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/auth/package-summary.html">com.google.android.gms.auth</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/auth/api/package-summary.html">com.google.android.gms.auth.api</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/cast/package-summary.html">com.google.android.gms.cast</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/package-summary.html">com.google.android.gms.common</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/annotation/package-summary.html">com.google.android.gms.common.annotation</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/api/package-summary.html">com.google.android.gms.common.api</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/data/package-summary.html">com.google.android.gms.common.data</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/images/package-summary.html">com.google.android.gms.common.images</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/package-summary.html">com.google.android.gms.drive</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/events/package-summary.html">com.google.android.gms.drive.events</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/metadata/package-summary.html">com.google.android.gms.drive.metadata</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/query/package-summary.html">com.google.android.gms.drive.query</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/widget/package-summary.html">com.google.android.gms.drive.widget</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/fitness/package-summary.html">com.google.android.gms.fitness</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/fitness/data/package-summary.html">com.google.android.gms.fitness.data</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/fitness/request/package-summary.html">com.google.android.gms.fitness.request</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/fitness/result/package-summary.html">com.google.android.gms.fitness.result</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/fitness/service/package-summary.html">com.google.android.gms.fitness.service</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/package-summary.html">com.google.android.gms.games</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/achievement/package-summary.html">com.google.android.gms.games.achievement</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/event/package-summary.html">com.google.android.gms.games.event</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/leaderboard/package-summary.html">com.google.android.gms.games.leaderboard</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/package-summary.html">com.google.android.gms.games.multiplayer</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/realtime/package-summary.html">com.google.android.gms.games.multiplayer.realtime</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/turnbased/package-summary.html">com.google.android.gms.games.multiplayer.turnbased</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/quest/package-summary.html">com.google.android.gms.games.quest</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/request/package-summary.html">com.google.android.gms.games.request</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/snapshot/package-summary.html">com.google.android.gms.games.snapshot</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/gcm/package-summary.html">com.google.android.gms.gcm</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/identity/intents/package-summary.html">com.google.android.gms.identity.intents</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/identity/intents/model/package-summary.html">com.google.android.gms.identity.intents.model</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/location/package-summary.html">com.google.android.gms.location</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/maps/package-summary.html">com.google.android.gms.maps</a></li>
<li class="selected api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/maps/model/package-summary.html">com.google.android.gms.maps.model</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/panorama/package-summary.html">com.google.android.gms.panorama</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/package-summary.html">com.google.android.gms.plus</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/model/moments/package-summary.html">com.google.android.gms.plus.model.moments</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/model/people/package-summary.html">com.google.android.gms.plus.model.people</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/security/package-summary.html">com.google.android.gms.security</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/tagmanager/package-summary.html">com.google.android.gms.tagmanager</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/wallet/package-summary.html">com.google.android.gms.wallet</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/wallet/fragment/package-summary.html">com.google.android.gms.wallet.fragment</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/wearable/package-summary.html">com.google.android.gms.wearable</a></li>
</ul><br/>
</div> <!-- end packages-nav -->
</div> <!-- end resize-packages -->
<div id="classes-nav" class="scroll-pane">
<ul>
<li><h2>Interfaces</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/TileProvider.html">TileProvider</a></li>
</ul>
</li>
<li><h2>Classes</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/BitmapDescriptor.html">BitmapDescriptor</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/BitmapDescriptorFactory.html">BitmapDescriptorFactory</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CameraPosition.html">CameraPosition</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CameraPosition.Builder.html">CameraPosition.Builder</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Circle.html">Circle</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/GroundOverlay.html">GroundOverlay</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/GroundOverlayOptions.html">GroundOverlayOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/IndoorBuilding.html">IndoorBuilding</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/IndoorLevel.html">IndoorLevel</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLngBounds.html">LatLngBounds</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLngBounds.Builder.html">LatLngBounds.Builder</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Marker.html">Marker</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/MarkerOptions.html">MarkerOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polygon.html">Polygon</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/PolygonOptions.html">PolygonOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html">Polyline</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/PolylineOptions.html">PolylineOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaCamera.html">StreetViewPanoramaCamera</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaCamera.Builder.html">StreetViewPanoramaCamera.Builder</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaLink.html">StreetViewPanoramaLink</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaLocation.html">StreetViewPanoramaLocation</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.html">StreetViewPanoramaOrientation</a></li>
<li class="selected api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.Builder.html">StreetViewPanoramaOrientation.Builder</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Tile.html">Tile</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/TileOverlay.html">TileOverlay</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/TileOverlayOptions.html">TileOverlayOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/UrlTileProvider.html">UrlTileProvider</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/VisibleRegion.html">VisibleRegion</a></li>
</ul>
</li>
<li><h2>Exceptions</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/RuntimeRemoteException.html">RuntimeRemoteException</a></li>
</ul>
</li>
</ul><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none" class="scroll-pane">
<div id="tree-list"></div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
<div id="nav-swap">
<a class="fullscreen">fullscreen</a>
<a href='#' onclick='swapNav();return false;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>
</div>
</div> <!-- end devdoc-nav -->
</div> <!-- end side-nav -->
<script type="text/javascript">
// init fullscreen based on user pref
var fullscreen = readCookie("fullscreen");
if (fullscreen != 0) {
if (fullscreen == "false") {
toggleFullscreen(false);
} else {
toggleFullscreen(true);
}
}
// init nav version for mobile
if (isMobile) {
swapNav(); // tree view should be used on mobile
$('#nav-swap').hide();
} else {
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
init_default_navtree("../../../../../../../");
}
}
// scroll the selected page into view
$(document).ready(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
</script>
<div class="col-12" id="doc-col">
<div id="api-info-block">
<div class="sum-details-links">
Summary:
<a href="#lfields">Fields</a>
| <a href="#pubctors">Ctors</a>
| <a href="#pubmethods">Methods</a>
| <a href="#inhmethods">Inherited Methods</a>
| <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a>
</div><!-- end sum-details-links -->
<div class="api-level">
</div>
</div><!-- end api-info-block -->
<!-- ======== START OF CLASS DATA ======== -->
<div id="jd-header">
public
static
final
class
<h1 itemprop="name">StreetViewPanoramaOrientation.Builder</h1>
extends <a href="http://developer.android.com/reference/java/lang/Object.html">Object</a><br/>
</div><!-- end header -->
<div id="naMessage"></div>
<div id="jd-content" class="api apilevel-">
<table class="jd-inheritance-table">
<tr>
<td colspan="2" class="jd-inheritance-class-cell"><a href="http://developer.android.com/reference/java/lang/Object.html">java.lang.Object</a></td>
</tr>
<tr>
<td class="jd-inheritance-space"> ↳</td>
<td colspan="1" class="jd-inheritance-class-cell">com.google.android.gms.maps.model.StreetViewPanoramaOrientation.Builder</td>
</tr>
</table>
<div class="jd-descr">
<h2>Class Overview</h2>
<p itemprop="articleBody">Builds Street View panorama orientations. </p>
</div><!-- jd-descr -->
<div class="jd-descr">
<h2>Summary</h2>
<!-- =========== FIELD SUMMARY =========== -->
<table id="lfields" class="jd-sumtable"><tr><th colspan="12">Fields</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
public
float</nobr></td>
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.Builder.html#bearing">bearing</a></td>
<td class="jd-descrcol" width="100%"></td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
public
float</nobr></td>
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.Builder.html#tilt">tilt</a></td>
<td class="jd-descrcol" width="100%"></td>
</tr>
</table>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<table id="pubctors" class="jd-sumtable"><tr><th colspan="12">Public Constructors</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.Builder.html#StreetViewPanoramaOrientation.Builder()">StreetViewPanoramaOrientation.Builder</a></span>()</nobr>
<div class="jd-descrdiv">Creates an empty builder.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.Builder.html#StreetViewPanoramaOrientation.Builder(com.google.android.gms.maps.model.StreetViewPanoramaOrientation)">StreetViewPanoramaOrientation.Builder</a></span>(<a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.html">StreetViewPanoramaOrientation</a> previous)</nobr>
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.Builder.html">StreetViewPanoramaOrientation.Builder</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.Builder.html#bearing(float)">bearing</a></span>(float bearing)</nobr>
<div class="jd-descrdiv">Sets the direction of the orientation, in degrees clockwise from north.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.html">StreetViewPanoramaOrientation</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.Builder.html#build()">build</a></span>()</nobr>
<div class="jd-descrdiv">Builds a <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.html">StreetViewPanoramaOrientation</a></code>.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.Builder.html">StreetViewPanoramaOrientation.Builder</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.Builder.html#tilt(float)">tilt</a></span>(float tilt)</nobr>
<div class="jd-descrdiv">Sets the angle, in degrees, of the orientation
This value is restricted to being between -90 (directly down) and 90 (directly up).</div>
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="inhmethods" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Methods</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Object" class="jd-expando-trigger closed"
><img id="inherited-methods-java.lang.Object-trigger"
src="../../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From class
<a href="http://developer.android.com/reference/java/lang/Object.html">java.lang.Object</a>
<div id="inherited-methods-java.lang.Object">
<div id="inherited-methods-java.lang.Object-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-java.lang.Object-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="http://developer.android.com/reference/java/lang/Object.html">Object</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">clone</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
boolean</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">equals</span>(<a href="http://developer.android.com/reference/java/lang/Object.html">Object</a> arg0)</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">finalize</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
<a href="http://developer.android.com/reference/java/lang/Class.html">Class</a><?></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">getClass</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">hashCode</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">notify</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">notifyAll</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="http://developer.android.com/reference/java/lang/String.html">String</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">toString</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>(long arg0, int arg1)</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>(long arg0)</nobr>
</td></tr>
</table>
</div>
</div>
</td></tr>
</table>
</div><!-- jd-descr (summary) -->
<!-- Details -->
<!-- XML Attributes -->
<!-- Enum Values -->
<!-- Constants -->
<!-- Fields -->
<!-- ========= FIELD DETAIL ======== -->
<h2>Fields</h2>
<A NAME="bearing"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
float
</span>
bearing
</h4>
<div class="api-level">
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<A NAME="tilt"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
float
</span>
tilt
</h4>
<div class="api-level">
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<!-- Public ctors -->
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<h2>Public Constructors</h2>
<A NAME="StreetViewPanoramaOrientation.Builder()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
</span>
<span class="sympad">StreetViewPanoramaOrientation.Builder</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Creates an empty builder.
</p></div>
</div>
</div>
<A NAME="StreetViewPanoramaOrientation.Builder(com.google.android.gms.maps.model.StreetViewPanoramaOrientation)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
</span>
<span class="sympad">StreetViewPanoramaOrientation.Builder</span>
<span class="normal">(<a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.html">StreetViewPanoramaOrientation</a> previous)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<!-- Protected ctors -->
<!-- ========= METHOD DETAIL ======== -->
<!-- Public methdos -->
<h2>Public Methods</h2>
<A NAME="bearing(float)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.Builder.html">StreetViewPanoramaOrientation.Builder</a>
</span>
<span class="sympad">bearing</span>
<span class="normal">(float bearing)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the direction of the orientation, in degrees clockwise from north.
</p></div>
</div>
</div>
<A NAME="build()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.html">StreetViewPanoramaOrientation</a>
</span>
<span class="sympad">build</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Builds a <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.html">StreetViewPanoramaOrientation</a></code>. </p></div>
</div>
</div>
<A NAME="tilt(float)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/StreetViewPanoramaOrientation.Builder.html">StreetViewPanoramaOrientation.Builder</a>
</span>
<span class="sympad">tilt</span>
<span class="normal">(float tilt)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the angle, in degrees, of the orientation
This value is restricted to being between -90 (directly down) and 90 (directly up).
</p></div>
</div>
</div>
<!-- ========= METHOD DETAIL ======== -->
<!-- ========= END OF CLASS DATA ========= -->
<A NAME="navbar_top"></A>
<div id="footer" class="wrap" >
<div id="copyright">
Except as noted, this content is licensed under <a
href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>.
For details and restrictions, see the <a href="../../../../../../../license.html">
Content License</a>.
</div>
<div id="build_info">
Android GmsCore 1501030 r —
<script src="../../../../../../../timestamp.js" type="text/javascript"></script>
<script>document.write(BUILD_TIMESTAMP)</script>
</div>
<div id="footerlinks">
<p>
<a href="../../../../../../../about/index.html">About Android</a> |
<a href="../../../../../../../legal.html">Legal</a> |
<a href="../../../../../../../support.html">Support</a>
</p>
</div>
</div> <!-- end footer -->
</div> <!-- jd-content -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
</body>
</html>
|
apache-2.0
|
leads-project/multicloud-mr
|
common/src/main/java/eu/leads/processor/common/infinispan/ClearCompletedRunnable.java
|
1476
|
package eu.leads.processor.common.infinispan;
import org.infinispan.commons.util.concurrent.NotifyingFuture;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ExecutionException;
/**
* Created by vagvaz on 19/05/15.
*/
public class ClearCompletedRunnable extends Thread {
private final Set<Thread> threads;
private final Queue<NotifyingFuture<Void>> concurrentQueue;
private volatile Object mutex;
public ClearCompletedRunnable(Queue<NotifyingFuture<Void>> concurrentQuue, Object mutex,
Set<Thread> threads) {
this.concurrentQueue = concurrentQuue;
this.mutex = mutex;
this.threads = threads;
}
@Override public void run() {
super.run();
Iterator<NotifyingFuture<Void>> iterator = concurrentQueue.iterator();
NotifyingFuture current = concurrentQueue.poll();
while(current != null){
try {
// iterator.next().get();
current.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// iterator.remove();
// if(iterator.next().isDone()){
// iterator.remove();
// }
current = concurrentQueue.poll();
}
// synchronized (mutex){
// threads.remove(this);
// }
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Chlorophyta/Chlorophyceae/Chlorococcales/Oocystaceae/Oocystis/Oocystis asymmetrica/README.md
|
198
|
# Oocystis asymmetrica W. West & G.S. West SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
l81893521/spring-example
|
src/test/java/com/babylove/www/spring/ioc/demo4/Demo4Test.java
|
403
|
package com.babylove.www.spring.ioc.demo4;
import org.junit.Test;
import com.babylove.www.JUnitBase;
public class Demo4Test extends JUnitBase{
public Demo4Test() {
super("classpath:/ioc/demo4.xml");
}
/**
* 直接执行即可,/iocAndAop/demo4.xml里面声明的bean的方法,会在初始化时候执行
*/
@Test
public void applicationContextAwareAndBeanNameAwareTest(){
}
}
|
apache-2.0
|
eneim/smooth-app-bar-layout
|
sample/src/main/java/me/henrytao/smoothappbarlayoutdemo/fragment/DummyNestedScrollViewFragment.java
|
3280
|
/*
* Copyright 2015 "Henry Tao <[email protected]>"
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.henrytao.smoothappbarlayoutdemo.fragment;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import me.henrytao.smoothappbarlayoutdemo.R;
public class DummyNestedScrollViewFragment extends Fragment implements ObservableScrollView {
private static final String ARG_HEADER_LAYOUT = "ARG_HEADER_LAYOUT";
private static final String ARG_TEXT = "ARG_TEXT";
public static DummyNestedScrollViewFragment newInstance(String text) {
return DummyNestedScrollViewFragment.newInstance(text, 0);
}
public static DummyNestedScrollViewFragment newInstance(String text, @LayoutRes int headerLayout) {
DummyNestedScrollViewFragment fragment = new DummyNestedScrollViewFragment();
Bundle bundle = new Bundle();
bundle.putString(ARG_TEXT, text);
bundle.putInt(ARG_HEADER_LAYOUT, headerLayout);
fragment.setArguments(bundle);
return fragment;
}
@Bind(R.id.frame_layout)
FrameLayout vFrameLayout;
@Bind(android.R.id.list)
NestedScrollView vNestedScrollView;
@Bind(R.id.text)
TextView vText;
public DummyNestedScrollViewFragment() {
// Required empty public constructor
}
@Override
public View getScrollView() {
if (isAdded()) {
return vNestedScrollView;
}
return null;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dummy_nested_scroll_view, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
vText.setText(getArgText());
int headerLayout = getArgHeaderLayout();
if (headerLayout > 0) {
vFrameLayout.removeAllViews();
vFrameLayout.addView(LayoutInflater.from(getContext()).inflate(headerLayout, null));
}
}
private int getArgHeaderLayout() {
Bundle bundle = getArguments();
if (bundle != null) {
return bundle.getInt(ARG_HEADER_LAYOUT);
}
return 0;
}
private String getArgText() {
Bundle bundle = getArguments();
if (bundle != null) {
return bundle.getString(ARG_TEXT);
}
return "";
}
}
|
apache-2.0
|
temper55/icc_vasu
|
README.md
|
11
|
# icc_vasu
|
apache-2.0
|
dice-project/DICE-Chef-Repository
|
cookbooks/scylla/test/integration/config/serverspec/config_spec.rb
|
1055
|
require 'spec_helper'
describe file('/etc/scylla/scylla.yaml') do
it { should be_file }
its(:content_as_yaml) do
should include('listen_address' => '123.135.147.159')
end
its(:content_as_yaml) do
should include('rpc_address' => '0.0.0.0')
end
its(:content_as_yaml) do
should include('broadcast_rpc_address' => '123.135.147.159')
end
its(:content_as_yaml) do
should include(
'seed_provider' => include(
'class_name' => 'org.apache.cassandra.locator.SimpleSeedProvider',
'parameters' => include(
'seeds' => '111.11.1.123,111.11.1.124'
)
)
)
end
its(:content_as_yaml) do
should include('conf_1' => 'string_value')
end
its(:content_as_yaml) do
should include('conf_2' => 123)
end
its(:content_as_yaml) do
should include(
'conf_3' => include(
'this' => 'is',
'nested' => 'dict',
'with' => %w(array of strings)
)
)
end
end
describe file('/etc/scylla/cassandra-rackdc.properties') do
it { should be_file }
end
|
apache-2.0
|
bkoelman/TestableFileSystem
|
src/Fakes.Tests/Specs/DiskSpace/InsufficientSpaceSpecs.cs
|
11685
|
using System;
using System.IO;
using FluentAssertions;
using JetBrains.Annotations;
using TestableFileSystem.Fakes.Builders;
using TestableFileSystem.Interfaces;
using Xunit;
namespace TestableFileSystem.Fakes.Tests.Specs.DiskSpace
{
public sealed class InsufficientSpaceSpecs
{
[Fact]
private void When_writing_to_file_it_must_fail()
{
// Arrange
const string path = @"C:\file.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(512))
.Build();
// Act
Action action = () => fileSystem.File.WriteAllBytes(path, BufferFactory.Create(1024));
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFileSize(fileSystem, path, 0);
AssertFreeSpaceOnDrive(fileSystem, "C:", 512);
}
[Fact]
private void When_overwriting_file_it_must_fail()
{
// Arrange
const string path = @"C:\file.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(3072))
.IncludingBinaryFile(path, BufferFactory.Create(1024))
.Build();
// Act
Action action = () => fileSystem.File.WriteAllBytes(path, BufferFactory.Create(4000));
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFreeSpaceOnDrive(fileSystem, "C:", 3072);
AssertFileSize(fileSystem, path, 0);
}
[Fact]
private void When_increasing_file_size_using_SetLength_it_must_fail()
{
// Arrange
const string path = @"C:\file.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(512))
.IncludingBinaryFile(path, BufferFactory.Create(32))
.Build();
using (IFileStream stream = fileSystem.File.OpenWrite(path))
{
byte[] buffer = BufferFactory.Create(64);
stream.Write(buffer, 0, buffer.Length);
// Act
// ReSharper disable once AccessToDisposedClosure
Action action = () => stream.SetLength(1280);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFreeSpaceOnDrive(fileSystem, "C:", 448);
}
AssertFileSize(fileSystem, path, 64);
}
[Fact]
private void When_increasing_file_size_using_Seek_followed_by_write_it_must_fail()
{
// Arrange
const string path = @"C:\file.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(512))
.IncludingBinaryFile(path, BufferFactory.Create(32))
.Build();
using (IFileStream stream = fileSystem.File.OpenWrite(path))
{
byte[] buffer = BufferFactory.Create(64);
stream.Write(buffer, 0, buffer.Length);
stream.Seek(1280, SeekOrigin.Begin);
// Act
// ReSharper disable once AccessToDisposedClosure
Action action = () => stream.WriteByte(0x33);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFreeSpaceOnDrive(fileSystem, "C:", 448);
}
AssertFileSize(fileSystem, path, 64);
}
[Fact]
private void When_increasing_file_size_using_Position_followed_by_write_it_must_fail()
{
// Arrange
const string path = @"C:\file.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(512))
.IncludingBinaryFile(path, BufferFactory.Create(32))
.Build();
using (IFileStream stream = fileSystem.File.OpenWrite(path))
{
byte[] buffer = BufferFactory.Create(64);
stream.Write(buffer, 0, buffer.Length);
stream.Position = 1280;
// Act
// ReSharper disable once AccessToDisposedClosure
Action action = () => stream.WriteByte(0x33);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFreeSpaceOnDrive(fileSystem, "C:", 448);
}
AssertFileSize(fileSystem, path, 64);
}
[Fact]
private void When_copying_file_to_same_drive_it_must_fail()
{
// Arrange
const string sourcePath = @"C:\source.txt";
const string targetPath = @"C:\target.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(1024))
.IncludingBinaryFile(sourcePath, BufferFactory.Create(768))
.Build();
// Act
Action action = () => fileSystem.File.Copy(sourcePath, targetPath);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFreeSpaceOnDrive(fileSystem, "C:", 256);
AssertFileSize(fileSystem, sourcePath, 768);
fileSystem.File.Exists(targetPath).Should().BeFalse();
}
[Fact]
private void When_copying_over_existing_file_to_same_drive_it_must_fail()
{
// Arrange
const string sourcePath = @"C:\source.txt";
const string targetPath = @"C:\target.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(1024))
.IncludingBinaryFile(sourcePath, BufferFactory.Create(768))
.IncludingEmptyFile(targetPath)
.Build();
// Act
Action action = () => fileSystem.File.Copy(sourcePath, targetPath, true);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFreeSpaceOnDrive(fileSystem, "C:", 256);
AssertFileSize(fileSystem, sourcePath, 768);
fileSystem.File.Exists(targetPath).Should().BeTrue();
}
[Fact]
private void When_copying_file_to_other_drive_it_must_fail()
{
// Arrange
const string sourcePath = @"C:\source.txt";
const string targetPath = @"D:\target.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(4096))
.IncludingBinaryFile(sourcePath, BufferFactory.Create(768))
.IncludingVolume("D:", new FakeVolumeInfoBuilder()
.OfCapacity(16384)
.WithFreeSpace(512))
.Build();
// Act
Action action = () => fileSystem.File.Copy(sourcePath, targetPath);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFreeSpaceOnDrive(fileSystem, "C:", 3328);
AssertFileSize(fileSystem, sourcePath, 768);
AssertFreeSpaceOnDrive(fileSystem, "D:", 512);
fileSystem.File.Exists(targetPath).Should().BeFalse();
}
[Fact]
private void When_copying_over_existing_file_to_other_drive_it_must_fail()
{
// Arrange
const string sourcePath = @"C:\source.txt";
const string targetPath = @"D:\target.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(4096))
.IncludingBinaryFile(sourcePath, BufferFactory.Create(768))
.IncludingVolume("D:", new FakeVolumeInfoBuilder()
.OfCapacity(16384)
.WithFreeSpace(512))
.IncludingEmptyFile(targetPath)
.Build();
// Act
Action action = () => fileSystem.File.Copy(sourcePath, targetPath, true);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFreeSpaceOnDrive(fileSystem, "C:", 3328);
AssertFileSize(fileSystem, sourcePath, 768);
AssertFreeSpaceOnDrive(fileSystem, "D:", 512);
fileSystem.File.Exists(targetPath).Should().BeTrue();
}
[Fact]
private void When_moving_file_to_other_drive_it_must_fail()
{
// Arrange
const string sourcePath = @"C:\source.txt";
const string targetPath = @"D:\target.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(4096))
.IncludingBinaryFile(sourcePath, BufferFactory.Create(768))
.IncludingVolume("D:", new FakeVolumeInfoBuilder()
.OfCapacity(16384)
.WithFreeSpace(512))
.Build();
// Act
Action action = () => fileSystem.File.Move(sourcePath, targetPath);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
// Assert
AssertFreeSpaceOnDrive(fileSystem, "C:", 3328);
AssertFileSize(fileSystem, sourcePath, 768);
AssertFreeSpaceOnDrive(fileSystem, "D:", 512);
fileSystem.File.Exists(targetPath).Should().BeFalse();
}
[AssertionMethod]
private static void AssertFileSize([NotNull] IFileSystem fileSystem, [NotNull] string path, long fileSizeExpected)
{
IFileInfo fileInfo = fileSystem.ConstructFileInfo(path);
fileInfo.Length.Should().Be(fileSizeExpected);
}
[AssertionMethod]
private static void AssertFreeSpaceOnDrive([NotNull] IFileSystem fileSystem, [NotNull] string driveName,
long freeSpaceExpected)
{
#if !NETCOREAPP1_1
IDriveInfo driveInfo = fileSystem.ConstructDriveInfo(driveName);
driveInfo.AvailableFreeSpace.Should().Be(freeSpaceExpected);
#endif
}
}
}
|
apache-2.0
|
FasterXML/jackson-jr
|
docs/javadoc/jr-objects/2.7/com/fasterxml/jackson/jr/ob/comp/class-use/SequenceComposer.html
|
9688
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_25) on Sun Jan 10 17:36:35 PST 2016 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class com.fasterxml.jackson.jr.ob.comp.SequenceComposer (jackson-jr-objects 2.7.0 API)</title>
<meta name="date" content="2016-01-10">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.fasterxml.jackson.jr.ob.comp.SequenceComposer (jackson-jr-objects 2.7.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../com/fasterxml/jackson/jr/ob/comp/SequenceComposer.html" title="class in com.fasterxml.jackson.jr.ob.comp">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/fasterxml/jackson/jr/ob/comp/class-use/SequenceComposer.html" target="_top">Frames</a></li>
<li><a href="SequenceComposer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.fasterxml.jackson.jr.ob.comp.SequenceComposer" class="title">Uses of Class<br>com.fasterxml.jackson.jr.ob.comp.SequenceComposer</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../com/fasterxml/jackson/jr/ob/comp/SequenceComposer.html" title="class in com.fasterxml.jackson.jr.ob.comp">SequenceComposer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.fasterxml.jackson.jr.ob">com.fasterxml.jackson.jr.ob</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.fasterxml.jackson.jr.ob.comp">com.fasterxml.jackson.jr.ob.comp</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.fasterxml.jackson.jr.ob">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../com/fasterxml/jackson/jr/ob/comp/SequenceComposer.html" title="class in com.fasterxml.jackson.jr.ob.comp">SequenceComposer</a> in <a href="../../../../../../../com/fasterxml/jackson/jr/ob/package-summary.html">com.fasterxml.jackson.jr.ob</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../../../com/fasterxml/jackson/jr/ob/comp/SequenceComposer.html" title="class in com.fasterxml.jackson.jr.ob.comp">SequenceComposer</a> in <a href="../../../../../../../com/fasterxml/jackson/jr/ob/package-summary.html">com.fasterxml.jackson.jr.ob</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../com/fasterxml/jackson/jr/ob/JSONComposer.html" title="class in com.fasterxml.jackson.jr.ob">JSONComposer</a><T></strong></code>
<div class="block">Root-level composer object that acts as streaming "builder"
object, using an underlying <a href="http://fasterxml.github.com/jackson-core/javadoc/2.7/com/fasterxml/jackson/core/JsonGenerator.html?is-external=true" title="class or interface in com.fasterxml.jackson.core"><code>JsonGenerator</code></a> object.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.fasterxml.jackson.jr.ob.comp">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../com/fasterxml/jackson/jr/ob/comp/SequenceComposer.html" title="class in com.fasterxml.jackson.jr.ob.comp">SequenceComposer</a> in <a href="../../../../../../../com/fasterxml/jackson/jr/ob/comp/package-summary.html">com.fasterxml.jackson.jr.ob.comp</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../../com/fasterxml/jackson/jr/ob/comp/package-summary.html">com.fasterxml.jackson.jr.ob.comp</a> with type parameters of type <a href="../../../../../../../com/fasterxml/jackson/jr/ob/comp/SequenceComposer.html" title="class in com.fasterxml.jackson.jr.ob.comp">SequenceComposer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../com/fasterxml/jackson/jr/ob/comp/SequenceComposer.html" title="class in com.fasterxml.jackson.jr.ob.comp">SequenceComposer</a><THIS extends <a href="../../../../../../../com/fasterxml/jackson/jr/ob/comp/SequenceComposer.html" title="class in com.fasterxml.jackson.jr.ob.comp">SequenceComposer</a><THIS>></strong></code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../../../com/fasterxml/jackson/jr/ob/comp/SequenceComposer.html" title="class in com.fasterxml.jackson.jr.ob.comp">SequenceComposer</a> in <a href="../../../../../../../com/fasterxml/jackson/jr/ob/comp/package-summary.html">com.fasterxml.jackson.jr.ob.comp</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../com/fasterxml/jackson/jr/ob/comp/ArrayComposer.html" title="class in com.fasterxml.jackson.jr.ob.comp">ArrayComposer</a><PARENT extends <a href="../../../../../../../com/fasterxml/jackson/jr/ob/comp/ComposerBase.html" title="class in com.fasterxml.jackson.jr.ob.comp">ComposerBase</a>></strong></code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../com/fasterxml/jackson/jr/ob/comp/SequenceComposer.html" title="class in com.fasterxml.jackson.jr.ob.comp">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/fasterxml/jackson/jr/ob/comp/class-use/SequenceComposer.html" target="_top">Frames</a></li>
<li><a href="SequenceComposer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2016 <a href="http://fasterxml.com/">FasterXML</a>. All rights reserved.</small></p>
</body>
</html>
|
apache-2.0
|
zandero/rest.vertx
|
src/test/java/com/zandero/rest/RouteRegistrationTest.java
|
2744
|
package com.zandero.rest;
import com.zandero.rest.test.*;
import com.zandero.rest.test.json.Dummy;
import com.zandero.utils.extra.JsonUtils;
import io.vertx.core.buffer.Buffer;
import io.vertx.ext.web.Router;
import io.vertx.junit5.*;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ExtendWith(VertxExtension.class)
class RouteRegistrationTest extends VertxTest {
@BeforeAll
static void start() {
before();
TestRest testRest = new TestRest();
TestPostRest testPostRest = new TestPostRest();
Router router = RestRouter.register(vertx, testRest, testPostRest);
vertx.createHttpServer()
.requestHandler(router)
.listen(PORT);
}
@Test
void registerTwoRoutesTest(VertxTestContext context) {
// check if both are active
Dummy json = new Dummy("test", "me");
// 2nd REST
client.post(PORT, HOST, "/post/json")
.putHeader("content-type", "application/json")
.sendBuffer(Buffer.buffer(JsonUtils.toJson(json)),
context.succeeding(response -> context.verify(() -> {
assertEquals(200, response.statusCode());
assertEquals("{\"name\":\"Received-test\",\"value\":\"Received-me\"}", response.bodyAsString());
context.completeNow();
})));
}
@Test
void registerTwoRoutesSeparate(VertxTestContext context) {
// check if both are active
Dummy json = new Dummy("test", "me");
client.post(PORT, HOST, "/test/json/post")
.putHeader("content-type", "application/json")
.sendBuffer(Buffer.buffer(JsonUtils.toJson(json)),
context.succeeding(response -> context.verify(() -> {
assertEquals(200, response.statusCode());
assertEquals("{\"name\":\"Received-test\",\"value\":\"Received-me\"}", response.bodyAsString());
context.completeNow();
})));
// 2nd REST
client.post(PORT, HOST, "/post/json")
.putHeader("content-type", "application/json")
.sendBuffer(Buffer.buffer(JsonUtils.toJson(json)),
context.succeeding(response -> context.verify(() -> {
assertEquals(200, response.statusCode());
assertEquals("{\"name\":\"Received-test\",\"value\":\"Received-me\"}", response.bodyAsString());
context.completeNow();
})));
}
}
|
apache-2.0
|
MicrosoftResearch/SHS
|
ASP/ASP.cs
|
5581
|
/*
* SHS -- The Scalable Hyperlink Store
*
* Copyright (c) Microsoft Corporation
* 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
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
* A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using SHS;
public class ASP {
private static void ProcessBatch(Store shs, UidState<byte> dists, UidState<long> seeds, long[] uids, byte dist, Dir dir) {
var uidSeeds = seeds.GetMany(uids);
var nborUids = shs.BatchedGetLinks(uids, dir);
var map = new UidMap(nborUids);
var distChunk = dists.GetMany(map);
var seedChunk = seeds.GetMany(map);
for (int i = 0; i < nborUids.Length; i++) {
for (int j = 0; j < nborUids[i].Length; j++) {
int x = map[nborUids[i][j]];
if (distChunk[x] > dist) {
distChunk[x] = dist;
seedChunk[x] = uidSeeds[i];
}
}
}
dists.SetMany(map, distChunk);
seeds.SetMany(map, seedChunk);
}
public static void Main(string[] args) {
if (args.Length != 3) {
Console.Error.WriteLine("Usage: SHS.ASP <leader> <store> [f|b|u]");
} else {
var sw = Stopwatch.StartNew();
var shs = new Service(args[0]).OpenStore(Guid.Parse(args[1]));
var dists = shs.AllocateUidState<byte>();
var seeds = shs.AllocateUidState<long>();
var cands = shs.AllocateUidState<bool>();
var batch = new Batch<long>(1000000);
long numCands = 0;
bool fwd = args[2] == "f" || args[2] == "u";
bool bwd = args[2] == "b" || args[2] == "u";
foreach (long u in shs.Uids()) {
batch.Add(u);
if (batch.Full || shs.IsLastUid(u)) {
int[] fwdDegs = shs.BatchedGetDegree(batch, Dir.Fwd);
int[] bwdDegs = shs.BatchedGetDegree(batch, Dir.Bwd);
bool[] isCands = new bool[batch.Count];
for (int i = 0; i < batch.Count; i++) {
isCands[i] = fwd && bwd ? fwdDegs[i] + bwdDegs[i] > 1 : fwdDegs[i] > 0 && bwdDegs[i] > 0;
if (isCands[i]) numCands++;
}
cands.SetMany(batch, isCands);
batch.Reset();
}
}
System.Random rand = new System.Random(12345);
int dim = 0;
batch = new Batch<long>(1000);
for (; (long)1 << dim <= numCands; dim++) {
long numSeeds = (long)1 << dim;
dists.SetAll(x => 0xff);
seeds.SetAll(x => -1);
double remainingSamps = numSeeds;
double remainingCands = numCands;
foreach (var uc in cands.GetAll()) {
if (uc.val) {
if (rand.NextDouble() < remainingSamps / remainingCands) {
batch.Add(uc.uid);
remainingSamps--;
}
remainingCands--;
}
if (batch.Full || shs.IsLastUid(uc.uid)) {
dists.SetMany(batch, ((long[])batch).Select(x => (byte)0).ToArray());
seeds.SetMany(batch, batch);
batch.Reset();
}
}
for (byte k = 0; k < 0xff; k++) {
long hits = 0;
foreach (var x in dists.GetAll()) {
if (x.val == k) {
batch.Add(x.uid);
hits++;
}
if (batch.Full || shs.IsLastUid(x.uid)) {
if (bwd) ProcessBatch(shs, dists, seeds, batch, (byte)(k + 1), Dir.Fwd);
if (fwd) ProcessBatch(shs, dists, seeds, batch, (byte)(k + 1), Dir.Bwd);
batch.Reset();
}
}
if (hits == 0) break;
}
using (var wr = new BinaryWriter(new GZipStream(new BufferedStream(new FileStream("sketchslice-" + args[2] + "-" + dim.ToString("d2") + ".bin", FileMode.Create, FileAccess.Write)), CompressionMode.Compress))) {
long rch = 0; // Number of reachable URls
foreach (var x in dists.GetAll().Zip(seeds.GetAll(), (d, s) => System.Tuple.Create(d, s))) {
if (x.Item1.val < 0xff) rch++;
wr.Write(x.Item1.val);
wr.Write(x.Item2.val);
}
}
}
using (var wr = new BinaryWriter(new GZipStream(new BufferedStream(new FileStream("sketches-" + args[2] + ".bin", FileMode.Create, FileAccess.Write)), CompressionMode.Compress))) {
wr.Write(dim);
var readers = new BinaryReader[dim];
for (int i = 0; i < dim; i++) {
readers[i] = new BinaryReader(new GZipStream(new BufferedStream(new FileStream("sketchslice-" + args[2] + "-" + i.ToString("d2") + ".bin", FileMode.Open, FileAccess.Read)), CompressionMode.Decompress));
}
while (true) {
try {
for (int i = 0; i < dim; i++) {
wr.Write(readers[i].ReadByte());
wr.Write(readers[i].ReadInt64());
}
} catch (EndOfStreamException) {
break;
}
}
for (int i = 0; i < dim; i++) {
readers[i].Close();
}
}
Console.WriteLine("Done. Job took {0} seconds.", 0.001 * sw.ElapsedMilliseconds);
}
}
}
|
apache-2.0
|
dcarda/aba.route.validator
|
target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_15_testAbaNumberCheck_34022_bad_1a.html
|
10978
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_15.html">Class Test_AbaRouteValidator_15</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_34022_bad
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_15.html?line=35833#src-35833" >testAbaNumberCheck_34022_bad</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:44:23
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_34022_bad</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/exceptions/AbaRouteValidationException.html?id=46#AbaRouteValidationException" title="AbaRouteValidationException" name="sl-43">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/ErrorCodes.html?id=46#ErrorCodes" title="ErrorCodes" name="sl-42">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=46#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.29411766</span>29.4%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="29.4% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:29.4%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html>
|
apache-2.0
|
dcarda/aba.route.validator
|
target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_09_testAbaNumberCheck_18430_bad_8q0.html
|
10987
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_09.html">Class Test_AbaRouteValidator_09</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_18430_bad
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_09.html?line=19867#src-19867" >testAbaNumberCheck_18430_bad</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:38:58
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_18430_bad</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/exceptions/AbaRouteValidationException.html?id=11304#AbaRouteValidationException" title="AbaRouteValidationException" name="sl-43">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/ErrorCodes.html?id=11304#ErrorCodes" title="ErrorCodes" name="sl-42">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=11304#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.29411766</span>29.4%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="29.4% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:29.4%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html>
|
apache-2.0
|
anuragkapur/cassandra-2.1.2-ak-skynet
|
apache-cassandra-2.0.15/javadoc/org/apache/cassandra/thrift/class-use/Cassandra.Processor.system_add_keyspace.html
|
4627
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_72) on Wed May 13 11:47:55 EDT 2015 -->
<title>Uses of Class org.apache.cassandra.thrift.Cassandra.Processor.system_add_keyspace (apache-cassandra API)</title>
<meta name="date" content="2015-05-13">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.cassandra.thrift.Cassandra.Processor.system_add_keyspace (apache-cassandra API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/cassandra/thrift/Cassandra.Processor.system_add_keyspace.html" title="class in org.apache.cassandra.thrift">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/thrift/class-use/Cassandra.Processor.system_add_keyspace.html" target="_top">Frames</a></li>
<li><a href="Cassandra.Processor.system_add_keyspace.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.cassandra.thrift.Cassandra.Processor.system_add_keyspace" class="title">Uses of Class<br>org.apache.cassandra.thrift.Cassandra.Processor.system_add_keyspace</h2>
</div>
<div class="classUseContainer">No usage of org.apache.cassandra.thrift.Cassandra.Processor.system_add_keyspace</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/cassandra/thrift/Cassandra.Processor.system_add_keyspace.html" title="class in org.apache.cassandra.thrift">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/thrift/class-use/Cassandra.Processor.system_add_keyspace.html" target="_top">Frames</a></li>
<li><a href="Cassandra.Processor.system_add_keyspace.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2015 The Apache Software Foundation</small></p>
</body>
</html>
|
apache-2.0
|
bjornna/hapi-fhir
|
hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/RestfulServerUtils.java
|
25340
|
package ca.uhn.fhir.rest.server;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* 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 static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBaseBinary;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IIdType;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.RuntimeResourceDefinition;
import ca.uhn.fhir.model.api.Bundle;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.api.Include;
import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum;
import ca.uhn.fhir.model.api.Tag;
import ca.uhn.fhir.model.api.TagList;
import ca.uhn.fhir.model.primitive.InstantDt;
import ca.uhn.fhir.model.valueset.BundleTypeEnum;
import ca.uhn.fhir.parser.IParser;
import ca.uhn.fhir.rest.api.PreferReturnEnum;
import ca.uhn.fhir.rest.api.SummaryEnum;
import ca.uhn.fhir.rest.method.ElementsParameter;
import ca.uhn.fhir.rest.method.RequestDetails;
import ca.uhn.fhir.rest.method.SummaryEnumParameter;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
public class RestfulServerUtils {
static final Pattern ACCEPT_HEADER_PATTERN = Pattern.compile("\\s*([a-zA-Z0-9+.*/-]+)\\s*(;\\s*([a-zA-Z]+)\\s*=\\s*([a-zA-Z0-9.]+)\\s*)?(,?)");
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(RestfulServerUtils.class);
private static final HashSet<String> TEXT_ENCODE_ELEMENTS = new HashSet<String>(Arrays.asList("Bundle", "*.text"));
public static void addProfileToBundleEntry(FhirContext theContext, IBaseResource theResource, String theServerBase) {
if (theResource instanceof IResource) {
TagList tl = ResourceMetadataKeyEnum.TAG_LIST.get((IResource) theResource);
if (tl == null) {
tl = new TagList();
ResourceMetadataKeyEnum.TAG_LIST.put((IResource) theResource, tl);
}
RuntimeResourceDefinition nextDef = theContext.getResourceDefinition(theResource);
String profile = nextDef.getResourceProfile(theServerBase);
if (isNotBlank(profile)) {
tl.add(new Tag(Tag.HL7_ORG_PROFILE_TAG, profile, null));
}
}
}
public static void configureResponseParser(RequestDetails theRequestDetails, IParser parser) {
// Pretty print
boolean prettyPrint = RestfulServerUtils.prettyPrintResponse(theRequestDetails.getServer(), theRequestDetails);
parser.setPrettyPrint(prettyPrint);
parser.setServerBaseUrl(theRequestDetails.getFhirServerBase());
// Summary mode
Set<SummaryEnum> summaryMode = RestfulServerUtils.determineSummaryMode(theRequestDetails);
// _elements
Set<String> elements = ElementsParameter.getElementsValueOrNull(theRequestDetails);
if (elements != null && summaryMode != null && !summaryMode.equals(Collections.singleton(SummaryEnum.FALSE))) {
throw new InvalidRequestException("Cannot combine the " + Constants.PARAM_SUMMARY + " and " + Constants.PARAM_ELEMENTS + " parameters");
}
Set<String> elementsAppliesTo = null;
if (elements != null && isNotBlank(theRequestDetails.getResourceName())) {
elementsAppliesTo = Collections.singleton(theRequestDetails.getResourceName());
}
if (summaryMode != null) {
if (summaryMode.contains(SummaryEnum.COUNT)) {
parser.setEncodeElements(Collections.singleton("Bundle.total"));
} else if (summaryMode.contains(SummaryEnum.TEXT)) {
parser.setEncodeElements(TEXT_ENCODE_ELEMENTS);
} else {
parser.setSuppressNarratives(summaryMode.contains(SummaryEnum.DATA));
parser.setSummaryMode(summaryMode.contains(SummaryEnum.TRUE));
}
}
if (elements != null && elements.size() > 0) {
Set<String> newElements = new HashSet<String>();
for (String next : elements) {
newElements.add("*." + next);
}
parser.setEncodeElements(newElements);
parser.setEncodeElementsAppliesToResourceTypes(elementsAppliesTo);
}
}
public static String createPagingLink(Set<Include> theIncludes, String theServerBase, String theSearchId, int theOffset, int theCount, EncodingEnum theResponseEncoding, boolean thePrettyPrint, BundleTypeEnum theBundleType) {
try {
StringBuilder b = new StringBuilder();
b.append(theServerBase);
b.append('?');
b.append(Constants.PARAM_PAGINGACTION);
b.append('=');
b.append(URLEncoder.encode(theSearchId, "UTF-8"));
b.append('&');
b.append(Constants.PARAM_PAGINGOFFSET);
b.append('=');
b.append(theOffset);
b.append('&');
b.append(Constants.PARAM_COUNT);
b.append('=');
b.append(theCount);
if (theResponseEncoding != null) {
b.append('&');
b.append(Constants.PARAM_FORMAT);
b.append('=');
b.append(theResponseEncoding.getRequestContentType());
}
if (thePrettyPrint) {
b.append('&');
b.append(Constants.PARAM_PRETTY);
b.append('=');
b.append(Constants.PARAM_PRETTY_VALUE_TRUE);
}
if (theIncludes != null) {
for (Include nextInclude : theIncludes) {
if (isNotBlank(nextInclude.getValue())) {
b.append('&');
b.append(Constants.PARAM_INCLUDE);
b.append('=');
b.append(URLEncoder.encode(nextInclude.getValue(), "UTF-8"));
}
}
}
if (theBundleType != null) {
b.append('&');
b.append(Constants.PARAM_BUNDLETYPE);
b.append('=');
b.append(theBundleType.getCode());
}
return b.toString();
} catch (UnsupportedEncodingException e) {
throw new Error("UTF-8 not supported", e);// should not happen
}
}
public static EncodingEnum determineRequestEncoding(RequestDetails theReq) {
EncodingEnum retVal = determineRequestEncodingNoDefault(theReq);
if (retVal != null) {
return retVal;
}
return EncodingEnum.XML;
}
public static EncodingEnum determineRequestEncodingNoDefault(RequestDetails theReq) {
EncodingEnum retVal = null;
Enumeration<String> acceptValues = theReq.getServletRequest().getHeaders(Constants.HEADER_CONTENT_TYPE);
if (acceptValues != null) {
while (acceptValues.hasMoreElements() && retVal == null) {
String nextAcceptHeaderValue = acceptValues.nextElement();
if (nextAcceptHeaderValue != null && isNotBlank(nextAcceptHeaderValue)) {
for (String nextPart : nextAcceptHeaderValue.split(",")) {
int scIdx = nextPart.indexOf(';');
if (scIdx == 0) {
continue;
}
if (scIdx != -1) {
nextPart = nextPart.substring(0, scIdx);
}
nextPart = nextPart.trim();
retVal = Constants.FORMAT_VAL_TO_ENCODING.get(nextPart);
if (retVal != null) {
break;
}
}
}
}
}
return retVal;
}
/**
* Returns null if the request doesn't express that it wants FHIR. If it expresses that it wants
* XML and JSON equally, returns thePrefer.
*/
public static EncodingEnum determineResponseEncodingNoDefault(HttpServletRequest theReq, EncodingEnum thePrefer) {
String[] format = theReq.getParameterValues(Constants.PARAM_FORMAT);
if (format != null) {
for (String nextFormat : format) {
EncodingEnum retVal = Constants.FORMAT_VAL_TO_ENCODING.get(nextFormat);
if (retVal != null) {
return retVal;
}
}
}
/*
* The Accept header is kind of ridiculous, e.g.
*/
// text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8, image/png, */*;q=0.5
Enumeration<String> acceptValues = theReq.getHeaders(Constants.HEADER_ACCEPT);
if (acceptValues != null) {
float bestQ = -1f;
EncodingEnum retVal = null;
while (acceptValues.hasMoreElements()) {
String nextAcceptHeaderValue = acceptValues.nextElement();
StringTokenizer tok = new StringTokenizer(nextAcceptHeaderValue, ",");
while (tok.hasMoreTokens()) {
String nextToken = tok.nextToken();
int startSpaceIndex = -1;
for (int i = 0; i < nextToken.length(); i++) {
if (nextToken.charAt(i) != ' ') {
startSpaceIndex = i;
break;
}
}
if (startSpaceIndex == -1) {
continue;
}
int endSpaceIndex = -1;
for (int i = startSpaceIndex; i < nextToken.length(); i++) {
if (nextToken.charAt(i) == ' ' || nextToken.charAt(i) == ';') {
endSpaceIndex = i;
break;
}
}
float q = 1.0f;
EncodingEnum encoding;
boolean pretty = false;
if (endSpaceIndex == -1) {
if (startSpaceIndex == 0) {
encoding = Constants.FORMAT_VAL_TO_ENCODING.get(nextToken);
} else {
encoding = Constants.FORMAT_VAL_TO_ENCODING.get(nextToken.substring(startSpaceIndex));
}
} else {
encoding = Constants.FORMAT_VAL_TO_ENCODING.get(nextToken.substring(startSpaceIndex, endSpaceIndex));
String remaining = nextToken.substring(endSpaceIndex + 1);
StringTokenizer qualifierTok = new StringTokenizer(remaining, ";");
while (qualifierTok.hasMoreTokens()) {
String nextQualifier = qualifierTok.nextToken();
int equalsIndex = nextQualifier.indexOf('=');
if (equalsIndex != -1) {
String nextQualifierKey = nextQualifier.substring(0, equalsIndex).trim();
String nextQualifierValue = nextQualifier.substring(equalsIndex+1, nextQualifier.length()).trim();
if (nextQualifierKey.equals("q")) {
try {
q = Float.parseFloat(nextQualifierValue);
q = Math.max(q, 0.0f);
} catch (NumberFormatException e) {
ourLog.debug("Invalid Accept header q value: {}", nextQualifierValue);
}
}
}
}
}
if (encoding != null) {
if (q > bestQ || (q == bestQ && encoding == thePrefer)) {
retVal = encoding;
bestQ = q;
}
}
}
//
//
//
//
// Matcher m = ACCEPT_HEADER_PATTERN.matcher(nextAcceptHeaderValue);
// float q = 1.0f;
// while (m.find()) {
// String contentTypeGroup = m.group(1);
// EncodingEnum encoding = Constants.FORMAT_VAL_TO_ENCODING.get(contentTypeGroup);
// if (encoding != null) {
//
// String name = m.group(3);
// String value = m.group(4);
// if (name != null && value != null) {
// if ("q".equals(name)) {
// try {
// q = Float.parseFloat(value);
// q = Math.max(q, 0.0f);
// } catch (NumberFormatException e) {
// ourLog.debug("Invalid Accept header q value: {}", value);
// }
// }
// }
// }
//
// if (encoding != null) {
// if (q > bestQ || (q == bestQ && encoding == thePrefer)) {
// retVal = encoding;
// bestQ = q;
// }
// }
//
// if (!",".equals(m.group(5))) {
// break;
// }
// }
//
}
return retVal;
}
return null;
}
/**
* Determine whether a response should be given in JSON or XML format based on the incoming HttpServletRequest's <code>"_format"</code> parameter and <code>"Accept:"</code> HTTP header.
*/
public static EncodingEnum determineResponseEncodingWithDefault(RestfulServer theServer, HttpServletRequest theReq) {
EncodingEnum retVal = determineResponseEncodingNoDefault(theReq, theServer.getDefaultResponseEncoding());
if (retVal == null) {
retVal = theServer.getDefaultResponseEncoding();
}
return retVal;
}
public static Set<SummaryEnum> determineSummaryMode(RequestDetails theRequest) {
Map<String, String[]> requestParams = theRequest.getParameters();
Set<SummaryEnum> retVal = SummaryEnumParameter.getSummaryValueOrNull(theRequest);
if (retVal == null) {
/*
* HAPI originally supported a custom parameter called _narrative, but this has been superceded by an official parameter called _summary
*/
String[] narrative = requestParams.get(Constants.PARAM_NARRATIVE);
if (narrative != null && narrative.length > 0) {
try {
NarrativeModeEnum narrativeMode = NarrativeModeEnum.valueOfCaseInsensitive(narrative[0]);
switch (narrativeMode) {
case NORMAL:
retVal = Collections.singleton(SummaryEnum.FALSE);
break;
case ONLY:
retVal = Collections.singleton(SummaryEnum.TEXT);
break;
case SUPPRESS:
retVal = Collections.singleton(SummaryEnum.DATA);
break;
}
} catch (IllegalArgumentException e) {
ourLog.debug("Invalid {} parameger: {}", Constants.PARAM_NARRATIVE, narrative[0]);
}
}
}
if (retVal == null) {
retVal = Collections.singleton(SummaryEnum.FALSE);
}
return retVal;
}
public static Integer extractCountParameter(RequestDetails theRequest) {
String paramName = Constants.PARAM_COUNT;
return tryToExtractNamedParameter(theRequest, paramName);
}
public static IParser getNewParser(FhirContext theContext, RequestDetails theRequestDetails) {
// Determine response encoding
EncodingEnum responseEncoding = RestfulServerUtils.determineResponseEncodingWithDefault(theRequestDetails.getServer(), theRequestDetails.getServletRequest());
IParser parser;
switch (responseEncoding) {
case JSON:
parser = theContext.newJsonParser();
break;
case XML:
default:
parser = theContext.newXmlParser();
break;
}
configureResponseParser(theRequestDetails, parser);
return parser;
}
static Writer getWriter(HttpServletResponse theHttpResponse, boolean theRespondGzip) throws UnsupportedEncodingException, IOException {
Writer writer;
if (theRespondGzip) {
theHttpResponse.addHeader(Constants.HEADER_CONTENT_ENCODING, Constants.ENCODING_GZIP);
writer = new OutputStreamWriter(new GZIPOutputStream(theHttpResponse.getOutputStream()), "UTF-8");
} else {
writer = theHttpResponse.getWriter();
}
return writer;
}
public static Set<String> parseAcceptHeaderAndReturnHighestRankedOptions(HttpServletRequest theRequest) {
Set<String> retVal = new HashSet<String>();
Enumeration<String> acceptValues = theRequest.getHeaders(Constants.HEADER_ACCEPT);
if (acceptValues != null) {
float bestQ = -1f;
while (acceptValues.hasMoreElements()) {
String nextAcceptHeaderValue = acceptValues.nextElement();
Matcher m = ACCEPT_HEADER_PATTERN.matcher(nextAcceptHeaderValue);
float q = 1.0f;
while (m.find()) {
String contentTypeGroup = m.group(1);
if (isNotBlank(contentTypeGroup)) {
String name = m.group(3);
String value = m.group(4);
if (name != null && value != null) {
if ("q".equals(name)) {
try {
q = Float.parseFloat(value);
q = Math.max(q, 0.0f);
} catch (NumberFormatException e) {
ourLog.debug("Invalid Accept header q value: {}", value);
}
}
}
if (q > bestQ) {
retVal.clear();
bestQ = q;
}
if (q == bestQ) {
retVal.add(contentTypeGroup.trim());
}
}
if (!",".equals(m.group(5))) {
break;
}
}
}
}
return retVal;
}
public static PreferReturnEnum parsePreferHeader(String theValue) {
if (isBlank(theValue)) {
return null;
}
StringTokenizer tok = new StringTokenizer(theValue, ",");
while (tok.hasMoreTokens()) {
String next = tok.nextToken();
int eqIndex = next.indexOf('=');
if (eqIndex == -1 || eqIndex >= next.length() - 2) {
continue;
}
String key = next.substring(0, eqIndex).trim();
if (key.equals(Constants.HEADER_PREFER_RETURN) == false) {
continue;
}
String value = next.substring(eqIndex + 1).trim();
if (value.length() < 2) {
continue;
}
if ('"' == value.charAt(0) && '"' == value.charAt(value.length() - 1)) {
value = value.substring(1, value.length() - 1);
}
return PreferReturnEnum.fromHeaderValue(value);
}
return null;
}
public static boolean prettyPrintResponse(RestfulServer theServer, RequestDetails theRequest) {
Map<String, String[]> requestParams = theRequest.getParameters();
String[] pretty = requestParams.get(Constants.PARAM_PRETTY);
boolean prettyPrint;
if (pretty != null && pretty.length > 0) {
if (Constants.PARAM_PRETTY_VALUE_TRUE.equals(pretty[0])) {
prettyPrint = true;
} else {
prettyPrint = false;
}
} else {
prettyPrint = theServer.isDefaultPrettyPrint();
Enumeration<String> acceptValues = theRequest.getServletRequest().getHeaders(Constants.HEADER_ACCEPT);
if (acceptValues != null) {
while (acceptValues.hasMoreElements()) {
String nextAcceptHeaderValue = acceptValues.nextElement();
if (nextAcceptHeaderValue.contains("pretty=true")) {
prettyPrint = true;
}
}
}
}
return prettyPrint;
}
public static void streamResponseAsBundle(RestfulServer theServer, HttpServletResponse theHttpResponse, Bundle bundle, String theServerBase, Set<SummaryEnum> theSummaryMode, boolean theRespondGzip,
boolean theRequestIsBrowser, RequestDetails theRequestDetails) throws IOException {
assert!theServerBase.endsWith("/");
theHttpResponse.setStatus(200);
// Determine response encoding
EncodingEnum responseEncoding = RestfulServerUtils.determineResponseEncodingWithDefault(theServer, theRequestDetails.getServletRequest());
if (theRequestIsBrowser && theServer.isUseBrowserFriendlyContentTypes()) {
theHttpResponse.setContentType(responseEncoding.getBrowserFriendlyBundleContentType());
} else {
theHttpResponse.setContentType(responseEncoding.getBundleContentType());
}
theHttpResponse.setCharacterEncoding(Constants.CHARSET_NAME_UTF8);
theServer.addHeadersToResponse(theHttpResponse);
Writer writer = RestfulServerUtils.getWriter(theHttpResponse, theRespondGzip);
try {
IParser parser = RestfulServerUtils.getNewParser(theServer.getFhirContext(), theRequestDetails);
if (theSummaryMode.contains(SummaryEnum.TEXT)) {
parser.setEncodeElements(TEXT_ENCODE_ELEMENTS);
}
parser.encodeBundleToWriter(bundle, writer);
} finally {
writer.close();
}
}
public static void streamResponseAsResource(RestfulServer theServer, HttpServletResponse theHttpResponse, IBaseResource theResource, boolean theRequestIsBrowser, Set<SummaryEnum> theSummaryMode,
int stausCode, boolean theRespondGzip, boolean theAddContentLocationHeader, RequestDetails theRequestDetails) throws IOException {
theHttpResponse.setStatus(stausCode);
// Determine response encoding
EncodingEnum responseEncoding = RestfulServerUtils.determineResponseEncodingNoDefault(theRequestDetails.getServletRequest(), theServer.getDefaultResponseEncoding());
String serverBase = theRequestDetails.getFhirServerBase();
if (theAddContentLocationHeader && theResource.getIdElement() != null && theResource.getIdElement().hasIdPart() && isNotBlank(serverBase)) {
String resName = theServer.getFhirContext().getResourceDefinition(theResource).getName();
IIdType fullId = theResource.getIdElement().withServerBase(serverBase, resName);
theHttpResponse.addHeader(Constants.HEADER_CONTENT_LOCATION, fullId.getValue());
}
if (theServer.getETagSupport() == ETagSupportEnum.ENABLED) {
if (theResource.getIdElement().hasVersionIdPart()) {
theHttpResponse.addHeader(Constants.HEADER_ETAG, "W/\"" + theResource.getIdElement().getVersionIdPart() + '"');
}
}
if (theServer.getAddProfileTag() != AddProfileTagEnum.NEVER) {
RuntimeResourceDefinition def = theServer.getFhirContext().getResourceDefinition(theResource);
if (theServer.getAddProfileTag() == AddProfileTagEnum.ALWAYS || !def.isStandardProfile()) {
addProfileToBundleEntry(theServer.getFhirContext(), theResource, serverBase);
}
}
if (theResource instanceof IBaseBinary && responseEncoding == null) {
IBaseBinary bin = (IBaseBinary) theResource;
if (isNotBlank(bin.getContentType())) {
theHttpResponse.setContentType(bin.getContentType());
} else {
theHttpResponse.setContentType(Constants.CT_OCTET_STREAM);
}
if (bin.getContent() == null || bin.getContent().length == 0) {
return;
}
// Force binary resources to download - This is a security measure to prevent
// malicious images or HTML blocks being served up as content.
theHttpResponse.addHeader(Constants.HEADER_CONTENT_DISPOSITION, "Attachment;");
theHttpResponse.setContentLength(bin.getContent().length);
ServletOutputStream oos = theHttpResponse.getOutputStream();
oos.write(bin.getContent());
oos.close();
return;
}
// Ok, we're not serving a binary resource, so apply default encoding
responseEncoding = responseEncoding != null ? responseEncoding : theServer.getDefaultResponseEncoding();
boolean encodingDomainResourceAsText = theSummaryMode.contains(SummaryEnum.TEXT);
if (encodingDomainResourceAsText) {
/*
* If the user requests "text" for a bundle, only suppress the non text elements in the Element.entry.resource parts, we're not streaming just the narrative as HTML (since bundles don't even
* have one)
*/
if ("Bundle".equals(theServer.getFhirContext().getResourceDefinition(theResource).getName())) {
encodingDomainResourceAsText = false;
}
}
if (theRequestIsBrowser && theServer.isUseBrowserFriendlyContentTypes()) {
theHttpResponse.setContentType(responseEncoding.getBrowserFriendlyBundleContentType());
} else if (encodingDomainResourceAsText) {
theHttpResponse.setContentType(Constants.CT_HTML);
} else {
theHttpResponse.setContentType(responseEncoding.getResourceContentType());
}
theHttpResponse.setCharacterEncoding(Constants.CHARSET_NAME_UTF8);
theServer.addHeadersToResponse(theHttpResponse);
if (theResource instanceof IResource) {
InstantDt lastUpdated = ResourceMetadataKeyEnum.UPDATED.get((IResource) theResource);
if (lastUpdated != null && lastUpdated.isEmpty() == false) {
theHttpResponse.addHeader(Constants.HEADER_LAST_MODIFIED, DateUtils.formatDate(lastUpdated.getValue()));
}
TagList list = (TagList) ((IResource) theResource).getResourceMetadata().get(ResourceMetadataKeyEnum.TAG_LIST);
if (list != null) {
for (Tag tag : list) {
if (StringUtils.isNotBlank(tag.getTerm())) {
theHttpResponse.addHeader(Constants.HEADER_CATEGORY, tag.toHeaderValue());
}
}
}
} else {
Date lastUpdated = ((IAnyResource) theResource).getMeta().getLastUpdated();
if (lastUpdated != null) {
theHttpResponse.addHeader(Constants.HEADER_LAST_MODIFIED, DateUtils.formatDate(lastUpdated));
}
}
Writer writer = getWriter(theHttpResponse, theRespondGzip);
try {
if (encodingDomainResourceAsText && theResource instanceof IResource) {
writer.append(((IResource) theResource).getText().getDiv().getValueAsString());
} else {
IParser parser = getNewParser(theServer.getFhirContext(), theRequestDetails);
parser.encodeResourceToWriter(theResource, writer);
}
} finally {
writer.close();
}
}
// static Integer tryToExtractNamedParameter(HttpServletRequest theRequest, String name) {
// String countString = theRequest.getParameter(name);
// Integer count = null;
// if (isNotBlank(countString)) {
// try {
// count = Integer.parseInt(countString);
// } catch (NumberFormatException e) {
// ourLog.debug("Failed to parse _count value '{}': {}", countString, e);
// }
// }
// return count;
// }
public static void validateResourceListNotNull(List<? extends IBaseResource> theResourceList) {
if (theResourceList == null) {
throw new InternalErrorException("IBundleProvider returned a null list of resources - This is not allowed");
}
}
private static enum NarrativeModeEnum {
NORMAL, ONLY, SUPPRESS;
public static NarrativeModeEnum valueOfCaseInsensitive(String theCode) {
return valueOf(NarrativeModeEnum.class, theCode.toUpperCase());
}
}
public static Integer tryToExtractNamedParameter(RequestDetails theRequest, String theParamName) {
String[] retVal = theRequest.getParameters().get(theParamName);
if (retVal == null) {
return null;
}
try {
return Integer.parseInt(retVal[0]);
} catch (NumberFormatException e) {
ourLog.debug("Failed to parse {} value '{}': {}", new Object[] {theParamName, retVal[0], e});
return null;
}
}
}
|
apache-2.0
|
janzoner/cw-omnibus
|
MapsV2/Popups/app/src/main/java/com/commonsware/android/mapsv2/popups/AbstractMapActivity.java
|
5111
|
/***
Copyright (c) 2012-2015 CommonsWare, 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.
From _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.mapsv2.popups;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.FeatureInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
public class AbstractMapActivity extends Activity {
static final String TAG_ERROR_DIALOG_FRAGMENT="errorDialog";
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return(super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.legal) {
startActivity(new Intent(this, LegalNoticesActivity.class));
return(true);
}
return super.onOptionsItemSelected(item);
}
protected boolean readyToGo() {
GoogleApiAvailability checker=
GoogleApiAvailability.getInstance();
int status=checker.isGooglePlayServicesAvailable(this);
if (status == ConnectionResult.SUCCESS) {
if (getVersionFromPackageManager(this)>=2) {
return(true);
}
else {
Toast.makeText(this, R.string.no_maps, Toast.LENGTH_LONG).show();
finish();
}
}
else if (checker.isUserResolvableError(status)) {
ErrorDialogFragment.newInstance(status)
.show(getFragmentManager(),
TAG_ERROR_DIALOG_FRAGMENT);
}
else {
Toast.makeText(this, R.string.no_maps, Toast.LENGTH_LONG).show();
finish();
}
return(false);
}
public static class ErrorDialogFragment extends DialogFragment {
static final String ARG_ERROR_CODE="errorCode";
static ErrorDialogFragment newInstance(int errorCode) {
Bundle args=new Bundle();
ErrorDialogFragment result=new ErrorDialogFragment();
args.putInt(ARG_ERROR_CODE, errorCode);
result.setArguments(args);
return(result);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle args=getArguments();
GoogleApiAvailability checker=
GoogleApiAvailability.getInstance();
return(checker.getErrorDialog(getActivity(),
args.getInt(ARG_ERROR_CODE), 0));
}
@Override
public void onDismiss(DialogInterface dlg) {
if (getActivity()!=null) {
getActivity().finish();
}
}
}
// following from
// https://android.googlesource.com/platform/cts/+/master/tests/tests/graphics/src/android/opengl/cts/OpenGlEsVersionTest.java
/*
* Copyright (C) 2010 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.
*/
private static int getVersionFromPackageManager(Context context) {
PackageManager packageManager=context.getPackageManager();
FeatureInfo[] featureInfos=
packageManager.getSystemAvailableFeatures();
if (featureInfos != null && featureInfos.length > 0) {
for (FeatureInfo featureInfo : featureInfos) {
// Null feature name means this feature is the open
// gl es version feature.
if (featureInfo.name == null) {
if (featureInfo.reqGlEsVersion != FeatureInfo.GL_ES_VERSION_UNDEFINED) {
return getMajorVersion(featureInfo.reqGlEsVersion);
}
else {
return 1; // Lack of property means OpenGL ES
// version 1
}
}
}
}
return 1;
}
/** @see FeatureInfo#getGlEsVersion() */
private static int getMajorVersion(int glEsVersion) {
return((glEsVersion & 0xffff0000) >> 16);
}
}
|
apache-2.0
|
apixandru/intellij-community
|
java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodProcessor.java
|
90417
|
/*
* Copyright 2000-2017 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.refactoring.extractMethod;
import com.intellij.codeInsight.*;
import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil;
import com.intellij.codeInsight.daemon.impl.quickfix.AnonymousTargetClassPreselectionUtil;
import com.intellij.codeInsight.generation.GenerateMembersUtil;
import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.codeInsight.intention.AddAnnotationPsiFix;
import com.intellij.codeInsight.intention.impl.AddNullableNotNullAnnotationFix;
import com.intellij.codeInsight.navigation.NavigationUtil;
import com.intellij.codeInspection.dataFlow.*;
import com.intellij.codeInspection.dataFlow.instructions.BranchingInstruction;
import com.intellij.codeInspection.dataFlow.instructions.CheckReturnValueInstruction;
import com.intellij.codeInspection.dataFlow.instructions.Instruction;
import com.intellij.ide.DataManager;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.ide.util.PsiClassListCellRenderer;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Pass;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.*;
import com.intellij.psi.controlFlow.*;
import com.intellij.psi.controlFlow.ControlFlow;
import com.intellij.psi.impl.source.codeStyle.JavaCodeStyleManagerImpl;
import com.intellij.psi.scope.processor.VariablesProcessor;
import com.intellij.psi.scope.util.PsiScopesUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.*;
import com.intellij.refactoring.HelpID;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.extractMethodObject.ExtractMethodObjectHandler;
import com.intellij.refactoring.introduceField.ElementToWorkOn;
import com.intellij.refactoring.introduceVariable.IntroduceVariableBase;
import com.intellij.refactoring.util.*;
import com.intellij.refactoring.util.classMembers.ElementNeedsThis;
import com.intellij.refactoring.util.duplicates.*;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.VisibilityUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.*;
public class ExtractMethodProcessor implements MatchProvider {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.extractMethod.ExtractMethodProcessor");
protected final Project myProject;
private final Editor myEditor;
protected final PsiElement[] myElements;
private final PsiBlockStatement myEnclosingBlockStatement;
private final PsiType myForcedReturnType;
private final String myRefactoringName;
protected final String myInitialMethodName;
private final String myHelpId;
private final PsiManager myManager;
private final PsiElementFactory myElementFactory;
private final CodeStyleManager myStyleManager;
private PsiExpression myExpression;
private PsiElement myCodeFragmentMember; // parent of myCodeFragment
protected String myMethodName; // name for extracted method
protected PsiType myReturnType; // return type for extracted method
protected PsiTypeParameterList myTypeParameterList; //type parameter list of extracted method
protected VariableData[] myVariableDatum; // parameter data for extracted method
protected PsiClassType[] myThrownExceptions; // exception to declare as thrown by extracted method
protected boolean myStatic; // whether to declare extracted method static
protected PsiClass myTargetClass; // class to create the extracted method in
private PsiElement myAnchor; // anchor to insert extracted method after it
protected ControlFlowWrapper myControlFlowWrapper;
protected InputVariables myInputVariables; // input variables
protected PsiVariable[] myOutputVariables; // output variables
protected PsiVariable myOutputVariable; // the only output variable
protected PsiVariable myArtificialOutputVariable;
private Collection<PsiStatement> myExitStatements;
private boolean myHasReturnStatement; // there is a return statement
private boolean myHasReturnStatementOutput; // there is a return statement and its type is not void
protected boolean myHasExpressionOutput; // extracted code is an expression with non-void type
private boolean myNeedChangeContext; // target class is not immediate container of the code to be extracted
private boolean myShowErrorDialogs = true;
protected boolean myCanBeStatic;
protected boolean myCanBeChainedConstructor;
protected boolean myIsChainedConstructor;
private List<Match> myDuplicates;
@PsiModifier.ModifierConstant protected String myMethodVisibility = PsiModifier.PRIVATE;
protected boolean myGenerateConditionalExit;
protected PsiStatement myFirstExitStatementCopy;
protected PsiMethod myExtractedMethod;
private PsiMethodCallExpression myMethodCall;
protected boolean myNullConditionalCheck;
protected boolean myNotNullConditionalCheck;
private Nullness myNullness;
public ExtractMethodProcessor(Project project,
Editor editor,
PsiElement[] elements,
PsiType forcedReturnType,
String refactoringName,
String initialMethodName,
String helpId) {
myProject = project;
myEditor = editor;
if (elements.length != 1 || !(elements[0] instanceof PsiBlockStatement)) {
myElements = elements.length == 1 && elements[0] instanceof PsiParenthesizedExpression
? new PsiElement[] {PsiUtil.skipParenthesizedExprDown((PsiExpression)elements[0])} : elements;
myEnclosingBlockStatement = null;
}
else {
myEnclosingBlockStatement = (PsiBlockStatement)elements[0];
PsiElement[] codeBlockChildren = myEnclosingBlockStatement.getCodeBlock().getChildren();
myElements = processCodeBlockChildren(codeBlockChildren);
}
myForcedReturnType = forcedReturnType;
myRefactoringName = refactoringName;
myInitialMethodName = initialMethodName;
myHelpId = helpId;
myManager = PsiManager.getInstance(myProject);
myElementFactory = JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory();
myStyleManager = CodeStyleManager.getInstance(myProject);
}
private static PsiElement[] processCodeBlockChildren(PsiElement[] codeBlockChildren) {
int resultLast = codeBlockChildren.length;
if (codeBlockChildren.length == 0) return PsiElement.EMPTY_ARRAY;
final PsiElement first = codeBlockChildren[0];
int resultStart = 0;
if (PsiUtil.isJavaToken(first, JavaTokenType.LBRACE)) {
resultStart++;
}
final PsiElement last = codeBlockChildren[codeBlockChildren.length - 1];
if (PsiUtil.isJavaToken(last, JavaTokenType.RBRACE)) {
resultLast--;
}
final ArrayList<PsiElement> result = new ArrayList<>();
for (int i = resultStart; i < resultLast; i++) {
PsiElement element = codeBlockChildren[i];
if (!(element instanceof PsiWhiteSpace)) {
result.add(element);
}
}
return PsiUtilCore.toPsiElementArray(result);
}
/**
* Method for test purposes
*/
public void setShowErrorDialogs(boolean showErrorDialogs) {
myShowErrorDialogs = showErrorDialogs;
}
public void setChainedConstructor(final boolean isChainedConstructor) {
myIsChainedConstructor = isChainedConstructor;
}
public boolean prepare() throws PrepareFailedException {
return prepare(null);
}
/**
* Invoked in atomic action
*/
public boolean prepare(@Nullable Pass<ExtractMethodProcessor> pass) throws PrepareFailedException {
myExpression = null;
if (myElements.length == 1 && myElements[0] instanceof PsiExpression) {
final PsiExpression expression = (PsiExpression)myElements[0];
if (expression instanceof PsiAssignmentExpression && expression.getParent() instanceof PsiExpressionStatement) {
myElements[0] = expression.getParent();
}
else {
myExpression = expression;
}
}
final PsiElement codeFragment = ControlFlowUtil.findCodeFragment(myElements[0]);
myCodeFragmentMember = codeFragment.getUserData(ElementToWorkOn.PARENT);
if (myCodeFragmentMember == null) {
myCodeFragmentMember = codeFragment.getParent();
}
if (myCodeFragmentMember == null) {
myCodeFragmentMember = ControlFlowUtil.findCodeFragment(codeFragment.getContext()).getParent();
}
myControlFlowWrapper = new ControlFlowWrapper(myProject, codeFragment, myElements);
try {
myExitStatements = myControlFlowWrapper.prepareExitStatements(myElements, codeFragment);
if (myControlFlowWrapper.isGenerateConditionalExit()) {
myGenerateConditionalExit = true;
} else {
myHasReturnStatement = myExpression == null && myControlFlowWrapper.isReturnPresentBetween();
}
myFirstExitStatementCopy = myControlFlowWrapper.getFirstExitStatementCopy();
}
catch (ControlFlowWrapper.ExitStatementsNotSameException e) {
myExitStatements = myControlFlowWrapper.getExitStatements();
myNotNullConditionalCheck = areAllExitPointsNotNull(getExpectedReturnType());
if (!myNotNullConditionalCheck) {
showMultipleExitPointsMessage();
return false;
}
}
myOutputVariables = myControlFlowWrapper.getOutputVariables();
return chooseTargetClass(codeFragment, pass);
}
private boolean checkExitPoints() throws PrepareFailedException {
PsiType expressionType = null;
if (myExpression != null) {
if (myForcedReturnType != null) {
expressionType = myForcedReturnType;
}
else {
expressionType = RefactoringUtil.getTypeByExpressionWithExpectedType(myExpression);
if (expressionType == null && !(myExpression.getParent() instanceof PsiExpressionStatement)) {
expressionType = PsiType.getJavaLangObject(myExpression.getManager(), GlobalSearchScope.allScope(myProject));
}
}
}
if (expressionType == null) {
expressionType = PsiType.VOID;
}
myHasExpressionOutput = !PsiType.VOID.equals(expressionType);
final PsiType returnStatementType = getExpectedReturnType();
myHasReturnStatementOutput = myHasReturnStatement && returnStatementType != null && !PsiType.VOID.equals(returnStatementType);
if (myGenerateConditionalExit && myOutputVariables.length == 1) {
if (!(myOutputVariables[0].getType() instanceof PsiPrimitiveType)) {
myNullConditionalCheck = isNullInferred(myOutputVariables[0].getName()) && getReturnsNullability(true);
}
myNotNullConditionalCheck = areAllExitPointsNotNull(returnStatementType);
}
if (!myHasReturnStatementOutput && checkOutputVariablesCount() && !myNullConditionalCheck && !myNotNullConditionalCheck) {
showMultipleOutputMessage(expressionType);
return false;
}
myOutputVariable = myOutputVariables.length > 0 ? myOutputVariables[0] : null;
if (myNotNullConditionalCheck) {
myReturnType = returnStatementType instanceof PsiPrimitiveType ? ((PsiPrimitiveType)returnStatementType).getBoxedType(myCodeFragmentMember)
: returnStatementType;
} else if (myHasReturnStatementOutput) {
myReturnType = returnStatementType;
}
else if (myOutputVariable != null) {
myReturnType = myOutputVariable.getType();
}
else if (myGenerateConditionalExit) {
myReturnType = PsiType.BOOLEAN;
}
else {
myReturnType = expressionType;
}
PsiElement container = PsiTreeUtil.getParentOfType(myElements[0], PsiClass.class, PsiMethod.class);
while (container instanceof PsiMethod && ((PsiMethod)container).getContainingClass() != myTargetClass) {
container = PsiTreeUtil.getParentOfType(container, PsiMethod.class, true);
}
if (container instanceof PsiMethod) {
PsiElement[] elements = myElements;
if (myExpression == null) {
if (myOutputVariable != null) {
elements = ArrayUtil.append(myElements, myOutputVariable, PsiElement.class);
}
if (myCodeFragmentMember instanceof PsiMethod && myReturnType == ((PsiMethod)myCodeFragmentMember).getReturnType()) {
elements = ArrayUtil.append(myElements, ((PsiMethod)myCodeFragmentMember).getReturnTypeElement(), PsiElement.class);
}
}
myTypeParameterList = RefactoringUtil.createTypeParameterListWithUsedTypeParameters(((PsiMethod)container).getTypeParameterList(),
elements);
}
List<PsiClassType> exceptions = ExceptionUtil.getThrownCheckedExceptions(myElements);
myThrownExceptions = exceptions.toArray(new PsiClassType[exceptions.size()]);
if (container instanceof PsiMethod) {
checkLocalClasses((PsiMethod) container);
}
return true;
}
private PsiType getExpectedReturnType() {
return myCodeFragmentMember instanceof PsiMethod
? ((PsiMethod)myCodeFragmentMember).getReturnType()
: myCodeFragmentMember instanceof PsiLambdaExpression
? LambdaUtil.getFunctionalInterfaceReturnType((PsiLambdaExpression)myCodeFragmentMember)
: null;
}
@Nullable
protected PsiVariable getArtificialOutputVariable() {
if (myOutputVariables.length == 0 && myExitStatements.isEmpty()) {
if (myCanBeChainedConstructor) {
final Set<PsiField> fields = new HashSet<>();
for (PsiElement element : myElements) {
element.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitReferenceExpression(PsiReferenceExpression expression) {
super.visitReferenceExpression(expression);
final PsiElement resolve = expression.resolve();
if (resolve instanceof PsiField && ((PsiField)resolve).hasModifierProperty(PsiModifier.FINAL) &&
PsiUtil.isAccessedForWriting(expression)) {
fields.add((PsiField)resolve);
}
}
});
}
if (!fields.isEmpty()) {
return fields.size() == 1 ? fields.iterator().next() : null;
}
}
final VariablesProcessor processor = new VariablesProcessor(true) {
@Override
protected boolean check(PsiVariable var, ResolveState state) {
return isDeclaredInside(var);
}
};
PsiScopesUtil.treeWalkUp(processor, myElements[myElements.length - 1], myCodeFragmentMember);
if (processor.size() == 1) {
return processor.getResult(0);
}
}
return null;
}
private boolean areAllExitPointsNotNull(PsiType returnStatementType) {
if (insertNotNullCheckIfPossible() && myControlFlowWrapper.getOutputVariables(false).length == 0) {
if (returnStatementType != null && !PsiType.VOID.equals(returnStatementType)) {
return getReturnsNullability(false);
}
}
return false;
}
/**
* @param nullsExpected when true check that all returned values are null, when false check that all returned values can't be null
*/
private boolean getReturnsNullability(boolean nullsExpected) {
PsiElement body = null;
if (myCodeFragmentMember instanceof PsiMethod) {
body = ((PsiMethod)myCodeFragmentMember).getBody();
}
else if (myCodeFragmentMember instanceof PsiLambdaExpression) {
body = ((PsiLambdaExpression)myCodeFragmentMember).getBody();
}
if (body == null) return false;
Set<PsiExpression> returnedExpressions = StreamEx.of(myExitStatements)
.select(PsiReturnStatement.class)
.map(PsiReturnStatement::getReturnValue)
.nonNull()
.toSet();
for (Iterator<PsiExpression> it = returnedExpressions.iterator(); it.hasNext(); ) {
PsiType type = it.next().getType();
if (nullsExpected) {
if (type == PsiType.NULL) {
it.remove(); // don't need to check
}
else if (type instanceof PsiPrimitiveType) {
return false;
}
}
else {
if (type == PsiType.NULL) {
return false;
}
else if (type instanceof PsiPrimitiveType) {
it.remove(); // don't need to check
}
}
}
if (returnedExpressions.isEmpty()) return true;
class ReturnChecker extends StandardInstructionVisitor {
boolean myResult = true;
@Override
public DfaInstructionState[] visitCheckReturnValue(CheckReturnValueInstruction instruction,
DataFlowRunner runner,
DfaMemoryState memState) {
PsiElement aReturn = instruction.getReturn();
if (aReturn instanceof PsiExpression && returnedExpressions.contains(aReturn)) {
myResult &= nullsExpected ? memState.isNull(memState.peek()) : memState.isNotNull(memState.peek());
}
return super.visitCheckReturnValue(instruction, runner, memState);
}
}
final StandardDataFlowRunner dfaRunner = new StandardDataFlowRunner();
final ReturnChecker returnChecker = new ReturnChecker();
if (dfaRunner.analyzeMethod(body, returnChecker) == RunnerResult.OK) {
return returnChecker.myResult;
}
return false;
}
protected boolean insertNotNullCheckIfPossible() {
return true;
}
private boolean isNullInferred(String exprText) {
final PsiCodeBlock block = myElementFactory.createCodeBlockFromText("{}", myElements[0]);
for (PsiElement element : myElements) {
block.add(element);
}
final PsiIfStatement statementFromText = (PsiIfStatement)myElementFactory.createStatementFromText("if (" + exprText + " == null);", null);
block.add(statementFromText);
final StandardDataFlowRunner dfaRunner = new StandardDataFlowRunner();
final StandardInstructionVisitor visitor = new StandardInstructionVisitor();
final RunnerResult rc = dfaRunner.analyzeMethod(block, visitor);
if (rc == RunnerResult.OK) {
final Pair<Set<Instruction>, Set<Instruction>> expressions = dfaRunner.getConstConditionalExpressions();
final Set<Instruction> set = expressions.getSecond();
for (Instruction instruction : set) {
if (instruction instanceof BranchingInstruction) {
if (((BranchingInstruction)instruction).getPsiAnchor().getText().equals(statementFromText.getCondition().getText())) {
return true;
}
}
}
}
return false;
}
protected boolean checkOutputVariablesCount() {
int outputCount = (myHasExpressionOutput ? 1 : 0) + (myGenerateConditionalExit ? 1 : 0) + myOutputVariables.length;
return outputCount > 1;
}
private void checkCanBeChainedConstructor() {
if (!(myCodeFragmentMember instanceof PsiMethod)) {
return;
}
final PsiMethod method = (PsiMethod)myCodeFragmentMember;
if (!method.isConstructor() || !PsiType.VOID.equals(myReturnType)) {
return;
}
final PsiCodeBlock body = method.getBody();
if (body == null) return;
final PsiStatement[] psiStatements = body.getStatements();
if (psiStatements.length > 0 && myElements [0] == psiStatements [0]) {
myCanBeChainedConstructor = true;
}
}
private void checkLocalClasses(final PsiMethod container) throws PrepareFailedException {
final List<PsiClass> localClasses = new ArrayList<>();
container.accept(new JavaRecursiveElementWalkingVisitor() {
@Override public void visitClass(final PsiClass aClass) {
localClasses.add(aClass);
}
@Override public void visitAnonymousClass(final PsiAnonymousClass aClass) {
visitElement(aClass);
}
@Override public void visitTypeParameter(final PsiTypeParameter classParameter) {
visitElement(classParameter);
}
});
for(PsiClass localClass: localClasses) {
final boolean classExtracted = isExtractedElement(localClass);
final List<PsiElement> extractedReferences = Collections.synchronizedList(new ArrayList<PsiElement>());
final List<PsiElement> remainingReferences = Collections.synchronizedList(new ArrayList<PsiElement>());
ReferencesSearch.search(localClass).forEach(psiReference -> {
final PsiElement element = psiReference.getElement();
final boolean elementExtracted = isExtractedElement(element);
if (elementExtracted && !classExtracted) {
extractedReferences.add(element);
return false;
}
if (!elementExtracted && classExtracted) {
remainingReferences.add(element);
return false;
}
return true;
});
if (!extractedReferences.isEmpty()) {
throw new PrepareFailedException("Cannot extract method because the selected code fragment uses local classes defined outside of the fragment", extractedReferences.get(0));
}
if (!remainingReferences.isEmpty()) {
throw new PrepareFailedException("Cannot extract method because the selected code fragment defines local classes used outside of the fragment", remainingReferences.get(0));
}
if (classExtracted) {
for (PsiVariable variable : myControlFlowWrapper.getUsedVariables()) {
if (isDeclaredInside(variable) && !variable.equals(myOutputVariable) && PsiUtil.resolveClassInType(variable.getType()) == localClass) {
throw new PrepareFailedException("Cannot extract method because the selected code fragment defines variable of local class type used outside of the fragment", variable);
}
}
}
}
}
private boolean isExtractedElement(final PsiElement element) {
boolean isExtracted = false;
for(PsiElement psiElement: myElements) {
if (PsiTreeUtil.isAncestor(psiElement, element, false)) {
isExtracted = true;
break;
}
}
return isExtracted;
}
private boolean shouldBeStatic() {
for(PsiElement element: myElements) {
final PsiExpressionStatement statement = PsiTreeUtil.getParentOfType(element, PsiExpressionStatement.class);
if (statement != null && JavaHighlightUtil.isSuperOrThisCall(statement, true, true)) {
return true;
}
}
PsiElement codeFragmentMember = myCodeFragmentMember;
while (codeFragmentMember != null && PsiTreeUtil.isAncestor(myTargetClass, codeFragmentMember, true)) {
if (codeFragmentMember instanceof PsiModifierListOwner && ((PsiModifierListOwner)codeFragmentMember).hasModifierProperty(PsiModifier.STATIC)) {
return true;
}
codeFragmentMember = PsiTreeUtil.getParentOfType(codeFragmentMember, PsiModifierListOwner.class, true);
}
return false;
}
public boolean showDialog(final boolean direct) {
AbstractExtractDialog dialog = createExtractMethodDialog(direct);
dialog.show();
if (!dialog.isOK()) return false;
apply(dialog);
return true;
}
protected void apply(final AbstractExtractDialog dialog) {
myMethodName = dialog.getChosenMethodName();
myVariableDatum = dialog.getChosenParameters();
myStatic = isStatic() | dialog.isMakeStatic();
myIsChainedConstructor = dialog.isChainedConstructor();
myMethodVisibility = dialog.getVisibility();
final PsiType returnType = dialog.getReturnType();
if (returnType != null) {
myReturnType = returnType;
}
}
protected AbstractExtractDialog createExtractMethodDialog(final boolean direct) {
setDataFromInputVariables();
myNullness = initNullness();
myArtificialOutputVariable = PsiType.VOID.equals(myReturnType) ? getArtificialOutputVariable() : null;
final PsiType returnType = myArtificialOutputVariable != null ? myArtificialOutputVariable.getType() : myReturnType;
return new ExtractMethodDialog(myProject, myTargetClass, myInputVariables, returnType, getTypeParameterList(),
getThrownExceptions(), isStatic(), isCanBeStatic(), myCanBeChainedConstructor,
myRefactoringName, myHelpId, myNullness, myElements) {
protected boolean areTypesDirected() {
return direct;
}
@Override
protected String[] suggestMethodNames() {
return suggestInitialMethodName();
}
@Override
protected PsiExpression[] findOccurrences() {
return ExtractMethodProcessor.this.findOccurrences();
}
@Override
protected boolean isOutputVariable(PsiVariable var) {
return ExtractMethodProcessor.this.isOutputVariable(var);
}
protected boolean isVoidReturn() {
return myArtificialOutputVariable != null && !(myArtificialOutputVariable instanceof PsiField);
}
@Override
protected void checkMethodConflicts(MultiMap<PsiElement, String> conflicts) {
super.checkMethodConflicts(conflicts);
final VariableData[] parameters = getChosenParameters();
final Map<String, PsiLocalVariable> vars = new HashMap<>();
for (PsiElement element : myElements) {
element.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitLocalVariable(PsiLocalVariable variable) {
super.visitLocalVariable(variable);
vars.put(variable.getName(), variable);
}
@Override
public void visitClass(PsiClass aClass) {}
});
}
for (VariableData parameter : parameters) {
final String paramName = parameter.name;
final PsiLocalVariable variable = vars.get(paramName);
if (variable != null) {
conflicts.putValue(variable, "Variable with name " + paramName + " is already defined in the selected scope");
}
}
}
};
}
public void setDataFromInputVariables() {
final List<VariableData> variables = myInputVariables.getInputVariables();
myVariableDatum = variables.toArray(new VariableData[variables.size()]);
}
public PsiExpression[] findOccurrences() {
if (myExpression != null) {
return new PsiExpression[] {myExpression};
}
if (myOutputVariable != null) {
final PsiElement scope = myOutputVariable instanceof PsiLocalVariable
? RefactoringUtil.getVariableScope((PsiLocalVariable)myOutputVariable)
: PsiTreeUtil.findCommonParent(myElements);
return CodeInsightUtil.findReferenceExpressions(scope, myOutputVariable);
}
final List<PsiStatement> filter = ContainerUtil.filter(myExitStatements, statement -> statement instanceof PsiReturnStatement && ((PsiReturnStatement)statement).getReturnValue() != null);
final List<PsiExpression> map = ContainerUtil.map(filter, statement -> ((PsiReturnStatement)statement).getReturnValue());
return map.toArray(new PsiExpression[map.size()]);
}
private Nullness initNullness() {
if (!PsiUtil.isLanguageLevel5OrHigher(myElements[0]) || PsiUtil.resolveClassInType(myReturnType) == null) return null;
final NullableNotNullManager manager = NullableNotNullManager.getInstance(myProject);
final PsiClass nullableAnnotationClass = JavaPsiFacade.getInstance(myProject)
.findClass(manager.getDefaultNullable(), myElements[0].getResolveScope());
if (nullableAnnotationClass != null) {
final PsiElement elementInCopy = myTargetClass.getContainingFile().copy().findElementAt(myTargetClass.getTextOffset());
final PsiClass classCopy = PsiTreeUtil.getParentOfType(elementInCopy, PsiClass.class);
if (classCopy == null) {
return null;
}
final PsiMethod emptyMethod = (PsiMethod)classCopy.addAfter(generateEmptyMethod("name", null), classCopy.getLBrace());
prepareMethodBody(emptyMethod, false);
if (myNotNullConditionalCheck || myNullConditionalCheck) {
return Nullness.NULLABLE;
}
return DfaUtil.inferMethodNullity(emptyMethod);
}
return null;
}
protected String[] suggestInitialMethodName() {
if (StringUtil.isEmpty(myInitialMethodName)) {
final Set<String> initialMethodNames = new LinkedHashSet<>();
final JavaCodeStyleManagerImpl codeStyleManager = (JavaCodeStyleManagerImpl)JavaCodeStyleManager.getInstance(myProject);
if (myExpression != null || !(myReturnType instanceof PsiPrimitiveType)) {
final String[] names = codeStyleManager.suggestVariableName(VariableKind.FIELD, null, myExpression, myReturnType).names;
for (String name : names) {
initialMethodNames.add(codeStyleManager.variableNameToPropertyName(name, VariableKind.FIELD));
}
}
if (myOutputVariable != null) {
final VariableKind outKind = codeStyleManager.getVariableKind(myOutputVariable);
final SuggestedNameInfo nameInfo = codeStyleManager
.suggestVariableName(VariableKind.FIELD, codeStyleManager.variableNameToPropertyName(myOutputVariable.getName(), outKind), null, myOutputVariable.getType());
for (String name : nameInfo.names) {
initialMethodNames.add(codeStyleManager.variableNameToPropertyName(name, VariableKind.FIELD));
}
}
final String nameByComment = getNameByComment();
final PsiField field = JavaPsiFacade.getElementFactory(myProject).createField("fieldNameToReplace", myReturnType instanceof PsiEllipsisType ? ((PsiEllipsisType)myReturnType).toArrayType() : myReturnType);
final List<String> getters = new ArrayList<>(ContainerUtil.map(initialMethodNames, propertyName -> {
if (!PsiNameHelper.getInstance(myProject).isIdentifier(propertyName)) {
LOG.info(propertyName + "; " + myExpression);
return null;
}
field.setName(propertyName);
return GenerateMembersUtil.suggestGetterName(field);
}));
ContainerUtil.addIfNotNull(getters, nameByComment);
return ArrayUtil.toStringArray(getters);
}
return new String[] {myInitialMethodName};
}
private String getNameByComment() {
PsiElement prevSibling = PsiTreeUtil.skipWhitespacesBackward(myElements[0]);
if (prevSibling instanceof PsiComment && ((PsiComment)prevSibling).getTokenType() == JavaTokenType.END_OF_LINE_COMMENT) {
final String text = StringUtil.decapitalize(StringUtil.capitalizeWords(prevSibling.getText().trim().substring(2), true)).replaceAll(" ", "");
if (PsiNameHelper.getInstance(myProject).isIdentifier(text) && text.length() < 20) {
return text;
}
}
return null;
}
public boolean isOutputVariable(PsiVariable var) {
return ArrayUtil.find(myOutputVariables, var) != -1;
}
public boolean showDialog() {
return showDialog(true);
}
@TestOnly
public void testRun() throws IncorrectOperationException {
testPrepare();
testNullness();
ExtractMethodHandler.extractMethod(myProject, this);
}
@TestOnly
public void testNullness() {
myNullness = initNullness();
}
@TestOnly
public void testPrepare() {
myInputVariables.setFoldingAvailable(myInputVariables.isFoldingSelectedByDefault());
myMethodName = myInitialMethodName;
myVariableDatum = new VariableData[myInputVariables.getInputVariables().size()];
for (int i = 0; i < myInputVariables.getInputVariables().size(); i++) {
myVariableDatum[i] = myInputVariables.getInputVariables().get(i);
}
}
@TestOnly
public void testTargetClass(PsiClass targetClass) {
if (targetClass != null) {
myTargetClass = targetClass;
myNeedChangeContext = true;
}
}
@TestOnly
public void testPrepare(PsiType returnType, boolean makeStatic) throws PrepareFailedException{
if (makeStatic) {
if (!isCanBeStatic()) {
throw new PrepareFailedException("Failed to make static", myElements[0]);
}
myInputVariables.setPassFields(true);
myStatic = true;
}
if (PsiType.VOID.equals(myReturnType)) {
myArtificialOutputVariable = getArtificialOutputVariable();
}
testPrepare();
if (returnType != null) {
myReturnType = returnType;
}
}
@TestOnly
public void doNotPassParameter(int i) {
myVariableDatum[i].passAsParameter = false;
}
@TestOnly
public void changeParamName(int i, String param) {
myVariableDatum[i].name = param;
}
/**
* Invoked in command and in atomic action
*/
public void doRefactoring() throws IncorrectOperationException {
initDuplicates();
chooseAnchor();
LogicalPosition pos1;
if (myEditor != null) {
int col = myEditor.getCaretModel().getLogicalPosition().column;
int line = myEditor.getCaretModel().getLogicalPosition().line;
pos1 = new LogicalPosition(line, col);
LogicalPosition pos = new LogicalPosition(0, 0);
myEditor.getCaretModel().moveToLogicalPosition(pos);
} else {
pos1 = null;
}
final SearchScope processConflictsScope = myMethodVisibility.equals(PsiModifier.PRIVATE) ?
new LocalSearchScope(myTargetClass) :
GlobalSearchScope.projectScope(myProject);
final Map<PsiMethodCallExpression, PsiMethod> overloadsResolveMap = new HashMap<>();
final Runnable collectOverloads = () -> ApplicationManager.getApplication().runReadAction(() -> {
Map<PsiMethodCallExpression, PsiMethod> overloads =
ExtractMethodUtil.encodeOverloadTargets(myTargetClass, processConflictsScope, myMethodName, myCodeFragmentMember);
overloadsResolveMap.putAll(overloads);
});
final Runnable extract = () -> {
doExtract();
ExtractMethodUtil.decodeOverloadTargets(overloadsResolveMap, myExtractedMethod, myCodeFragmentMember);
};
if (ApplicationManager.getApplication().isWriteAccessAllowed()) {
collectOverloads.run();
extract.run();
} else {
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(collectOverloads, "Collect overloads...", true, myProject)) return;
ApplicationManager.getApplication().runWriteAction(extract);
}
if (myEditor != null) {
myEditor.getCaretModel().moveToLogicalPosition(pos1);
int offset = myMethodCall.getMethodExpression().getTextRange().getStartOffset();
myEditor.getCaretModel().moveToOffset(offset);
myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
myEditor.getSelectionModel().removeSelection();
}
}
@Nullable
private DuplicatesFinder initDuplicates() {
List<PsiElement> elements = new ArrayList<>();
for (PsiElement element : myElements) {
if (!(element instanceof PsiWhiteSpace || element instanceof PsiComment)) {
elements.add(element);
}
}
if (myExpression != null) {
DuplicatesFinder finder = new DuplicatesFinder(PsiUtilCore.toPsiElementArray(elements), myInputVariables.copy(),
new ArrayList<>());
myDuplicates = finder.findDuplicates(myTargetClass);
return finder;
}
else if (elements.size() > 0){
DuplicatesFinder myDuplicatesFinder = new DuplicatesFinder(PsiUtilCore.toPsiElementArray(elements), myInputVariables.copy(),
myOutputVariable != null ? new VariableReturnValue(myOutputVariable) : null,
Arrays.asList(myOutputVariables));
myDuplicates = myDuplicatesFinder.findDuplicates(myTargetClass);
return myDuplicatesFinder;
} else {
myDuplicates = new ArrayList<>();
}
return null;
}
public void doExtract() throws IncorrectOperationException {
PsiMethod newMethod = generateEmptyMethod();
myExpression = myInputVariables.replaceWrappedReferences(myElements, myExpression);
renameInputVariables();
LOG.assertTrue(myElements[0].isValid());
PsiCodeBlock body = newMethod.getBody();
myMethodCall = generateMethodCall(null, true);
LOG.assertTrue(myElements[0].isValid());
final PsiStatement exitStatementCopy = prepareMethodBody(newMethod, true);
if (myExpression == null) {
if (myNeedChangeContext && isNeedToChangeCallContext()) {
for (PsiElement element : myElements) {
ChangeContextUtil.encodeContextInfo(element, false);
}
}
if (myNullConditionalCheck) {
final String varName = myOutputVariable.getName();
if (isDeclaredInside(myOutputVariable)) {
declareVariableAtMethodCallLocation(varName);
}
else {
PsiExpressionStatement assignmentExpression =
(PsiExpressionStatement)myElementFactory.createStatementFromText(varName + "=x;", null);
assignmentExpression = (PsiExpressionStatement)addToMethodCallLocation(assignmentExpression);
myMethodCall =
(PsiMethodCallExpression)((PsiAssignmentExpression)assignmentExpression.getExpression()).getRExpression().replace(myMethodCall);
}
declareNecessaryVariablesAfterCall(myOutputVariable);
PsiIfStatement ifStatement;
if (myHasReturnStatementOutput) {
ifStatement = (PsiIfStatement)myElementFactory.createStatementFromText("if (" + varName + "==null) return null;", null);
}
else if (myGenerateConditionalExit) {
if (myFirstExitStatementCopy instanceof PsiReturnStatement && ((PsiReturnStatement)myFirstExitStatementCopy).getReturnValue() != null) {
ifStatement = (PsiIfStatement)myElementFactory.createStatementFromText("if (" + varName + "==null) return null;", null);
}
else {
ifStatement = (PsiIfStatement)myElementFactory.createStatementFromText("if (" + varName + "==null) " + myFirstExitStatementCopy.getText(), null);
}
}
else {
ifStatement = (PsiIfStatement)myElementFactory.createStatementFromText("if (" + varName + "==null) return;", null);
}
ifStatement = (PsiIfStatement)addToMethodCallLocation(ifStatement);
CodeStyleManager.getInstance(myProject).reformat(ifStatement);
}
else if (myNotNullConditionalCheck) {
String varName = myOutputVariable != null ? myOutputVariable.getName() : "x";
varName = declareVariableAtMethodCallLocation(varName, myReturnType instanceof PsiPrimitiveType ? ((PsiPrimitiveType)myReturnType).getBoxedType(myCodeFragmentMember) : myReturnType);
addToMethodCallLocation(myElementFactory.createStatementFromText("if (" + varName + " != null) return " + varName + ";", null));
declareVariableReusedAfterCall(myOutputVariable);
}
else if (myGenerateConditionalExit) {
PsiIfStatement ifStatement = (PsiIfStatement)myElementFactory.createStatementFromText("if (a) b;", null);
ifStatement = (PsiIfStatement)addToMethodCallLocation(ifStatement);
myMethodCall = (PsiMethodCallExpression)ifStatement.getCondition().replace(myMethodCall);
myFirstExitStatementCopy = (PsiStatement)ifStatement.getThenBranch().replace(myFirstExitStatementCopy);
CodeStyleManager.getInstance(myProject).reformat(ifStatement);
}
else if (myOutputVariable != null || isArtificialOutputUsed()) {
boolean toDeclare = isArtificialOutputUsed() ? !(myArtificialOutputVariable instanceof PsiField) : isDeclaredInside(myOutputVariable);
String name = isArtificialOutputUsed() ? myArtificialOutputVariable.getName() : myOutputVariable.getName();
if (!toDeclare) {
PsiExpressionStatement statement = (PsiExpressionStatement)myElementFactory.createStatementFromText(name + "=x;", null);
statement = (PsiExpressionStatement)myStyleManager.reformat(statement);
statement = (PsiExpressionStatement)addToMethodCallLocation(statement);
PsiAssignmentExpression assignment = (PsiAssignmentExpression)statement.getExpression();
myMethodCall = (PsiMethodCallExpression)assignment.getRExpression().replace(myMethodCall);
}
else {
declareVariableAtMethodCallLocation(name);
}
}
else if (myHasReturnStatementOutput) {
PsiStatement statement = myElementFactory.createStatementFromText("return x;", null);
statement = (PsiStatement)addToMethodCallLocation(statement);
myMethodCall = (PsiMethodCallExpression)((PsiReturnStatement)statement).getReturnValue().replace(myMethodCall);
}
else {
PsiStatement statement = myElementFactory.createStatementFromText("x();", null);
statement = (PsiStatement)addToMethodCallLocation(statement);
myMethodCall = (PsiMethodCallExpression)((PsiExpressionStatement)statement).getExpression().replace(myMethodCall);
}
if (myHasReturnStatement && !myHasReturnStatementOutput && !hasNormalExit()) {
PsiStatement statement = myElementFactory.createStatementFromText("return;", null);
addToMethodCallLocation(statement);
}
else if (!myGenerateConditionalExit && exitStatementCopy != null) {
addToMethodCallLocation(exitStatementCopy);
}
if (!myNullConditionalCheck && !myNotNullConditionalCheck) {
declareNecessaryVariablesAfterCall(myOutputVariable);
}
deleteExtracted();
}
else {
PsiExpression expression2Replace = expressionToReplace(myExpression);
myExpression = (PsiExpression)IntroduceVariableBase.replace(expression2Replace, myMethodCall, myProject);
myMethodCall = PsiTreeUtil.getParentOfType(myExpression.findElementAt(myExpression.getText().indexOf(myMethodCall.getText())), PsiMethodCallExpression.class);
declareNecessaryVariablesAfterCall(myOutputVariable);
}
if (myAnchor instanceof PsiField) {
((PsiField)myAnchor).normalizeDeclaration();
}
adjustFinalParameters(newMethod);
int i = 0;
for (VariableData data : myVariableDatum) {
if (!data.passAsParameter) continue;
final PsiParameter psiParameter = newMethod.getParameterList().getParameters()[i++];
final PsiType paramType = psiParameter.getType();
for (PsiReference reference : ReferencesSearch.search(psiParameter, new LocalSearchScope(body))){
final PsiElement element = reference.getElement();
if (element != null) {
final PsiElement parent = element.getParent();
if (parent instanceof PsiTypeCastExpression) {
final PsiTypeCastExpression typeCastExpression = (PsiTypeCastExpression)parent;
final PsiTypeElement castType = typeCastExpression.getCastType();
if (castType != null && Comparing.equal(castType.getType(), paramType)) {
RedundantCastUtil.removeCast(typeCastExpression);
}
}
}
}
}
if (myNullness != null &&
PsiUtil.resolveClassInType(newMethod.getReturnType()) != null &&
PropertiesComponent.getInstance(myProject).getBoolean(ExtractMethodDialog.EXTRACT_METHOD_GENERATE_ANNOTATIONS, true)) {
final NullableNotNullManager notNullManager = NullableNotNullManager.getInstance(myProject);
AddNullableNotNullAnnotationFix annotationFix;
switch (myNullness) {
case NOT_NULL:
annotationFix = new AddNullableNotNullAnnotationFix(notNullManager.getDefaultNotNull(), newMethod);
break;
case NULLABLE:
annotationFix = new AddNullableNotNullAnnotationFix(notNullManager.getDefaultNullable(), newMethod);
break;
default:
annotationFix = null;
}
if (annotationFix != null) {
annotationFix.invoke(myProject, myTargetClass.getContainingFile(), newMethod, newMethod);
}
}
myExtractedMethod = addExtractedMethod(newMethod);
if (isNeedToChangeCallContext() && myNeedChangeContext) {
ChangeContextUtil.decodeContextInfo(myExtractedMethod, myTargetClass, RefactoringChangeUtil.createThisExpression(myManager, null));
if (myMethodCall.resolveMethod() != myExtractedMethod) {
final PsiReferenceExpression methodExpression = myMethodCall.getMethodExpression();
RefactoringChangeUtil.qualifyReference(methodExpression, myExtractedMethod, PsiUtil.getEnclosingStaticElement(methodExpression, myTargetClass) != null ? myTargetClass : null);
}
}
}
protected PsiExpression expressionToReplace(PsiExpression expression) {
if (expression instanceof PsiAssignmentExpression) {
return ((PsiAssignmentExpression)expression).getRExpression();
}
return expression;
}
protected PsiMethod addExtractedMethod(PsiMethod newMethod) {
return (PsiMethod)myTargetClass.addAfter(newMethod, myAnchor);
}
@Nullable
private PsiStatement prepareMethodBody(PsiMethod newMethod, boolean doExtract) {
PsiCodeBlock body = newMethod.getBody();
if (myExpression != null) {
declareNecessaryVariablesInsideBody(body);
if (myHasExpressionOutput) {
PsiReturnStatement returnStatement = (PsiReturnStatement)myElementFactory.createStatementFromText("return x;", null);
final PsiExpression returnValue = RefactoringUtil.convertInitializerToNormalExpression(myExpression, myForcedReturnType);
returnStatement.getReturnValue().replace(returnValue);
body.add(returnStatement);
}
else {
PsiExpressionStatement statement = (PsiExpressionStatement)myElementFactory.createStatementFromText("x;", null);
statement.getExpression().replace(myExpression);
body.add(statement);
}
return null;
}
final boolean hasNormalExit = hasNormalExit();
String outVariableName = myOutputVariable != null ? getNewVariableName(myOutputVariable) : null;
PsiReturnStatement returnStatement;
if (myNullConditionalCheck) {
returnStatement = (PsiReturnStatement)myElementFactory.createStatementFromText("return null;", null);
} else if (myOutputVariable != null) {
returnStatement = (PsiReturnStatement)myElementFactory.createStatementFromText("return " + outVariableName + ";", null);
}
else if (myGenerateConditionalExit) {
returnStatement = (PsiReturnStatement)myElementFactory.createStatementFromText("return true;", null);
}
else {
returnStatement = (PsiReturnStatement)myElementFactory.createStatementFromText("return;", null);
}
PsiStatement exitStatementCopy = !doExtract || myNotNullConditionalCheck ? null : myControlFlowWrapper.getExitStatementCopy(returnStatement, myElements);
declareNecessaryVariablesInsideBody(body);
body.addRange(myElements[0], myElements[myElements.length - 1]);
if (myNullConditionalCheck) {
body.add(myElementFactory.createStatementFromText("return " + myOutputVariable.getName() + ";", null));
}
else if (myNotNullConditionalCheck) {
body.add(myElementFactory.createStatementFromText("return null;", null));
}
else if (myGenerateConditionalExit) {
body.add(myElementFactory.createStatementFromText("return false;", null));
}
else if (!myHasReturnStatement && hasNormalExit && myOutputVariable != null) {
final PsiReturnStatement insertedReturnStatement = (PsiReturnStatement)body.add(returnStatement);
if (myOutputVariables.length == 1) {
final PsiExpression returnValue = insertedReturnStatement.getReturnValue();
if (returnValue instanceof PsiReferenceExpression) {
final PsiElement resolved = ((PsiReferenceExpression)returnValue).resolve();
if (resolved instanceof PsiLocalVariable && Comparing.strEqual(((PsiVariable)resolved).getName(), outVariableName)) {
final PsiStatement statement = PsiTreeUtil.getPrevSiblingOfType(insertedReturnStatement, PsiStatement.class);
if (statement instanceof PsiDeclarationStatement) {
final PsiElement[] declaredElements = ((PsiDeclarationStatement)statement).getDeclaredElements();
if (ArrayUtil.find(declaredElements, resolved) != -1) {
InlineUtil.inlineVariable((PsiVariable)resolved, ((PsiVariable)resolved).getInitializer(),
(PsiReferenceExpression)returnValue);
resolved.delete();
}
}
}
}
}
}
else if (isArtificialOutputUsed()) {
body.add(myElementFactory.createStatementFromText("return " + myArtificialOutputVariable.getName() + ";", null));
}
return exitStatementCopy;
}
private boolean isArtificialOutputUsed() {
return myArtificialOutputVariable != null && !PsiType.VOID.equals(myReturnType) && !myIsChainedConstructor;
}
private boolean hasNormalExit() {
try {
PsiCodeBlock block = JavaPsiFacade.getElementFactory(myProject).createCodeBlock();
block.addRange(myElements[0], myElements[myElements.length - 1]);
ControlFlow flow = ControlFlowFactory.getInstance(myProject).getControlFlow(block, new LocalsControlFlowPolicy(block), false, false);
return ControlFlowUtil.canCompleteNormally(flow, 0, flow.getSize());
}
catch (AnalysisCanceledException e) {
//check incomplete code as simple as possible
PsiElement lastElement = myElements[myElements.length - 1];
if (!(lastElement instanceof PsiReturnStatement || lastElement instanceof PsiBreakStatement ||
lastElement instanceof PsiContinueStatement)) {
return true;
}
return false;
}
}
protected boolean isNeedToChangeCallContext() {
return true;
}
private void declareVariableAtMethodCallLocation(String name) {
declareVariableAtMethodCallLocation(name, myReturnType);
}
private String declareVariableAtMethodCallLocation(String name, PsiType type) {
if (myControlFlowWrapper.getOutputVariables(false).length == 0) {
PsiElement lastStatement = PsiTreeUtil.getNextSiblingOfType(myEnclosingBlockStatement != null ? myEnclosingBlockStatement : myElements[myElements.length - 1], PsiStatement.class);
if (lastStatement != null) {
name = JavaCodeStyleManager.getInstance(myProject).suggestUniqueVariableName(name, lastStatement, true);
}
}
PsiDeclarationStatement statement = myElementFactory.createVariableDeclarationStatement(name, type, myMethodCall);
statement =
(PsiDeclarationStatement)JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(addToMethodCallLocation(statement));
PsiVariable var = (PsiVariable)statement.getDeclaredElements()[0];
myMethodCall = (PsiMethodCallExpression)var.getInitializer();
if (myOutputVariable != null) {
var.getModifierList().replace(myOutputVariable.getModifierList());
}
return name;
}
private void adjustFinalParameters(final PsiMethod method) throws IncorrectOperationException {
final IncorrectOperationException[] exc = new IncorrectOperationException[1];
exc[0] = null;
final PsiParameter[] parameters = method.getParameterList().getParameters();
if (parameters.length > 0) {
if (CodeStyleSettingsManager.getSettings(myProject).getCustomSettings(JavaCodeStyleSettings.class).GENERATE_FINAL_PARAMETERS) {
method.accept(new JavaRecursiveElementVisitor() {
@Override public void visitReferenceExpression(PsiReferenceExpression expression) {
final PsiElement resolved = expression.resolve();
if (resolved != null) {
final int index = ArrayUtil.find(parameters, resolved);
if (index >= 0) {
final PsiParameter param = parameters[index];
if (param.hasModifierProperty(PsiModifier.FINAL) && PsiUtil.isAccessedForWriting(expression)) {
try {
PsiUtil.setModifierProperty(param, PsiModifier.FINAL, false);
}
catch (IncorrectOperationException e) {
exc[0] = e;
}
}
}
}
super.visitReferenceExpression(expression);
}
});
}
else if (!PsiUtil.isLanguageLevel8OrHigher(myTargetClass)){
method.accept(new JavaRecursiveElementVisitor() {
@Override public void visitReferenceExpression(PsiReferenceExpression expression) {
final PsiElement resolved = expression.resolve();
final int index = ArrayUtil.find(parameters, resolved);
if (index >= 0) {
final PsiParameter param = parameters[index];
if (!param.hasModifierProperty(PsiModifier.FINAL) && RefactoringUtil.isInsideAnonymousOrLocal(expression, method)) {
try {
PsiUtil.setModifierProperty(param, PsiModifier.FINAL, true);
}
catch (IncorrectOperationException e) {
exc[0] = e;
}
}
}
super.visitReferenceExpression(expression);
}
});
}
if (exc[0] != null) {
throw exc[0];
}
}
}
public List<Match> getDuplicates() {
if (myIsChainedConstructor) {
return filterChainedConstructorDuplicates(myDuplicates);
}
return myDuplicates;
}
private static List<Match> filterChainedConstructorDuplicates(final List<Match> duplicates) {
List<Match> result = new ArrayList<>();
for(Match duplicate: duplicates) {
final PsiElement matchStart = duplicate.getMatchStart();
final PsiMethod method = PsiTreeUtil.getParentOfType(matchStart, PsiMethod.class);
if (method != null && method.isConstructor()) {
final PsiCodeBlock body = method.getBody();
if (body != null) {
final PsiStatement[] psiStatements = body.getStatements();
if (psiStatements.length > 0 && matchStart == psiStatements [0]) {
result.add(duplicate);
}
}
}
}
return result;
}
@Override
public void prepareSignature(Match match) {
MatchUtil.changeSignature(match, myExtractedMethod);
}
public PsiElement processMatch(Match match) throws IncorrectOperationException {
if (PsiTreeUtil.isContextAncestor(myExtractedMethod.getContainingClass(), match.getMatchStart(), false) &&
RefactoringUtil.isInStaticContext(match.getMatchStart(), myExtractedMethod.getContainingClass())) {
PsiUtil.setModifierProperty(myExtractedMethod, PsiModifier.STATIC, true);
}
final PsiMethodCallExpression methodCallExpression = generateMethodCall(match.getInstanceExpression(), false);
ArrayList<VariableData> datas = new ArrayList<>();
for (final VariableData variableData : myVariableDatum) {
if (variableData.passAsParameter) {
datas.add(variableData);
}
}
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject);
for (VariableData data : datas) {
final List<PsiElement> parameterValue = match.getParameterValues(data.variable);
if (parameterValue != null) {
for (PsiElement val : parameterValue) {
if (val instanceof PsiExpression) {
final PsiType exprType = ((PsiExpression)val).getType();
if (exprType != null && !TypeConversionUtil.isAssignable(data.type, exprType)) {
final PsiTypeCastExpression cast = (PsiTypeCastExpression)elementFactory.createExpressionFromText("(A)a", val);
cast.getCastType().replace(elementFactory.createTypeElement(data.type));
cast.getOperand().replace(val.copy());
val = cast;
}
}
methodCallExpression.getArgumentList().add(val);
}
} else {
methodCallExpression.getArgumentList().add(myElementFactory.createExpressionFromText(data.variable.getName(), methodCallExpression));
}
}
return match.replace(myExtractedMethod, methodCallExpression, myOutputVariable);
}
@Nullable
protected PsiMethodCallExpression getMatchMethodCallExpression(PsiElement element) {
PsiMethodCallExpression methodCallExpression = null;
if (element instanceof PsiMethodCallExpression) {
methodCallExpression = (PsiMethodCallExpression)element;
}
else if (element instanceof PsiExpressionStatement) {
final PsiExpression expression = ((PsiExpressionStatement)element).getExpression();
if (expression instanceof PsiMethodCallExpression) {
methodCallExpression = (PsiMethodCallExpression)expression;
}
else if (expression instanceof PsiAssignmentExpression) {
final PsiExpression psiExpression = ((PsiAssignmentExpression)expression).getRExpression();
if (psiExpression instanceof PsiMethodCallExpression) {
methodCallExpression = (PsiMethodCallExpression)psiExpression;
}
}
}
else if (element instanceof PsiDeclarationStatement) {
final PsiElement[] declaredElements = ((PsiDeclarationStatement)element).getDeclaredElements();
for (PsiElement declaredElement : declaredElements) {
if (declaredElement instanceof PsiLocalVariable) {
final PsiExpression initializer = ((PsiLocalVariable)declaredElement).getInitializer();
if (initializer instanceof PsiMethodCallExpression) {
methodCallExpression = (PsiMethodCallExpression)initializer;
break;
}
}
}
}
else if (element instanceof PsiIfStatement) {
PsiExpression condition = ((PsiIfStatement)element).getCondition();
if (condition instanceof PsiMethodCallExpression) {
methodCallExpression = (PsiMethodCallExpression)condition;
}
}
return methodCallExpression;
}
protected void deleteExtracted() throws IncorrectOperationException {
if (myEnclosingBlockStatement == null) {
myElements[0].getParent().deleteChildRange(myElements[0], myElements[myElements.length - 1]);
}
else {
myEnclosingBlockStatement.delete();
}
}
protected PsiElement addToMethodCallLocation(PsiStatement statement) throws IncorrectOperationException {
if (myEnclosingBlockStatement == null) {
PsiElement containingStatement = myElements[0] instanceof PsiComment ? myElements[0] : PsiTreeUtil.getParentOfType(myExpression != null ? myExpression : myElements[0], PsiStatement.class, false);
if (containingStatement == null) {
containingStatement = PsiTreeUtil.getParentOfType(myExpression != null ? myExpression : myElements[0], PsiComment.class, false);
}
return containingStatement.getParent().addBefore(statement, containingStatement);
}
else {
return myEnclosingBlockStatement.getParent().addBefore(statement, myEnclosingBlockStatement);
}
}
private void renameInputVariables() throws IncorrectOperationException {
//when multiple input variables should have the same name, unique names are generated
//without reverse, the second rename would rename variable without a prefix into second one though it was already renamed
LocalSearchScope localSearchScope = null;
for (int i = myVariableDatum.length - 1; i >= 0; i--) {
VariableData data = myVariableDatum[i];
PsiVariable variable = data.variable;
if (!data.name.equals(variable.getName()) || variable instanceof PsiField) {
if (localSearchScope == null) {
localSearchScope = new LocalSearchScope(myElements);
}
for (PsiReference reference : ReferencesSearch.search(variable, localSearchScope)) {
reference.handleElementRename(data.name);
final PsiElement element = reference.getElement();
if (element instanceof PsiReferenceExpression) {
final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)element;
final PsiExpression qualifierExpression = referenceExpression.getQualifierExpression();
if (qualifierExpression instanceof PsiThisExpression || qualifierExpression instanceof PsiSuperExpression) {
referenceExpression.setQualifierExpression(null);
}
}
}
}
}
}
public PsiClass getTargetClass() {
return myTargetClass;
}
public PsiType getReturnType() {
return myReturnType;
}
private PsiMethod generateEmptyMethod() throws IncorrectOperationException {
return generateEmptyMethod(myMethodName, null);
}
public PsiMethod generateEmptyMethod(String methodName, PsiElement context) throws IncorrectOperationException {
PsiMethod newMethod;
if (myIsChainedConstructor) {
newMethod = myElementFactory.createConstructor();
}
else {
newMethod = context != null ? myElementFactory.createMethod(methodName, myReturnType, context)
: myElementFactory.createMethod(methodName, myReturnType);
PsiUtil.setModifierProperty(newMethod, PsiModifier.STATIC, isStatic());
}
PsiUtil.setModifierProperty(newMethod, myMethodVisibility, true);
if (getTypeParameterList() != null) {
newMethod.getTypeParameterList().replace(getTypeParameterList());
}
PsiCodeBlock body = newMethod.getBody();
LOG.assertTrue(body != null);
boolean isFinal = CodeStyleSettingsManager.getSettings(myProject).getCustomSettings(JavaCodeStyleSettings.class).GENERATE_FINAL_PARAMETERS;
PsiParameterList list = newMethod.getParameterList();
for (VariableData data : myVariableDatum) {
if (data.passAsParameter) {
PsiParameter parm = myElementFactory.createParameter(data.name, data.type);
copyParamAnnotations(parm);
if (isFinal) {
PsiUtil.setModifierProperty(parm, PsiModifier.FINAL, true);
}
list.add(parm);
}
else if (defineVariablesForUnselectedParameters()){
@NonNls StringBuilder buffer = new StringBuilder();
if (isFinal) {
buffer.append("final ");
}
buffer.append("int ");
buffer.append(data.name);
buffer.append("=;");
String text = buffer.toString();
PsiDeclarationStatement declaration = (PsiDeclarationStatement)myElementFactory.createStatementFromText(text, null);
declaration = (PsiDeclarationStatement)myStyleManager.reformat(declaration);
final PsiTypeElement typeElement = myElementFactory.createTypeElement(data.type);
((PsiVariable)declaration.getDeclaredElements()[0]).getTypeElement().replace(typeElement);
body.add(declaration);
}
}
PsiReferenceList throwsList = newMethod.getThrowsList();
for (PsiClassType exception : getThrownExceptions()) {
throwsList.add(JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory().createReferenceElementByType(exception));
}
if (myTargetClass.isInterface() && PsiUtil.isLanguageLevel8OrHigher(myTargetClass)) {
final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(myCodeFragmentMember, PsiMethod.class, false);
if (containingMethod != null && containingMethod.hasModifierProperty(PsiModifier.DEFAULT)) {
PsiUtil.setModifierProperty(newMethod, PsiModifier.DEFAULT, true);
}
}
return (PsiMethod)myStyleManager.reformat(newMethod);
}
protected boolean defineVariablesForUnselectedParameters() {
return true;
}
private void copyParamAnnotations(PsiParameter parm) {
final PsiVariable variable = PsiResolveHelper.SERVICE.getInstance(myProject).resolveReferencedVariable(parm.getName(), myElements[0]);
if (variable instanceof PsiParameter) {
final PsiModifierList modifierList = variable.getModifierList();
if (modifierList != null) {
PsiModifierList parmModifierList = parm.getModifierList();
LOG.assertTrue(parmModifierList != null);
GenerateMembersUtil.copyAnnotations(modifierList, parmModifierList, SuppressWarnings.class.getName());
updateNullabilityAnnotation(parm, variable);
}
}
}
private void updateNullabilityAnnotation(@NotNull PsiParameter parm, @NotNull PsiVariable variable) {
final NullableNotNullManager nullabilityManager = NullableNotNullManager.getInstance(myProject);
final List<String> notNullAnnotations = nullabilityManager.getNotNulls();
final List<String> nullableAnnotations = nullabilityManager.getNullables();
if (AnnotationUtil.isAnnotated(variable, nullableAnnotations) ||
AnnotationUtil.isAnnotated(variable, notNullAnnotations) ||
PropertiesComponent.getInstance(myProject).getBoolean(ExtractMethodDialog.EXTRACT_METHOD_GENERATE_ANNOTATIONS, false)) {
final Boolean isNotNull = isNotNullAt(variable, myElements[0]);
if (isNotNull != null) {
final List<String> toKeep = isNotNull ? notNullAnnotations : nullableAnnotations;
final String[] toRemove = (!isNotNull ? notNullAnnotations : nullableAnnotations).toArray(ArrayUtil.EMPTY_STRING_ARRAY);
AddAnnotationPsiFix.removePhysicalAnnotations(parm, toRemove);
if (!AnnotationUtil.isAnnotated(parm, toKeep)) {
final String toAdd = isNotNull ? nullabilityManager.getDefaultNotNull() : nullabilityManager.getDefaultNullable();
final PsiAnnotation added =
AddAnnotationPsiFix.addPhysicalAnnotation(toAdd, PsiNameValuePair.EMPTY_ARRAY, parm.getModifierList());
JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(added);
}
}
}
}
@Nullable
private static Boolean isNotNullAt(@NotNull PsiVariable variable, PsiElement startElement) {
String variableName = variable.getName();
if (variableName == null) return null;
PsiElement methodOrLambdaBody = null;
if (variable instanceof PsiLocalVariable || variable instanceof PsiParameter) {
final PsiParameterListOwner methodOrLambda = PsiTreeUtil.getParentOfType(variable, PsiMethod.class, PsiLambdaExpression.class);
if (methodOrLambda != null) {
methodOrLambdaBody = methodOrLambda.getBody();
}
}
if (methodOrLambdaBody instanceof PsiCodeBlock) {
PsiElement topmostLambdaOrAnonymousClass = null;
for (PsiElement element = startElement; element != null && element != methodOrLambdaBody; element = element.getParent()) {
if (element instanceof PsiLambdaExpression || element instanceof PsiAnonymousClass) {
topmostLambdaOrAnonymousClass = element;
}
}
if (topmostLambdaOrAnonymousClass != null) {
startElement = topmostLambdaOrAnonymousClass;
}
Project project = methodOrLambdaBody.getProject();
PsiFile file = methodOrLambdaBody.getContainingFile();
final PsiFile copy = PsiFileFactory.getInstance(project)
.createFileFromText(file.getName(), file.getFileType(), file.getText(), file.getModificationStamp(), false);
PsiCodeBlock bodyCopy = findCopy(copy, methodOrLambdaBody, PsiCodeBlock.class);
PsiVariable variableCopy = findCopy(copy, variable, PsiVariable.class);
if (startElement instanceof PsiExpression) {
startElement = PsiTreeUtil.getParentOfType(startElement, PsiStatement.class);
}
if (startElement instanceof PsiStatement) {
PsiStatement startStatementCopy = findCopy(copy, startElement, PsiStatement.class);
try {
PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
startStatementCopy = wrapWithBlockStatementIfNeeded(startStatementCopy, factory);
String dummyName = JavaCodeStyleManager.getInstance(project).suggestUniqueVariableName("_Dummy_", startElement.getParent(), true);
PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement)factory.createStatementFromText(
CommonClassNames.JAVA_LANG_OBJECT + " " + dummyName + " = " + variableName + ";", startStatementCopy);
PsiElement parent = startStatementCopy.getParent();
declarationStatement = (PsiDeclarationStatement)parent.addBefore(declarationStatement, startStatementCopy);
PsiElement[] declaredElements = declarationStatement.getDeclaredElements();
PsiExpression initializer = ((PsiVariable)declaredElements[0]).getInitializer();
Nullness nullness = DfaUtil.checkNullness(variableCopy, initializer, bodyCopy);
return nullness == Nullness.NOT_NULL;
}
catch (IncorrectOperationException ignore) {
return null;
}
}
}
return null;
}
private static <T extends PsiElement> T findCopy(@NotNull PsiFile copy, @NotNull PsiElement element, @NotNull Class<T> clazz) {
TextRange range = element.getTextRange();
return CodeInsightUtil.findElementInRange(copy, range.getStartOffset(), range.getEndOffset(), clazz);
}
private static PsiStatement wrapWithBlockStatementIfNeeded(@NotNull PsiStatement statement, @NotNull PsiElementFactory factory) {
PsiElement parent = statement.getParent();
if (parent instanceof PsiLoopStatement && ((PsiLoopStatement)parent).getBody() == statement ||
parent instanceof PsiIfStatement &&
(((PsiIfStatement)parent).getThenBranch() == statement || ((PsiIfStatement)parent).getElseBranch() == statement)) {
PsiBlockStatement blockStatement = (PsiBlockStatement)factory.createStatementFromText("{}", statement);
blockStatement.getCodeBlock().add(statement);
blockStatement = (PsiBlockStatement)statement.replace(blockStatement);
return blockStatement.getCodeBlock().getStatements()[0];
}
if (parent instanceof PsiForStatement) {
if (((PsiForStatement)parent).getInitialization() == statement || ((PsiForStatement)parent).getUpdate() == statement) {
return wrapWithBlockStatementIfNeeded((PsiForStatement)parent, factory);
}
}
return statement;
}
@NotNull
protected PsiMethodCallExpression generateMethodCall(PsiExpression instanceQualifier, final boolean generateArgs) throws IncorrectOperationException {
@NonNls StringBuilder buffer = new StringBuilder();
final boolean skipInstanceQualifier;
if (myIsChainedConstructor) {
skipInstanceQualifier = true;
buffer.append(PsiKeyword.THIS);
}
else {
skipInstanceQualifier = instanceQualifier == null || instanceQualifier instanceof PsiThisExpression;
if (skipInstanceQualifier) {
if (isNeedToChangeCallContext() && myNeedChangeContext) {
boolean needsThisQualifier = false;
PsiElement parent = myCodeFragmentMember;
while (!myTargetClass.equals(parent)) {
if (parent instanceof PsiMethod) {
String methodName = ((PsiMethod)parent).getName();
if (methodName.equals(myMethodName)) {
needsThisQualifier = true;
break;
}
}
parent = parent.getParent();
}
if (needsThisQualifier) {
buffer.append(myTargetClass.getName());
buffer.append(".this.");
}
}
}
else {
buffer.append("qqq.");
}
buffer.append(myMethodName);
}
buffer.append("(");
if (generateArgs) {
int count = 0;
for (VariableData data : myVariableDatum) {
if (data.passAsParameter) {
if (count > 0) {
buffer.append(",");
}
myInputVariables.appendCallArguments(data, buffer);
count++;
}
}
}
buffer.append(")");
String text = buffer.toString();
PsiMethodCallExpression expr = (PsiMethodCallExpression)myElementFactory.createExpressionFromText(text, null);
expr = (PsiMethodCallExpression)myStyleManager.reformat(expr);
if (!skipInstanceQualifier) {
PsiExpression qualifierExpression = expr.getMethodExpression().getQualifierExpression();
LOG.assertTrue(qualifierExpression != null);
qualifierExpression.replace(instanceQualifier);
}
return (PsiMethodCallExpression)JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(expr);
}
private boolean chooseTargetClass(PsiElement codeFragment, final Pass<ExtractMethodProcessor> extractPass) throws PrepareFailedException {
final List<PsiVariable> inputVariables = myControlFlowWrapper.getInputVariables(codeFragment, myElements, myOutputVariables);
myNeedChangeContext = false;
myTargetClass = myCodeFragmentMember instanceof PsiMember
? ((PsiMember)myCodeFragmentMember).getContainingClass()
: PsiTreeUtil.getParentOfType(myCodeFragmentMember, PsiClass.class);
if (myTargetClass == null) {
LOG.error(myElements[0].getContainingFile());
}
if (!shouldAcceptCurrentTarget(extractPass, myTargetClass)) {
final LinkedHashMap<PsiClass, List<PsiVariable>> classes = new LinkedHashMap<>();
final PsiElementProcessor<PsiClass> processor = new PsiElementProcessor<PsiClass>() {
@Override
public boolean execute(@NotNull PsiClass selectedClass) {
AnonymousTargetClassPreselectionUtil.rememberSelection(selectedClass, myTargetClass);
final List<PsiVariable> array = classes.get(selectedClass);
myNeedChangeContext = myTargetClass != selectedClass;
myTargetClass = selectedClass;
if (array != null) {
for (PsiVariable variable : array) {
if (!inputVariables.contains(variable)) {
inputVariables.addAll(array);
}
}
}
try {
return applyChosenClassAndExtract(inputVariables, extractPass);
}
catch (PrepareFailedException e) {
if (myShowErrorDialogs) {
CommonRefactoringUtil
.showErrorHint(myProject, myEditor, e.getMessage(), ExtractMethodHandler.REFACTORING_NAME, HelpID.EXTRACT_METHOD);
ExtractMethodHandler.highlightPrepareError(e, e.getFile(), myEditor, myProject);
}
return false;
}
}
};
classes.put(myTargetClass, null);
PsiElement target = myTargetClass.getParent();
PsiElement targetMember = myTargetClass;
while (true) {
if (target instanceof PsiFile) break;
if (target instanceof PsiClass) {
boolean success = true;
final List<PsiVariable> array = new ArrayList<>();
for (PsiElement el : myElements) {
if (!ControlFlowUtil.collectOuterLocals(array, el, myCodeFragmentMember, targetMember)) {
success = false;
break;
}
}
if (success) {
classes.put((PsiClass)target, array);
if (shouldAcceptCurrentTarget(extractPass, target)) {
return processor.execute((PsiClass)target);
}
}
}
targetMember = target;
target = target.getParent();
}
if (classes.size() > 1) {
final PsiClass[] psiClasses = classes.keySet().toArray(new PsiClass[classes.size()]);
final PsiClass preselection = AnonymousTargetClassPreselectionUtil.getPreselection(classes.keySet(), psiClasses[0]);
NavigationUtil.getPsiElementPopup(psiClasses, new PsiClassListCellRenderer(), "Choose Destination Class", processor, preselection)
.showInBestPositionFor(myEditor);
return true;
}
}
return applyChosenClassAndExtract(inputVariables, extractPass);
}
private void declareNecessaryVariablesInsideBody(PsiCodeBlock body) throws IncorrectOperationException {
List<PsiVariable> usedVariables = myControlFlowWrapper.getUsedVariablesInBody(ControlFlowUtil.findCodeFragment(myElements[0]), myOutputVariables);
for (PsiVariable variable : usedVariables) {
boolean toDeclare = !isDeclaredInside(variable) && myInputVariables.toDeclareInsideBody(variable);
if (toDeclare) {
String name = variable.getName();
PsiDeclarationStatement statement = myElementFactory.createVariableDeclarationStatement(name, variable.getType(), null);
body.add(statement);
}
}
if (myArtificialOutputVariable instanceof PsiField && !myIsChainedConstructor) {
body.add(myElementFactory.createVariableDeclarationStatement(myArtificialOutputVariable.getName(), myArtificialOutputVariable.getType(), null));
}
}
protected void declareNecessaryVariablesAfterCall(PsiVariable outputVariable) throws IncorrectOperationException {
if (myHasExpressionOutput) return;
List<PsiVariable> usedVariables = myControlFlowWrapper.getUsedVariables();
Collection<ControlFlowUtil.VariableInfo> reassigned = myControlFlowWrapper.getInitializedTwice();
for (PsiVariable variable : usedVariables) {
boolean toDeclare = isDeclaredInside(variable) && !variable.equals(outputVariable);
if (toDeclare) {
String name = variable.getName();
PsiDeclarationStatement statement = myElementFactory.createVariableDeclarationStatement(name, variable.getType(), null);
if (reassigned.contains(new ControlFlowUtil.VariableInfo(variable, null))) {
final PsiElement[] psiElements = statement.getDeclaredElements();
assert psiElements.length > 0;
PsiVariable var = (PsiVariable) psiElements [0];
PsiUtil.setModifierProperty(var, PsiModifier.FINAL, false);
}
addToMethodCallLocation(statement);
}
}
}
public PsiMethodCallExpression getMethodCall() {
return myMethodCall;
}
public void setMethodCall(PsiMethodCallExpression methodCall) {
myMethodCall = methodCall;
}
public boolean isDeclaredInside(PsiVariable variable) {
if (variable instanceof ImplicitVariable) return false;
int startOffset;
int endOffset;
if (myExpression != null) {
final TextRange range = myExpression.getTextRange();
startOffset = range.getStartOffset();
endOffset = range.getEndOffset();
} else {
startOffset = myElements[0].getTextRange().getStartOffset();
endOffset = myElements[myElements.length - 1].getTextRange().getEndOffset();
}
PsiIdentifier nameIdentifier = variable.getNameIdentifier();
if (nameIdentifier == null) return false;
final TextRange range = nameIdentifier.getTextRange();
if (range == null) return false;
int offset = range.getStartOffset();
return startOffset <= offset && offset <= endOffset;
}
private String getNewVariableName(PsiVariable variable) {
for (VariableData data : myVariableDatum) {
if (data.variable.equals(variable)) {
return data.name;
}
}
return variable.getName();
}
private static boolean shouldAcceptCurrentTarget(Pass<ExtractMethodProcessor> extractPass, PsiElement target) {
return extractPass == null && !(target instanceof PsiAnonymousClass);
}
private boolean applyChosenClassAndExtract(List<PsiVariable> inputVariables, @Nullable Pass<ExtractMethodProcessor> extractPass)
throws PrepareFailedException {
myStatic = shouldBeStatic();
final Set<PsiField> fields = new LinkedHashSet<>();
myCanBeStatic = canBeStatic(myTargetClass, myCodeFragmentMember, myElements, fields);
myInputVariables = new InputVariables(inputVariables, myProject, new LocalSearchScope(myElements), isFoldingApplicable());
myInputVariables.setUsedInstanceFields(fields);
if (!checkExitPoints()){
return false;
}
checkCanBeChainedConstructor();
if (extractPass != null) {
extractPass.pass(this);
}
return true;
}
public static boolean canBeStatic(final PsiClass targetClass, final PsiElement place, final PsiElement[] elements, Set<PsiField> usedFields) {
if (!PsiUtil.isLocalOrAnonymousClass(targetClass) && (targetClass.getContainingClass() == null || targetClass.hasModifierProperty(PsiModifier.STATIC))) {
boolean canBeStatic = true;
if (targetClass.isInterface()) {
final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(place, PsiMethod.class, false);
canBeStatic = containingMethod == null || containingMethod.hasModifierProperty(PsiModifier.STATIC);
}
if (canBeStatic) {
ElementNeedsThis needsThis = new ElementNeedsThis(targetClass) {
@Override
protected void visitClassMemberReferenceElement(PsiMember classMember, PsiJavaCodeReferenceElement classMemberReference) {
if (classMember instanceof PsiField && !classMember.hasModifierProperty(PsiModifier.STATIC)) {
final PsiExpression expression = PsiTreeUtil.getParentOfType(classMemberReference, PsiExpression.class, false);
if (expression == null || !PsiUtil.isAccessedForWriting(expression)) {
usedFields.add((PsiField)classMember);
return;
}
}
super.visitClassMemberReferenceElement(classMember, classMemberReference);
}
};
for (int i = 0; i < elements.length && !needsThis.usesMembers(); i++) {
PsiElement element = elements[i];
element.accept(needsThis);
}
return !needsThis.usesMembers();
}
}
return false;
}
protected boolean isFoldingApplicable() {
return true;
}
protected void chooseAnchor() {
myAnchor = myCodeFragmentMember;
while (!myAnchor.getParent().equals(myTargetClass)) {
myAnchor = myAnchor.getParent();
}
}
private void declareVariableReusedAfterCall(PsiVariable variable) {
if (variable != null &&
variable.getName() != null &&
isDeclaredInside(variable) &&
myControlFlowWrapper.getUsedVariables().contains(variable) &&
!myControlFlowWrapper.needVariableValueAfterEnd(variable)) {
PsiDeclarationStatement declaration =
myElementFactory.createVariableDeclarationStatement(variable.getName(), variable.getType(), null);
addToMethodCallLocation(declaration);
}
}
private void showMultipleExitPointsMessage() {
if (myShowErrorDialogs) {
HighlightManager highlightManager = HighlightManager.getInstance(myProject);
PsiStatement[] exitStatementsArray = myExitStatements.toArray(new PsiStatement[myExitStatements.size()]);
EditorColorsManager manager = EditorColorsManager.getInstance();
TextAttributes attributes = manager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
highlightManager.addOccurrenceHighlights(myEditor, exitStatementsArray, attributes, true, null);
String message = RefactoringBundle
.getCannotRefactorMessage(RefactoringBundle.message("there.are.multiple.exit.points.in.the.selected.code.fragment"));
CommonRefactoringUtil.showErrorHint(myProject, myEditor, message, myRefactoringName, myHelpId);
WindowManager.getInstance().getStatusBar(myProject).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting"));
}
}
protected void showMultipleOutputMessage(PsiType expressionType) throws PrepareFailedException {
if (myShowErrorDialogs) {
String message = buildMultipleOutputMessageError(expressionType) + "\nWould you like to Extract Method Object?";
if (ApplicationManager.getApplication().isUnitTestMode()) throw new RuntimeException(message);
RefactoringMessageDialog dialog = new RefactoringMessageDialog(myRefactoringName, message, myHelpId, "OptionPane.errorIcon", true,
myProject);
if (dialog.showAndGet()) {
new ExtractMethodObjectHandler()
.invoke(myProject, myEditor, myTargetClass.getContainingFile(), DataManager.getInstance().getDataContext());
}
}
}
protected String buildMultipleOutputMessageError(PsiType expressionType) {
StringBuilder buffer = new StringBuilder();
buffer.append(RefactoringBundle.getCannotRefactorMessage(
RefactoringBundle.message("there.are.multiple.output.values.for.the.selected.code.fragment")));
buffer.append("\n");
if (myHasExpressionOutput) {
buffer.append(" ").append(RefactoringBundle.message("expression.result")).append(": ");
buffer.append(PsiFormatUtil.formatType(expressionType, 0, PsiSubstitutor.EMPTY));
buffer.append(",\n");
}
if (myGenerateConditionalExit) {
buffer.append(" ").append(RefactoringBundle.message("boolean.method.result"));
buffer.append(",\n");
}
for (int i = 0; i < myOutputVariables.length; i++) {
PsiVariable var = myOutputVariables[i];
buffer.append(" ");
buffer.append(var.getName());
buffer.append(" : ");
buffer.append(PsiFormatUtil.formatType(var.getType(), 0, PsiSubstitutor.EMPTY));
if (i < myOutputVariables.length - 1) {
buffer.append(",\n");
}
else {
buffer.append(".");
}
}
return buffer.toString();
}
public PsiMethod getExtractedMethod() {
return myExtractedMethod;
}
public void setMethodName(String methodName) {
myMethodName = methodName;
}
public Boolean hasDuplicates() {
List<Match> duplicates = getDuplicates();
if (duplicates != null && !duplicates.isEmpty()) {
return true;
}
if (myExtractedMethod != null) {
final ExtractMethodSignatureSuggester suggester = new ExtractMethodSignatureSuggester(myProject, myExtractedMethod, myMethodCall, myVariableDatum);
duplicates = suggester.getDuplicates(myExtractedMethod, myMethodCall, myInputVariables.getFolding());
if (duplicates != null && !duplicates.isEmpty()) {
myDuplicates = duplicates;
myExtractedMethod = suggester.getExtractedMethod();
myMethodCall = suggester.getMethodCall();
myVariableDatum = suggester.getVariableData();
final List<PsiVariable> outputVariables = new ArrayList<>();
for (PsiReturnStatement statement : PsiUtil.findReturnStatements(myExtractedMethod)) {
final PsiExpression returnValue = statement.getReturnValue();
if (returnValue instanceof PsiReferenceExpression) {
final PsiElement resolve = ((PsiReferenceExpression)returnValue).resolve();
if (resolve instanceof PsiLocalVariable) {
outputVariables.add((PsiVariable)resolve);
}
}
}
if (outputVariables.size() == 1) {
myOutputVariable = outputVariables.get(0);
}
return null;
}
}
return false;
}
public boolean hasDuplicates(Set<VirtualFile> files) {
final DuplicatesFinder finder = initDuplicates();
final Boolean hasDuplicates = hasDuplicates();
if (hasDuplicates == null || hasDuplicates) return true;
if (finder != null) {
final PsiManager psiManager = PsiManager.getInstance(myProject);
for (VirtualFile file : files) {
if (!finder.findDuplicates(psiManager.findFile(file)).isEmpty()) return true;
}
}
return false;
}
@Nullable
public String getConfirmDuplicatePrompt(Match match) {
final boolean needToBeStatic = RefactoringUtil.isInStaticContext(match.getMatchStart(), myExtractedMethod.getContainingClass());
final String changedSignature = MatchUtil
.getChangedSignature(match, myExtractedMethod, needToBeStatic, VisibilityUtil.getVisibilityStringToDisplay(myExtractedMethod));
if (changedSignature != null) {
return RefactoringBundle.message("replace.this.code.fragment.and.change.signature", changedSignature);
}
if (needToBeStatic && !myExtractedMethod.hasModifierProperty(PsiModifier.STATIC)) {
return RefactoringBundle.message("replace.this.code.fragment.and.make.method.static");
}
return null;
}
@Override
public String getReplaceDuplicatesTitle(int idx, int size) {
return RefactoringBundle.message("process.duplicates.title", idx, size);
}
public InputVariables getInputVariables() {
return myInputVariables;
}
public PsiTypeParameterList getTypeParameterList() {
return myTypeParameterList;
}
public PsiClassType[] getThrownExceptions() {
return myThrownExceptions;
}
public boolean isStatic() {
return myStatic;
}
public boolean isCanBeStatic() {
return myCanBeStatic;
}
public PsiElement[] getElements() {
return myElements;
}
public PsiVariable[] getOutputVariables() {
return myOutputVariables;
}
public void setMethodVisibility(String methodVisibility) {
myMethodVisibility = methodVisibility;
}
}
|
apache-2.0
|
Tpo76/centreon-plugins
|
hardware/devices/polycom/trio/restapi/mode/callsrt.pm
|
6715
|
#
# Copyright 2021 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# 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 hardware::devices::polycom::trio::restapi::mode::callsrt;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
use Digest::MD5 qw(md5_hex);
sub custom_loss_calc {
my ($self, %options) = @_;
$self->{result_values}->{display} = $options{new_datas}->{$self->{instance} . '_display'};
my $diff_pkts = ($options{new_datas}->{$self->{instance} . '_packets'} - $options{old_datas}->{$self->{instance} . '_packets'});
my $diff_loss = ($options{new_datas}->{$self->{instance} . '_loss'} - $options{old_datas}->{$self->{instance} . '_loss'});
$self->{result_values}->{packets_loss} = $diff_loss;
$self->{result_values}->{packets_loss_prct} = 0;
$self->{result_values}->{packets} = $diff_pkts;
if ($diff_pkts > 0) {
$self->{result_values}->{packets_loss_prct} = ($diff_loss * 100) / $diff_pkts;
}
return 0;
}
sub custom_loss_output {
my ($self, %options) = @_;
return sprintf(
"packets loss: %.2f%% (%s on %s)",
$self->{result_values}->{packets_loss_prct},
$self->{result_values}->{packets_loss},
$self->{result_values}->{packets}
);
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'channels', type => 1, cb_prefix_output => 'prefix_channels_output', message_multiple => 'All call channels are ok', skipped_code => { -10 => 1 } }
];
$self->{maps_counters}->{channels} = [
{ label => 'channel-traffic-in', nlabel => 'call.channel.traffic.in.bytes', set => {
key_values => [ { name => 'traffic_in', per_second => 1 }, { name => 'display' } ],
output_change_bytes => 1,
output_template => 'traffic in: %s %s/s',
perfdatas => [
{ template => '%d', unit => 'B/s', min => 0, label_extra_instance => 1 },
],
}
},
{ label => 'channel-traffic-out', nlabel => 'call.channel.traffic.out.bytes', set => {
key_values => [ { name => 'traffic_out', per_second => 1 }, { name => 'display' } ],
output_change_bytes => 1,
output_template => 'traffic out: %s %s/s',
perfdatas => [
{ template => '%d', unit => 'B/s', min => 0, label_extra_instance => 1 },
],
}
},
{ label => 'channel-maxjitter', nlabel => 'call.channel.maxjitter.milliseconds', set => {
key_values => [ { name => 'max_jitter' }, { name => 'display' } ],
output_template => 'max jitter: %s ms',
perfdatas => [
{ template => '%d', unit => 'ms', min => 0, label_extra_instance => 1 },
],
}
},
{ label => 'channel-packetloss', nlabel => 'call.channel.packetloss.count', set => {
key_values => [ { name => 'loss', diff => 1 }, { name => 'packets', diff => 1 }, { name => 'display' } ],
closure_custom_calc => $self->can('custom_loss_calc'),
closure_custom_output => $self->can('custom_loss_output'),
threshold_use => 'packets_loss',
perfdatas => [
{ value => 'packets_loss', template => '%d', min => 0, label_extra_instance => 1 }
],
}
},
{ label => 'channel-packetloss-prct', nlabel => 'call.channel.packetloss.percentage', display_ok => 0, set => {
key_values => [ { name => 'loss', diff => 1 }, { name => 'packets', diff => 1 }, { name => 'display' } ],
closure_custom_calc => $self->can('custom_loss_calc'),
closure_custom_output => $self->can('custom_loss_output'),
threshold_use => 'packets_loss_prct',
perfdatas => [
{ value => 'packets_loss_prct', template => '%.2f', unit => '%', min => 0, max => 100, label_extra_instance => 1 }
]
}
}
];
}
sub prefix_channels_output {
my ($self, %options) = @_;
return "Channel '" . $options{instance_value}->{display} ."' ";
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1, statefile => 1);
bless $self, $class;
$self->{version} = '1.0';
$options{options}->add_options(arguments => {
});
return $self;
}
sub manage_selection {
my ($self, %options) = @_;
$self->{cache_name} = 'polycom_trio_' . $options{custom}->{hostname} . '_' . $self->{mode} . '_' .
(defined($self->{option_results}->{filter_counters}) ? md5_hex($self->{option_results}->{filter_counters}) : md5_hex('all'));
my $result = $options{custom}->request_api(url_path => '/api/v1/mgmt/media/sessionStats');
$self->{channels} = {};
if (!defined($result->{data}) || ref($result->{data}) ne 'ARRAY') {
$self->{output}->add_option_msg(short_msg => "cannot find session information.");
$self->{output}->option_exit();
}
if (!defined($result->{data}->[0]->{Streams})) {
$self->{output}->output_add(
severity => 'OK',
short_msg => ' no audio/video call running'
);
return ;
}
foreach (@{$result->{data}->[0]->{Streams}}) {
$self->{channels}->{lc($_->{Category})} = {
display => lc($_->{Category}),
traffic_in => $_->{OctetsReceived},
traffic_out => $_->{OctetsSent},
max_jitter => $_->{MaxJitter},
loss => $_->{PacketsLost},
packets => $_->{PacketsReceived}
};
}
}
1;
__END__
=head1 MODE
Check call audio/video channels in real-time.
=over 8
=item B<--warning-*> B<--critical-*>
Thresholds.
Can be: 'channel-traffic-in', 'channel-traffic-out', 'channel-maxjitter'
'channel-packetloss', 'channel-packetloss-prct'.
=back
=cut
|
apache-2.0
|
wooga/airflow
|
airflow/ti_deps/deps/trigger_rule_dep.py
|
10691
|
#
# 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.
from collections import Counter
import airflow
from airflow.ti_deps.deps.base_ti_dep import BaseTIDep
from airflow.utils.session import provide_session
from airflow.utils.state import State
class TriggerRuleDep(BaseTIDep):
"""
Determines if a task's upstream tasks are in a state that allows a given task instance
to run.
"""
NAME = "Trigger Rule"
IGNOREABLE = True
IS_TASK_DEP = True
@staticmethod
def _get_states_count_upstream_ti(ti, finished_tasks):
"""
This function returns the states of the upstream tis for a specific ti in order to determine
whether this ti can run in this iteration
:param ti: the ti that we want to calculate deps for
:type ti: airflow.models.TaskInstance
:param finished_tasks: all the finished tasks of the dag_run
:type finished_tasks: list[airflow.models.TaskInstance]
"""
counter = Counter(task.state for task in finished_tasks if task.task_id in ti.task.upstream_task_ids)
return counter.get(State.SUCCESS, 0), counter.get(State.SKIPPED, 0), counter.get(State.FAILED, 0), \
counter.get(State.UPSTREAM_FAILED, 0), sum(counter.values())
@provide_session
def _get_dep_statuses(self, ti, session, dep_context):
TR = airflow.utils.trigger_rule.TriggerRule
# Checking that all upstream dependencies have succeeded
if not ti.task.upstream_list:
yield self._passing_status(
reason="The task instance did not have any upstream tasks.")
return
if ti.task.trigger_rule == TR.DUMMY:
yield self._passing_status(reason="The task had a dummy trigger rule set.")
return
# see if the task name is in the task upstream for our task
successes, skipped, failed, upstream_failed, done = self._get_states_count_upstream_ti(
ti=ti,
finished_tasks=dep_context.ensure_finished_tasks(ti.task.dag, ti.execution_date, session))
yield from self._evaluate_trigger_rule(
ti=ti,
successes=successes,
skipped=skipped,
failed=failed,
upstream_failed=upstream_failed,
done=done,
flag_upstream_failed=dep_context.flag_upstream_failed,
session=session)
@provide_session
def _evaluate_trigger_rule( # pylint: disable=too-many-branches
self,
ti,
successes,
skipped,
failed,
upstream_failed,
done,
flag_upstream_failed,
session):
"""
Yields a dependency status that indicate whether the given task instance's trigger
rule was met.
:param ti: the task instance to evaluate the trigger rule of
:type ti: airflow.models.TaskInstance
:param successes: Number of successful upstream tasks
:type successes: int
:param skipped: Number of skipped upstream tasks
:type skipped: int
:param failed: Number of failed upstream tasks
:type failed: int
:param upstream_failed: Number of upstream_failed upstream tasks
:type upstream_failed: int
:param done: Number of completed upstream tasks
:type done: int
:param flag_upstream_failed: This is a hack to generate
the upstream_failed state creation while checking to see
whether the task instance is runnable. It was the shortest
path to add the feature
:type flag_upstream_failed: bool
:param session: database session
:type session: sqlalchemy.orm.session.Session
"""
TR = airflow.utils.trigger_rule.TriggerRule
task = ti.task
upstream = len(task.upstream_task_ids)
trigger_rule = task.trigger_rule
upstream_done = done >= upstream
upstream_tasks_state = {
"total": upstream, "successes": successes, "skipped": skipped,
"failed": failed, "upstream_failed": upstream_failed, "done": done
}
# TODO(aoen): Ideally each individual trigger rules would be its own class, but
# this isn't very feasible at the moment since the database queries need to be
# bundled together for efficiency.
# handling instant state assignment based on trigger rules
if flag_upstream_failed:
if trigger_rule == TR.ALL_SUCCESS:
if upstream_failed or failed:
ti.set_state(State.UPSTREAM_FAILED, session)
elif skipped:
ti.set_state(State.SKIPPED, session)
elif trigger_rule == TR.ALL_FAILED:
if successes or skipped:
ti.set_state(State.SKIPPED, session)
elif trigger_rule == TR.ONE_SUCCESS:
if upstream_done and not successes:
ti.set_state(State.SKIPPED, session)
elif trigger_rule == TR.ONE_FAILED:
if upstream_done and not (failed or upstream_failed):
ti.set_state(State.SKIPPED, session)
elif trigger_rule == TR.NONE_FAILED:
if upstream_failed or failed:
ti.set_state(State.UPSTREAM_FAILED, session)
elif trigger_rule == TR.NONE_FAILED_OR_SKIPPED:
if upstream_failed or failed:
ti.set_state(State.UPSTREAM_FAILED, session)
elif skipped == upstream:
ti.set_state(State.SKIPPED, session)
elif trigger_rule == TR.NONE_SKIPPED:
if skipped:
ti.set_state(State.SKIPPED, session)
if trigger_rule == TR.ONE_SUCCESS:
if successes <= 0:
yield self._failing_status(
reason="Task's trigger rule '{0}' requires one upstream "
"task success, but none were found. "
"upstream_tasks_state={1}, upstream_task_ids={2}"
.format(trigger_rule, upstream_tasks_state, task.upstream_task_ids))
elif trigger_rule == TR.ONE_FAILED:
if not failed and not upstream_failed:
yield self._failing_status(
reason="Task's trigger rule '{0}' requires one upstream "
"task failure, but none were found. "
"upstream_tasks_state={1}, upstream_task_ids={2}"
.format(trigger_rule, upstream_tasks_state, task.upstream_task_ids))
elif trigger_rule == TR.ALL_SUCCESS:
num_failures = upstream - successes
if num_failures > 0:
yield self._failing_status(
reason="Task's trigger rule '{0}' requires all upstream "
"tasks to have succeeded, but found {1} non-success(es). "
"upstream_tasks_state={2}, upstream_task_ids={3}"
.format(trigger_rule, num_failures, upstream_tasks_state,
task.upstream_task_ids))
elif trigger_rule == TR.ALL_FAILED:
num_successes = upstream - failed - upstream_failed
if num_successes > 0:
yield self._failing_status(
reason="Task's trigger rule '{0}' requires all upstream "
"tasks to have failed, but found {1} non-failure(s). "
"upstream_tasks_state={2}, upstream_task_ids={3}"
.format(trigger_rule, num_successes, upstream_tasks_state,
task.upstream_task_ids))
elif trigger_rule == TR.ALL_DONE:
if not upstream_done:
yield self._failing_status(
reason="Task's trigger rule '{0}' requires all upstream "
"tasks to have completed, but found {1} task(s) that "
"weren't done. upstream_tasks_state={2}, "
"upstream_task_ids={3}"
.format(trigger_rule, upstream_done, upstream_tasks_state,
task.upstream_task_ids))
elif trigger_rule == TR.NONE_FAILED:
num_failures = upstream - successes - skipped
if num_failures > 0:
yield self._failing_status(
reason="Task's trigger rule '{0}' requires all upstream "
"tasks to have succeeded or been skipped, but found {1} non-success(es). "
"upstream_tasks_state={2}, upstream_task_ids={3}"
.format(trigger_rule, num_failures, upstream_tasks_state,
task.upstream_task_ids))
elif trigger_rule == TR.NONE_FAILED_OR_SKIPPED:
num_failures = upstream - successes - skipped
if num_failures > 0:
yield self._failing_status(
reason="Task's trigger rule '{0}' requires all upstream "
"tasks to have succeeded or been skipped, but found {1} non-success(es). "
"upstream_tasks_state={2}, upstream_task_ids={3}"
.format(trigger_rule, num_failures, upstream_tasks_state,
task.upstream_task_ids))
elif trigger_rule == TR.NONE_SKIPPED:
if not upstream_done or (skipped > 0):
yield self._failing_status(
reason="Task's trigger rule '{0}' requires all upstream "
"tasks to not have been skipped, but found {1} task(s) skipped. "
"upstream_tasks_state={2}, upstream_task_ids={3}"
.format(trigger_rule, skipped, upstream_tasks_state,
task.upstream_task_ids))
else:
yield self._failing_status(
reason="No strategy to evaluate trigger rule '{0}'.".format(trigger_rule))
|
apache-2.0
|
rafd123/aws-sdk-net
|
sdk/src/Services/EC2/Generated/Model/RouteTableAssociation.cs
|
3312
|
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describes an association between a route table and a subnet.
/// </summary>
public partial class RouteTableAssociation
{
private bool? _main;
private string _routeTableAssociationId;
private string _routeTableId;
private string _subnetId;
/// <summary>
/// Gets and sets the property Main.
/// <para>
/// Indicates whether this is the main route table.
/// </para>
/// </summary>
public bool Main
{
get { return this._main.GetValueOrDefault(); }
set { this._main = value; }
}
// Check to see if Main property is set
internal bool IsSetMain()
{
return this._main.HasValue;
}
/// <summary>
/// Gets and sets the property RouteTableAssociationId.
/// <para>
/// The ID of the association between a route table and a subnet.
/// </para>
/// </summary>
public string RouteTableAssociationId
{
get { return this._routeTableAssociationId; }
set { this._routeTableAssociationId = value; }
}
// Check to see if RouteTableAssociationId property is set
internal bool IsSetRouteTableAssociationId()
{
return this._routeTableAssociationId != null;
}
/// <summary>
/// Gets and sets the property RouteTableId.
/// <para>
/// The ID of the route table.
/// </para>
/// </summary>
public string RouteTableId
{
get { return this._routeTableId; }
set { this._routeTableId = value; }
}
// Check to see if RouteTableId property is set
internal bool IsSetRouteTableId()
{
return this._routeTableId != null;
}
/// <summary>
/// Gets and sets the property SubnetId.
/// <para>
/// The ID of the subnet. A subnet ID is not returned for an implicit association.
/// </para>
/// </summary>
public string SubnetId
{
get { return this._subnetId; }
set { this._subnetId = value; }
}
// Check to see if SubnetId property is set
internal bool IsSetSubnetId()
{
return this._subnetId != null;
}
}
}
|
apache-2.0
|
CodeArcsInc/candlestack
|
src/main/java/io/codearcs/candlestack/aws/rds/RDSCloudWatchMetric.java
|
5836
|
package io.codearcs.candlestack.aws.rds;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import io.codearcs.candlestack.CandlestackPropertiesException;
import io.codearcs.candlestack.MetricsReaderWriter;
import io.codearcs.candlestack.aws.CloudWatchStatistic;
import io.codearcs.candlestack.aws.GlobalAWSProperties;
import io.codearcs.candlestack.aws.cloudwatch.CloudWatchMetric;
import io.codearcs.candlestack.nagios.object.commands.Command;
import io.codearcs.candlestack.nagios.object.services.Service;
public enum RDSCloudWatchMetric implements CloudWatchMetric {
CPUUtilization( CloudWatchStatistic.Average,
"check-cpu",
"check-aws-rds-cpu",
"check-aws-rds-cpu-via-es.sh",
"Checks to see if the RDS instance is experiencing heavy CPU load. In the event an alert is triggered check the RDS instance for potential query issues causing the heavy CPU load.",
new HashSet<>( Arrays.asList( RDSType.AURORA, RDSType.AURORA_MYSQL, RDSType.MARIADB ) ),
false,
false ),
DatabaseConnections( CloudWatchStatistic.Maximum,
"check-db-connections",
"check-aws-rds-db-connections",
"check-aws-rds-db-connections-via-es.sh",
"Checks to see if the RDS instance is experiencing high number of database connections. In the event an alert is triggered check the users of the RDS instance for potential connection leaks.",
new HashSet<>( Arrays.asList( RDSType.AURORA, RDSType.AURORA_MYSQL, RDSType.MARIADB ) ),
false,
false ),
FreeStorageSpace( CloudWatchStatistic.Minimum,
"check-free-storage",
"check-aws-rds-free-storage",
"check-aws-rds-free-storage-via-es.sh",
"Checks to see if the RDS instance is running low on available storage space. In the event an alert is triggered check the RDS instance for potential issues causing a spike in data usage.",
new HashSet<>( Arrays.asList( RDSType.MARIADB ) ),
false,
false ),
VolumeBytesUsed( CloudWatchStatistic.Average,
"check-storage-used",
"check-aws-rds-storage-used",
"check-aws-rds-storage-used-via-es.sh",
"Checks to see if the RDS instance has used more storage space than has been specified. In the event an alert is triggered check the RDS instance for potential issues causing a spike in data usage.",
new HashSet<>( Arrays.asList( RDSType.AURORA, RDSType.AURORA_MYSQL ) ),
false,
true ),
AuroraReplicaLag( CloudWatchStatistic.Maximum,
"check-replica-lag",
"check-aws-rds-replica-lag",
"check-aws-rds-replica-lag-via-es.sh",
"Checks to see if the Aurora read replica is experiencing a high replication lag. In the event an alert is triggered check the Aurora cluster for potential issues causing the lag.",
new HashSet<>( Arrays.asList( RDSType.AURORA, RDSType.AURORA_MYSQL ) ),
true,
false ),
ActiveTransactions( CloudWatchStatistic.Maximum,
"check-active-transactions",
"check-aws-rds-active-transactions",
"check-aws-rds-active-transactions-via-es.sh",
"Checks to see if the RDS instance is experiencing a large number of active transactions. In the event an alert is triggered check the RDS instance for potential query issues causing the transaction build up.",
new HashSet<>( Arrays.asList( RDSType.AURORA, RDSType.AURORA_MYSQL ) ),
false,
false );
private static final String NAMESPACE = "AWS/RDS";
private String serviceName, commandName, scriptFileName, notes, logsHost, logsAuthToken;
private CloudWatchStatistic statistic;
private Set<RDSType> supportedRDSTypes;
private boolean replicaOnly, clusterOnly;
private RDSCloudWatchMetric( CloudWatchStatistic statistic, String serviceName, String commandName, String scriptFileName, String notes, Set<RDSType> supportedRDSTypes, boolean replicaOnly, boolean clusterOnly ) {
this.statistic = statistic;
this.serviceName = serviceName;
this.commandName = commandName;
this.scriptFileName = scriptFileName;
this.notes = notes;
this.supportedRDSTypes = supportedRDSTypes;
this.replicaOnly = replicaOnly;
this.clusterOnly = clusterOnly;
try {
logsHost = GlobalAWSProperties.getLogsHost();
logsAuthToken = GlobalAWSProperties.getLogsAuthToken();
} catch ( CandlestackPropertiesException ignore ) {
// We will see this error else where if this is the case
}
}
@Override
public CloudWatchStatistic getStatistic() {
return statistic;
}
@Override
public String getServiceName() {
return serviceName;
}
@Override
public String getCommandName() {
return commandName;
}
@Override
public String getScriptFileName() {
return scriptFileName;
}
public boolean isRDSTypeSupported( RDSType rdsType ) {
return supportedRDSTypes.contains( rdsType );
}
public boolean isReplicaOnlyMetric() {
return replicaOnly;
}
public boolean isClusterOnlyMetric() {
return clusterOnly;
}
@Override
public Service getService( String dbInstanceId, Set<String> contactGroups ) throws CandlestackPropertiesException {
long warning = GlobalAWSProperties.getRDSCloudWatchMetricWarningLevel( dbInstanceId, this );
long critical = GlobalAWSProperties.getRDSCloudWatchMetricCriticalLevel( dbInstanceId, this );
String command = commandName + "!" + MetricsReaderWriter.sanitizeString( dbInstanceId ) + "!" + warning + "!" + critical;
String notificationPeriod = GlobalAWSProperties.getRDSServiceNotificationPeriod( dbInstanceId );
return new Service( serviceName, dbInstanceId, command, notes, notificationPeriod, contactGroups );
}
@Override
public Command getMonitorCommand( String relativePathToMonitorResource ) {
return new Command( commandName, relativePathToMonitorResource + scriptFileName + " " + logsHost + " " + logsAuthToken + " $ARG1$ $ARG2$ $ARG3$" );
}
@Override
public String getNamespace() {
return NAMESPACE;
}
@Override
public String getName() {
return name();
}
}
|
apache-2.0
|
stackforge/python-openstacksdk
|
openstack/baremetal_introspection/v1/_proxy.py
|
7038
|
# 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.
from openstack import _log
from openstack.baremetal.v1 import node as _node
from openstack.baremetal_introspection.v1 import introspection as _introspect
from openstack import exceptions
from openstack import proxy
_logger = _log.setup_logging('openstack')
class Proxy(proxy.Proxy):
def introspections(self, **query):
"""Retrieve a generator of introspection records.
:param dict query: Optional query parameters to be sent to restrict
the records to be returned. Available parameters include:
* ``fields``: A list containing one or more fields to be returned
in the response. This may lead to some performance gain
because other fields of the resource are not refreshed.
* ``limit``: Requests at most the specified number of items be
returned from the query.
* ``marker``: Specifies the ID of the last-seen introspection. Use
the ``limit`` parameter to make an initial limited request and
use the ID of the last-seen introspection from the response as
the ``marker`` value in a subsequent limited request.
* ``sort_dir``: Sorts the response by the requested sort direction.
A valid value is ``asc`` (ascending) or ``desc``
(descending). Default is ``asc``. You can specify multiple
pairs of sort key and sort direction query parameters. If
you omit the sort direction in a pair, the API uses the
natural sorting direction of the server attribute that is
provided as the ``sort_key``.
* ``sort_key``: Sorts the response by the this attribute value.
Default is ``id``. You can specify multiple pairs of sort
key and sort direction query parameters. If you omit the
sort direction in a pair, the API uses the natural sorting
direction of the server attribute that is provided as the
``sort_key``.
:returns: A generator of :class:`~.introspection.Introspection`
objects
"""
return _introspect.Introspection.list(self, **query)
def start_introspection(self, node, manage_boot=None):
"""Create a new introspection from attributes.
:param node: The value can be either the name or ID of a node or
a :class:`~openstack.baremetal.v1.node.Node` instance.
:param bool manage_boot: Whether to manage boot parameters for the
node. Defaults to the server default (which is `True`).
:returns: :class:`~.introspection.Introspection` instance.
"""
node = self._get_resource(_node.Node, node)
res = _introspect.Introspection.new(connection=self._get_connection(),
id=node.id)
kwargs = {}
if manage_boot is not None:
kwargs['manage_boot'] = manage_boot
return res.create(self, **kwargs)
def get_introspection(self, introspection):
"""Get a specific introspection.
:param introspection: The value can be the name or ID of an
introspection (matching bare metal node name or ID) or
an :class:`~.introspection.Introspection` instance.
:returns: :class:`~.introspection.Introspection` instance.
:raises: :class:`~openstack.exceptions.ResourceNotFound` when no
introspection matching the name or ID could be found.
"""
return self._get(_introspect.Introspection, introspection)
def get_introspection_data(self, introspection, processed=True):
"""Get introspection data.
:param introspection: The value can be the name or ID of an
introspection (matching bare metal node name or ID) or
an :class:`~.introspection.Introspection` instance.
:param processed: Whether to fetch the final processed data (the
default) or the raw unprocessed data as received from the ramdisk.
:returns: introspection data from the most recent successful run.
:rtype: dict
"""
res = self._get_resource(_introspect.Introspection, introspection)
return res.get_data(self, processed=processed)
def abort_introspection(self, introspection, ignore_missing=True):
"""Abort an introspection.
Note that the introspection is not aborted immediately, you may use
`wait_for_introspection` with `ignore_error=True`.
:param introspection: The value can be the name or ID of an
introspection (matching bare metal node name or ID) or
an :class:`~.introspection.Introspection` instance.
:param bool ignore_missing: When set to ``False``, an exception
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the introspection could not be found. When set to ``True``, no
exception will be raised when attempting to abort a non-existent
introspection.
:returns: nothing
"""
res = self._get_resource(_introspect.Introspection, introspection)
try:
res.abort(self)
except exceptions.ResourceNotFound:
if not ignore_missing:
raise
def wait_for_introspection(self, introspection, timeout=None,
ignore_error=False):
"""Wait for the introspection to finish.
:param introspection: The value can be the name or ID of an
introspection (matching bare metal node name or ID) or
an :class:`~.introspection.Introspection` instance.
:param timeout: How much (in seconds) to wait for the introspection.
The value of ``None`` (the default) means no client-side timeout.
:param ignore_error: If ``True``, this call will raise an exception
if the introspection reaches the ``error`` state. Otherwise the
error state is considered successful and the call returns.
:returns: :class:`~.introspection.Introspection` instance.
:raises: :class:`~openstack.exceptions.ResourceFailure` if
introspection fails and ``ignore_error`` is ``False``.
:raises: :class:`~openstack.exceptions.ResourceTimeout` on timeout.
"""
res = self._get_resource(_introspect.Introspection, introspection)
return res.wait(self, timeout=timeout, ignore_error=ignore_error)
|
apache-2.0
|
indashnet/InDashNet.Open.UN2000
|
android/frameworks/base/services/java/com/android/server/accessibility/TouchExplorer.java
|
81944
|
/*
** Copyright 2011, 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.android.server.accessibility;
import android.content.Context;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GesturePoint;
import android.gesture.GestureStore;
import android.gesture.GestureStroke;
import android.gesture.Prediction;
import android.graphics.Rect;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Slog;
import android.view.MotionEvent;
import android.view.MotionEvent.PointerCoords;
import android.view.MotionEvent.PointerProperties;
import android.view.VelocityTracker;
import android.view.ViewConfiguration;
import android.view.WindowManagerPolicy;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import com.android.internal.R;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* This class is a strategy for performing touch exploration. It
* transforms the motion event stream by modifying, adding, replacing,
* and consuming certain events. The interaction model is:
*
* <ol>
* <li>1. One finger moving slow around performs touch exploration.</li>
* <li>2. One finger moving fast around performs gestures.</li>
* <li>3. Two close fingers moving in the same direction perform a drag.</li>
* <li>4. Multi-finger gestures are delivered to view hierarchy.</li>
* <li>5. Two fingers moving in different directions are considered a multi-finger gesture.</li>
* <li>7. Double tapping clicks on the on the last touch explored location if it was in
* a window that does not take focus, otherwise the click is within the accessibility
* focused rectangle.</li>
* <li>7. Tapping and holding for a while performs a long press in a similar fashion
* as the click above.</li>
* <ol>
*
* @hide
*/
class TouchExplorer implements EventStreamTransformation {
private static final boolean DEBUG = false;
// Tag for logging received events.
private static final String LOG_TAG = "TouchExplorer";
// States this explorer can be in.
private static final int STATE_TOUCH_EXPLORING = 0x00000001;
private static final int STATE_DRAGGING = 0x00000002;
private static final int STATE_DELEGATING = 0x00000004;
private static final int STATE_GESTURE_DETECTING = 0x00000005;
// The minimum of the cosine between the vectors of two moving
// pointers so they can be considered moving in the same direction.
private static final float MAX_DRAGGING_ANGLE_COS = 0.525321989f; // cos(pi/4)
// Constant referring to the ids bits of all pointers.
private static final int ALL_POINTER_ID_BITS = 0xFFFFFFFF;
// This constant captures the current implementation detail that
// pointer IDs are between 0 and 31 inclusive (subject to change).
// (See MAX_POINTER_ID in frameworks/base/include/ui/Input.h)
private static final int MAX_POINTER_COUNT = 32;
// Invalid pointer ID.
private static final int INVALID_POINTER_ID = -1;
// The velocity above which we detect gestures.
private static final int GESTURE_DETECTION_VELOCITY_DIP = 1000;
// The minimal distance before we take the middle of the distance between
// the two dragging pointers as opposed to use the location of the primary one.
private static final int MIN_POINTER_DISTANCE_TO_USE_MIDDLE_LOCATION_DIP = 200;
// The timeout after which we are no longer trying to detect a gesture.
private static final int EXIT_GESTURE_DETECTION_TIMEOUT = 2000;
// Timeout before trying to decide what the user is trying to do.
private final int mDetermineUserIntentTimeout;
// Timeout within which we try to detect a tap.
private final int mTapTimeout;
// Timeout within which we try to detect a double tap.
private final int mDoubleTapTimeout;
// Slop between the down and up tap to be a tap.
private final int mTouchSlop;
// Slop between the first and second tap to be a double tap.
private final int mDoubleTapSlop;
// The current state of the touch explorer.
private int mCurrentState = STATE_TOUCH_EXPLORING;
// The ID of the pointer used for dragging.
private int mDraggingPointerId;
// Handler for performing asynchronous operations.
private final Handler mHandler;
// Command for delayed sending of a hover enter and move event.
private final SendHoverEnterAndMoveDelayed mSendHoverEnterAndMoveDelayed;
// Command for delayed sending of a hover exit event.
private final SendHoverExitDelayed mSendHoverExitDelayed;
// Command for delayed sending of touch exploration end events.
private final SendAccessibilityEventDelayed mSendTouchExplorationEndDelayed;
// Command for delayed sending of touch interaction end events.
private final SendAccessibilityEventDelayed mSendTouchInteractionEndDelayed;
// Command for delayed sending of a long press.
private final PerformLongPressDelayed mPerformLongPressDelayed;
// Command for exiting gesture detection mode after a timeout.
private final ExitGestureDetectionModeDelayed mExitGestureDetectionModeDelayed;
// Helper to detect and react to double tap in touch explore mode.
private final DoubleTapDetector mDoubleTapDetector;
// The scaled minimal distance before we take the middle of the distance between
// the two dragging pointers as opposed to use the location of the primary one.
private final int mScaledMinPointerDistanceToUseMiddleLocation;
// The scaled velocity above which we detect gestures.
private final int mScaledGestureDetectionVelocity;
// The handler to which to delegate events.
private EventStreamTransformation mNext;
// Helper to track gesture velocity.
private final VelocityTracker mVelocityTracker = VelocityTracker.obtain();
// Helper class to track received pointers.
private final ReceivedPointerTracker mReceivedPointerTracker;
// Helper class to track injected pointers.
private final InjectedPointerTracker mInjectedPointerTracker;
// Handle to the accessibility manager service.
private final AccessibilityManagerService mAms;
// Temporary rectangle to avoid instantiation.
private final Rect mTempRect = new Rect();
// Context in which this explorer operates.
private final Context mContext;
// The X of the previous event.
private float mPreviousX;
// The Y of the previous event.
private float mPreviousY;
// Buffer for storing points for gesture detection.
private final ArrayList<GesturePoint> mStrokeBuffer = new ArrayList<GesturePoint>(100);
// The minimal delta between moves to add a gesture point.
private static final int TOUCH_TOLERANCE = 3;
// The minimal score for accepting a predicted gesture.
private static final float MIN_PREDICTION_SCORE = 2.0f;
// The library for gesture detection.
private GestureLibrary mGestureLibrary;
// The long pressing pointer id if coordinate remapping is needed.
private int mLongPressingPointerId = -1;
// The long pressing pointer X if coordinate remapping is needed.
private int mLongPressingPointerDeltaX;
// The long pressing pointer Y if coordinate remapping is needed.
private int mLongPressingPointerDeltaY;
// The id of the last touch explored window.
private int mLastTouchedWindowId;
// Whether touch exploration is in progress.
private boolean mTouchExplorationInProgress;
/**
* Creates a new instance.
*
* @param inputFilter The input filter associated with this explorer.
* @param context A context handle for accessing resources.
*/
public TouchExplorer(Context context, AccessibilityManagerService service) {
mContext = context;
mAms = service;
mReceivedPointerTracker = new ReceivedPointerTracker();
mInjectedPointerTracker = new InjectedPointerTracker();
mTapTimeout = ViewConfiguration.getTapTimeout();
mDetermineUserIntentTimeout = ViewConfiguration.getDoubleTapTimeout();
mDoubleTapTimeout = ViewConfiguration.getDoubleTapTimeout();
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mDoubleTapSlop = ViewConfiguration.get(context).getScaledDoubleTapSlop();
mHandler = new Handler(context.getMainLooper());
mPerformLongPressDelayed = new PerformLongPressDelayed();
mExitGestureDetectionModeDelayed = new ExitGestureDetectionModeDelayed();
mGestureLibrary = GestureLibraries.fromRawResource(context, R.raw.accessibility_gestures);
mGestureLibrary.setOrientationStyle(8);
mGestureLibrary.setSequenceType(GestureStore.SEQUENCE_SENSITIVE);
mGestureLibrary.load();
mSendHoverEnterAndMoveDelayed = new SendHoverEnterAndMoveDelayed();
mSendHoverExitDelayed = new SendHoverExitDelayed();
mSendTouchExplorationEndDelayed = new SendAccessibilityEventDelayed(
AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END,
mDetermineUserIntentTimeout);
mSendTouchInteractionEndDelayed = new SendAccessibilityEventDelayed(
AccessibilityEvent.TYPE_TOUCH_INTERACTION_END,
mDetermineUserIntentTimeout);
mDoubleTapDetector = new DoubleTapDetector();
final float density = context.getResources().getDisplayMetrics().density;
mScaledMinPointerDistanceToUseMiddleLocation =
(int) (MIN_POINTER_DISTANCE_TO_USE_MIDDLE_LOCATION_DIP * density);
mScaledGestureDetectionVelocity = (int) (GESTURE_DETECTION_VELOCITY_DIP * density);
}
public void clear() {
// If we have not received an event then we are in initial
// state. Therefore, there is not need to clean anything.
MotionEvent event = mReceivedPointerTracker.getLastReceivedEvent();
if (event != null) {
clear(mReceivedPointerTracker.getLastReceivedEvent(), WindowManagerPolicy.FLAG_TRUSTED);
}
}
public void onDestroy() {
// TODO: Implement
}
private void clear(MotionEvent event, int policyFlags) {
switch (mCurrentState) {
case STATE_TOUCH_EXPLORING: {
// If a touch exploration gesture is in progress send events for its end.
sendHoverExitAndTouchExplorationGestureEndIfNeeded(policyFlags);
} break;
case STATE_DRAGGING: {
mDraggingPointerId = INVALID_POINTER_ID;
// Send exit to all pointers that we have delivered.
sendUpForInjectedDownPointers(event, policyFlags);
} break;
case STATE_DELEGATING: {
// Send exit to all pointers that we have delivered.
sendUpForInjectedDownPointers(event, policyFlags);
} break;
case STATE_GESTURE_DETECTING: {
// Clear the current stroke.
mStrokeBuffer.clear();
} break;
}
// Remove all pending callbacks.
mSendHoverEnterAndMoveDelayed.cancel();
mSendHoverExitDelayed.cancel();
mPerformLongPressDelayed.cancel();
mExitGestureDetectionModeDelayed.cancel();
mSendTouchExplorationEndDelayed.cancel();
mSendTouchInteractionEndDelayed.cancel();
// Reset the pointer trackers.
mReceivedPointerTracker.clear();
mInjectedPointerTracker.clear();
// Clear the double tap detector
mDoubleTapDetector.clear();
// Go to initial state.
// Clear the long pressing pointer remap data.
mLongPressingPointerId = -1;
mLongPressingPointerDeltaX = 0;
mLongPressingPointerDeltaY = 0;
mCurrentState = STATE_TOUCH_EXPLORING;
if (mNext != null) {
mNext.clear();
}
mTouchExplorationInProgress = false;
mAms.onTouchInteractionEnd();
}
@Override
public void setNext(EventStreamTransformation next) {
mNext = next;
}
@Override
public void onMotionEvent(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
if (DEBUG) {
Slog.d(LOG_TAG, "Received event: " + event + ", policyFlags=0x"
+ Integer.toHexString(policyFlags));
Slog.d(LOG_TAG, getStateSymbolicName(mCurrentState));
}
mReceivedPointerTracker.onMotionEvent(rawEvent);
switch(mCurrentState) {
case STATE_TOUCH_EXPLORING: {
handleMotionEventStateTouchExploring(event, rawEvent, policyFlags);
} break;
case STATE_DRAGGING: {
handleMotionEventStateDragging(event, policyFlags);
} break;
case STATE_DELEGATING: {
handleMotionEventStateDelegating(event, policyFlags);
} break;
case STATE_GESTURE_DETECTING: {
handleMotionEventGestureDetecting(rawEvent, policyFlags);
} break;
default:
throw new IllegalStateException("Illegal state: " + mCurrentState);
}
}
public void onAccessibilityEvent(AccessibilityEvent event) {
final int eventType = event.getEventType();
// The event for gesture end should be strictly after the
// last hover exit event.
if (mSendTouchExplorationEndDelayed.isPending()
&& eventType == AccessibilityEvent.TYPE_VIEW_HOVER_EXIT) {
mSendTouchExplorationEndDelayed.cancel();
sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END);
}
// The event for touch interaction end should be strictly after the
// last hover exit and the touch exploration gesture end events.
if (mSendTouchInteractionEndDelayed.isPending()
&& eventType == AccessibilityEvent.TYPE_VIEW_HOVER_EXIT) {
mSendTouchInteractionEndDelayed.cancel();
sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_INTERACTION_END);
}
// If a new window opens or the accessibility focus moves we no longer
// want to click/long press on the last touch explored location.
switch (eventType) {
case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
if (mInjectedPointerTracker.mLastInjectedHoverEventForClick != null) {
mInjectedPointerTracker.mLastInjectedHoverEventForClick.recycle();
mInjectedPointerTracker.mLastInjectedHoverEventForClick = null;
}
mLastTouchedWindowId = -1;
} break;
case AccessibilityEvent.TYPE_VIEW_HOVER_ENTER:
case AccessibilityEvent.TYPE_VIEW_HOVER_EXIT: {
mLastTouchedWindowId = event.getWindowId();
} break;
}
if (mNext != null) {
mNext.onAccessibilityEvent(event);
}
}
/**
* Handles a motion event in touch exploring state.
*
* @param event The event to be handled.
* @param rawEvent The raw (unmodified) motion event.
* @param policyFlags The policy flags associated with the event.
*/
private void handleMotionEventStateTouchExploring(MotionEvent event, MotionEvent rawEvent,
int policyFlags) {
ReceivedPointerTracker receivedTracker = mReceivedPointerTracker;
mVelocityTracker.addMovement(rawEvent);
mDoubleTapDetector.onMotionEvent(event, policyFlags);
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
mAms.onTouchInteractionStart();
// Pre-feed the motion events to the gesture detector since we
// have a distance slop before getting into gesture detection
// mode and not using the points within this slop significantly
// decreases the quality of gesture recognition.
handleMotionEventGestureDetecting(rawEvent, policyFlags);
sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_INTERACTION_START);
// If we still have not notified the user for the last
// touch, we figure out what to do. If were waiting
// we resent the delayed callback and wait again.
mSendHoverEnterAndMoveDelayed.cancel();
mSendHoverExitDelayed.cancel();
mPerformLongPressDelayed.cancel();
if (mSendTouchExplorationEndDelayed.isPending()) {
mSendTouchExplorationEndDelayed.forceSendAndRemove();
}
if (mSendTouchInteractionEndDelayed.isPending()) {
mSendTouchInteractionEndDelayed.forceSendAndRemove();
}
// If we have the first tap, schedule a long press and break
// since we do not want to schedule hover enter because
// the delayed callback will kick in before the long click.
// This would lead to a state transition resulting in long
// pressing the item below the double taped area which is
// not necessary where accessibility focus is.
if (mDoubleTapDetector.firstTapDetected()) {
// We got a tap now post a long press action.
mPerformLongPressDelayed.post(event, policyFlags);
break;
}
if (!mTouchExplorationInProgress) {
if (!mSendHoverEnterAndMoveDelayed.isPending()) {
// Deliver hover enter with a delay to have a chance
// to detect what the user is trying to do.
final int pointerId = receivedTracker.getPrimaryPointerId();
final int pointerIdBits = (1 << pointerId);
mSendHoverEnterAndMoveDelayed.post(event, true, pointerIdBits,
policyFlags);
}
// Cache the event until we discern exploration from gesturing.
mSendHoverEnterAndMoveDelayed.addEvent(event);
}
} break;
case MotionEvent.ACTION_POINTER_DOWN: {
/* do nothing - let the code for ACTION_MOVE decide what to do */
} break;
case MotionEvent.ACTION_MOVE: {
final int pointerId = receivedTracker.getPrimaryPointerId();
final int pointerIndex = event.findPointerIndex(pointerId);
final int pointerIdBits = (1 << pointerId);
switch (event.getPointerCount()) {
case 1: {
// We have not started sending events since we try to
// figure out what the user is doing.
if (mSendHoverEnterAndMoveDelayed.isPending()) {
// Pre-feed the motion events to the gesture detector since we
// have a distance slop before getting into gesture detection
// mode and not using the points within this slop significantly
// decreases the quality of gesture recognition.
handleMotionEventGestureDetecting(rawEvent, policyFlags);
// Cache the event until we discern exploration from gesturing.
mSendHoverEnterAndMoveDelayed.addEvent(event);
// It is *important* to use the distance traveled by the pointers
// on the screen which may or may not be magnified.
final float deltaX = receivedTracker.getReceivedPointerDownX(pointerId)
- rawEvent.getX(pointerIndex);
final float deltaY = receivedTracker.getReceivedPointerDownY(pointerId)
- rawEvent.getY(pointerIndex);
final double moveDelta = Math.hypot(deltaX, deltaY);
// The user has moved enough for us to decide.
if (moveDelta > mDoubleTapSlop) {
// Check whether the user is performing a gesture. We
// detect gestures if the pointer is moving above a
// given velocity.
mVelocityTracker.computeCurrentVelocity(1000);
final float maxAbsVelocity = Math.max(
Math.abs(mVelocityTracker.getXVelocity(pointerId)),
Math.abs(mVelocityTracker.getYVelocity(pointerId)));
if (maxAbsVelocity > mScaledGestureDetectionVelocity) {
// We have to perform gesture detection, so
// clear the current state and try to detect.
mCurrentState = STATE_GESTURE_DETECTING;
mVelocityTracker.clear();
mSendHoverEnterAndMoveDelayed.cancel();
mSendHoverExitDelayed.cancel();
mPerformLongPressDelayed.cancel();
mExitGestureDetectionModeDelayed.post();
// Send accessibility event to announce the start
// of gesture recognition.
sendAccessibilityEvent(
AccessibilityEvent.TYPE_GESTURE_DETECTION_START);
} else {
// We have just decided that the user is touch,
// exploring so start sending events.
mSendHoverEnterAndMoveDelayed.forceSendAndRemove();
mSendHoverExitDelayed.cancel();
mPerformLongPressDelayed.cancel();
sendMotionEvent(event, MotionEvent.ACTION_HOVER_MOVE,
pointerIdBits, policyFlags);
}
break;
}
} else {
// Cancel the long press if pending and the user
// moved more than the slop.
if (mPerformLongPressDelayed.isPending()) {
final float deltaX =
receivedTracker.getReceivedPointerDownX(pointerId)
- rawEvent.getX(pointerIndex);
final float deltaY =
receivedTracker.getReceivedPointerDownY(pointerId)
- rawEvent.getY(pointerIndex);
final double moveDelta = Math.hypot(deltaX, deltaY);
// The user has moved enough for us to decide.
if (moveDelta > mTouchSlop) {
mPerformLongPressDelayed.cancel();
}
}
// The user is either double tapping or performing a long
// press, so do not send move events yet.
if (mDoubleTapDetector.firstTapDetected()) {
break;
}
sendTouchExplorationGestureStartAndHoverEnterIfNeeded(policyFlags);
sendMotionEvent(event, MotionEvent.ACTION_HOVER_MOVE, pointerIdBits,
policyFlags);
}
} break;
case 2: {
// More than one pointer so the user is not touch exploring
// and now we have to decide whether to delegate or drag.
if (mSendHoverEnterAndMoveDelayed.isPending()) {
// We have not started sending events so cancel
// scheduled sending events.
mSendHoverEnterAndMoveDelayed.cancel();
mSendHoverExitDelayed.cancel();
mPerformLongPressDelayed.cancel();
} else {
mPerformLongPressDelayed.cancel();
// If the user is touch exploring the second pointer may be
// performing a double tap to activate an item without need
// for the user to lift his exploring finger.
// It is *important* to use the distance traveled by the pointers
// on the screen which may or may not be magnified.
final float deltaX = receivedTracker.getReceivedPointerDownX(pointerId)
- rawEvent.getX(pointerIndex);
final float deltaY = receivedTracker.getReceivedPointerDownY(pointerId)
- rawEvent.getY(pointerIndex);
final double moveDelta = Math.hypot(deltaX, deltaY);
if (moveDelta < mDoubleTapSlop) {
break;
}
// We are sending events so send exit and gesture
// end since we transition to another state.
sendHoverExitAndTouchExplorationGestureEndIfNeeded(policyFlags);
}
// We know that a new state transition is to happen and the
// new state will not be gesture recognition, so clear the
// stashed gesture strokes.
mStrokeBuffer.clear();
if (isDraggingGesture(event)) {
// Two pointers moving in the same direction within
// a given distance perform a drag.
mCurrentState = STATE_DRAGGING;
mDraggingPointerId = pointerId;
event.setEdgeFlags(receivedTracker.getLastReceivedDownEdgeFlags());
sendMotionEvent(event, MotionEvent.ACTION_DOWN, pointerIdBits,
policyFlags);
} else {
// Two pointers moving arbitrary are delegated to the view hierarchy.
mCurrentState = STATE_DELEGATING;
sendDownForAllNotInjectedPointers(event, policyFlags);
}
mVelocityTracker.clear();
} break;
default: {
// More than one pointer so the user is not touch exploring
// and now we have to decide whether to delegate or drag.
if (mSendHoverEnterAndMoveDelayed.isPending()) {
// We have not started sending events so cancel
// scheduled sending events.
mSendHoverEnterAndMoveDelayed.cancel();
mSendHoverExitDelayed.cancel();
mPerformLongPressDelayed.cancel();
} else {
mPerformLongPressDelayed.cancel();
// We are sending events so send exit and gesture
// end since we transition to another state.
sendHoverExitAndTouchExplorationGestureEndIfNeeded(policyFlags);
}
// More than two pointers are delegated to the view hierarchy.
mCurrentState = STATE_DELEGATING;
sendDownForAllNotInjectedPointers(event, policyFlags);
mVelocityTracker.clear();
}
}
} break;
case MotionEvent.ACTION_UP: {
mAms.onTouchInteractionEnd();
// We know that we do not need the pre-fed gesture points are not
// needed anymore since the last pointer just went up.
mStrokeBuffer.clear();
final int pointerId = event.getPointerId(event.getActionIndex());
final int pointerIdBits = (1 << pointerId);
mPerformLongPressDelayed.cancel();
mVelocityTracker.clear();
if (mSendHoverEnterAndMoveDelayed.isPending()) {
// If we have not delivered the enter schedule an exit.
mSendHoverExitDelayed.post(event, pointerIdBits, policyFlags);
} else {
// The user is touch exploring so we send events for end.
sendHoverExitAndTouchExplorationGestureEndIfNeeded(policyFlags);
}
if (!mSendTouchInteractionEndDelayed.isPending()) {
mSendTouchInteractionEndDelayed.post();
}
} break;
case MotionEvent.ACTION_CANCEL: {
clear(event, policyFlags);
} break;
}
}
/**
* Handles a motion event in dragging state.
*
* @param event The event to be handled.
* @param policyFlags The policy flags associated with the event.
*/
private void handleMotionEventStateDragging(MotionEvent event, int policyFlags) {
final int pointerIdBits = (1 << mDraggingPointerId);
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
throw new IllegalStateException("Dragging state can be reached only if two "
+ "pointers are already down");
}
case MotionEvent.ACTION_POINTER_DOWN: {
// We are in dragging state so we have two pointers and another one
// goes down => delegate the three pointers to the view hierarchy
mCurrentState = STATE_DELEGATING;
if (mDraggingPointerId != INVALID_POINTER_ID) {
sendMotionEvent(event, MotionEvent.ACTION_UP, pointerIdBits, policyFlags);
}
sendDownForAllNotInjectedPointers(event, policyFlags);
} break;
case MotionEvent.ACTION_MOVE: {
switch (event.getPointerCount()) {
case 1: {
// do nothing
} break;
case 2: {
if (isDraggingGesture(event)) {
final float firstPtrX = event.getX(0);
final float firstPtrY = event.getY(0);
final float secondPtrX = event.getX(1);
final float secondPtrY = event.getY(1);
final float deltaX = firstPtrX - secondPtrX;
final float deltaY = firstPtrY - secondPtrY;
final double distance = Math.hypot(deltaX, deltaY);
if (distance > mScaledMinPointerDistanceToUseMiddleLocation) {
event.setLocation(deltaX / 2, deltaY / 2);
}
// If still dragging send a drag event.
sendMotionEvent(event, MotionEvent.ACTION_MOVE, pointerIdBits,
policyFlags);
} else {
// The two pointers are moving either in different directions or
// no close enough => delegate the gesture to the view hierarchy.
mCurrentState = STATE_DELEGATING;
// Send an event to the end of the drag gesture.
sendMotionEvent(event, MotionEvent.ACTION_UP, pointerIdBits,
policyFlags);
// Deliver all pointers to the view hierarchy.
sendDownForAllNotInjectedPointers(event, policyFlags);
}
} break;
default: {
mCurrentState = STATE_DELEGATING;
// Send an event to the end of the drag gesture.
sendMotionEvent(event, MotionEvent.ACTION_UP, pointerIdBits,
policyFlags);
// Deliver all pointers to the view hierarchy.
sendDownForAllNotInjectedPointers(event, policyFlags);
}
}
} break;
case MotionEvent.ACTION_POINTER_UP: {
final int pointerId = event.getPointerId(event.getActionIndex());
if (pointerId == mDraggingPointerId) {
mDraggingPointerId = INVALID_POINTER_ID;
// Send an event to the end of the drag gesture.
sendMotionEvent(event, MotionEvent.ACTION_UP, pointerIdBits, policyFlags);
}
} break;
case MotionEvent.ACTION_UP: {
mAms.onTouchInteractionEnd();
// Announce the end of a new touch interaction.
sendAccessibilityEvent(
AccessibilityEvent.TYPE_TOUCH_INTERACTION_END);
final int pointerId = event.getPointerId(event.getActionIndex());
if (pointerId == mDraggingPointerId) {
mDraggingPointerId = INVALID_POINTER_ID;
// Send an event to the end of the drag gesture.
sendMotionEvent(event, MotionEvent.ACTION_UP, pointerIdBits, policyFlags);
}
mCurrentState = STATE_TOUCH_EXPLORING;
} break;
case MotionEvent.ACTION_CANCEL: {
clear(event, policyFlags);
} break;
}
}
/**
* Handles a motion event in delegating state.
*
* @param event The event to be handled.
* @param policyFlags The policy flags associated with the event.
*/
private void handleMotionEventStateDelegating(MotionEvent event, int policyFlags) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
throw new IllegalStateException("Delegating state can only be reached if "
+ "there is at least one pointer down!");
}
case MotionEvent.ACTION_UP: {
mAms.onTouchInteractionEnd();
// Announce the end of a the touch interaction.
sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_INTERACTION_END);
mLongPressingPointerId = -1;
mLongPressingPointerDeltaX = 0;
mLongPressingPointerDeltaY = 0;
mCurrentState = STATE_TOUCH_EXPLORING;
} break;
case MotionEvent.ACTION_CANCEL: {
clear(event, policyFlags);
} break;
}
// Deliver the event.
sendMotionEvent(event, event.getAction(), ALL_POINTER_ID_BITS, policyFlags);
}
private void handleMotionEventGestureDetecting(MotionEvent event, int policyFlags) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
final float x = event.getX();
final float y = event.getY();
mPreviousX = x;
mPreviousY = y;
mStrokeBuffer.add(new GesturePoint(x, y, event.getEventTime()));
} break;
case MotionEvent.ACTION_MOVE: {
final float x = event.getX();
final float y = event.getY();
final float dX = Math.abs(x - mPreviousX);
final float dY = Math.abs(y - mPreviousY);
if (dX >= TOUCH_TOLERANCE || dY >= TOUCH_TOLERANCE) {
mPreviousX = x;
mPreviousY = y;
mStrokeBuffer.add(new GesturePoint(x, y, event.getEventTime()));
}
} break;
case MotionEvent.ACTION_UP: {
mAms.onTouchInteractionEnd();
// Announce the end of the gesture recognition.
sendAccessibilityEvent(AccessibilityEvent.TYPE_GESTURE_DETECTION_END);
// Announce the end of a the touch interaction.
sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_INTERACTION_END);
float x = event.getX();
float y = event.getY();
mStrokeBuffer.add(new GesturePoint(x, y, event.getEventTime()));
Gesture gesture = new Gesture();
gesture.addStroke(new GestureStroke(mStrokeBuffer));
ArrayList<Prediction> predictions = mGestureLibrary.recognize(gesture);
if (!predictions.isEmpty()) {
Prediction bestPrediction = predictions.get(0);
if (bestPrediction.score >= MIN_PREDICTION_SCORE) {
if (DEBUG) {
Slog.i(LOG_TAG, "gesture: " + bestPrediction.name + " score: "
+ bestPrediction.score);
}
try {
final int gestureId = Integer.parseInt(bestPrediction.name);
mAms.onGesture(gestureId);
} catch (NumberFormatException nfe) {
Slog.w(LOG_TAG, "Non numeric gesture id:" + bestPrediction.name);
}
}
}
mStrokeBuffer.clear();
mExitGestureDetectionModeDelayed.cancel();
mCurrentState = STATE_TOUCH_EXPLORING;
} break;
case MotionEvent.ACTION_CANCEL: {
clear(event, policyFlags);
} break;
}
}
/**
* Sends an accessibility event of the given type.
*
* @param type The event type.
*/
private void sendAccessibilityEvent(int type) {
AccessibilityManager accessibilityManager = AccessibilityManager.getInstance(mContext);
if (accessibilityManager.isEnabled()) {
AccessibilityEvent event = AccessibilityEvent.obtain(type);
event.setWindowId(mAms.getActiveWindowId());
accessibilityManager.sendAccessibilityEvent(event);
switch (type) {
case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START: {
mTouchExplorationInProgress = true;
} break;
case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END: {
mTouchExplorationInProgress = false;
} break;
}
}
}
/**
* Sends down events to the view hierarchy for all pointers which are
* not already being delivered i.e. pointers that are not yet injected.
*
* @param prototype The prototype from which to create the injected events.
* @param policyFlags The policy flags associated with the event.
*/
private void sendDownForAllNotInjectedPointers(MotionEvent prototype, int policyFlags) {
InjectedPointerTracker injectedPointers = mInjectedPointerTracker;
// Inject the injected pointers.
int pointerIdBits = 0;
final int pointerCount = prototype.getPointerCount();
for (int i = 0; i < pointerCount; i++) {
final int pointerId = prototype.getPointerId(i);
// Do not send event for already delivered pointers.
if (!injectedPointers.isInjectedPointerDown(pointerId)) {
pointerIdBits |= (1 << pointerId);
final int action = computeInjectionAction(MotionEvent.ACTION_DOWN, i);
sendMotionEvent(prototype, action, pointerIdBits, policyFlags);
}
}
}
/**
* Sends the exit events if needed. Such events are hover exit and touch explore
* gesture end.
*
* @param policyFlags The policy flags associated with the event.
*/
private void sendHoverExitAndTouchExplorationGestureEndIfNeeded(int policyFlags) {
MotionEvent event = mInjectedPointerTracker.getLastInjectedHoverEvent();
if (event != null && event.getActionMasked() != MotionEvent.ACTION_HOVER_EXIT) {
final int pointerIdBits = event.getPointerIdBits();
if (!mSendTouchExplorationEndDelayed.isPending()) {
mSendTouchExplorationEndDelayed.post();
}
sendMotionEvent(event, MotionEvent.ACTION_HOVER_EXIT, pointerIdBits, policyFlags);
}
}
/**
* Sends the enter events if needed. Such events are hover enter and touch explore
* gesture start.
*
* @param policyFlags The policy flags associated with the event.
*/
private void sendTouchExplorationGestureStartAndHoverEnterIfNeeded(int policyFlags) {
MotionEvent event = mInjectedPointerTracker.getLastInjectedHoverEvent();
if (event != null && event.getActionMasked() == MotionEvent.ACTION_HOVER_EXIT) {
final int pointerIdBits = event.getPointerIdBits();
sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START);
sendMotionEvent(event, MotionEvent.ACTION_HOVER_ENTER, pointerIdBits, policyFlags);
}
}
/**
* Sends up events to the view hierarchy for all pointers which are
* already being delivered i.e. pointers that are injected.
*
* @param prototype The prototype from which to create the injected events.
* @param policyFlags The policy flags associated with the event.
*/
private void sendUpForInjectedDownPointers(MotionEvent prototype, int policyFlags) {
final InjectedPointerTracker injectedTracked = mInjectedPointerTracker;
int pointerIdBits = 0;
final int pointerCount = prototype.getPointerCount();
for (int i = 0; i < pointerCount; i++) {
final int pointerId = prototype.getPointerId(i);
// Skip non injected down pointers.
if (!injectedTracked.isInjectedPointerDown(pointerId)) {
continue;
}
pointerIdBits |= (1 << pointerId);
final int action = computeInjectionAction(MotionEvent.ACTION_UP, i);
sendMotionEvent(prototype, action, pointerIdBits, policyFlags);
}
}
/**
* Sends an up and down events.
*
* @param prototype The prototype from which to create the injected events.
* @param policyFlags The policy flags associated with the event.
*/
private void sendActionDownAndUp(MotionEvent prototype, int policyFlags) {
// Tap with the pointer that last explored.
final int pointerId = prototype.getPointerId(prototype.getActionIndex());
final int pointerIdBits = (1 << pointerId);
sendMotionEvent(prototype, MotionEvent.ACTION_DOWN, pointerIdBits, policyFlags);
sendMotionEvent(prototype, MotionEvent.ACTION_UP, pointerIdBits, policyFlags);
}
/**
* Sends an event.
*
* @param prototype The prototype from which to create the injected events.
* @param action The action of the event.
* @param pointerIdBits The bits of the pointers to send.
* @param policyFlags The policy flags associated with the event.
*/
private void sendMotionEvent(MotionEvent prototype, int action, int pointerIdBits,
int policyFlags) {
prototype.setAction(action);
MotionEvent event = null;
if (pointerIdBits == ALL_POINTER_ID_BITS) {
event = prototype;
} else {
event = prototype.split(pointerIdBits);
}
if (action == MotionEvent.ACTION_DOWN) {
event.setDownTime(event.getEventTime());
} else {
event.setDownTime(mInjectedPointerTracker.getLastInjectedDownEventTime());
}
// If the user is long pressing but the long pressing pointer
// was not exactly over the accessibility focused item we need
// to remap the location of that pointer so the user does not
// have to explicitly touch explore something to be able to
// long press it, or even worse to avoid the user long pressing
// on the wrong item since click and long press behave differently.
if (mLongPressingPointerId >= 0) {
final int remappedIndex = event.findPointerIndex(mLongPressingPointerId);
final int pointerCount = event.getPointerCount();
PointerProperties[] props = PointerProperties.createArray(pointerCount);
PointerCoords[] coords = PointerCoords.createArray(pointerCount);
for (int i = 0; i < pointerCount; i++) {
event.getPointerProperties(i, props[i]);
event.getPointerCoords(i, coords[i]);
if (i == remappedIndex) {
coords[i].x -= mLongPressingPointerDeltaX;
coords[i].y -= mLongPressingPointerDeltaY;
}
}
MotionEvent remapped = MotionEvent.obtain(event.getDownTime(),
event.getEventTime(), event.getAction(), event.getPointerCount(),
props, coords, event.getMetaState(), event.getButtonState(),
1.0f, 1.0f, event.getDeviceId(), event.getEdgeFlags(),
event.getSource(), event.getFlags());
if (event != prototype) {
event.recycle();
}
event = remapped;
}
if (DEBUG) {
Slog.d(LOG_TAG, "Injecting event: " + event + ", policyFlags=0x"
+ Integer.toHexString(policyFlags));
}
// Make sure that the user will see the event.
policyFlags |= WindowManagerPolicy.FLAG_PASS_TO_USER;
if (mNext != null) {
// TODO: For now pass null for the raw event since the touch
// explorer is the last event transformation and it does
// not care about the raw event.
mNext.onMotionEvent(event, null, policyFlags);
}
mInjectedPointerTracker.onMotionEvent(event);
if (event != prototype) {
event.recycle();
}
}
/**
* Computes the action for an injected event based on a masked action
* and a pointer index.
*
* @param actionMasked The masked action.
* @param pointerIndex The index of the pointer which has changed.
* @return The action to be used for injection.
*/
private int computeInjectionAction(int actionMasked, int pointerIndex) {
switch (actionMasked) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN: {
InjectedPointerTracker injectedTracker = mInjectedPointerTracker;
// Compute the action based on how many down pointers are injected.
if (injectedTracker.getInjectedPointerDownCount() == 0) {
return MotionEvent.ACTION_DOWN;
} else {
return (pointerIndex << MotionEvent.ACTION_POINTER_INDEX_SHIFT)
| MotionEvent.ACTION_POINTER_DOWN;
}
}
case MotionEvent.ACTION_POINTER_UP: {
InjectedPointerTracker injectedTracker = mInjectedPointerTracker;
// Compute the action based on how many down pointers are injected.
if (injectedTracker.getInjectedPointerDownCount() == 1) {
return MotionEvent.ACTION_UP;
} else {
return (pointerIndex << MotionEvent.ACTION_POINTER_INDEX_SHIFT)
| MotionEvent.ACTION_POINTER_UP;
}
}
default:
return actionMasked;
}
}
private class DoubleTapDetector {
private MotionEvent mDownEvent;
private MotionEvent mFirstTapEvent;
public void onMotionEvent(MotionEvent event, int policyFlags) {
final int actionIndex = event.getActionIndex();
final int action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN: {
if (mFirstTapEvent != null
&& !GestureUtils.isSamePointerContext(mFirstTapEvent, event)) {
clear();
}
mDownEvent = MotionEvent.obtain(event);
} break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP: {
if (mDownEvent == null) {
return;
}
if (!GestureUtils.isSamePointerContext(mDownEvent, event)) {
clear();
return;
}
if (GestureUtils.isTap(mDownEvent, event, mTapTimeout, mTouchSlop,
actionIndex)) {
if (mFirstTapEvent == null || GestureUtils.isTimedOut(mFirstTapEvent,
event, mDoubleTapTimeout)) {
mFirstTapEvent = MotionEvent.obtain(event);
mDownEvent.recycle();
mDownEvent = null;
return;
}
if (GestureUtils.isMultiTap(mFirstTapEvent, event, mDoubleTapTimeout,
mDoubleTapSlop, actionIndex)) {
onDoubleTap(event, policyFlags);
mFirstTapEvent.recycle();
mFirstTapEvent = null;
mDownEvent.recycle();
mDownEvent = null;
return;
}
mFirstTapEvent.recycle();
mFirstTapEvent = null;
} else {
if (mFirstTapEvent != null) {
mFirstTapEvent.recycle();
mFirstTapEvent = null;
}
}
mDownEvent.recycle();
mDownEvent = null;
} break;
}
}
public void onDoubleTap(MotionEvent secondTapUp, int policyFlags) {
// This should never be called when more than two pointers are down.
if (secondTapUp.getPointerCount() > 2) {
return;
}
// Remove pending event deliveries.
mSendHoverEnterAndMoveDelayed.cancel();
mSendHoverExitDelayed.cancel();
mPerformLongPressDelayed.cancel();
if (mSendTouchExplorationEndDelayed.isPending()) {
mSendTouchExplorationEndDelayed.forceSendAndRemove();
}
if (mSendTouchInteractionEndDelayed.isPending()) {
mSendTouchInteractionEndDelayed.forceSendAndRemove();
}
int clickLocationX;
int clickLocationY;
final int pointerId = secondTapUp.getPointerId(secondTapUp.getActionIndex());
final int pointerIndex = secondTapUp.findPointerIndex(pointerId);
MotionEvent lastExploreEvent =
mInjectedPointerTracker.getLastInjectedHoverEventForClick();
if (lastExploreEvent == null) {
// No last touch explored event but there is accessibility focus in
// the active window. We click in the middle of the focus bounds.
Rect focusBounds = mTempRect;
if (mAms.getAccessibilityFocusBoundsInActiveWindow(focusBounds)) {
clickLocationX = focusBounds.centerX();
clickLocationY = focusBounds.centerY();
} else {
// Out of luck - do nothing.
return;
}
} else {
// If the click is within the active window but not within the
// accessibility focus bounds we click in the focus center.
final int lastExplorePointerIndex = lastExploreEvent.getActionIndex();
clickLocationX = (int) lastExploreEvent.getX(lastExplorePointerIndex);
clickLocationY = (int) lastExploreEvent.getY(lastExplorePointerIndex);
Rect activeWindowBounds = mTempRect;
if (mLastTouchedWindowId == mAms.getActiveWindowId()) {
mAms.getActiveWindowBounds(activeWindowBounds);
if (activeWindowBounds.contains(clickLocationX, clickLocationY)) {
Rect focusBounds = mTempRect;
if (mAms.getAccessibilityFocusBoundsInActiveWindow(focusBounds)) {
if (!focusBounds.contains(clickLocationX, clickLocationY)) {
clickLocationX = focusBounds.centerX();
clickLocationY = focusBounds.centerY();
}
}
}
}
}
// Do the click.
PointerProperties[] properties = new PointerProperties[1];
properties[0] = new PointerProperties();
secondTapUp.getPointerProperties(pointerIndex, properties[0]);
PointerCoords[] coords = new PointerCoords[1];
coords[0] = new PointerCoords();
coords[0].x = clickLocationX;
coords[0].y = clickLocationY;
MotionEvent event = MotionEvent.obtain(secondTapUp.getDownTime(),
secondTapUp.getEventTime(), MotionEvent.ACTION_DOWN, 1, properties,
coords, 0, 0, 1.0f, 1.0f, secondTapUp.getDeviceId(), 0,
secondTapUp.getSource(), secondTapUp.getFlags());
sendActionDownAndUp(event, policyFlags);
event.recycle();
}
public void clear() {
if (mDownEvent != null) {
mDownEvent.recycle();
mDownEvent = null;
}
if (mFirstTapEvent != null) {
mFirstTapEvent.recycle();
mFirstTapEvent = null;
}
}
public boolean firstTapDetected() {
return mFirstTapEvent != null
&& SystemClock.uptimeMillis() - mFirstTapEvent.getEventTime() < mDoubleTapTimeout;
}
}
/**
* Determines whether a two pointer gesture is a dragging one.
*
* @param event The event with the pointer data.
* @return True if the gesture is a dragging one.
*/
private boolean isDraggingGesture(MotionEvent event) {
ReceivedPointerTracker receivedTracker = mReceivedPointerTracker;
final float firstPtrX = event.getX(0);
final float firstPtrY = event.getY(0);
final float secondPtrX = event.getX(1);
final float secondPtrY = event.getY(1);
final float firstPtrDownX = receivedTracker.getReceivedPointerDownX(0);
final float firstPtrDownY = receivedTracker.getReceivedPointerDownY(0);
final float secondPtrDownX = receivedTracker.getReceivedPointerDownX(1);
final float secondPtrDownY = receivedTracker.getReceivedPointerDownY(1);
return GestureUtils.isDraggingGesture(firstPtrDownX, firstPtrDownY, secondPtrDownX,
secondPtrDownY, firstPtrX, firstPtrY, secondPtrX, secondPtrY,
MAX_DRAGGING_ANGLE_COS);
}
/**
* Gets the symbolic name of a state.
*
* @param state A state.
* @return The state symbolic name.
*/
private static String getStateSymbolicName(int state) {
switch (state) {
case STATE_TOUCH_EXPLORING:
return "STATE_TOUCH_EXPLORING";
case STATE_DRAGGING:
return "STATE_DRAGGING";
case STATE_DELEGATING:
return "STATE_DELEGATING";
case STATE_GESTURE_DETECTING:
return "STATE_GESTURE_DETECTING";
default:
throw new IllegalArgumentException("Unknown state: " + state);
}
}
/**
* Class for delayed exiting from gesture detecting mode.
*/
private final class ExitGestureDetectionModeDelayed implements Runnable {
public void post() {
mHandler.postDelayed(this, EXIT_GESTURE_DETECTION_TIMEOUT);
}
public void cancel() {
mHandler.removeCallbacks(this);
}
@Override
public void run() {
// Announce the end of gesture recognition.
sendAccessibilityEvent(AccessibilityEvent.TYPE_GESTURE_DETECTION_END);
// Clearing puts is in touch exploration state with a finger already
// down, so announce the transition to exploration state.
sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START);
clear();
}
}
/**
* Class for delayed sending of long press.
*/
private final class PerformLongPressDelayed implements Runnable {
private MotionEvent mEvent;
private int mPolicyFlags;
public void post(MotionEvent prototype, int policyFlags) {
mEvent = MotionEvent.obtain(prototype);
mPolicyFlags = policyFlags;
mHandler.postDelayed(this, ViewConfiguration.getLongPressTimeout());
}
public void cancel() {
if (mEvent != null) {
mHandler.removeCallbacks(this);
clear();
}
}
private boolean isPending() {
return mHandler.hasCallbacks(this);
}
@Override
public void run() {
// Pointers should not be zero when running this command.
if (mReceivedPointerTracker.getLastReceivedEvent().getPointerCount() == 0) {
return;
}
int clickLocationX;
int clickLocationY;
final int pointerId = mEvent.getPointerId(mEvent.getActionIndex());
final int pointerIndex = mEvent.findPointerIndex(pointerId);
MotionEvent lastExploreEvent =
mInjectedPointerTracker.getLastInjectedHoverEventForClick();
if (lastExploreEvent == null) {
// No last touch explored event but there is accessibility focus in
// the active window. We click in the middle of the focus bounds.
Rect focusBounds = mTempRect;
if (mAms.getAccessibilityFocusBoundsInActiveWindow(focusBounds)) {
clickLocationX = focusBounds.centerX();
clickLocationY = focusBounds.centerY();
} else {
// Out of luck - do nothing.
return;
}
} else {
// If the click is within the active window but not within the
// accessibility focus bounds we click in the focus center.
final int lastExplorePointerIndex = lastExploreEvent.getActionIndex();
clickLocationX = (int) lastExploreEvent.getX(lastExplorePointerIndex);
clickLocationY = (int) lastExploreEvent.getY(lastExplorePointerIndex);
Rect activeWindowBounds = mTempRect;
if (mLastTouchedWindowId == mAms.getActiveWindowId()) {
mAms.getActiveWindowBounds(activeWindowBounds);
if (activeWindowBounds.contains(clickLocationX, clickLocationY)) {
Rect focusBounds = mTempRect;
if (mAms.getAccessibilityFocusBoundsInActiveWindow(focusBounds)) {
if (!focusBounds.contains(clickLocationX, clickLocationY)) {
clickLocationX = focusBounds.centerX();
clickLocationY = focusBounds.centerY();
}
}
}
}
}
mLongPressingPointerId = pointerId;
mLongPressingPointerDeltaX = (int) mEvent.getX(pointerIndex) - clickLocationX;
mLongPressingPointerDeltaY = (int) mEvent.getY(pointerIndex) - clickLocationY;
sendHoverExitAndTouchExplorationGestureEndIfNeeded(mPolicyFlags);
mCurrentState = STATE_DELEGATING;
sendDownForAllNotInjectedPointers(mEvent, mPolicyFlags);
clear();
}
private void clear() {
mEvent.recycle();
mEvent = null;
mPolicyFlags = 0;
}
}
/**
* Class for delayed sending of hover enter and move events.
*/
class SendHoverEnterAndMoveDelayed implements Runnable {
private final String LOG_TAG_SEND_HOVER_DELAYED = "SendHoverEnterAndMoveDelayed";
private final List<MotionEvent> mEvents = new ArrayList<MotionEvent>();
private int mPointerIdBits;
private int mPolicyFlags;
public void post(MotionEvent event, boolean touchExplorationInProgress,
int pointerIdBits, int policyFlags) {
cancel();
addEvent(event);
mPointerIdBits = pointerIdBits;
mPolicyFlags = policyFlags;
mHandler.postDelayed(this, mDetermineUserIntentTimeout);
}
public void addEvent(MotionEvent event) {
mEvents.add(MotionEvent.obtain(event));
}
public void cancel() {
if (isPending()) {
mHandler.removeCallbacks(this);
clear();
}
}
private boolean isPending() {
return mHandler.hasCallbacks(this);
}
private void clear() {
mPointerIdBits = -1;
mPolicyFlags = 0;
final int eventCount = mEvents.size();
for (int i = eventCount - 1; i >= 0; i--) {
mEvents.remove(i).recycle();
}
}
public void forceSendAndRemove() {
if (isPending()) {
run();
cancel();
}
}
public void run() {
// Send an accessibility event to announce the touch exploration start.
sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START);
if (!mEvents.isEmpty()) {
// Deliver a down event.
sendMotionEvent(mEvents.get(0), MotionEvent.ACTION_HOVER_ENTER,
mPointerIdBits, mPolicyFlags);
if (DEBUG) {
Slog.d(LOG_TAG_SEND_HOVER_DELAYED,
"Injecting motion event: ACTION_HOVER_ENTER");
}
// Deliver move events.
final int eventCount = mEvents.size();
for (int i = 1; i < eventCount; i++) {
sendMotionEvent(mEvents.get(i), MotionEvent.ACTION_HOVER_MOVE,
mPointerIdBits, mPolicyFlags);
if (DEBUG) {
Slog.d(LOG_TAG_SEND_HOVER_DELAYED,
"Injecting motion event: ACTION_HOVER_MOVE");
}
}
}
clear();
}
}
/**
* Class for delayed sending of hover exit events.
*/
class SendHoverExitDelayed implements Runnable {
private final String LOG_TAG_SEND_HOVER_DELAYED = "SendHoverExitDelayed";
private MotionEvent mPrototype;
private int mPointerIdBits;
private int mPolicyFlags;
public void post(MotionEvent prototype, int pointerIdBits, int policyFlags) {
cancel();
mPrototype = MotionEvent.obtain(prototype);
mPointerIdBits = pointerIdBits;
mPolicyFlags = policyFlags;
mHandler.postDelayed(this, mDetermineUserIntentTimeout);
}
public void cancel() {
if (isPending()) {
mHandler.removeCallbacks(this);
clear();
}
}
private boolean isPending() {
return mHandler.hasCallbacks(this);
}
private void clear() {
mPrototype.recycle();
mPrototype = null;
mPointerIdBits = -1;
mPolicyFlags = 0;
}
public void forceSendAndRemove() {
if (isPending()) {
run();
cancel();
}
}
public void run() {
if (DEBUG) {
Slog.d(LOG_TAG_SEND_HOVER_DELAYED, "Injecting motion event:"
+ " ACTION_HOVER_EXIT");
}
sendMotionEvent(mPrototype, MotionEvent.ACTION_HOVER_EXIT,
mPointerIdBits, mPolicyFlags);
if (!mSendTouchExplorationEndDelayed.isPending()) {
mSendTouchExplorationEndDelayed.cancel();
mSendTouchExplorationEndDelayed.post();
}
if (mSendTouchInteractionEndDelayed.isPending()) {
mSendTouchInteractionEndDelayed.cancel();
mSendTouchInteractionEndDelayed.post();
}
clear();
}
}
private class SendAccessibilityEventDelayed implements Runnable {
private final int mEventType;
private final int mDelay;
public SendAccessibilityEventDelayed(int eventType, int delay) {
mEventType = eventType;
mDelay = delay;
}
public void cancel() {
mHandler.removeCallbacks(this);
}
public void post() {
mHandler.postDelayed(this, mDelay);
}
public boolean isPending() {
return mHandler.hasCallbacks(this);
}
public void forceSendAndRemove() {
if (isPending()) {
run();
cancel();
}
}
@Override
public void run() {
sendAccessibilityEvent(mEventType);
}
}
@Override
public String toString() {
return LOG_TAG;
}
class InjectedPointerTracker {
private static final String LOG_TAG_INJECTED_POINTER_TRACKER = "InjectedPointerTracker";
// Keep track of which pointers sent to the system are down.
private int mInjectedPointersDown;
// The time of the last injected down.
private long mLastInjectedDownEventTime;
// The last injected hover event.
private MotionEvent mLastInjectedHoverEvent;
// The last injected hover event used for performing clicks.
private MotionEvent mLastInjectedHoverEventForClick;
/**
* Processes an injected {@link MotionEvent} event.
*
* @param event The event to process.
*/
public void onMotionEvent(MotionEvent event) {
final int action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN: {
final int pointerId = event.getPointerId(event.getActionIndex());
final int pointerFlag = (1 << pointerId);
mInjectedPointersDown |= pointerFlag;
mLastInjectedDownEventTime = event.getDownTime();
} break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP: {
final int pointerId = event.getPointerId(event.getActionIndex());
final int pointerFlag = (1 << pointerId);
mInjectedPointersDown &= ~pointerFlag;
if (mInjectedPointersDown == 0) {
mLastInjectedDownEventTime = 0;
}
} break;
case MotionEvent.ACTION_HOVER_ENTER:
case MotionEvent.ACTION_HOVER_MOVE:
case MotionEvent.ACTION_HOVER_EXIT: {
if (mLastInjectedHoverEvent != null) {
mLastInjectedHoverEvent.recycle();
}
mLastInjectedHoverEvent = MotionEvent.obtain(event);
if (mLastInjectedHoverEventForClick != null) {
mLastInjectedHoverEventForClick.recycle();
}
mLastInjectedHoverEventForClick = MotionEvent.obtain(event);
} break;
}
if (DEBUG) {
Slog.i(LOG_TAG_INJECTED_POINTER_TRACKER, "Injected pointer:\n" + toString());
}
}
/**
* Clears the internals state.
*/
public void clear() {
mInjectedPointersDown = 0;
}
/**
* @return The time of the last injected down event.
*/
public long getLastInjectedDownEventTime() {
return mLastInjectedDownEventTime;
}
/**
* @return The number of down pointers injected to the view hierarchy.
*/
public int getInjectedPointerDownCount() {
return Integer.bitCount(mInjectedPointersDown);
}
/**
* @return The bits of the injected pointers that are down.
*/
public int getInjectedPointersDown() {
return mInjectedPointersDown;
}
/**
* Whether an injected pointer is down.
*
* @param pointerId The unique pointer id.
* @return True if the pointer is down.
*/
public boolean isInjectedPointerDown(int pointerId) {
final int pointerFlag = (1 << pointerId);
return (mInjectedPointersDown & pointerFlag) != 0;
}
/**
* @return The the last injected hover event.
*/
public MotionEvent getLastInjectedHoverEvent() {
return mLastInjectedHoverEvent;
}
/**
* @return The the last injected hover event.
*/
public MotionEvent getLastInjectedHoverEventForClick() {
return mLastInjectedHoverEventForClick;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("=========================");
builder.append("\nDown pointers #");
builder.append(Integer.bitCount(mInjectedPointersDown));
builder.append(" [ ");
for (int i = 0; i < MAX_POINTER_COUNT; i++) {
if ((mInjectedPointersDown & i) != 0) {
builder.append(i);
builder.append(" ");
}
}
builder.append("]");
builder.append("\n=========================");
return builder.toString();
}
}
class ReceivedPointerTracker {
private static final String LOG_TAG_RECEIVED_POINTER_TRACKER = "ReceivedPointerTracker";
// Keep track of where and when a pointer went down.
private final float[] mReceivedPointerDownX = new float[MAX_POINTER_COUNT];
private final float[] mReceivedPointerDownY = new float[MAX_POINTER_COUNT];
private final long[] mReceivedPointerDownTime = new long[MAX_POINTER_COUNT];
// Which pointers are down.
private int mReceivedPointersDown;
// The edge flags of the last received down event.
private int mLastReceivedDownEdgeFlags;
// Primary pointer which is either the first that went down
// or if it goes up the next one that most recently went down.
private int mPrimaryPointerId;
// Keep track of the last up pointer data.
private long mLastReceivedUpPointerDownTime;
private int mLastReceivedUpPointerId;
private float mLastReceivedUpPointerDownX;
private float mLastReceivedUpPointerDownY;
private MotionEvent mLastReceivedEvent;
/**
* Clears the internals state.
*/
public void clear() {
Arrays.fill(mReceivedPointerDownX, 0);
Arrays.fill(mReceivedPointerDownY, 0);
Arrays.fill(mReceivedPointerDownTime, 0);
mReceivedPointersDown = 0;
mPrimaryPointerId = 0;
mLastReceivedUpPointerDownTime = 0;
mLastReceivedUpPointerId = 0;
mLastReceivedUpPointerDownX = 0;
mLastReceivedUpPointerDownY = 0;
}
/**
* Processes a received {@link MotionEvent} event.
*
* @param event The event to process.
*/
public void onMotionEvent(MotionEvent event) {
if (mLastReceivedEvent != null) {
mLastReceivedEvent.recycle();
}
mLastReceivedEvent = MotionEvent.obtain(event);
final int action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_DOWN: {
handleReceivedPointerDown(event.getActionIndex(), event);
} break;
case MotionEvent.ACTION_POINTER_DOWN: {
handleReceivedPointerDown(event.getActionIndex(), event);
} break;
case MotionEvent.ACTION_UP: {
handleReceivedPointerUp(event.getActionIndex(), event);
} break;
case MotionEvent.ACTION_POINTER_UP: {
handleReceivedPointerUp(event.getActionIndex(), event);
} break;
}
if (DEBUG) {
Slog.i(LOG_TAG_RECEIVED_POINTER_TRACKER, "Received pointer:\n" + toString());
}
}
/**
* @return The last received event.
*/
public MotionEvent getLastReceivedEvent() {
return mLastReceivedEvent;
}
/**
* @return The number of received pointers that are down.
*/
public int getReceivedPointerDownCount() {
return Integer.bitCount(mReceivedPointersDown);
}
/**
* Whether an received pointer is down.
*
* @param pointerId The unique pointer id.
* @return True if the pointer is down.
*/
public boolean isReceivedPointerDown(int pointerId) {
final int pointerFlag = (1 << pointerId);
return (mReceivedPointersDown & pointerFlag) != 0;
}
/**
* @param pointerId The unique pointer id.
* @return The X coordinate where the pointer went down.
*/
public float getReceivedPointerDownX(int pointerId) {
return mReceivedPointerDownX[pointerId];
}
/**
* @param pointerId The unique pointer id.
* @return The Y coordinate where the pointer went down.
*/
public float getReceivedPointerDownY(int pointerId) {
return mReceivedPointerDownY[pointerId];
}
/**
* @param pointerId The unique pointer id.
* @return The time when the pointer went down.
*/
public long getReceivedPointerDownTime(int pointerId) {
return mReceivedPointerDownTime[pointerId];
}
/**
* @return The id of the primary pointer.
*/
public int getPrimaryPointerId() {
if (mPrimaryPointerId == INVALID_POINTER_ID) {
mPrimaryPointerId = findPrimaryPointerId();
}
return mPrimaryPointerId;
}
/**
* @return The time when the last up received pointer went down.
*/
public long getLastReceivedUpPointerDownTime() {
return mLastReceivedUpPointerDownTime;
}
/**
* @return The down X of the last received pointer that went up.
*/
public float getLastReceivedUpPointerDownX() {
return mLastReceivedUpPointerDownX;
}
/**
* @return The down Y of the last received pointer that went up.
*/
public float getLastReceivedUpPointerDownY() {
return mLastReceivedUpPointerDownY;
}
/**
* @return The edge flags of the last received down event.
*/
public int getLastReceivedDownEdgeFlags() {
return mLastReceivedDownEdgeFlags;
}
/**
* Handles a received pointer down event.
*
* @param pointerIndex The index of the pointer that has changed.
* @param event The event to be handled.
*/
private void handleReceivedPointerDown(int pointerIndex, MotionEvent event) {
final int pointerId = event.getPointerId(pointerIndex);
final int pointerFlag = (1 << pointerId);
mLastReceivedUpPointerId = 0;
mLastReceivedUpPointerDownTime = 0;
mLastReceivedUpPointerDownX = 0;
mLastReceivedUpPointerDownX = 0;
mLastReceivedDownEdgeFlags = event.getEdgeFlags();
mReceivedPointersDown |= pointerFlag;
mReceivedPointerDownX[pointerId] = event.getX(pointerIndex);
mReceivedPointerDownY[pointerId] = event.getY(pointerIndex);
mReceivedPointerDownTime[pointerId] = event.getEventTime();
mPrimaryPointerId = pointerId;
}
/**
* Handles a received pointer up event.
*
* @param pointerIndex The index of the pointer that has changed.
* @param event The event to be handled.
*/
private void handleReceivedPointerUp(int pointerIndex, MotionEvent event) {
final int pointerId = event.getPointerId(pointerIndex);
final int pointerFlag = (1 << pointerId);
mLastReceivedUpPointerId = pointerId;
mLastReceivedUpPointerDownTime = getReceivedPointerDownTime(pointerId);
mLastReceivedUpPointerDownX = mReceivedPointerDownX[pointerId];
mLastReceivedUpPointerDownY = mReceivedPointerDownY[pointerId];
mReceivedPointersDown &= ~pointerFlag;
mReceivedPointerDownX[pointerId] = 0;
mReceivedPointerDownY[pointerId] = 0;
mReceivedPointerDownTime[pointerId] = 0;
if (mPrimaryPointerId == pointerId) {
mPrimaryPointerId = INVALID_POINTER_ID;
}
}
/**
* @return The primary pointer id.
*/
private int findPrimaryPointerId() {
int primaryPointerId = INVALID_POINTER_ID;
long minDownTime = Long.MAX_VALUE;
// Find the pointer that went down first.
int pointerIdBits = mReceivedPointersDown;
while (pointerIdBits > 0) {
final int pointerId = Integer.numberOfTrailingZeros(pointerIdBits);
pointerIdBits &= ~(1 << pointerId);
final long downPointerTime = mReceivedPointerDownTime[pointerId];
if (downPointerTime < minDownTime) {
minDownTime = downPointerTime;
primaryPointerId = pointerId;
}
}
return primaryPointerId;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("=========================");
builder.append("\nDown pointers #");
builder.append(getReceivedPointerDownCount());
builder.append(" [ ");
for (int i = 0; i < MAX_POINTER_COUNT; i++) {
if (isReceivedPointerDown(i)) {
builder.append(i);
builder.append(" ");
}
}
builder.append("]");
builder.append("\nPrimary pointer id [ ");
builder.append(getPrimaryPointerId());
builder.append(" ]");
builder.append("\n=========================");
return builder.toString();
}
}
}
|
apache-2.0
|
jentfoo/aws-sdk-java
|
aws-java-sdk-redshift/src/main/java/com/amazonaws/services/redshift/model/VpcSecurityGroupMembership.java
|
5374
|
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.redshift.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* Describes the members of a VPC security group.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/VpcSecurityGroupMembership"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class VpcSecurityGroupMembership implements Serializable, Cloneable {
/**
* <p>
* The identifier of the VPC security group.
* </p>
*/
private String vpcSecurityGroupId;
/**
* <p>
* The status of the VPC security group.
* </p>
*/
private String status;
/**
* <p>
* The identifier of the VPC security group.
* </p>
*
* @param vpcSecurityGroupId
* The identifier of the VPC security group.
*/
public void setVpcSecurityGroupId(String vpcSecurityGroupId) {
this.vpcSecurityGroupId = vpcSecurityGroupId;
}
/**
* <p>
* The identifier of the VPC security group.
* </p>
*
* @return The identifier of the VPC security group.
*/
public String getVpcSecurityGroupId() {
return this.vpcSecurityGroupId;
}
/**
* <p>
* The identifier of the VPC security group.
* </p>
*
* @param vpcSecurityGroupId
* The identifier of the VPC security group.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public VpcSecurityGroupMembership withVpcSecurityGroupId(String vpcSecurityGroupId) {
setVpcSecurityGroupId(vpcSecurityGroupId);
return this;
}
/**
* <p>
* The status of the VPC security group.
* </p>
*
* @param status
* The status of the VPC security group.
*/
public void setStatus(String status) {
this.status = status;
}
/**
* <p>
* The status of the VPC security group.
* </p>
*
* @return The status of the VPC security group.
*/
public String getStatus() {
return this.status;
}
/**
* <p>
* The status of the VPC security group.
* </p>
*
* @param status
* The status of the VPC security group.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public VpcSecurityGroupMembership withStatus(String status) {
setStatus(status);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getVpcSecurityGroupId() != null)
sb.append("VpcSecurityGroupId: ").append(getVpcSecurityGroupId()).append(",");
if (getStatus() != null)
sb.append("Status: ").append(getStatus());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof VpcSecurityGroupMembership == false)
return false;
VpcSecurityGroupMembership other = (VpcSecurityGroupMembership) obj;
if (other.getVpcSecurityGroupId() == null ^ this.getVpcSecurityGroupId() == null)
return false;
if (other.getVpcSecurityGroupId() != null && other.getVpcSecurityGroupId().equals(this.getVpcSecurityGroupId()) == false)
return false;
if (other.getStatus() == null ^ this.getStatus() == null)
return false;
if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getVpcSecurityGroupId() == null) ? 0 : getVpcSecurityGroupId().hashCode());
hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
return hashCode;
}
@Override
public VpcSecurityGroupMembership clone() {
try {
return (VpcSecurityGroupMembership) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Marasmiaceae/Marasmius/Marasmius olneii/README.md
|
201
|
# Marasmius olneii Berk. & M.A. Curtis SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Marasmius olneii Berk. & M.A. Curtis
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Pezizomycetes/Pezizales/Pyronemataceae/Trichophaea/Trichophaea sublivida/ Syn. Humaria sublivida/README.md
|
252
|
# Humaria sublivida Sacc. & Speg., 1878 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Michelia 1(no. 4): 443 (1878)
#### Original name
Humaria sublivida Sacc. & Speg., 1878
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Helotiaceae/Crocicreas/Crocicreas culmicola/ Syn. Hymenoscyphus culmicola/README.md
|
236
|
# Hymenoscyphus culmicola (Desm.) Kuntze, 1898 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Revis. gen. pl. (Leipzig) 3: 485 (1898)
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Spiropes/Spiropes palmetto/ Syn. Helmisporium palmetto/README.md
|
194
|
# Helmisporium palmetto W.R. Gerard SPECIES
#### Status
SYNONYM
#### According to
Index Fungorum
#### Published in
null
#### Original name
Helmisporium palmetto W.R. Gerard
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Goodeniaceae/Lechenaultia/Lechenaultia glauca/README.md
|
176
|
# Lechenaultia glauca Lindl. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Chlorophyta/Chlorophyceae/Donezellidae/README.md
|
151
|
# Donezellidae FAMILY
#### Status
ACCEPTED
#### According to
Paleobiology Database
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Amaranthaceae/Trichinium/Trichinium holosericeum/README.md
|
178
|
# Trichinium holosericeum Moq. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Cattleya/Cattleya devoniana/README.md
|
185
|
# Cattleya ×devoniana Hort. ex Will. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Dioscoreales/Dioscoreaceae/Dioscorea/Dioscorea mundtii/README.md
|
173
|
# Dioscorea mundtii Baker SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
DenverArtMuseum/OctoberFriends
|
api/resources/RatingResource.php
|
12864
|
<?php namespace DMA\Friends\API\Resources;
use Response;
use Request;
use Validator;
use DMA\Friends\Models\Rating;
use DMA\Friends\Models\Activity;
use DMA\Friends\Classes\API\BaseResource;
use DMA\Friends\API\Transformers\UserProfileTransformer;
use RainLab\User\Models\User;
class RatingResource extends BaseResource {
protected $model = '\DMA\Friends\Models\Rating';
protected $transformer = '\DMA\Friends\API\Transformers\RatingTransformer';
public function __construct()
{
// Add additional routes to Activity resource
$this->addAdditionalRoute('ratingsByObject', '{object}/{objectId}', ['GET']);
$this->addAdditionalRoute('addObjectRateJson', 'rate/{object}/', ['POST']);
$this->addAdditionalRoute('addObjectRating', 'rate/{object}/{objectId}/user/{user}/{rate}', ['GET']);
}
/**
* Get instance of the object
* @param string $objectType
* @param string $objectId
* @return mixed
*/
protected function getObject($objectType, $objectId)
{
$registry = [
'activity' => '\DMA\Friends\Models\Activity',
'badge' => '\DMA\Friends\Models\Badge',
];
$model = array_get($registry, $objectType);
if ($model){
return call_user_func_array("{$model}::find", [$objectId]);
}else{
$options = implode(', ', array_keys($registry));
throw new \Exception("$objectType is not register as rateable. Options are $options");
}
}
/**
* @SWG\GET(
* path="ratings/{object}/{objectId}",
* description="Get all object ratings",
* tags={ "ratings"},
*
* @SWG\Parameter(
* description="Object",
* in="path",
* name="object",
* required=true,
* type="string",
* enum={"activity", "badge"}
* ),
* @SWG\Parameter(
* description="ID of object to fetch",
* format="int64",
* in="path",
* name="objectId",
* required=true,
* type="integer"
* ),
* @SWG\Response(
* response=200,
* description="Successful response",
* @SWG\Schema(ref="#/definitions/rate")
* ),
* @SWG\Response(
* response=500,
* description="Unexpected error",
* @SWG\Schema(ref="#/definitions/error500")
* ),
* @SWG\Response(
* response=404,
* description="User not found",
* @SWG\Schema(ref="#/definitions/UserError404")
* )
* )
*/
/**
* Get ratings by object
* @param string $objectType
* @param int $objectId
*/
public function ratingsByObject($objectType, $objectId)
{
if($instance = $this->getObject($objectType, $objectId)){
$pageSize = $this->getPageSize();
$paginator = $instance->getRates()->paginate($pageSize);
$meta = [
'rating' => array_merge(
$instance->getRatingStats(),
[
'object_type' => $objectType,
'object_id' => intval($objectId)
]
)
];
$transformer = new \DMA\Friends\API\Transformers\RateTransformer;
return Response::api()->withPaginator($paginator, $transformer, null, $meta);
} else {
return Response::api()->errorNotFound("$objectType not found");
}
}
/**
* @SWG\Definition(
* definition="response.rate",
* required={"data"},
* @SWG\Property(
* property="data",
* type="object",
* ref="#/definitions/rate.payload"
* )
* )
*
* @SWG\Definition(
* definition="rate.payload",
* required={"success", "message", "user", "rating"},
* @SWG\Property(
* property="success",
* type="boolean"
* ),
* @SWG\Property(
* property="message",
* type="string"
* ),
* @SWG\Property(
* property="user",
* type="object",
* ref="#/definitions/user.info.points"
* ),
* @SWG\Property(
* property="rating",
* type="object",
* ref="#/definitions/rating.stats"
* )
* )
*
* @SWG\Definition(
* definition="rating.stats",
* required={"total", "average", "object_type", "object_id"},
* @SWG\Property(
* property="total",
* type="number",
* format="float"
* ),
* @SWG\Property(
* property="average",
* type="number",
* format="float"
* ),
* @SWG\Property(
* property="object_type",
* type="string"
* ),
* @SWG\Property(
* property="object_id",
* type="integer",
* format="int32"
* )
* )
*
*
* @SWG\GET(
* path="ratings/rate/{object}/{objectId}/user/{user}/{rate}",
* description="Get all object ratings",
* tags={ "ratings"},
*
* @SWG\Parameter(
* description="Object to rate",
* in="path",
* name="object",
* required=true,
* type="string",
* enum={"activity", "badge"}
* ),
* @SWG\Parameter(
* description="ID of object to rate",
* format="int64",
* in="path",
* name="objectId",
* required=true,
* type="integer"
* ),
* @SWG\Parameter(
* description="ID of user",
* format="int64",
* in="path",
* name="user",
* required=true,
* type="integer"
* ),
* @SWG\Parameter(
* description="Rate value",
* format="float",
* in="path",
* name="rate",
* required=true,
* type="number",
* minimum=1,
* maximum=5
* ),
* @SWG\Response(
* response=200,
* description="Successful response",
* @SWG\Schema(ref="#/definitions/response.rate")
* ),
* @SWG\Response(
* response=500,
* description="Unexpected error",
* @SWG\Schema(ref="#/definitions/error500")
* ),
* @SWG\Response(
* response=404,
* description="User not found",
* @SWG\Schema(ref="#/definitions/UserError404")
* )
* )
*/
public function addObjectRating($objectType, $objectId, $user, $rateValue, $comment = null)
{
if($user = User::find($user)){
if($instance = $this->getObject($objectType, $objectId)){
list($success, $rating) = $instance->addRating($user, $rateValue, $comment);
// Get common user points format via UserProfileTransformer
$userTransformer = new UserProfileTransformer();
$points = $userTransformer->getUserPoints($user);
$payload = [
'data' => [
'success' => $success,
'message' => "$objectType has been rate succesfully.",
'user' => [
'id' => $user->getKey(),
'points' => $points
],
'rating' => array_merge(
$instance->getRatingStats(),
[
'object_type' => $objectType,
'object_id' => intVal($objectId)
]
)
]
];
$httpCode = 201;
if( !$success ) {
$httpCode = 200;
$payload['data']['message'] = "User has already rate this $objectType";
}
return Response::api()->setStatusCode($httpCode)->withArray($payload);
} else {
return Response::api()->errorNotFound("$object not found");
}
}else{
return Response::api()->errorNotFound('User not found');
}
}
/**
* @SWG\Definition(
* definition="request.rate",
* required={"id", "rate", "user_id"},
* @SWG\Property(
* property="id",
* type="integer",
* format="int32"
* ),
* @SWG\Property(
* property="rate",
* type="number",
* format="float"
* ),
* @SWG\Property(
* property="user_id",
* type="integer",
* format="int32"
* )
* )
*
*
* @SWG\Post(
* path="ratings/rate/{object}/",
* description="Get all object ratings",
* tags={ "ratings"},
*
* @SWG\Parameter(
* description="Object to rate",
* in="path",
* name="object",
* required=true,
* type="string",
* enum={"activity", "badge"}
* ),
* @SWG\Parameter(
* in="body",
* name="body",
* required=true,
* type="object",
* schema=@SWG\Schema(ref="#/definitions/request.rate")
* ),
* @SWG\Response(
* response=200,
* description="Successful response",
* @SWG\Schema(ref="#/definitions/response.rate")
* ),
* @SWG\Response(
* response=500,
* description="Unexpected error",
* @SWG\Schema(ref="#/definitions/error500")
* ),
* @SWG\Response(
* response=404,
* description="User not found",
* @SWG\Schema(ref="#/definitions/UserError404")
* )
* )
*/
public function addObjectRateJson($objectType){
$data = Request::all();
$rules = [
'id' => "required",
'rate' => "required",
'user_id' => "required"
];
$validation = Validator::make($data, $rules);
if ($validation->fails()){
return $this->errorDataValidation('rate data fails to validated', $validation->errors());
}
$comment = array_get($data, 'comment', '');
return $this->addObjectRating($objectType, $data['id'], $data['user_id'], $data['rate'], $comment);
}
public function index()
{
# TODO : stop default behaviour of the base resource and
# return and error
return Response::api()->errorForbidden();
#return parent::index();
}
/**
* @SWG\Get(
* path="ratings/{id}",
* description="Returns an rating by id",
* tags={ "ratings"},
*
* @SWG\Parameter(
* description="ID of rating to fetch",
* format="int64",
* in="path",
* name="id",
* required=true,
* type="integer"
* ),
*
* @SWG\Response(
* response=200,
* description="Successful response",
* @SWG\Schema(ref="#/definitions/rate")
* ),
* @SWG\Response(
* response=500,
* description="Unexpected error",
* @SWG\Schema(ref="#/definitions/error500")
* ),
* @SWG\Response(
* response=404,
* description="Not Found",
* @SWG\Schema(ref="#/definitions/error404")
* )
* )
*/
public function show($id)
{
return parent::show($id);
}
}
|
apache-2.0
|
cloudfoundry-community/java-nats
|
client/src/main/java/nats/codec/ServerFrameEncoder.java
|
3415
|
/*
* Copyright (c) 2013 Mike Heath. 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.
*
*/
package nats.codec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import nats.NatsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
/**
* Encodes {@link ServerFrame} objects to binary to be sent over the network.
*
* @author Mike Heath
*/
public class ServerFrameEncoder extends MessageToByteEncoder<ServerFrame> {
private static final Logger LOGGER = LoggerFactory.getLogger(ServerFrameEncoder.class);
private static final Charset UTF8 = Charset.forName("utf-8");
public static final byte[] CMD_PUB = "MSG".getBytes(UTF8);
public static final byte[] CMD_ERR = "-ERR".getBytes(UTF8);
public static final byte[] CMD_INFO = "INFO".getBytes(UTF8);
public static final byte[] OK = "+OK\r\n".getBytes(UTF8);
public static final byte[] PING = "PING\r\n".getBytes(UTF8);
public static final byte[] PONG = "PONG\r\n".getBytes(UTF8);
@Override
public void encode(ChannelHandlerContext ctx, ServerFrame frame, ByteBuf out) throws Exception {
LOGGER.trace("Encoding {}", frame);
if (frame instanceof ServerPublishFrame) {
final ServerPublishFrame publishFrame = (ServerPublishFrame) frame;
out.writeBytes(CMD_PUB);
out.writeByte(' ');
out.writeBytes(publishFrame.getSubject().getBytes(UTF8));
out.writeByte(' ');
out.writeBytes(publishFrame.getId().getBytes(UTF8));
out.writeByte(' ');
final String replyTo = publishFrame.getReplyTo();
if (replyTo != null) {
out.writeBytes(replyTo.getBytes(UTF8));
out.writeByte(' ');
}
final byte[] bodyBytes = publishFrame.getBody().getBytes(UTF8);
ByteBufUtil.writeIntegerAsString(out, bodyBytes.length);
out.writeBytes(ByteBufUtil.CRLF);
out.writeBytes(bodyBytes);
out.writeBytes(ByteBufUtil.CRLF);
} else if (frame instanceof ServerErrorFrame) {
final ServerErrorFrame message = (ServerErrorFrame) frame;
final String errorMessage = message.getErrorMessage();
out.writeBytes(CMD_ERR);
if (errorMessage != null) {
out.writeByte(' ');
out.writeBytes(errorMessage.getBytes(UTF8));
}
out.writeBytes(ByteBufUtil.CRLF);
} else if (frame instanceof ServerInfoFrame) {
final ServerInfoFrame infoFrame = (ServerInfoFrame) frame;
out.writeBytes(CMD_INFO);
out.writeByte(' ');
out.writeBytes(infoFrame.getInfo().getBytes(UTF8));
out.writeBytes(ByteBufUtil.CRLF);
} else if (frame instanceof ServerOkFrame) {
out.writeBytes(OK);
} else if (frame instanceof ServerPingFrame) {
out.writeBytes(PING);
} else if (frame instanceof ServerPongFrame) {
out.writeBytes(PONG);
} else {
throw new NatsException("Unable to encode server of type " + frame.getClass().getName());
}
}
}
|
apache-2.0
|
PRImA-Research-Lab/semantic-labelling
|
doc/org/primaresearch/clc/phd/repository/search/matching/gui/model/class-use/ActivityMatchValueTreeItem.html
|
5199
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_11) on Mon Jan 26 08:49:14 GMT 2015 -->
<title>Uses of Class org.primaresearch.clc.phd.repository.search.matching.gui.model.ActivityMatchValueTreeItem</title>
<meta name="date" content="2015-01-26">
<link rel="stylesheet" type="text/css" href="../../../../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.primaresearch.clc.phd.repository.search.matching.gui.model.ActivityMatchValueTreeItem";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../../../org/primaresearch/clc/phd/repository/search/matching/gui/model/ActivityMatchValueTreeItem.html" title="class in org.primaresearch.clc.phd.repository.search.matching.gui.model">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../../../index.html?org/primaresearch/clc/phd/repository/search/matching/gui/model/class-use/ActivityMatchValueTreeItem.html" target="_top">Frames</a></li>
<li><a href="ActivityMatchValueTreeItem.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.primaresearch.clc.phd.repository.search.matching.gui.model.ActivityMatchValueTreeItem" class="title">Uses of Class<br>org.primaresearch.clc.phd.repository.search.matching.gui.model.ActivityMatchValueTreeItem</h2>
</div>
<div class="classUseContainer">No usage of org.primaresearch.clc.phd.repository.search.matching.gui.model.ActivityMatchValueTreeItem</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../../../org/primaresearch/clc/phd/repository/search/matching/gui/model/ActivityMatchValueTreeItem.html" title="class in org.primaresearch.clc.phd.repository.search.matching.gui.model">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../../../index.html?org/primaresearch/clc/phd/repository/search/matching/gui/model/class-use/ActivityMatchValueTreeItem.html" target="_top">Frames</a></li>
<li><a href="ActivityMatchValueTreeItem.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
apache-2.0
|
cassinius/AnonymizationJS
|
src/config/SaNGreeAConfig_house.ts
|
1589
|
var CONFIG = {
// remote URL education target
'REMOTE_URL': 'http://berndmalle.com/anonymization/adults',
// remote target
'REMOTE_TARGET': 'education', //'marital', //'income'
// The path to the input dataset
'INPUT_FILE' : './test/io/test_input/house_data.csv',
// CSV TRIM RegExp, if necessary
'TRIM': '',
'TRIM_MOD': '',
// CSV Separator char
'SEPARATOR' : '\\s+',
'SEP_MOD': 'g',
// columns to preserve for later processing of anonymized dataset
'TARGET_COLUMN' : 'MEDV',
// Shall we write out a range or an average value?
'AVERAGE_OUTPUT_RANGES' : true,
// How many data points to fetch
'NR_DRAWS' : 506,
// Do we wnat to sample the dataset randomly?
'RANDOM_DRAWS': false,
// Min # of edges per node for graph generation
'EDGE_MIN' : 3,
// Max # of edges per node for graph generation
'EDGE_MAX' : 10,
// The k anonymization factor
'K_FACTOR' : 19,
// Weight of the Generalization Information Loss
'ALPHA' : 1,
// Weight of the Structural Information Loss
'BETA' : 0,
// Weight vector for generalization hierarchies
'GEN_WEIGHT_VECTORS' : {
'equal': {
'range': {
'CRIM': 1.0/13.0,
'ZN': 1.0/13.0,
'INDUS': 1.0/13.0,
'CHAS': 1.0/13.0,
'NOX': 1.0/13.0,
'RM': 1.0/13.0,
'AGE': 1.0/13.0,
'DIS': 1.0/13.0,
'RAD': 1.0/13.0,
'TAX': 1.0/13.0,
'PTRATIO': 1.0/13.0,
'B': 1.0/13.0,
'LSTAT': 1.0/13.0
}
}
},
// default weight vector
'VECTOR' : 'equal'
}
export { CONFIG };
|
apache-2.0
|
realbite/blix
|
lib/blix/core/json_rpc_parser.rb
|
6698
|
require 'crack'
require 'json'
require 'core/make_json'
module Blix
# this is a parser to parse and format json rpc messages.
#
class JsonRpcParser < AbstractParser
def format_request(request)
{"jsonrpc"=>"2.0", "method"=>request.method, "params"=>request.parameters, "id"=>request.id }.to_blix_json
end
# decode the message into request message format. Convert all objects to objects
# that are recognised on the server.
#
def parse_request(json)
begin
ck = Crack::JSON.parse json
rescue Crack::ParseError
raise ParseError
end
obj = RequestMessage.new
obj.data = json
obj.method = ck["method"]
parameters = ck["params"]
obj.id = ck["id"]
raise ParseError,"method missing" unless obj.method
raise ParseError,"id missing" unless obj.id
myparameters = {}
# convert any compound parameter values to local
# classes if possible.
parameters && parameters.each do |key,value|
if value.kind_of? Hash
myparameters[key.to_sym] = convert_to_class value
elsif value.kind_of? Array
myparameters[key.to_sym] = convert_to_class value
else
myparameters[key.to_sym] = convert_to_class value
end
end
obj.parameters = myparameters
obj
end
# format a response message into data
#
def format_response(message)
if message.error?
error={"code"=>message.code, "message"=>message.description}
{"jsonrpc"=>"2.0", "error"=>error, "id"=>message.id }.to_json
else
{"jsonrpc"=>"2.0", "result"=>message.value, "id"=>message.id }.to_blix_json
end
end
# parse response data into a response message
#
def parse_response(json)
begin
ck = Crack::JSON.parse json
rescue Crack::ParseError
raise ParseError
end
obj = ResponseMessage.new
obj.data = json
obj.id = ck["id"]
error = ck["error"]
if error
obj.set_error
obj.code = error["code"]
obj.description = error["message"]
else
obj.value = convert_to_class ck["result"]
end
obj
end
# format a notification into a json-rpc string
def format_notification(message)
hash = {:item=>message.value}
{"jsonrpc"=>"2.0", "method"=>message.signal, "params"=>hash }.to_blix_json
end
# parse notification data
def parse_notification(json)
begin
ck = Crack::JSON.parse json
rescue Crack::ParseError
raise ParseError
end
params = ck["params"]
obj = NotificationMessage.new
obj.data = json
obj.signal = ck["method"]
value = params && params["item"]
obj.value = convert_to_class value
obj
end
def convert_to_class( hash)
if hash.kind_of? Hash
klass = singular hash.keys.first # the name of the class
values = hash.values.first
if klass == 'value'
klass_info = [String]
elsif klass=='datetime'
klass_info = [Time]
elsif klass=='date'
klass_info = [Date]
elsif klass=='base64Binary'
klass_info = [String]
elsif klass=='decimal'
klass_info = [BigDecimal]
elsif klass[-3,3] == "_id" # aggregation class
klass = klass[0..-4]
raise ParseError,"#{klass} is not Valid!" unless klass_info = valid_klass[klass.downcase.to_sym]
puts "aggregation #{klass}: id:#{values}(#{values.class})" if $DEBUG
id = values
return defined?( DataMapper) ? klass_info[0].get(id) : klass_info[0].find(id)
else
raise ParseError,"#{klass} is not Valid!" unless klass_info = valid_klass[klass.downcase.to_sym]
end
if values.kind_of? Array
values.map do |av|
if false #av.kind_of? Hash
convert_to_class(av)
else
convert_to_class({klass=>av})
# values.map{ |av| convert_to_class({klass=>av})}
end
#
end
elsif values.kind_of? Hash
if ((defined? ActiveRecord) && ( klass_info[0].superclass == ActiveRecord::Base )) ||
((defined? DataMapper) && ( klass_info[0].included_modules.index( DataMapper::Resource) ))
myclass = klass_info[0].new
puts "[convert] class=#{myclass.class.name}, values=#{values.inspect}" if $DEBUG
else
myclass = klass_info[0].allocate
end
values.each do |k,v|
method = "#{k.downcase}=".to_sym
# we will trust the server and accept that values are valid
c_val = convert_to_class(v)
if myclass.respond_to? method
# first try to assign the value via a method
myclass.send method, c_val
else
# otherwise set an instance with this value
attr = "@#{k.downcase}".to_sym
myclass.instance_variable_set attr, c_val
end
end
# rationalize this value if neccessary
#myclass = myclass.blix_rationalize if myclass.respond_to? :blix_rationalize
myclass
elsif values.kind_of? NilClass
nil
else
if klass=='datetime'
values # crack converts the time!
elsif klass=='date'
#Date.parse(values)
values # crack converts the date!
elsif klass=="base64Binary"
Base64.decode64(values)
elsif klass=="decimal"
BigDecimal.new(values)
else
from_binary_data values
end
#raise ParseError, "inner values has class=#{values.class.name}\n#{values.inspect}" # inner value must be either a Hash or an array of Hashes
end
elsif hash.kind_of? Array
hash.map{|i| convert_to_class(i)}
else
hash
end
end
# convert plural class names to singular... if there are class names that end in 's'
# then we will have to code in an exception for this class.
def singular(txt)
parts = txt.split('_')
if (parts.length>1) && (parts[-1]=="array")
return parts[0..-2].join('_')
end
return txt[0..-2] if txt[-1].chr == 's'
txt
end
def array?(txt)
(parts.length>1) && (parts[-1]=="array")
end
end #Handler
end #Blix
|
apache-2.0
|
seattlepublicrecords/seattlepublicrecords.github.io
|
information/agencies/city_of_seattle/seattle_police_department/copbook/7401/index.md
|
196
|
---
layout: page
title: Seattle Police Officer 7401 George M. Derezes
permalink: /information/agencies/city_of_seattle/seattle_police_department/copbook/7401/
---
**Age as of Feb. 24, 2016:** 30
|
apache-2.0
|
dbflute-example/dbflute-example-with-non-rdb
|
src/main/java/org/docksidestage/app/web/es/product/EsProductAddForm.java
|
298
|
package org.docksidestage.app.web.es.product;
public class EsProductAddForm {
public String productDescription;
public String productCategoryCode;
public String productHandleCode;
public String productName;
public Integer regularPrice;
public String productStatusCode;
}
|
apache-2.0
|
Guityyo/minerparty
|
Assets/_Scripts/AIWandering/Wander.cs
|
1056
|
using UnityEngine;
using System.Collections;
public class Wander : MonoBehaviour
{
private Vector3 tarPos;
public float movementSpeed = 5.0f;
private float rotSpeed = 2.0f;
private float minX, maxX, minZ, maxZ;
public float wanderRadius = 30.0f;
// Use this for initialization
void Start ()
{
minX = -wanderRadius;
maxX = wanderRadius;
minZ = -wanderRadius;
maxZ = wanderRadius;
//Get Wander Position
GetNextPosition();
}
// Update is called once per frame
void Update ()
{
if(Vector3.Distance(tarPos, transform.position) <= 5.0f)
GetNextPosition();
Quaternion tarRot = Quaternion.LookRotation(tarPos - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, tarRot, rotSpeed * Time.deltaTime);
transform.Translate(new Vector3(0, 0, movementSpeed * Time.deltaTime));
}
void GetNextPosition()
{
tarPos = new Vector3(Random.Range(minX, maxX), 0.5f, Random.Range(minZ, maxZ));
}
}
|
apache-2.0
|
aws/aws-sdk-java
|
aws-java-sdk-inspector2/src/main/java/com/amazonaws/services/inspector2/model/GetMemberResult.java
|
3656
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.inspector2.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/inspector2-2020-06-08/GetMember" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetMemberResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* Details of the retrieved member account.
* </p>
*/
private Member member;
/**
* <p>
* Details of the retrieved member account.
* </p>
*
* @param member
* Details of the retrieved member account.
*/
public void setMember(Member member) {
this.member = member;
}
/**
* <p>
* Details of the retrieved member account.
* </p>
*
* @return Details of the retrieved member account.
*/
public Member getMember() {
return this.member;
}
/**
* <p>
* Details of the retrieved member account.
* </p>
*
* @param member
* Details of the retrieved member account.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetMemberResult withMember(Member member) {
setMember(member);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getMember() != null)
sb.append("Member: ").append(getMember());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetMemberResult == false)
return false;
GetMemberResult other = (GetMemberResult) obj;
if (other.getMember() == null ^ this.getMember() == null)
return false;
if (other.getMember() != null && other.getMember().equals(this.getMember()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getMember() == null) ? 0 : getMember().hashCode());
return hashCode;
}
@Override
public GetMemberResult clone() {
try {
return (GetMemberResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
apache-2.0
|
tranquang9a1/ECRM
|
App/ECRM/src/main/java/com/ecrm/DAO/ScheduleConfigDAO.java
|
177
|
package com.ecrm.DAO;
import org.springframework.stereotype.Repository;
/**
* Created by Htang on 7/10/2015.
*/
@Repository
public interface ScheduleConfigDAO {
}
|
apache-2.0
|
mpmlj/clarifai-client-go
|
response.go
|
667
|
package clarifai
// Response is a universal Clarifai API response object.
type Response struct {
Status *ServiceStatus `json:"status,omitempty"`
Outputs []*Output `json:"outputs,omitempty"`
Input *Input `json:"input,omitempty"` // Request for one input.
Inputs []*Input `json:"inputs,omitempty"`
Hits []*Hit `json:"hits,omitempty"` // Search hits.
Model *Model `json:"model,omitempty"`
Models []*Model `json:"models,omitempty"`
ModelVersion *ModelVersion `json:"model_version,omitempty"`
ModelVersions []*ModelVersion `json:"model_versions,omitempty"`
}
|
apache-2.0
|
ChinaQuants/Strata
|
modules/calc/src/test/java/com/opengamma/strata/calc/runner/CalculationTaskTest.java
|
31891
|
/**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.calc.runner;
import static com.opengamma.strata.basics.currency.Currency.EUR;
import static com.opengamma.strata.basics.currency.Currency.GBP;
import static com.opengamma.strata.basics.currency.Currency.USD;
import static com.opengamma.strata.collect.CollectProjectAssertions.assertThat;
import static com.opengamma.strata.collect.Guavate.toImmutableList;
import static com.opengamma.strata.collect.TestHelper.coverBeanEquals;
import static com.opengamma.strata.collect.TestHelper.coverImmutableBean;
import static com.opengamma.strata.collect.TestHelper.date;
import static org.assertj.core.api.Assertions.assertThat;
import static org.testng.Assert.assertNotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.opengamma.strata.basics.CalculationTarget;
import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.basics.ReferenceDataNotFoundException;
import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.basics.currency.CurrencyAmount;
import com.opengamma.strata.basics.currency.FxRate;
import com.opengamma.strata.calc.Measure;
import com.opengamma.strata.calc.ReportingCurrency;
import com.opengamma.strata.calc.TestingMeasures;
import com.opengamma.strata.calc.marketdata.MarketDataRequirements;
import com.opengamma.strata.calc.marketdata.TestId;
import com.opengamma.strata.calc.marketdata.TestObservableId;
import com.opengamma.strata.collect.array.DoubleArray;
import com.opengamma.strata.collect.result.FailureReason;
import com.opengamma.strata.collect.result.Result;
import com.opengamma.strata.data.FxRateId;
import com.opengamma.strata.data.MarketDataId;
import com.opengamma.strata.data.MarketDataNotFoundException;
import com.opengamma.strata.data.ObservableId;
import com.opengamma.strata.data.ObservableSource;
import com.opengamma.strata.data.scenario.CurrencyScenarioArray;
import com.opengamma.strata.data.scenario.ImmutableScenarioMarketData;
import com.opengamma.strata.data.scenario.ScenarioArray;
import com.opengamma.strata.data.scenario.ScenarioMarketData;
/**
* Test {@link CalculationTask}.
*/
@Test
public class CalculationTaskTest {
static final ObservableSource OBS_SOURCE = ObservableSource.of("MarketDataVendor");
private static final ReferenceData REF_DATA = ReferenceData.standard();
private static final ReportingCurrency NATURAL = ReportingCurrency.NATURAL;
private static final ReportingCurrency REPORTING_CURRENCY_USD = ReportingCurrency.of(Currency.USD);
private static final TestTarget TARGET = new TestTarget();
private static final Set<Measure> MEASURES =
ImmutableSet.of(TestingMeasures.PRESENT_VALUE, TestingMeasures.PRESENT_VALUE_MULTI_CCY);
public void requirements() {
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, NATURAL);
CalculationTask task = CalculationTask.of(TARGET, new TestFunction(), cell);
MarketDataRequirements requirements = task.requirements(REF_DATA);
Set<? extends MarketDataId<?>> nonObservables = requirements.getNonObservables();
ImmutableSet<? extends ObservableId> observables = requirements.getObservables();
ImmutableSet<ObservableId> timeSeries = requirements.getTimeSeries();
MarketDataId<?> timeSeriesId = TestObservableId.of("3", OBS_SOURCE);
assertThat(timeSeries).hasSize(1);
assertThat(timeSeries.iterator().next()).isEqualTo(timeSeriesId);
MarketDataId<?> nonObservableId = new TestId("1");
assertThat(nonObservables).hasSize(1);
assertThat(nonObservables.iterator().next()).isEqualTo(nonObservableId);
MarketDataId<?> observableId = TestObservableId.of("2", OBS_SOURCE);
assertThat(observables).hasSize(1);
assertThat(observables.iterator().next()).isEqualTo(observableId);
}
/**
* Test that the result is converted to the reporting currency if it implements ScenarioFxConvertible and
* the FX rates are available in the market data.
*/
public void convertResultCurrencyUsingReportingCurrency() {
DoubleArray values = DoubleArray.of(1, 2, 3);
List<FxRate> rates = ImmutableList.of(1.61, 1.62, 1.63).stream()
.map(rate -> FxRate.of(GBP, USD, rate))
.collect(toImmutableList());
CurrencyScenarioArray list = CurrencyScenarioArray.of(GBP, values);
ScenarioMarketData marketData = ImmutableScenarioMarketData.builder(date(2011, 3, 8))
.addScenarioValue(FxRateId.of(GBP, USD), rates)
.build();
ConvertibleFunction fn = ConvertibleFunction.of(() -> list, GBP);
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
DoubleArray expectedValues = DoubleArray.of(1 * 1.61, 2 * 1.62, 3 * 1.63);
CurrencyScenarioArray expectedArray = CurrencyScenarioArray.of(USD, expectedValues);
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result = calculationResults.getCells().get(0).getResult();
assertThat(result).hasValue(expectedArray);
}
/**
* Test that the result is not converted if the isCurrencyConvertible flag on the measure is false.
*/
public void currencyConversionHonoursConvertibleFlagOnMeasure() {
DoubleArray values = DoubleArray.of(1, 2, 3);
List<FxRate> rates = ImmutableList.of(1.61, 1.62, 1.63).stream()
.map(rate -> FxRate.of(GBP, USD, rate))
.collect(toImmutableList());
CurrencyScenarioArray list = CurrencyScenarioArray.of(GBP, values);
ScenarioMarketData marketData = ImmutableScenarioMarketData.builder(date(2011, 3, 8))
.addScenarioValue(FxRateId.of(GBP, USD), rates)
.build();
ConvertibleFunction fn = ConvertibleFunction.of(() -> list, GBP);
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE_MULTI_CCY, REPORTING_CURRENCY_USD);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
CurrencyScenarioArray expectedArray = CurrencyScenarioArray.of(GBP, values);
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result = calculationResults.getCells().get(0).getResult();
assertThat(result).hasValue(expectedArray);
}
/**
* Test that the result is converted to the reporting currency if it implements ScenarioFxConvertible and
* the FX rates are available in the market data. The "natural" currency is taken from the function.
*/
public void convertResultCurrencyUsingDefaultReportingCurrency() {
DoubleArray values = DoubleArray.of(1, 2, 3);
List<FxRate> rates = ImmutableList.of(1.61, 1.62, 1.63).stream()
.map(rate -> FxRate.of(GBP, USD, rate))
.collect(toImmutableList());
CurrencyScenarioArray list = CurrencyScenarioArray.of(GBP, values);
ScenarioMarketData marketData = ImmutableScenarioMarketData.builder(date(2011, 3, 8))
.addScenarioValue(FxRateId.of(GBP, USD), rates)
.build();
ConvertibleFunction fn = ConvertibleFunction.of(() -> list, USD);
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, NATURAL);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
DoubleArray expectedValues = DoubleArray.of(1 * 1.61, 2 * 1.62, 3 * 1.63);
CurrencyScenarioArray expectedArray = CurrencyScenarioArray.of(USD, expectedValues);
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result = calculationResults.getCells().get(0).getResult();
assertThat(result).hasValue(expectedArray);
}
/**
* Test that the result is returned unchanged if it is a failure.
*/
public void convertResultCurrencyFailure() {
ConvertibleFunction fn = ConvertibleFunction.of(() -> {
throw new RuntimeException("This is a failure");
}, GBP);
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
ScenarioMarketData marketData = ScenarioMarketData.empty();
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result = calculationResults.getCells().get(0).getResult();
assertThat(result)
.isFailure(FailureReason.CALCULATION_FAILED)
.hasFailureMessageMatching("Error when invoking function 'ConvertibleFunction' for ID '123': This is a failure");
}
/**
* Test the result is returned unchanged if using ReportingCurrency.NONE.
*/
public void convertResultCurrencyNoConversionRequested() {
SupplierFunction<CurrencyAmount> fn = SupplierFunction.of(() -> CurrencyAmount.of(EUR, 1d));
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, ReportingCurrency.NONE);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
ScenarioMarketData marketData = ImmutableScenarioMarketData.builder(date(2011, 3, 8)).build();
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result = calculationResults.getCells().get(0).getResult();
assertThat(result).hasValue(ScenarioArray.of(CurrencyAmount.of(EUR, 1d)));
}
/**
* Test the result is returned unchanged if it is not ScenarioFxConvertible.
*/
public void convertResultCurrencyNotConvertible() {
TestFunction fn = new TestFunction();
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
ScenarioMarketData marketData = ImmutableScenarioMarketData.builder(date(2011, 3, 8)).build();
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result = calculationResults.getCells().get(0).getResult();
assertThat(result).hasValue(ScenarioArray.of("bar"));
}
/**
* Test a non-convertible result is returned even if there is no reporting currency.
*/
public void nonConvertibleResultReturnedWhenNoReportingCurrency() {
TestFunction fn = new TestFunction();
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, NATURAL);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
ScenarioMarketData marketData = ImmutableScenarioMarketData.builder(date(2011, 3, 8)).build();
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result = calculationResults.getCells().get(0).getResult();
assertThat(result).hasValue(ScenarioArray.of("bar"));
}
/**
* Test that a failure is returned if currency conversion fails.
*/
public void convertResultCurrencyConversionFails() {
DoubleArray values = DoubleArray.of(1, 2, 3);
CurrencyScenarioArray list = CurrencyScenarioArray.of(GBP, values);
// Market data doesn't include FX rates, conversion to USD will fail
ScenarioMarketData marketData = ScenarioMarketData.empty();
ConvertibleFunction fn = ConvertibleFunction.of(() -> list, GBP);
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result = calculationResults.getCells().get(0).getResult();
assertThat(result)
.isFailure(FailureReason.CURRENCY_CONVERSION)
.hasFailureMessageMatching("Failed to convert value '.*' to currency 'USD'");
}
/**
* Tests that executing a function wraps its return value in a success result.
*/
public void execute() {
SupplierFunction<String> fn = SupplierFunction.of(() -> "foo");
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
ScenarioMarketData marketData = ImmutableScenarioMarketData.builder(date(2011, 3, 8)).build();
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result = calculationResults.getCells().get(0).getResult();
assertThat(result).hasValue(ScenarioArray.of("foo"));
}
/**
* Test executing a bad function that fails to return expected measure.
*/
public void executeMissingMeasure() {
// function claims it supports 'PresentValueMultiCurrency' but fails to return it when asked
MeasureCheckFunction fn = new MeasureCheckFunction(ImmutableSet.of(TestingMeasures.PRESENT_VALUE), Optional.of("123"));
CalculationTaskCell cell0 = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTaskCell cell1 = CalculationTaskCell.of(0, 1, TestingMeasures.PRESENT_VALUE_MULTI_CCY, REPORTING_CURRENCY_USD);
CalculationTask task = CalculationTask.of(TARGET, fn, cell0, cell1);
ScenarioMarketData marketData = ScenarioMarketData.empty();
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result0 = calculationResults.getCells().get(0).getResult();
assertThat(result0)
.isSuccess()
.hasValue(ImmutableSet.of(TestingMeasures.PRESENT_VALUE, TestingMeasures.PRESENT_VALUE_MULTI_CCY));
Result<?> result1 = calculationResults.getCells().get(1).getResult();
assertThat(result1)
.isFailure(FailureReason.CALCULATION_FAILED)
.hasFailureMessageMatching(
"Function 'MeasureCheckFunction' did not return requested measure 'PresentValueMultiCurrency' for ID '123'");
}
/**
* Tests that executing a function filters the set of measures sent to function.
*/
public void executeFilterMeasures() {
// function does not support 'ParRate', so it should not be asked for it
MeasureCheckFunction fn = new MeasureCheckFunction(ImmutableSet.of(TestingMeasures.PRESENT_VALUE), Optional.of("123"));
CalculationTaskCell cell0 = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTaskCell cell1 = CalculationTaskCell.of(0, 1, TestingMeasures.PAR_RATE, REPORTING_CURRENCY_USD);
CalculationTask task = CalculationTask.of(TARGET, fn, cell0, cell1);
ScenarioMarketData marketData = ScenarioMarketData.empty();
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result0 = calculationResults.getCells().get(0).getResult();
assertThat(result0)
.isSuccess()
.hasValue(ImmutableSet.of(TestingMeasures.PRESENT_VALUE)); // ParRate not requested
Result<?> result1 = calculationResults.getCells().get(1).getResult();
assertThat(result1)
.isFailure(FailureReason.UNSUPPORTED)
.hasFailureMessageMatching("Measure 'ParRate' is not supported by function 'MeasureCheckFunction'");
}
/**
* Tests that executing a function that throws an exception wraps the exception in a failure result.
*/
public void executeException() {
SupplierFunction<String> fn = SupplierFunction.of(() -> {
throw new IllegalArgumentException("foo");
});
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
ScenarioMarketData marketData = ScenarioMarketData.empty();
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result = calculationResults.getCells().get(0).getResult();
assertThat(result)
.isFailure(FailureReason.CALCULATION_FAILED)
.hasFailureMessageMatching("Error when invoking function 'SupplierFunction' for ID '123': foo");
}
/**
* Tests that executing a function that throws a market data exception wraps the exception in a failure result.
*/
public void executeException_marketData() {
SupplierFunction<String> fn = SupplierFunction.of(() -> {
throw new MarketDataNotFoundException("foo");
});
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
ScenarioMarketData marketData = ScenarioMarketData.empty();
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result = calculationResults.getCells().get(0).getResult();
assertThat(result)
.isFailure(FailureReason.MISSING_DATA)
.hasFailureMessageMatching("Missing market data when invoking function 'SupplierFunction' for ID '123': foo");
}
/**
* Tests that executing a function that throws a market data exception wraps the exception in a failure result.
* Target has no identifier.
*/
public void executeException_marketData_noIdentifier() {
SupplierFunction<String> fn = SupplierFunction.of(() -> {
throw new MarketDataNotFoundException("foo");
}, Optional.empty());
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
ScenarioMarketData marketData = ScenarioMarketData.empty();
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result = calculationResults.getCells().get(0).getResult();
assertThat(result)
.isFailure(FailureReason.MISSING_DATA)
.hasFailureMessageMatching("Missing market data when invoking function 'SupplierFunction': foo: for target '.*'");
}
/**
* Tests that executing a function that throws a reference data exception wraps the exception in a failure result.
*/
public void executeException_referenceData() {
SupplierFunction<String> fn = SupplierFunction.of(() -> {
throw new ReferenceDataNotFoundException("foo");
});
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
ScenarioMarketData marketData = ScenarioMarketData.empty();
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result = calculationResults.getCells().get(0).getResult();
assertThat(result)
.isFailure(FailureReason.MISSING_DATA)
.hasFailureMessageMatching("Missing reference data when invoking function 'SupplierFunction' for ID '123': foo");
}
/**
* Tests that executing a function that throws an unsupported exception wraps the exception in a failure result.
*/
public void executeException_unsupported() {
SupplierFunction<String> fn = SupplierFunction.of(() -> {
throw new UnsupportedOperationException("foo");
});
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
ScenarioMarketData marketData = ScenarioMarketData.empty();
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result = calculationResults.getCells().get(0).getResult();
assertThat(result)
.isFailure(FailureReason.UNSUPPORTED)
.hasFailureMessageMatching("Unsupported operation when invoking function 'SupplierFunction' for ID '123': foo");
}
/**
* Tests that executing a function that returns a success result returns the underlying result without wrapping it.
*/
public void executeSuccessResultValue() {
SupplierFunction<Result<ScenarioArray<String>>> fn =
SupplierFunction.of(() -> Result.success(ScenarioArray.of("foo")));
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
ScenarioMarketData marketData = ImmutableScenarioMarketData.builder(date(2011, 3, 8)).build();
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result = calculationResults.getCells().get(0).getResult();
assertThat(result).hasValue(ScenarioArray.of("foo"));
}
/**
* Tests that executing a function that returns a failure result returns the underlying result without wrapping it.
*/
public void executeFailureResultValue() {
SupplierFunction<Result<String>> fn =
SupplierFunction.of(() -> Result.failure(FailureReason.NOT_APPLICABLE, "bar"));
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
ScenarioMarketData marketData = ScenarioMarketData.empty();
CalculationResults calculationResults = task.execute(marketData, REF_DATA);
Result<?> result = calculationResults.getCells().get(0).getResult();
assertThat(result).isFailure(FailureReason.NOT_APPLICABLE).hasFailureMessageMatching("bar");
}
/**
* Tests that requirements are added for the FX rates needed to convert the results into the reporting currency.
*/
public void fxConversionRequirements() {
OutputCurrenciesFunction fn = new OutputCurrenciesFunction();
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
MarketDataRequirements requirements = task.requirements(REF_DATA);
assertThat(requirements.getNonObservables()).containsOnly(
FxRateId.of(GBP, USD, OBS_SOURCE),
FxRateId.of(EUR, USD, OBS_SOURCE));
}
/**
* Tests that no requirements are added when not performing currency conversion.
*/
public void fxConversionRequirements_noConversion() {
OutputCurrenciesFunction fn = new OutputCurrenciesFunction();
CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, ReportingCurrency.NONE);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
MarketDataRequirements requirements = task.requirements(REF_DATA);
assertThat(requirements.getNonObservables()).isEmpty();
}
public void testToString() {
OutputCurrenciesFunction fn = new OutputCurrenciesFunction();
CalculationTaskCell cell = CalculationTaskCell.of(1, 2, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTask task = CalculationTask.of(TARGET, fn, cell);
assertThat(task.toString())
.isEqualTo("CalculationTask[CalculationTaskCell[(1, 2), measure=PresentValue, currency=Specific:USD]]");
}
//-------------------------------------------------------------------------
public void coverage() {
OutputCurrenciesFunction fn = new OutputCurrenciesFunction();
CalculationTaskCell cell = CalculationTaskCell.of(1, 2, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTask test = CalculationTask.of(TARGET, fn, cell);
coverImmutableBean(test);
OutputCurrenciesFunction fn2 = new OutputCurrenciesFunction();
CalculationTaskCell cell2 = CalculationTaskCell.of(1, 3, TestingMeasures.PRESENT_VALUE, REPORTING_CURRENCY_USD);
CalculationTask test2 = CalculationTask.of(new TestTarget(), fn2, cell2);
coverBeanEquals(test, test2);
assertNotNull(CalculationTask.meta());
}
//-------------------------------------------------------------------------
static class TestTarget implements CalculationTarget {
}
//-------------------------------------------------------------------------
/**
* Function that returns a value that is not currency convertible.
*/
public static final class TestFunction implements CalculationFunction<TestTarget> {
@Override
public Class<TestTarget> targetType() {
return TestTarget.class;
}
@Override
public Set<Measure> supportedMeasures() {
return MEASURES;
}
@Override
public Currency naturalCurrency(TestTarget trade, ReferenceData refData) {
return USD;
}
@Override
public FunctionRequirements requirements(
TestTarget target,
Set<Measure> measures,
CalculationParameters parameters,
ReferenceData refData) {
return FunctionRequirements.builder()
.valueRequirements(
ImmutableSet.of(
TestId.of("1"),
TestObservableId.of("2")))
.timeSeriesRequirements(TestObservableId.of("3"))
.observableSource(OBS_SOURCE)
.build();
}
@Override
public Map<Measure, Result<?>> calculate(
TestTarget target,
Set<Measure> measures,
CalculationParameters parameters,
ScenarioMarketData marketData,
ReferenceData refData) {
ScenarioArray<String> array = ScenarioArray.of("bar");
return ImmutableMap.of(TestingMeasures.PRESENT_VALUE, Result.success(array));
}
}
//-------------------------------------------------------------------------
/**
* Function that returns a value that is currency convertible.
*/
private static final class ConvertibleFunction
implements CalculationFunction<TestTarget> {
private final Supplier<CurrencyScenarioArray> supplier;
private final Currency naturalCurrency;
static ConvertibleFunction of(Supplier<CurrencyScenarioArray> supplier, Currency naturalCurrency) {
return new ConvertibleFunction(supplier, naturalCurrency);
}
private ConvertibleFunction(Supplier<CurrencyScenarioArray> supplier, Currency naturalCurrency) {
this.supplier = supplier;
this.naturalCurrency = naturalCurrency;
}
@Override
public Class<TestTarget> targetType() {
return TestTarget.class;
}
@Override
public Set<Measure> supportedMeasures() {
return MEASURES;
}
@Override
public Optional<String> identifier(TestTarget target) {
return Optional.of("123");
}
@Override
public Currency naturalCurrency(TestTarget trade, ReferenceData refData) {
return naturalCurrency;
}
@Override
public FunctionRequirements requirements(
TestTarget target,
Set<Measure> measures,
CalculationParameters parameters,
ReferenceData refData) {
return FunctionRequirements.empty();
}
@Override
public Map<Measure, Result<?>> calculate(
TestTarget target,
Set<Measure> measures,
CalculationParameters parameters,
ScenarioMarketData marketData,
ReferenceData refData) {
Result<CurrencyScenarioArray> result = Result.success(supplier.get());
return ImmutableMap.of(TestingMeasures.PRESENT_VALUE, result, TestingMeasures.PRESENT_VALUE_MULTI_CCY, result);
}
}
//-------------------------------------------------------------------------
/**
* Function that returns a value from a Supplier.
*/
private static final class SupplierFunction<T> implements CalculationFunction<TestTarget> {
private final Supplier<T> supplier;
private final Optional<String> id;
public static <T> SupplierFunction<T> of(Supplier<T> supplier) {
return of(supplier, Optional.of("123"));
}
public static <T> SupplierFunction<T> of(Supplier<T> supplier, Optional<String> id) {
return new SupplierFunction<>(supplier, id);
}
private SupplierFunction(Supplier<T> supplier, Optional<String> id) {
this.supplier = supplier;
this.id = id;
}
@Override
public Class<TestTarget> targetType() {
return TestTarget.class;
}
@Override
public Set<Measure> supportedMeasures() {
return MEASURES;
}
@Override
public Optional<String> identifier(TestTarget target) {
return id;
}
@Override
public Currency naturalCurrency(TestTarget trade, ReferenceData refData) {
return USD;
}
@Override
public FunctionRequirements requirements(
TestTarget target,
Set<Measure> measures,
CalculationParameters parameters,
ReferenceData refData) {
return FunctionRequirements.empty();
}
@SuppressWarnings("unchecked")
@Override
public Map<Measure, Result<?>> calculate(
TestTarget target,
Set<Measure> measures,
CalculationParameters parameters,
ScenarioMarketData marketData,
ReferenceData refData) {
T obj = supplier.get();
if (obj instanceof Result<?>) {
return ImmutableMap.of(TestingMeasures.PRESENT_VALUE, (Result<?>) obj);
}
ScenarioArray<Object> array = ScenarioArray.of(obj);
return ImmutableMap.of(TestingMeasures.PRESENT_VALUE, Result.success(array));
}
}
//-------------------------------------------------------------------------
/**
* Function that returns a value from a Supplier.
*/
private static final class MeasureCheckFunction implements CalculationFunction<TestTarget> {
private final Set<Measure> resultMeasures;
private final Optional<String> id;
private MeasureCheckFunction(Set<Measure> resultMeasures, Optional<String> id) {
this.resultMeasures = resultMeasures;
this.id = id;
}
@Override
public Class<TestTarget> targetType() {
return TestTarget.class;
}
@Override
public Set<Measure> supportedMeasures() {
return MEASURES;
}
@Override
public Optional<String> identifier(TestTarget target) {
return id;
}
@Override
public Currency naturalCurrency(TestTarget trade, ReferenceData refData) {
return USD;
}
@Override
public FunctionRequirements requirements(
TestTarget target,
Set<Measure> measures,
CalculationParameters parameters,
ReferenceData refData) {
return FunctionRequirements.empty();
}
@SuppressWarnings("unchecked")
@Override
public Map<Measure, Result<?>> calculate(
TestTarget target,
Set<Measure> measures,
CalculationParameters parameters,
ScenarioMarketData marketData,
ReferenceData refData) {
Map<Measure, Result<?>> map = new HashMap<>();
for (Measure measure : resultMeasures) {
map.put(measure, Result.success(measures));
}
return map;
}
}
//-------------------------------------------------------------------------
/**
* Function that returns requirements containing output currencies.
*/
private static final class OutputCurrenciesFunction implements CalculationFunction<TestTarget> {
@Override
public Class<TestTarget> targetType() {
return TestTarget.class;
}
@Override
public Set<Measure> supportedMeasures() {
return MEASURES;
}
@Override
public Currency naturalCurrency(TestTarget trade, ReferenceData refData) {
return USD;
}
@Override
public FunctionRequirements requirements(
TestTarget target,
Set<Measure> measures,
CalculationParameters parameters,
ReferenceData refData) {
return FunctionRequirements.builder()
.outputCurrencies(GBP, EUR, USD)
.observableSource(OBS_SOURCE)
.build();
}
@Override
public Map<Measure, Result<?>> calculate(
TestTarget target,
Set<Measure> measures,
CalculationParameters parameters,
ScenarioMarketData marketData,
ReferenceData refData) {
throw new UnsupportedOperationException("calculate not implemented");
}
}
}
|
apache-2.0
|
rzagabe/bazel
|
src/main/java/com/google/devtools/build/lib/actions/MutableActionGraph.java
|
6415
|
// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.actions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.syntax.Label;
import com.google.devtools.build.lib.util.StringUtil;
import java.util.Set;
/**
* A mutable action graph. Implementations of this interface must be thread-safe.
*/
public interface MutableActionGraph extends ActionGraph {
/**
* Attempts to register the action. If any of the action's outputs already has a generating
* action, and the two actions are not compatible, then an {@link ActionConflictException} is
* thrown. The internal data structure may be partially modified when that happens; it is not
* guaranteed that all potential conflicts are detected, but at least one of them is.
*
* <p>For example, take three actions A, B, and C, where A creates outputs a and b, B creates just
* b, and C creates c and b. There are two potential conflicts in this case, between A and B, and
* between B and C. Depending on the ordering of calls to this method and the ordering of outputs
* in the action output lists, either one or two conflicts are detected: if B is registered first,
* then both conflicts are detected; if either A or C is registered first, then only one conflict
* is detected.
*/
void registerAction(Action action) throws ActionConflictException;
/**
* Removes an action from this action graph if it is present.
*
* <p>Throws {@link IllegalStateException} if one of the outputs of the action is in fact
* generated by a different {@link Action} instance (even if they are sharable).
*/
void unregisterAction(Action action);
/**
* Clear the action graph.
*/
void clear();
/**
* This exception is thrown when a conflict between actions is detected. It contains information
* about the artifact for which the conflict is found, and data about the two conflicting actions
* and their owners.
*/
public static final class ActionConflictException extends Exception {
private final Artifact artifact;
private final Action previousAction;
private final Action attemptedAction;
public ActionConflictException(Artifact artifact, Action previousAction,
Action attemptedAction) {
super("for " + artifact);
this.artifact = artifact;
this.previousAction = previousAction;
this.attemptedAction = attemptedAction;
}
public Artifact getArtifact() {
return artifact;
}
public void reportTo(EventHandler eventListener) {
String msg = "file '" + artifact.prettyPrint()
+ "' is generated by these conflicting actions:\n" +
suffix(attemptedAction, previousAction);
eventListener.handle(Event.error(msg));
}
private void addStringDetail(StringBuilder sb, String key, String valueA, String valueB) {
valueA = valueA != null ? valueA : "(null)";
valueB = valueB != null ? valueB : "(null)";
sb.append(key).append(": ").append(valueA);
if (!valueA.equals(valueB)) {
sb.append(", ").append(valueB);
}
sb.append("\n");
}
private void addListDetail(StringBuilder sb, String key,
Iterable<Artifact> valueA, Iterable<Artifact> valueB) {
Set<Artifact> setA = ImmutableSet.copyOf(valueA);
Set<Artifact> setB = ImmutableSet.copyOf(valueB);
SetView<Artifact> diffA = Sets.difference(setA, setB);
SetView<Artifact> diffB = Sets.difference(setB, setA);
sb.append(key).append(": ");
if (diffA.isEmpty() && diffB.isEmpty()) {
sb.append("are equal");
} else {
if (!diffA.isEmpty() && !diffB.isEmpty()) {
sb.append("attempted action contains artifacts not in previous action and "
+ "previous action contains artifacts not in attempted action: "
+ diffA + ", " + diffB);
} else if (!diffA.isEmpty()) {
sb.append("attempted action contains artifacts not in previous action: ");
sb.append(StringUtil.joinEnglishList(diffA, "and"));
} else if (!diffB.isEmpty()) {
sb.append("previous action contains artifacts not in attempted action: ");
sb.append(StringUtil.joinEnglishList(diffB, "and"));
}
}
sb.append("\n");
}
// See also Actions.canBeShared()
private String suffix(Action a, Action b) {
// Note: the error message reveals to users the names of intermediate files that are not
// documented in the BUILD language. This error-reporting logic is rather elaborate but it
// does help to diagnose some tricky situations.
StringBuilder sb = new StringBuilder();
ActionOwner aOwner = a.getOwner();
ActionOwner bOwner = b.getOwner();
boolean aNull = aOwner == null;
boolean bNull = bOwner == null;
addStringDetail(sb, "Label", aNull ? null : Label.print(aOwner.getLabel()),
bNull ? null : Label.print(bOwner.getLabel()));
addStringDetail(sb, "RuleClass", aNull ? null : aOwner.getTargetKind(),
bNull ? null : bOwner.getTargetKind());
addStringDetail(sb, "Configuration", aNull ? null : aOwner.getConfigurationName(),
bNull ? null : bOwner.getConfigurationName());
addStringDetail(sb, "Mnemonic", a.getMnemonic(), b.getMnemonic());
addStringDetail(sb, "Progress message", a.getProgressMessage(), b.getProgressMessage());
addListDetail(sb, "MandatoryInputs", a.getMandatoryInputs(), b.getMandatoryInputs());
addListDetail(sb, "Outputs", a.getOutputs(), b.getOutputs());
return sb.toString();
}
}
}
|
apache-2.0
|
tallycheck/general
|
general-solution/src/main/java/com/taoswork/tallycheck/general/solution/threading/ThreadLocalHelper.java
|
1473
|
package com.taoswork.tallycheck.general.solution.threading;
import com.taoswork.tallycheck.general.solution.quickinterface.IValueMaker;
/**
* Created by Gao Yuan on 2015/8/16.
*/
public class ThreadLocalHelper {
public static <T> ThreadLocal<T> createThreadLocal(final Class<T> type, final IValueMaker<T> valueMaker) {
ThreadLocal<T> result = new ThreadLocal<T>() {
@Override
protected T initialValue() {
if(valueMaker != null){
return valueMaker.make();
}
return super.initialValue();
}
};
return result;
}
public static <T> ThreadLocal<T> createThreadLocal(final Class<T> type, final boolean createInitialValue) {
IValueMaker<T> valueMaker = createInitialValue ? new IValueMaker<T>() {
@Override
public T make() {
T obj = null;
try {
obj = type.newInstance();
} catch (InstantiationException exp) {
throw new RuntimeException(exp);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
return obj;
}
} : null;
return createThreadLocal(type, valueMaker);
}
public static <T> ThreadLocal<T> createThreadLocal(final Class<T> type) {
return createThreadLocal(type, true);
}
}
|
apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.