repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
jeltz/rust-debian-package
src/test/run-pass/iter-contains.rs
895
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub fn main() { assert!([].contains(&22u) == false); assert!([1u, 3u].contains(&22u) == false); assert!([22u, 1u, 3u].contains(&22u) == true); assert!([1u, 22u, 3u].contains(&22u) == true); assert!([1u, 3u, 22u].contains(&22u) == true); assert!(iter::contains(&None::<uint>, &22u) == false); assert!(iter::contains(&Some(1u), &22u) == false); assert!(iter::contains(&Some(22u), &22u) == true); }
apache-2.0
brunexmg/saude
src/test/java/com/oficina/saude/SaudepublicaApplicationTests.java
340
package com.oficina.saude; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SaudepublicaApplicationTests { @Test public void contextLoads() { } }
apache-2.0
medfreeman/remark-generic-extensions
src/locators/inline.js
126
const inlineExtensionLocator = (value, fromIndex) => value.indexOf("!", fromIndex); export default inlineExtensionLocator;
apache-2.0
peterarsentev/junior
chapter_013/src/main/java/ru/job4j/pattern/Messenger.java
85
package ru.job4j.pattern; public interface Messenger<T> { void send(T event); }
apache-2.0
Avetius/list.am_automation
list.casper.js
4521
/** * Created by avet.sargsyan@gmail.com on 9/9/17. */ // Այս կոդը browser-ի ավտոմատացման օրինակ է, որը իրականացնում է հայտարարության ավտոմատացված ավելացում list.am կայքում // Ամեն էջում կատարած գործողություններից հետո արվում է screenshot, որը պահվում է list.am դիրեկտորիայում var casper = require('casper').create({ verbose: false, logLevel: 'debug', userAgent: 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/56.0', pageSettings: {} }), email = require('./config').email, password = require('./config').password, // your password yourName = require('./config').yourName, // your name annTitle = require('./config').annTitle, // title of announcement annDesc = require('./config').annDesc, // description of announcement annPhone1 = require('./config').annPhone1, // contact phones annPhone2 = require('./config').annPhone2, annPhone3 = require('./config').annPhone3, login = 'https://www.list.am/login', my = 'https://www.list.am/my', startTime = Date.now(); casper.start(login, function() { // entering Login page this.echo('login page opened'); casper.capture('list.am/login.png'); // screenshot the Login page }); casper.then(function() { this.sendKeys('input[name="your_email"]', email); // fill in input with name 'your_email' this.sendKeys('input[name="password"]', password); // fill in input with name 'password' this.click('input[name="_form_action0"]'); // click on "send" button this.echo("logging in..."); // this.echo = console.log }); casper.then(function() { this.waitForSelector("a[href='/add']", // wait for a href=/add link to appear a[href='/add'] function pass () { casper.click("a[href='/add']"); this.echo("adding announcement..."); }, function fail(){ this.echo("Something went wrong"); this.exit(); }, 20000 // timeout limit in milliseconds ); casper.capture('list.am/myPage.png'); }); casper.thenOpen('https://www.list.am/add/162', function(){ this.echo("announcement page opened"); casper.capture('list.am/announcementDetails.png'); this.waitForSelector('input#_idtitle', function pass () { this.evaluate(function() { var form = document.querySelector('select#_idlocation'); // select select option index 7 form.selectedIndex = 7; $(form).change(); }); this.sendKeys('input#_idtitle', annTitle); this.sendKeys('textarea#_iddescription', annDesc); if(casper.exists('input#_idyour_name')){ this.sendKeys('input#_idyour_name', yourName); } this.sendKeys('input#_idphone_1', annPhone1); this.sendKeys('input#_idphone_2', annPhone2); this.sendKeys('input#_idphone_3', annPhone3); casper.capture('list.am/announcementFilled.png'); casper.click('input#postaction__form_action0'); }, function fail(){ this.echo("Something went wrong"); this.exit(); }, 10000 ); }); casper.then(function() { this.echo("waiting for errors.."); this.waitForSelector('div.error', function pass () { this.echo("Error On Publish..."); var errors = casper.getElementInfo('div.error td').text; this.echo(errors); console.log('errors -> ',errors); this.echo('Exiting with errors : '+ errors + ', Time elapsed = '+ (Date.now() - startTime)+'ms'); }, function fail () { this.echo("Published with no errors :)") }, 20000 ); casper.capture('list.am/waitingForErrors.png'); }); casper.then(function() { this.echo("publish page opened"); this.waitForSelector('input[name="_form_action1"]', function pass () { this.echo('Success!!! Time elapsed = '+ (Date.now() - startTime)+' ms'); casper.click('input[name="_form_action1"]'); }, function fail(){ this.echo("Something went wrong"); this.exit(); }, 20000 ); casper.capture('list.am/PublishReview.png'); }); casper.run(function() { });
apache-2.0
limoncello-php/framework
components/Events/tests/Data/Events/CreatedEvent.php
826
<?php declare(strict_types=1); namespace Limoncello\Tests\Events\Data\Events; /** * Copyright 2015-2019 info@neomerx.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use Limoncello\Events\Contracts\EventInterface; /** * @package Limoncello\Tests\Events */ interface CreatedEvent extends EventInterface { }
apache-2.0
CINERGI/SciGraph
SciGraph-core/src/test/java/io/scigraph/util/GraphTestBase.java
3737
/** * Copyright (C) 2014 The SciGraph authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.scigraph.util; import static com.google.common.collect.Sets.newHashSet; import io.scigraph.frames.CommonProperties; import io.scigraph.frames.Concept; import io.scigraph.frames.NodeProperties; import io.scigraph.internal.CypherUtil; import io.scigraph.neo4j.Graph; import io.scigraph.neo4j.GraphTransactionalImpl; import io.scigraph.neo4j.Neo4jConfiguration; import io.scigraph.neo4j.Neo4jModule; import io.scigraph.neo4j.RelationshipMap; import io.scigraph.owlapi.OwlLabels; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.Transaction; import org.neo4j.test.TestGraphDatabaseFactory; import org.prefixcommons.CurieUtil; public class GraphTestBase { protected static GraphDatabaseService graphDb; protected static CypherUtil cypherUtil; protected static Graph graph; protected static CurieUtil curieUtil; static ConcurrentHashMap<String, Long> idMap = new ConcurrentHashMap<>(); Transaction tx; static protected Node createNode(String iri) { long node = graph.createNode(iri); graph.setNodeProperty(node, CommonProperties.IRI, iri); if (iri.startsWith("_:")) { graph.addLabel(node, OwlLabels.OWL_ANONYMOUS); } return graphDb.getNodeById(node); } static protected Relationship addRelationship(String parentIri, String childIri, RelationshipType type) { Node parent = createNode(parentIri); Node child = createNode(childIri); return child.createRelationshipTo(parent, type); } @BeforeClass public static void setupDb() { graphDb = new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().newGraphDatabase(); // graphDb = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(new // File("/tmp/lucene")).newGraphDatabase(); // convenient for debugging Neo4jConfiguration config = new Neo4jConfiguration(); config.getExactNodeProperties().addAll( newHashSet(NodeProperties.LABEL, Concept.SYNONYM, Concept.ABREVIATION, Concept.ACRONYM)); config.getIndexedNodeProperties().addAll( newHashSet(NodeProperties.LABEL, Concept.CATEGORY, Concept.SYNONYM, Concept.ABREVIATION, Concept.ACRONYM)); Neo4jModule.setupAutoIndexing(graphDb, config); graph = new GraphTransactionalImpl(graphDb, idMap, new RelationshipMap()); curieUtil = new CurieUtil(Collections.<String, String>emptyMap()); cypherUtil = new CypherUtil(graphDb, curieUtil); } @AfterClass public static void shutdown() { graphDb.shutdown(); } @Before public void startTransaction() { tx = graphDb.beginTx(); } @After public void failTransaction() { idMap.clear(); tx.failure(); // tx.success(); // convenient for debugging tx.close(); } }
apache-2.0
MaferYangPointJun/Spring.net
test/Spring/Spring.Data.Tests/Data/Common/DbParametersTests.cs
2302
#region License /* * Copyright © 2002-2007 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. */ #endregion #if (NET_2_0) #region Imports using System.Data; using System.Data.OracleClient; using NUnit.Framework; #endregion namespace Spring.Data.Common { /// <summary> /// This class contains tests for DbParameters /// </summary> /// <author>Mark Pollack</author> [TestFixture] public class DbParametersTests { [SetUp] public void Setup() { } [Test] public void OracleClient() { IDbProvider dbProvider = DbProviderFactory.GetDbProvider("System.Data.OracleClient"); DbParameters dbParameters = new DbParameters(dbProvider); dbParameters.Add("p1", DbType.String); IDataParameter parameter = dbParameters[0]; Assert.AreEqual("p1", parameter.ParameterName); dbParameters.SetValue("p1", "foo"); object springParameter = dbParameters.GetValue("p1"); Assert.IsNotNull(springParameter); Assert.AreEqual("foo", springParameter); } [Test] public void SqlClient() { IDbProvider dbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); DbParameters dbParameters = new DbParameters(dbProvider); dbParameters.Add("p1", DbType.String); IDataParameter parameter = dbParameters[0]; Assert.AreEqual("@p1", parameter.ParameterName); dbParameters.SetValue("p1", "foo"); object springParameter = dbParameters.GetValue("p1"); Assert.IsNotNull(springParameter); Assert.AreEqual("foo", springParameter); } } } #endif
apache-2.0
x19990416/macrossx-guice
src/wechat/java/com/macrossx/wechat/entity/server/WechatTextRequest.java
1113
/** * Copyright (C) 2016 X-Forever. * * 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.macrossx.wechat.entity.server; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; @Data @EqualsAndHashCode(callSuper=false) @ToString(callSuper=true) @XmlRootElement(name="xml") public class WechatTextRequest extends WechatHttpEntity{ @XmlElement(name = "Content") private String Content; @XmlElement(name = "MsgId") private String MsgId; }
apache-2.0
jucimarjr/IPC_2017-1
lista08/ipc/matriz.py
7760
# Biblioteca de funções para as matrizes import random # função para criar matriz de ordem n x m def cria_matriz(n, m): matriz = [] for i in range(n): list = [] for j in range(m): # serão inseridos valores aleatórios na matriz (entre 1 e 4) value = random.randint(1, 4) list.append(value) matriz.append(list) return matriz # função para criar matriz quadrada de ordem n def cria_matriz_quadrada(n): matriz = [] for i in range(n): list = [] for j in range(n): # serão inseridos valores aleatórios na matriz (entre 1 e 4) value = random.randint(1, 4) list.append(value) matriz.append(list) return matriz # função para imprimir uma matriz de qualquer ordem def imprime_matriz(matriz): for i in matriz: print(i) #função para multiplicar duas matrizes(matriz A e matriz B) e retornar a matriz resultante(matriz AxB) def produto_matricial(matriz1, matriz2): matriz_result = [] linhas = len(matriz1) colunas = len(matriz2[0]) # verifica se o numero de colunas de A # é igual ao número de linhas de B if (len(matriz1[0])) == (len(matriz2)): for i in range(linhas): matriz_result.append([]) for j in range(colunas): value = 0 for aux in range(len(matriz2)): value += matriz1[i][aux] * matriz2[aux][j] matriz_result[i].append(value) return matriz_result else: return 'O produto não é possível' # função para imprimir os índices de uma matriz de qualquer ordem def imprime_matriz_indices(matriz): for i in range(len(matriz)): for j in range(len(matriz[0])): print("%d%d" % (i, j), end=" ") print() # lista 1 questão 3 # função para imprimir retângulo com uma matriz def imprime_retagulo_matriz(matriz): for i in range(len(matriz)): for j in range(len(matriz[0])): largura = len(matriz[i]) - 1 altura = len(matriz) - 1 if (j == 0 and i == altura) or (j == largura and i == 0) or (i == altura and i == 0) or ( i == 0 and j == 0) or ( i == altura and j == largura): caractere = "+" elif (j == largura): caractere = "|" elif (i == 0): caractere = "-" elif (j == 0): caractere = "|" elif (i == altura): caractere = "-" else: caractere = " " print("%s" % (caractere), end=" ") print() # função que pultiplica cada elemento da matriz por um número n e retorna um vetor def multiplica_matriz_por_inteiro(matriz, n): vetor = [] for i in range(len(matriz)): for j in range(len(matriz)): vetor.append(matriz[i][j] * n) return vetor # lista 2 questão 28 # função que retorna o maior elemento da diagonal principal def maior_da_diagonal_principal(matriz): maior = matriz[0][0] for i, n in enumerate(matriz): for j, m in enumerate(n): if i == j: if j > maior: maior = j return maior # função que retorna um vetor com os elementos da diagonal principal def diagonal_principal(matriz): vetor = [] for i, n in enumerate(matriz): for j, m in enumerate(n): if i == j: vetor.append(matriz[i][j]) return vetor # função que retorna um vetor com os elementos da diagonal secundária def diagonal_secundaria(matriz): ordem = len(matriz) j = ordem - 1 secundaria = [] for i in range(ordem): secundaria.append(matriz[i][j]) j -= 1 return secundaria # função que retorna a média dos elementos da diagonal principal def media_diagonal_principal(matriz): vetor = [] soma = 0 c = 0 for i, n in enumerate(matriz): for j, m in enumerate(n): if i == j: soma += matriz[i][j] c += 1 return soma / c # função que retorna a média dos elementos da diagonal secundária def media_diagonal_secundaria(matriz): ordem = len(matriz) j = ordem - 1 soma = 0 c = 0 for i in range(ordem): soma += matriz[i][j] j -= 1 c += 1 return soma / c # lista02_questao37 função que retorna o minimax de uma matriz # def funcao_minimax(mat): minimax = mat[0][0] maior = mat[0][0] for i in range(10): menor = mat[i][0] maior_aux = maior for j in range(10): if mat[i][j] > maior_aux: maior_aux = mat[i][j] if mat[i][j] < menor: menor = mat[i][j] if maior_aux > maior: minimax = menor maior = maior_aux return minimax # lista02_questao36 função que retorna a soma da multiplica linha por diagonal # def multiplica_linha(mat): for i in range(6): di = mat[i][i] for j in range(6): mat[i][j] *= di return mat # Lista 2 questão 27 retorna o menor item da diagonal secundaria def menor_item_secundaria(matriz): secundaria = diagonal_secundaria(matriz) menor = min(secundaria) return menor def diferenca_m_por_n(A, B, C): C = 4*[6*[None]] for i in range(4): for j in range(6): C[i][j] = A[i][j] - B[j][i] return C # lista 2 questão 26 def soma_matriz_parcial(matriz, linha, coluna): n = len(matriz) m = len(matriz[0]) soma = 0 for i in range(n): soma += matriz[i][coluna] for j in range(m): soma += matriz[linha][j] return soma - matriz[linha][coluna] # lista 2 questão 39 def soma_abaixo_diagonal_principal(matriz): n = min(len(matriz), len(matriz[0])) soma = 0 for i in range(n): for j in range(i): soma += matriz[i][j] return soma def media_abaixo_diagonal_principal(matriz): n = min(len(matriz), len(matriz[0])) qtd = (n*(n-1))//2 return soma_abaixo_diagonal_principal(matriz)/qtd # lista 2 questão 40 def soma_acima_diagonal_principal(matriz): n = len(matriz) m = len(matriz[0]) soma = 0 for i in range(n): for j in range(i+1, m): soma += matriz[i][j] return soma # funcao que retorna a soma dos elementos def soma_elementos_matriz(matriz): acumulador = 0 for i in matriz: for j in i: acumulador += j return acumulador # lista 2 questão 26 def soma_linha5_coluna3(matriz): soma = 0 for i in range(len(matriz)): for j in range(len(matriz[0])): if i == 4 or j == 2: soma += matriz[i][j] return soma # função que cria matriz zerada def cria_matriz_zerada(n, m): matriz = [] linha = [] for i in range(n): linha.append(0 * m) matriz.append(linha) return matriz # função que soma as diagonais def soma_diagonais(matriz): vetor = [] soma = 0 c = 0 ordem = len(matriz) j = ordem - 1 for i, n in enumerate(matriz): for j, m in enumerate(n): if i == j: soma += matriz[i][j] for i in range(ordem): soma += matriz[i][j] j -= 1 return soma # lista 2 questão 29 def produto_matriz(matriz1, matriz2): matrizvirgem = [] for i in range(len(matriz1)): vetbranco = [] for j in range(len(matriz2[0])): vetbranco.append((matriz1[i][0] * matriz2[0][j]) + (matriz1[i][1] * matriz2[1][j])) matrizvirgem.append(vetbranco) return matrizvirgem
apache-2.0
owlabs/incubator-airflow
airflow/example_dags/example_xcom.py
2175
# -*- coding: utf-8 -*- # # 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 __future__ import print_function from airflow import DAG from airflow.operators.python_operator import PythonOperator from airflow.utils.dates import days_ago args = { 'owner': 'Airflow', 'start_date': days_ago(2), 'provide_context': True, } dag = DAG('example_xcom', schedule_interval="@once", default_args=args, tags=['example']) value_1 = [1, 2, 3] value_2 = {'a': 'b'} def push(**kwargs): """Pushes an XCom without a specific target""" kwargs['ti'].xcom_push(key='value from pusher 1', value=value_1) def push_by_returning(**kwargs): """Pushes an XCom without a specific target, just by returning it""" return value_2 def puller(**kwargs): ti = kwargs['ti'] # get value_1 v1 = ti.xcom_pull(key=None, task_ids='push') assert v1 == value_1 # get value_2 v2 = ti.xcom_pull(task_ids='push_by_returning') assert v2 == value_2 # get both value_1 and value_2 v1, v2 = ti.xcom_pull(key=None, task_ids=['push', 'push_by_returning']) assert (v1, v2) == (value_1, value_2) push1 = PythonOperator( task_id='push', dag=dag, python_callable=push, ) push2 = PythonOperator( task_id='push_by_returning', dag=dag, python_callable=push_by_returning, ) pull = PythonOperator( task_id='puller', dag=dag, python_callable=puller, ) pull << [push1, push2]
apache-2.0
Banbury/cartwheel-3d
Python/App/__init__.py
179
from SNMApp import SNMApp from SnapshotTree import SnapshotBranch, Snapshot from ObservableList import ObservableList import Scenario import InstantChar import KeyframeEditor
apache-2.0
andrewlarkin/Photo-Rainbow
UnitTests/FlickrManagerTests.cs
1233
using System; namespace UnitTests { using NUnit.Framework; using Photo_Rainbow; using Moq; using FlickrNet; [TestFixture] public class FlickrManagerTests { private static FlickrManager f; private static Mock<FlickrManager> fMock; [SetUp] public void Init() { f = new FlickrManager(); fMock = new Mock<FlickrManager>(); } [Test] public void IsInstanceOfIAPIManager() { Assert.IsInstanceOf<IAPIManager>(f); } [Test] public void SetsFlickrInstance() { Assert.IsInstanceOf<Flickr>(f.Instance); } [Test] public void AuthenticationTest() { f.Authenticate(); Assert.IsNotNull(f.url); } // [Test] // public void CompleteAuthTest() // { // fMock.Verify(ff => ff.Authenticate(), Times.AtLeastOnce()); // Assert.IsTrue(f.IsAuthenticated()); // } // [Test] // public void GetPhotosTest() // { // Assert.IsNotNull(f.GetPhotos()); // } } }
apache-2.0
duwenjun199081/qihaosou
library_okhttputils/src/main/java/com/lzy/okhttputils/request/BaseRequest.java
10992
package com.lzy.okhttputils.request; import android.support.annotation.NonNull; import com.lzy.okhttputils.L; import com.lzy.okhttputils.OkHttpUtils; import com.lzy.okhttputils.SystemUtils; import com.lzy.okhttputils.callback.AbsCallback; import com.lzy.okhttputils.https.HttpsUtils; import com.lzy.okhttputils.https.TaskException; import com.lzy.okhttputils.model.RequestHeaders; import com.lzy.okhttputils.model.RequestParams; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.SocketTimeoutException; import java.net.URLEncoder; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.Headers; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * ================================================ * 作 者:廖子尧 * 版 本:1.0 * 创建日期:2016/1/12 * 描 述:所有请求的基类,其中泛型 R 主要用于属性设置方法后,返回对应的子类型,以便于实现链式调用 * 修订历史: * ================================================ */ public abstract class BaseRequest<R extends BaseRequest> { protected String url; protected Object tag; protected long readTimeOut; protected long writeTimeOut; protected long connectTimeout; protected InputStream[] certificates; protected RequestParams params = new RequestParams(); protected RequestHeaders headers = new RequestHeaders(); private AbsCallback mCallback; public BaseRequest(String url) { this.url = url; //添加公共请求参数 if (OkHttpUtils.getInstance().getCommonParams() != null) { params.put(OkHttpUtils.getInstance().getCommonParams()); } if (OkHttpUtils.getInstance().getCommonHeader() != null) { headers.put(OkHttpUtils.getInstance().getCommonHeader()); } } public R url(@NonNull String url) { this.url = url; return (R) this; } public R tag(Object tag) { this.tag = tag; return (R) this; } public R readTimeOut(long readTimeOut) { this.readTimeOut = readTimeOut; return (R) this; } public R writeTimeOut(long writeTimeOut) { this.writeTimeOut = writeTimeOut; return (R) this; } public R connTimeOut(long connTimeOut) { this.connectTimeout = connTimeOut; return (R) this; } public R setCertificates(@NonNull InputStream... certificates) { this.certificates = certificates; return (R) this; } public R headers(RequestHeaders headers) { this.headers.put(headers); return (R) this; } public R headers(String key, String value) { headers.put(key, value); return (R) this; } public R params(RequestParams params) { this.params.put(params); return (R) this; } public R params(String key, String value) { params.put(key, value); return (R) this; } public R params(String key, File file) { params.put(key, file); return (R) this; } public R params(String key, File file, String fileName) { params.put(key, file, fileName); return (R) this; } public R params(String key, File file, String fileName, MediaType contentType) { params.put(key, file, fileName, contentType); return (R) this; } public AbsCallback getCallback() { return mCallback; } public void setCallback(AbsCallback callback) { this.mCallback = callback; } /** 将传递进来的参数拼接成 url */ protected String createUrlFromParams(String url, Map<String, String> params) { try { StringBuilder sb = new StringBuilder(); sb.append(url); if (url.indexOf('&') > 0 || url.indexOf('?') > 0) sb.append("&"); else sb.append("?"); for (Map.Entry<String, String> urlParams : params.entrySet()) { String urlValue = URLEncoder.encode(urlParams.getValue(), "UTF-8"); sb.append(urlParams.getKey()).append("=").append(urlValue).append("&"); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return url; } /** 通用的拼接请求头 */ protected Request.Builder appendHeaders(Request.Builder requestBuilder) { Headers.Builder headerBuilder = new Headers.Builder(); ConcurrentHashMap<String, String> headerMap = headers.headersMap; if (headerMap.isEmpty()) return requestBuilder; for (String key : headerMap.keySet()) { headerBuilder.add(key, headerMap.get(key)); } requestBuilder.headers(headerBuilder.build()); return requestBuilder; } /** 根据不同的请求方式和参数,生成不同的RequestBody */ public abstract RequestBody generateRequestBody(); /** 对请求body进行包装,用于回调上传进度 */ public RequestBody wrapRequestBody(RequestBody requestBody) { return new ProgressRequestBody(requestBody, new ProgressRequestBody.Listener() { @Override public void onRequestProgress(final long bytesWritten, final long contentLength, final long networkSpeed) { OkHttpUtils.getInstance().getDelivery().post(new Runnable() { @Override public void run() { if (mCallback != null) mCallback.upProgress(bytesWritten, contentLength, bytesWritten * 1.0f / contentLength, networkSpeed); } }); } }); } /** 根据不同的请求方式,将RequestBody转换成Request对象 */ public abstract Request generateRequest(RequestBody requestBody); /** 根据当前的请求参数,生成对应的 Call 任务 */ public Call generateCall(Request request) { if (readTimeOut <= 0 && writeTimeOut <= 0 && connectTimeout <= 0 && certificates == null) { return OkHttpUtils.getInstance().getOkHttpClient().newCall(request); } else { OkHttpClient.Builder newClientBuilder = OkHttpUtils.getInstance().getOkHttpClient().newBuilder(); if (readTimeOut > 0) newClientBuilder.readTimeout(readTimeOut, TimeUnit.MILLISECONDS); if (writeTimeOut > 0) newClientBuilder.writeTimeout(writeTimeOut, TimeUnit.MILLISECONDS); if (connectTimeout > 0) newClientBuilder.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS); if (certificates != null) newClientBuilder.sslSocketFactory(HttpsUtils.getSslSocketFactory(certificates, null, null)); return newClientBuilder.build().newCall(request); } } /** 阻塞方法,同步请求执行 */ public Response execute() throws IOException { RequestBody requestBody = generateRequestBody(); final Request request = generateRequest(wrapRequestBody(requestBody)); Call call = generateCall(request); return call.execute(); } /** 非阻塞方法,异步请求,但是回调在子线程中执行 */ public <T> void execute(AbsCallback<T> callback) { mCallback = callback; if (mCallback == null) mCallback = AbsCallback.CALLBACK_DEFAULT; mCallback.onBefore(this); //请求执行前调用 (UI线程) // 是否有网络连接 if (SystemUtils.getNetworkType() == SystemUtils.NetWorkType.none){ sendFailResultCallback(null,null, new TaskException(TaskException.TaskError.noneNetwork.toString()),mCallback); }else { RequestBody requestBody = generateRequestBody(); Request request = generateRequest(wrapRequestBody(requestBody)); Call call = generateCall(request); call.enqueue(new okhttp3.Callback() { @Override public void onFailure(Request request, IOException e) { //请求失败,一般为url地址错误,网络错误等 sendFailResultCallback(request, null, new TaskException(TaskException.TaskError.socketTimeout.toString()), mCallback); } @Override public void onResponse(Response response) throws IOException { //响应失败,一般为服务器内部错误,或者找不到页面等 if (response.code() >= 400 && response.code() <= 599) { sendFailResultCallback(response.request(), response, new TaskException(TaskException.TaskError.timeout.toString()), mCallback); return; } try { //解析过程中抛出异常,一般为 json 格式错误,或者数据解析异常 T t = (T) mCallback.parseNetworkResponse(response); sendSuccessResultCallback(t, response.request(), response, mCallback); }catch(TaskException e){ L.e(e.getMessage()); sendFailResultCallback(response.request(),response,e,mCallback); } catch (Exception e) { sendFailResultCallback(response.request(), response, new TaskException(TaskException.TaskError.resultIllegal.toString()), mCallback); } } }); } } /** 失败回调,发送到主线程 */ public <T> void sendFailResultCallback(final Request request, final Response response, final IOException e, final AbsCallback<T> callback) { OkHttpUtils.getInstance().getDelivery().post(new Runnable() { @Override public void run() { callback.onError(request, response, (TaskException)e); //请求失败回调 (UI线程) callback.onAfter(null, request, response, (TaskException)e); //请求结束回调 (UI线程) } }); } /** 成功回调,发送到主线程 */ public <T> void sendSuccessResultCallback(final T t, final Request request, final Response response, final AbsCallback<T> callback) { OkHttpUtils.getInstance().getDelivery().post(new Runnable() { @Override public void run() { callback.onResponse(t); //请求成功回调 (UI线程) callback.onAfter(t, request, response, null); //请求结束回调 (UI线程) } }); } }
apache-2.0
m-m-m/client
ui/widget/impl-native-javafx/src/main/java/net/sf/mmm/client/ui/impl/javafx/widget/adapter/UiWidgetAdapterJavaFxLabeled.java
752
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.client.ui.impl.javafx.widget.adapter; import javafx.scene.control.Labeled; /** * This is the implementation of {@link net.sf.mmm.client.ui.base.widget.adapter.UiWidgetAdapter} using JavaFx * based on {@link Labeled}. * * @param <WIDGET> is the generic type of {@link #getToplevelWidget()}. * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 1.0.0 */ public abstract class UiWidgetAdapterJavaFxLabeled<WIDGET extends Labeled> extends UiWidgetAdapterJavaFxControl<WIDGET> { /** * The constructor. */ public UiWidgetAdapterJavaFxLabeled() { super(); } }
apache-2.0
taktos/ea2ddl
ea2ddl-dao/src/main/java/jp/sourceforge/ea2ddl/dao/bsbhv/BsTDiagramtypesBhv.java
12492
package jp.sourceforge.ea2ddl.dao.bsbhv; import java.util.List; import org.seasar.dbflute.*; import org.seasar.dbflute.cbean.ConditionBean; import org.seasar.dbflute.cbean.EntityRowHandler; import org.seasar.dbflute.cbean.ListResultBean; import org.seasar.dbflute.cbean.PagingBean; import org.seasar.dbflute.cbean.PagingHandler; import org.seasar.dbflute.cbean.PagingInvoker; import org.seasar.dbflute.cbean.PagingResultBean; import org.seasar.dbflute.cbean.ResultBeanBuilder; import org.seasar.dbflute.dbmeta.DBMeta; import org.seasar.dbflute.jdbc.StatementConfig; import jp.sourceforge.ea2ddl.dao.allcommon.*; import jp.sourceforge.ea2ddl.dao.exentity.*; import jp.sourceforge.ea2ddl.dao.bsentity.dbmeta.*; import jp.sourceforge.ea2ddl.dao.cbean.*; /** * The behavior of t_diagramtypes that the type is TABLE. <br /> * <pre> * [primary-key] * * * [column] * Diagram_Type, Name, Package_ID * * [sequence] * * * [identity] * * * [version-no] * * * [foreign-table] * * * [referrer-table] * * * [foreign-property] * * * [referrer-property] * * </pre> * @author DBFlute(AutoGenerator) */ public abstract class BsTDiagramtypesBhv extends org.seasar.dbflute.bhv.AbstractBehaviorReadable { // =================================================================================== // Definition // ========== /*df:BehaviorQueryPathBegin*/ /*df:BehaviorQueryPathEnd*/ // =================================================================================== // Table name // ========== /** @return The name on database of table. (NotNull) */ public String getTableDbName() { return "t_diagramtypes"; } // =================================================================================== // DBMeta // ====== /** @return The instance of DBMeta. (NotNull) */ public DBMeta getDBMeta() { return TDiagramtypesDbm.getInstance(); } /** @return The instance of DBMeta as my table type. (NotNull) */ public TDiagramtypesDbm getMyDBMeta() { return TDiagramtypesDbm.getInstance(); } // =================================================================================== // New Instance // ============ public Entity newEntity() { return newMyEntity(); } public ConditionBean newConditionBean() { return newMyConditionBean(); } public TDiagramtypes newMyEntity() { return new TDiagramtypes(); } public TDiagramtypesCB newMyConditionBean() { return new TDiagramtypesCB(); } // =================================================================================== // Current DBDef // ============= @Override protected DBDef getCurrentDBDef() { return DBCurrent.getInstance().currentDBDef(); } // =================================================================================== // Default StatementConfig // ======================= @Override protected StatementConfig getDefaultStatementConfig() { return DBFluteConfig.getInstance().getDefaultStatementConfig(); } // =================================================================================== // Count Select // ============ /** * Select the count by the condition-bean. {IgnorePagingCondition} * @param cb The condition-bean of TDiagramtypes. (NotNull) * @return The selected count. */ public int selectCount(TDiagramtypesCB cb) { assertCBNotNull(cb); return delegateSelectCount(cb); } // =================================================================================== // Cursor Select // ============= /** * Select the cursor by the condition-bean. <br /> * Attention: It has a mapping cost from result set to entity. * @param cb The condition-bean of TDiagramtypes. (NotNull) * @param entityRowHandler The handler of entity row of TDiagramtypes. (NotNull) */ public void selectCursor(TDiagramtypesCB cb, EntityRowHandler<TDiagramtypes> entityRowHandler) { assertCBNotNull(cb); assertObjectNotNull("entityRowHandler<TDiagramtypes>", entityRowHandler); delegateSelectCursor(cb, entityRowHandler); } // =================================================================================== // Entity Select // ============= /** * Select the entity by the condition-bean. * @param cb The condition-bean of TDiagramtypes. (NotNull) * @return The selected entity. (Nullalble) * @exception org.seasar.dbflute.exception.EntityDuplicatedException When the entity has been duplicated. */ public TDiagramtypes selectEntity(final TDiagramtypesCB cb) { return helpSelectEntityInternally(cb, new InternalSelectEntityCallback<TDiagramtypes, TDiagramtypesCB>() { public List<TDiagramtypes> callbackSelectList(TDiagramtypesCB cb) { return selectList(cb); } }); } /** * Select the entity by the condition-bean with deleted check. * @param cb The condition-bean of TDiagramtypes. (NotNull) * @return The selected entity. (NotNull) * @exception org.seasar.dbflute.exception.EntityAlreadyDeletedException When the entity has already been deleted. * @exception org.seasar.dbflute.exception.EntityDuplicatedException When the entity has been duplicated. */ public TDiagramtypes selectEntityWithDeletedCheck(final TDiagramtypesCB cb) { return helpSelectEntityWithDeletedCheckInternally(cb, new InternalSelectEntityWithDeletedCheckCallback<TDiagramtypes, TDiagramtypesCB>() { public List<TDiagramtypes> callbackSelectList(TDiagramtypesCB cb) { return selectList(cb); } }); } // =================================================================================== // List Select // =========== /** * Select the list as result bean. * @param cb The condition-bean of TDiagramtypes. (NotNull) * @return The result bean of selected list. (NotNull) */ public ListResultBean<TDiagramtypes> selectList(TDiagramtypesCB cb) { assertCBNotNull(cb); return new ResultBeanBuilder<TDiagramtypes>(getTableDbName()).buildListResultBean(cb, delegateSelectList(cb)); } // =================================================================================== // Page Select // =========== /** * Select the page as result bean. * @param cb The condition-bean of TDiagramtypes. (NotNull) * @return The result bean of selected page. (NotNull) */ public PagingResultBean<TDiagramtypes> selectPage(final TDiagramtypesCB cb) { assertCBNotNull(cb); final PagingInvoker<TDiagramtypes> invoker = new PagingInvoker<TDiagramtypes>(getTableDbName()); final PagingHandler<TDiagramtypes> handler = new PagingHandler<TDiagramtypes>() { public PagingBean getPagingBean() { return cb; } public int count() { return selectCount(cb); } public List<TDiagramtypes> paging() { return selectList(cb); } }; return invoker.invokePaging(handler); } // =================================================================================== // Scalar Select // ============= /** * Select the scalar value derived by a function. <br /> * Call a function method after this method called like as follows: * <pre> * tDiagramtypesBhv.scalarSelect(Date.class).max(new ScalarQuery(TDiagramtypesCB cb) { * cb.specify().columnXxxDatetime(); // the required specification of target column * cb.query().setXxxName_PrefixSearch("S"); // query as you like it * }); * </pre> * @param <RESULT> The type of result. * @param resultType The type of result. (NotNull) * @return The scalar value derived by a function. (Nullable) */ public <RESULT> SLFunction<TDiagramtypesCB, RESULT> scalarSelect(Class<RESULT> resultType) { TDiagramtypesCB cb = newMyConditionBean(); cb.xsetupForScalarSelect(); cb.getSqlClause().disableSelectIndex(); // for when you use union return new SLFunction<TDiagramtypesCB, RESULT>(cb, resultType); } // =================================================================================== // Pull out Foreign // ================ // =================================================================================== // Delegate Method // =============== // [Behavior Command] // ----------------------------------------------------- // Select // ------ protected int delegateSelectCount(TDiagramtypesCB cb) { return invoke(createSelectCountCBCommand(cb)); } protected void delegateSelectCursor(TDiagramtypesCB cb, EntityRowHandler<TDiagramtypes> entityRowHandler) { invoke(createSelectCursorCBCommand(cb, entityRowHandler, TDiagramtypes.class)); } protected int doCallReadCount(ConditionBean cb) { return delegateSelectCount((TDiagramtypesCB)cb); } protected List<TDiagramtypes> delegateSelectList(TDiagramtypesCB cb) { return invoke(createSelectListCBCommand(cb, TDiagramtypes.class)); } @SuppressWarnings("unchecked") protected List<Entity> doCallReadList(ConditionBean cb) { return (List)delegateSelectList((TDiagramtypesCB)cb); } // =================================================================================== // Optimistic Lock Info // ==================== @Override protected boolean hasVersionNoValue(Entity entity) { return false; } @Override protected boolean hasUpdateDateValue(Entity entity) { return false; } // =================================================================================== // Helper // ====== protected TDiagramtypes downcast(Entity entity) { return helpDowncastInternally(entity, TDiagramtypes.class); } }
apache-2.0
aayushkapoor206/whatshot
node_modules/angular2/src/web_workers/shared/render_view_with_fragments_store.js
7278
'use strict';var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; var di_1 = require("angular2/src/core/di"); var api_1 = require("angular2/src/core/render/api"); var api_2 = require("angular2/src/web_workers/shared/api"); var collection_1 = require("angular2/src/facade/collection"); var RenderViewWithFragmentsStore = (function () { function RenderViewWithFragmentsStore(onWebWorker) { this._nextIndex = 0; this._onWebWorker = onWebWorker; this._lookupByIndex = new Map(); this._lookupByView = new Map(); this._viewFragments = new Map(); } RenderViewWithFragmentsStore.prototype.allocate = function (fragmentCount) { var initialIndex = this._nextIndex; var viewRef = new WebWorkerRenderViewRef(this._nextIndex++); var fragmentRefs = collection_1.ListWrapper.createGrowableSize(fragmentCount); for (var i = 0; i < fragmentCount; i++) { fragmentRefs[i] = new WebWorkerRenderFragmentRef(this._nextIndex++); } var renderViewWithFragments = new api_1.RenderViewWithFragments(viewRef, fragmentRefs); this.store(renderViewWithFragments, initialIndex); return renderViewWithFragments; }; RenderViewWithFragmentsStore.prototype.store = function (view, startIndex) { var _this = this; this._lookupByIndex.set(startIndex, view.viewRef); this._lookupByView.set(view.viewRef, startIndex); startIndex++; view.fragmentRefs.forEach(function (ref) { _this._lookupByIndex.set(startIndex, ref); _this._lookupByView.set(ref, startIndex); startIndex++; }); this._viewFragments.set(view.viewRef, view.fragmentRefs); }; RenderViewWithFragmentsStore.prototype.remove = function (view) { var _this = this; this._removeRef(view); var fragments = this._viewFragments.get(view); fragments.forEach(function (fragment) { _this._removeRef(fragment); }); this._viewFragments.delete(view); }; RenderViewWithFragmentsStore.prototype._removeRef = function (ref) { var index = this._lookupByView.get(ref); this._lookupByView.delete(ref); this._lookupByIndex.delete(index); }; RenderViewWithFragmentsStore.prototype.serializeRenderViewRef = function (viewRef) { return this._serializeRenderFragmentOrViewRef(viewRef); }; RenderViewWithFragmentsStore.prototype.serializeRenderFragmentRef = function (fragmentRef) { return this._serializeRenderFragmentOrViewRef(fragmentRef); }; RenderViewWithFragmentsStore.prototype.deserializeRenderViewRef = function (ref) { if (ref == null) { return null; } return this._retrieve(ref); }; RenderViewWithFragmentsStore.prototype.deserializeRenderFragmentRef = function (ref) { if (ref == null) { return null; } return this._retrieve(ref); }; RenderViewWithFragmentsStore.prototype._retrieve = function (ref) { if (ref == null) { return null; } if (!this._lookupByIndex.has(ref)) { return null; } return this._lookupByIndex.get(ref); }; RenderViewWithFragmentsStore.prototype._serializeRenderFragmentOrViewRef = function (ref) { if (ref == null) { return null; } if (this._onWebWorker) { return ref.serialize(); } else { return this._lookupByView.get(ref); } }; RenderViewWithFragmentsStore.prototype.serializeViewWithFragments = function (view) { var _this = this; if (view == null) { return null; } if (this._onWebWorker) { return { 'viewRef': view.viewRef.serialize(), 'fragmentRefs': view.fragmentRefs.map(function (val) { return val.serialize(); }) }; } else { return { 'viewRef': this._lookupByView.get(view.viewRef), 'fragmentRefs': view.fragmentRefs.map(function (val) { return _this._lookupByView.get(val); }) }; } }; RenderViewWithFragmentsStore.prototype.deserializeViewWithFragments = function (obj) { var _this = this; if (obj == null) { return null; } var viewRef = this.deserializeRenderViewRef(obj['viewRef']); var fragments = obj['fragmentRefs'].map(function (val) { return _this.deserializeRenderFragmentRef(val); }); return new api_1.RenderViewWithFragments(viewRef, fragments); }; RenderViewWithFragmentsStore = __decorate([ di_1.Injectable(), __param(0, di_1.Inject(api_2.ON_WEB_WORKER)), __metadata('design:paramtypes', [Object]) ], RenderViewWithFragmentsStore); return RenderViewWithFragmentsStore; })(); exports.RenderViewWithFragmentsStore = RenderViewWithFragmentsStore; var WebWorkerRenderViewRef = (function (_super) { __extends(WebWorkerRenderViewRef, _super); function WebWorkerRenderViewRef(refNumber) { _super.call(this); this.refNumber = refNumber; } WebWorkerRenderViewRef.prototype.serialize = function () { return this.refNumber; }; WebWorkerRenderViewRef.deserialize = function (ref) { return new WebWorkerRenderViewRef(ref); }; return WebWorkerRenderViewRef; })(api_1.RenderViewRef); exports.WebWorkerRenderViewRef = WebWorkerRenderViewRef; var WebWorkerRenderFragmentRef = (function (_super) { __extends(WebWorkerRenderFragmentRef, _super); function WebWorkerRenderFragmentRef(refNumber) { _super.call(this); this.refNumber = refNumber; } WebWorkerRenderFragmentRef.prototype.serialize = function () { return this.refNumber; }; WebWorkerRenderFragmentRef.deserialize = function (ref) { return new WebWorkerRenderFragmentRef(ref); }; return WebWorkerRenderFragmentRef; })(api_1.RenderFragmentRef); exports.WebWorkerRenderFragmentRef = WebWorkerRenderFragmentRef; //# sourceMappingURL=render_view_with_fragments_store.js.map
apache-2.0
Intacct/intacct-sdk-php
src/Intacct/Functions/AccountsPayable/ApPaymentDelete.php
892
<?php /** * Copyright 2021 Sage Intacct, 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 * * 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. */ namespace Intacct\Functions\AccountsPayable; use Intacct\Xml\XMLWriter; use InvalidArgumentException; /** * Delete an existing AP payment request record */ class ApPaymentDelete extends AbstractApPaymentFunction { protected function getFunction(): string { return AbstractApPaymentFunction::DELETE; } }
apache-2.0
pkimber/hatherleighcommunitycentre_couk
settings/dev_patrick.py
518
# -*- encoding: utf-8 -*- from .local import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test_www_hatherleighcommunitycentre_co_uk_patrick', 'USER': 'patrick', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } #DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': 'temp.db', # 'USER': '', # 'PASSWORD': '', # 'HOST': '', # 'PORT': '', # } #}
apache-2.0
themarkypantz/kafka
core/src/test/scala/integration/kafka/api/EndToEndClusterIdTest.scala
10237
/** * 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 kafka.api import java.util.concurrent.ExecutionException import java.util.concurrent.atomic.AtomicReference import java.util.Properties import kafka.common.TopicAndPartition import kafka.integration.KafkaServerTestHarness import kafka.server._ import kafka.utils._ import kafka.utils.Implicits._ import org.apache.kafka.clients.consumer._ import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, ProducerRecord} import org.apache.kafka.common.{ClusterResource, ClusterResourceListener, TopicPartition} import org.apache.kafka.test.{TestUtils => _, _} import org.junit.Assert._ import org.junit.{Before, Test} import scala.collection.JavaConverters._ import org.apache.kafka.test.TestUtils.isValidClusterId import scala.collection.mutable.ArrayBuffer /** The test cases here verify the following conditions. * 1. The ProducerInterceptor receives the cluster id after the onSend() method is called and before onAcknowledgement() method is called. * 2. The Serializer receives the cluster id before the serialize() method is called. * 3. The producer MetricReporter receives the cluster id after send() method is called on KafkaProducer. * 4. The ConsumerInterceptor receives the cluster id before the onConsume() method. * 5. The Deserializer receives the cluster id before the deserialize() method is called. * 6. The consumer MetricReporter receives the cluster id after poll() is called on KafkaConsumer. * 7. The broker MetricReporter receives the cluster id after the broker startup is over. * 8. The broker KafkaMetricReporter receives the cluster id after the broker startup is over. * 9. All the components receive the same cluster id. */ object EndToEndClusterIdTest { object MockConsumerMetricsReporter { val CLUSTER_META = new AtomicReference[ClusterResource] } class MockConsumerMetricsReporter extends MockMetricsReporter with ClusterResourceListener { override def onUpdate(clusterMetadata: ClusterResource) { MockConsumerMetricsReporter.CLUSTER_META.set(clusterMetadata) } } object MockProducerMetricsReporter { val CLUSTER_META = new AtomicReference[ClusterResource] } class MockProducerMetricsReporter extends MockMetricsReporter with ClusterResourceListener { override def onUpdate(clusterMetadata: ClusterResource) { MockProducerMetricsReporter.CLUSTER_META.set(clusterMetadata) } } object MockBrokerMetricsReporter { val CLUSTER_META = new AtomicReference[ClusterResource] } class MockBrokerMetricsReporter extends MockMetricsReporter with ClusterResourceListener { override def onUpdate(clusterMetadata: ClusterResource) { MockBrokerMetricsReporter.CLUSTER_META.set(clusterMetadata) } } } class EndToEndClusterIdTest extends KafkaServerTestHarness { import EndToEndClusterIdTest._ val producerCount = 1 val consumerCount = 1 val serverCount = 1 lazy val producerConfig = new Properties lazy val consumerConfig = new Properties lazy val serverConfig = new Properties val numRecords = 1 val topic = "e2etopic" val part = 0 val tp = new TopicPartition(topic, part) val topicAndPartition = TopicAndPartition(topic, part) this.serverConfig.setProperty(KafkaConfig.MetricReporterClassesProp, classOf[MockBrokerMetricsReporter].getName) override def generateConfigs = { val cfgs = TestUtils.createBrokerConfigs(serverCount, zkConnect, interBrokerSecurityProtocol = Some(securityProtocol), trustStoreFile = trustStoreFile, saslProperties = serverSaslProperties) cfgs.foreach(_ ++= serverConfig) cfgs.map(KafkaConfig.fromProps) } @Before override def setUp() { super.setUp() MockDeserializer.resetStaticVariables // create the consumer offset topic TestUtils.createTopic(this.zkUtils, topic, 2, serverCount, this.servers) } @Test def testEndToEnd() { val appendStr = "mock" MockConsumerInterceptor.resetCounters() MockProducerInterceptor.resetCounters() assertNotNull(MockBrokerMetricsReporter.CLUSTER_META) isValidClusterId(MockBrokerMetricsReporter.CLUSTER_META.get.clusterId) val producerProps = new Properties() producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList) producerProps.put(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG, classOf[MockProducerInterceptor].getName) producerProps.put("mock.interceptor.append", appendStr) producerProps.put(ProducerConfig.METRIC_REPORTER_CLASSES_CONFIG, classOf[MockProducerMetricsReporter].getName) val testProducer = new KafkaProducer(producerProps, new MockSerializer, new MockSerializer) // Send one record and make sure clusterId is set after send and before onAcknowledgement sendRecords(testProducer, 1, tp) assertNotEquals(MockProducerInterceptor.CLUSTER_ID_BEFORE_ON_ACKNOWLEDGEMENT, MockProducerInterceptor.NO_CLUSTER_ID) assertNotNull(MockProducerInterceptor.CLUSTER_META) assertEquals(MockProducerInterceptor.CLUSTER_ID_BEFORE_ON_ACKNOWLEDGEMENT.get.clusterId, MockProducerInterceptor.CLUSTER_META.get.clusterId) isValidClusterId(MockProducerInterceptor.CLUSTER_META.get.clusterId) // Make sure that serializer gets the cluster id before serialize method. assertNotEquals(MockSerializer.CLUSTER_ID_BEFORE_SERIALIZE, MockSerializer.NO_CLUSTER_ID) assertNotNull(MockSerializer.CLUSTER_META) isValidClusterId(MockSerializer.CLUSTER_META.get.clusterId) assertNotNull(MockProducerMetricsReporter.CLUSTER_META) isValidClusterId(MockProducerMetricsReporter.CLUSTER_META.get.clusterId) this.consumerConfig.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList) this.consumerConfig.setProperty(ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG, classOf[MockConsumerInterceptor].getName) this.consumerConfig.put(ConsumerConfig.METRIC_REPORTER_CLASSES_CONFIG, classOf[MockConsumerMetricsReporter].getName) val testConsumer = new KafkaConsumer(this.consumerConfig, new MockDeserializer, new MockDeserializer) testConsumer.assign(List(tp).asJava) testConsumer.seek(tp, 0) // consume and verify that values are modified by interceptors consumeRecords(testConsumer, numRecords) // Check that cluster id is present after the first poll call. assertNotEquals(MockConsumerInterceptor.CLUSTER_ID_BEFORE_ON_CONSUME, MockConsumerInterceptor.NO_CLUSTER_ID) assertNotNull(MockConsumerInterceptor.CLUSTER_META) isValidClusterId(MockConsumerInterceptor.CLUSTER_META.get.clusterId) assertEquals(MockConsumerInterceptor.CLUSTER_ID_BEFORE_ON_CONSUME.get.clusterId, MockConsumerInterceptor.CLUSTER_META.get.clusterId) assertNotEquals(MockDeserializer.clusterIdBeforeDeserialize, MockDeserializer.noClusterId) assertNotNull(MockDeserializer.clusterMeta) isValidClusterId(MockDeserializer.clusterMeta.get.clusterId) assertEquals(MockDeserializer.clusterIdBeforeDeserialize.get.clusterId, MockDeserializer.clusterMeta.get.clusterId) assertNotNull(MockConsumerMetricsReporter.CLUSTER_META) isValidClusterId(MockConsumerMetricsReporter.CLUSTER_META.get.clusterId) // Make sure everyone receives the same cluster id. assertEquals(MockProducerInterceptor.CLUSTER_META.get.clusterId, MockSerializer.CLUSTER_META.get.clusterId) assertEquals(MockProducerInterceptor.CLUSTER_META.get.clusterId, MockProducerMetricsReporter.CLUSTER_META.get.clusterId) assertEquals(MockProducerInterceptor.CLUSTER_META.get.clusterId, MockConsumerInterceptor.CLUSTER_META.get.clusterId) assertEquals(MockProducerInterceptor.CLUSTER_META.get.clusterId, MockDeserializer.clusterMeta.get.clusterId) assertEquals(MockProducerInterceptor.CLUSTER_META.get.clusterId, MockConsumerMetricsReporter.CLUSTER_META.get.clusterId) assertEquals(MockProducerInterceptor.CLUSTER_META.get.clusterId, MockBrokerMetricsReporter.CLUSTER_META.get.clusterId) testConsumer.close() testProducer.close() MockConsumerInterceptor.resetCounters() MockProducerInterceptor.resetCounters() } private def sendRecords(producer: KafkaProducer[Array[Byte], Array[Byte]], numRecords: Int, tp: TopicPartition) { val futures = (0 until numRecords).map { i => val record = new ProducerRecord(tp.topic(), tp.partition(), s"$i".getBytes, s"$i".getBytes) debug(s"Sending this record: $record") producer.send(record) } try { futures.foreach(_.get) } catch { case e: ExecutionException => throw e.getCause } } private def consumeRecords(consumer: Consumer[Array[Byte], Array[Byte]], numRecords: Int, startingOffset: Int = 0, topic: String = topic, part: Int = part) { val records = new ArrayBuffer[ConsumerRecord[Array[Byte], Array[Byte]]]() val maxIters = numRecords * 50 var iters = 0 while (records.size < numRecords) { for (record <- consumer.poll(50).asScala) { records += record } if (iters > maxIters) throw new IllegalStateException("Failed to consume the expected records after " + iters + " iterations.") iters += 1 } for (i <- 0 until numRecords) { val record = records(i) val offset = startingOffset + i assertEquals(topic, record.topic) assertEquals(part, record.partition) assertEquals(offset.toLong, record.offset) } } }
apache-2.0
siuccwd/IOER
DataAccess/IoerContentBusinessEntities/Library_MemberSummary.cs
1712
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace IoerContentBusinessEntities { using System; using System.Collections.Generic; public partial class Library_MemberSummary { public int Id { get; set; } public int LibraryId { get; set; } public string Library { get; set; } public Nullable<int> OrgId { get; set; } public int UserId { get; set; } public string FullName { get; set; } public string SortName { get; set; } public string Email { get; set; } public string Organization { get; set; } public int OrganizationId { get; set; } public int MemberTypeId { get; set; } public string MemberType { get; set; } public int IsAnOrgMbr { get; set; } public int OrgMemberTypeId { get; set; } public string OrgMemberType { get; set; } public System.DateTime Created { get; set; } public Nullable<int> CreatedById { get; set; } public System.DateTime LastUpdated { get; set; } public Nullable<int> LastUpdatedById { get; set; } public string ImageUrl { get; set; } public string UserProfileUrl { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } }
apache-2.0
gzsombor/ranger
agents-common/src/main/java/org/apache/ranger/plugin/policyevaluator/RangerValidityScheduleEvaluator.java
26520
/* * 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.ranger.plugin.policyevaluator; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ranger.plugin.model.RangerValidityRecurrence; import org.apache.ranger.plugin.model.RangerValiditySchedule; import org.apache.ranger.plugin.resourcematcher.ScheduledTimeAlwaysMatcher; import org.apache.ranger.plugin.resourcematcher.ScheduledTimeExactMatcher; import org.apache.ranger.plugin.resourcematcher.ScheduledTimeMatcher; import org.apache.ranger.plugin.resourcematcher.ScheduledTimeRangeMatcher; import org.apache.ranger.plugin.util.RangerPerfTracer; import javax.annotation.Nonnull; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.TimeZone; public class RangerValidityScheduleEvaluator { private static final Log LOG = LogFactory.getLog(RangerValidityScheduleEvaluator.class); private static final Log PERF_LOG = LogFactory.getLog("test.perf.RangerValidityScheduleEvaluator"); private final static TimeZone defaultTZ = TimeZone.getDefault(); private static final ThreadLocal<DateFormat> DATE_FORMATTER = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat(RangerValiditySchedule.VALIDITY_SCHEDULE_DATE_STRING_SPECIFICATION); } }; private final Date startTime; private final Date endTime; private final String timeZone; private final List<RangerRecurrenceEvaluator> recurrenceEvaluators = new ArrayList<>(); public RangerValidityScheduleEvaluator(@Nonnull RangerValiditySchedule validitySchedule) { this(validitySchedule.getStartTime(), validitySchedule.getEndTime(), validitySchedule.getTimeZone(), validitySchedule.getRecurrences()); } public RangerValidityScheduleEvaluator(String startTimeStr, String endTimeStr, String timeZone, List<RangerValidityRecurrence> recurrences) { Date startTime = null; Date endTime = null; if (StringUtils.isNotEmpty(startTimeStr)) { try { startTime = DATE_FORMATTER.get().parse(startTimeStr); } catch (ParseException exception) { LOG.error("Error parsing startTime:[" + startTimeStr + "]", exception); } } if (StringUtils.isNotEmpty(endTimeStr)) { try { endTime = DATE_FORMATTER.get().parse(endTimeStr); } catch (ParseException exception) { LOG.error("Error parsing endTime:[" + endTimeStr + "]", exception); } } this.startTime = startTime; this.endTime = endTime; this.timeZone = timeZone; if (CollectionUtils.isNotEmpty(recurrences)) { for (RangerValidityRecurrence recurrence : recurrences) { recurrenceEvaluators.add(new RangerRecurrenceEvaluator(recurrence)); } } } public boolean isApplicable(long accessTime) { if (LOG.isDebugEnabled()) { LOG.debug("===> isApplicable(accessTime=" + accessTime + ")"); } boolean ret = false; RangerPerfTracer perf = null; if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerValidityScheduleEvaluator.isApplicable(accessTime=" + accessTime + ")"); } long startTimeInMSs = startTime == null ? 0 : startTime.getTime(); long endTimeInMSs = endTime == null ? 0 : endTime.getTime(); if (StringUtils.isNotBlank(timeZone)) { TimeZone targetTZ = TimeZone.getTimeZone(timeZone); if (startTimeInMSs > 0) { startTimeInMSs = getAdjustedTime(startTimeInMSs, targetTZ); } if (endTimeInMSs > 0) { endTimeInMSs = getAdjustedTime(endTimeInMSs, targetTZ); } } if ((startTimeInMSs == 0 || accessTime >= startTimeInMSs) && (endTimeInMSs == 0 || accessTime <= endTimeInMSs)) { if (CollectionUtils.isEmpty(recurrenceEvaluators)) { ret = true; } else { Calendar now = new GregorianCalendar(); now.setTime(new Date(accessTime)); for (RangerRecurrenceEvaluator recurrenceEvaluator : recurrenceEvaluators) { ret = recurrenceEvaluator.isApplicable(now); if (ret) { break; } } } } RangerPerfTracer.log(perf); if (LOG.isDebugEnabled()) { LOG.debug("<=== isApplicable(accessTime=" + accessTime + ") :" + ret); } return ret; } public static long getAdjustedTime(long localTime, TimeZone timeZone) { long ret = localTime; if (LOG.isDebugEnabled()) { LOG.debug("Input:[" + new Date(localTime) + ", target-timezone" + timeZone + "], default-timezone:[" + defaultTZ + "]"); } if (!defaultTZ.equals(timeZone)) { int targetOffset = timeZone.getOffset(localTime); int defaultOffset = defaultTZ.getOffset(localTime); int diff = defaultOffset - targetOffset; if (LOG.isDebugEnabled()) { LOG.debug("Offset of target-timezone from UTC :[" + targetOffset + "]"); LOG.debug("Offset of default-timezone from UTC :[" + defaultOffset + "]"); LOG.debug("Difference between default-timezone and target-timezone :[" + diff + "]"); } ret += diff; } if (LOG.isDebugEnabled()) { LOG.debug("Output:[" + new Date(ret) + "]"); } return ret; } static class RangerRecurrenceEvaluator { private final List<ScheduledTimeMatcher> minutes = new ArrayList<>(); private final List<ScheduledTimeMatcher> hours = new ArrayList<>(); private final List<ScheduledTimeMatcher> daysOfMonth = new ArrayList<>(); private final List<ScheduledTimeMatcher> daysOfWeek = new ArrayList<>(); private final List<ScheduledTimeMatcher> months = new ArrayList<>(); private final List<ScheduledTimeMatcher> years = new ArrayList<>(); private final RangerValidityRecurrence recurrence; private int intervalInMinutes = 0; public RangerRecurrenceEvaluator(RangerValidityRecurrence recurrence) { this.recurrence = recurrence; if (recurrence != null) { intervalInMinutes = RangerValidityRecurrence.ValidityInterval.getValidityIntervalInMinutes(recurrence.getInterval()); if (intervalInMinutes > 0) { addScheduledTime(RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec.minute, minutes); addScheduledTime(RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec.hour, hours); addScheduledTime(RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec.dayOfMonth, daysOfMonth); addScheduledTime(RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec.dayOfWeek, daysOfWeek); addScheduledTime(RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec.month, months); addScheduledTime(RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec.year, years); } } } public boolean isApplicable(Calendar now) { boolean ret = false; RangerPerfTracer perf = null; if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerRecurrenceEvaluator.isApplicable(accessTime=" + now.getTime().getTime() + ")"); } if (recurrence != null && intervalInMinutes > 0) { // recurring schedule if (LOG.isDebugEnabled()) { LOG.debug("Access-Time:[" + now.getTime() + "]"); } Calendar startOfInterval = getClosestPastEpoch(now); if (startOfInterval != null) { if (LOG.isDebugEnabled()) { LOG.debug("Start-of-Interval:[" + startOfInterval.getTime() + "]"); } Calendar endOfInterval = (Calendar) startOfInterval.clone(); endOfInterval.add(Calendar.MINUTE, recurrence.getInterval().getMinutes()); endOfInterval.add(Calendar.HOUR, recurrence.getInterval().getHours()); endOfInterval.add(Calendar.DAY_OF_MONTH, recurrence.getInterval().getDays()); endOfInterval.getTime(); // for recomputation now.getTime(); if (LOG.isDebugEnabled()) { LOG.debug("End-of-Interval:[" + endOfInterval.getTime() + "]"); } ret = startOfInterval.compareTo(now) <= 0 && endOfInterval.compareTo(now) >= 0; } } else { ret = true; } RangerPerfTracer.log(perf); return ret; } private void addScheduledTime(RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec fieldSpec, List<ScheduledTimeMatcher> list) { final String str = recurrence.getSchedule().getFieldValue(fieldSpec); final boolean isMonth = fieldSpec == RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec.month; if (StringUtils.isNotBlank(str)) { String[] specs = str.split(","); for (String spec : specs) { String[] range = spec.split("-"); if (range.length == 1) { if (StringUtils.equals(range[0], RangerValidityRecurrence.RecurrenceSchedule.WILDCARD)) { list.clear(); list.add(new ScheduledTimeAlwaysMatcher()); break; } else { list.add(new ScheduledTimeExactMatcher(Integer.valueOf(range[0]) - (isMonth ? 1 : 0))); } } else { if (StringUtils.equals(range[0], RangerValidityRecurrence.RecurrenceSchedule.WILDCARD) || StringUtils.equals(range[1], RangerValidityRecurrence.RecurrenceSchedule.WILDCARD)) { list.clear(); list.add(new ScheduledTimeAlwaysMatcher()); break; } else { list.add(new ScheduledTimeRangeMatcher(Integer.valueOf(range[0]) - (isMonth ? 1 : 0), Integer.valueOf(range[1]) - (isMonth ? 1 : 0))); } } } Collections.reverse(list); } } /* Given a Calendar object, get the closest, earlier Calendar object based on configured validity schedules. Returns - a valid Calendar object. Throws exception if any errors during processing or no suitable Calendar object is found. Description - Typically, a caller will call this with Calendar constructed with current time, and use returned object along with specified interval to ensure that next schedule time is after the input Calendar. Algorithm - This involves doing a Calendar arithmetic (subtraction) with borrow. The tricky parts are ensuring that Calendar arithmetic yields a valid Calendar object. - Start with minutes, and then hours. - Must make sure that the later of the two Calendars - one computed with dayOfMonth, another computed with dayOfWeek - is picked - For dayOfMonth calculation, consider that months have different number of days */ private static class ValueWithBorrow { int value; boolean borrow; ValueWithBorrow() { } ValueWithBorrow(int value) { this(value, false); } ValueWithBorrow(int value, boolean borrow) { this.value = value; this.borrow = borrow; } void setValue(int value) { this.value = value; } void setBorrow(boolean borrow) { this.borrow = borrow; } int getValue() { return value; } boolean getBorrow() { return borrow; } @Override public String toString() { return "value=" + value + ", borrow=" + borrow; } } private Calendar getClosestPastEpoch(Calendar current) { Calendar ret = null; try { ValueWithBorrow input = new ValueWithBorrow(); input.setValue(current.get(Calendar.MINUTE)); input.setBorrow(false); ValueWithBorrow closestMinute = getPastFieldValueWithBorrow(RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec.minute, minutes, input); input.setValue(current.get(Calendar.HOUR_OF_DAY)); input.setBorrow(closestMinute.borrow); ValueWithBorrow closestHour = getPastFieldValueWithBorrow(RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec.hour, hours, input); Calendar dayOfMonthCalendar = getClosestDayOfMonth(current, closestMinute, closestHour); Calendar dayOfWeekCalendar = getClosestDayOfWeek(current, closestMinute, closestHour); ret = getEarlierCalendar(dayOfMonthCalendar, dayOfWeekCalendar); if (LOG.isDebugEnabled()) { LOG.debug("ClosestPastEpoch:[" + (ret != null ? ret.getTime() : null) + "]"); } } catch (Exception e) { LOG.error("Could not find ClosestPastEpoch, Exception=", e); } return ret; } private Calendar getClosestDayOfMonth(Calendar current, ValueWithBorrow closestMinute, ValueWithBorrow closestHour) throws Exception { Calendar ret = null; if (StringUtils.isNotBlank(recurrence.getSchedule().getDayOfMonth())) { int initialDayOfMonth = current.get(Calendar.DAY_OF_MONTH); int currentDayOfMonth = initialDayOfMonth, currentMonth = current.get(Calendar.MONTH), currentYear = current.get(Calendar.YEAR); int maximumDaysInPreviousMonth = getMaximumValForPreviousMonth(current); if (closestHour.borrow) { initialDayOfMonth--; Calendar dayOfMonthCalc = (GregorianCalendar) current.clone(); dayOfMonthCalc.add(Calendar.DAY_OF_MONTH, -1); dayOfMonthCalc.getTime(); int previousDayOfMonth = dayOfMonthCalc.get(Calendar.DAY_OF_MONTH); if (initialDayOfMonth < previousDayOfMonth) { if (LOG.isDebugEnabled()) { LOG.debug("Need to borrow from previous month, initialDayOfMonth:[" + initialDayOfMonth + "], previousDayOfMonth:[" + previousDayOfMonth + "], dayOfMonthCalc:[" + dayOfMonthCalc.getTime() + "]"); } currentDayOfMonth = previousDayOfMonth; currentMonth = dayOfMonthCalc.get(Calendar.MONTH); currentYear = dayOfMonthCalc.get(Calendar.YEAR); maximumDaysInPreviousMonth = getMaximumValForPreviousMonth(dayOfMonthCalc); } else if (initialDayOfMonth == previousDayOfMonth) { if (LOG.isDebugEnabled()) { LOG.debug("No need to borrow from previous month, initialDayOfMonth:[" + initialDayOfMonth + "], previousDayOfMonth:[" + previousDayOfMonth + "]"); } } else { LOG.error("Should not get here, initialDayOfMonth:[" + initialDayOfMonth + "], previousDayOfMonth:[" + previousDayOfMonth + "]"); throw new Exception("Should not get here, initialDayOfMonth:[" + initialDayOfMonth + "], previousDayOfMonth:[" + previousDayOfMonth + "]"); } } if (LOG.isDebugEnabled()) { LOG.debug("currentDayOfMonth:[" + currentDayOfMonth + "], maximumDaysInPreviourMonth:[" + maximumDaysInPreviousMonth + "]"); } ValueWithBorrow input = new ValueWithBorrow(); input.setValue(currentDayOfMonth); input.setBorrow(false); ValueWithBorrow closestDayOfMonth = null; do { int i = 0; try { closestDayOfMonth = getPastFieldValueWithBorrow(RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec.dayOfMonth, daysOfMonth, input, maximumDaysInPreviousMonth); } catch (Exception e) { i++; Calendar c = (GregorianCalendar) current.clone(); c.set(Calendar.YEAR, currentYear); c.set(Calendar.MONTH, currentMonth); c.set(Calendar.DAY_OF_MONTH, currentDayOfMonth); c.add(Calendar.MONTH, -i); c.getTime(); currentMonth = c.get(Calendar.MONTH); currentYear = c.get(Calendar.YEAR); currentDayOfMonth = c.get(Calendar.DAY_OF_MONTH); maximumDaysInPreviousMonth = getMaximumValForPreviousMonth(c); input.setValue(currentDayOfMonth); input.setBorrow(false); } } while (closestDayOfMonth == null); // Build calendar for dayOfMonth ret = new GregorianCalendar(); ret.set(Calendar.DAY_OF_MONTH, closestDayOfMonth.value); ret.set(Calendar.HOUR_OF_DAY, closestHour.value); ret.set(Calendar.MINUTE, closestMinute.value); ret.set(Calendar.SECOND, 0); ret.set(Calendar.MILLISECOND, 0); ret.set(Calendar.YEAR, currentYear); if (closestDayOfMonth.borrow) { ret.set(Calendar.MONTH, currentMonth - 1); } else { ret.set(Calendar.MONTH, currentMonth); } ret.getTime(); // For recomputation if (LOG.isDebugEnabled()) { LOG.debug("Best guess using DAY_OF_MONTH:[" + ret.getTime() + "]"); } } return ret; } private Calendar getClosestDayOfWeek(Calendar current, ValueWithBorrow closestMinute, ValueWithBorrow closestHour) throws Exception { Calendar ret = null; if (StringUtils.isNotBlank(recurrence.getSchedule().getDayOfWeek())) { ValueWithBorrow input = new ValueWithBorrow(); input.setValue(current.get(Calendar.DAY_OF_WEEK)); input.setBorrow(closestHour.borrow); ValueWithBorrow closestDayOfWeek = getPastFieldValueWithBorrow(RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec.dayOfWeek, daysOfWeek, input); int daysToGoback = closestHour.borrow ? 1 : 0; int range = RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec.dayOfWeek.maximum - RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec.dayOfWeek.minimum + 1; if (closestDayOfWeek.borrow) { if (input.value - closestDayOfWeek.value != daysToGoback) { daysToGoback = range + input.value - closestDayOfWeek.value; } } else { daysToGoback = input.value - closestDayOfWeek.value; } if (LOG.isDebugEnabled()) { LOG.debug("Need to go back [" + daysToGoback + "] days to match dayOfWeek"); } ret = (GregorianCalendar) current.clone(); ret.set(Calendar.MINUTE, closestMinute.value); ret.set(Calendar.HOUR_OF_DAY, closestHour.value); ret.add(Calendar.DAY_OF_MONTH, (0 - daysToGoback)); ret.set(Calendar.SECOND, 0); ret.set(Calendar.MILLISECOND, 0); ret.getTime(); if (LOG.isDebugEnabled()) { LOG.debug("Best guess using DAY_OF_WEEK:[" + ret.getTime() + "]"); } } return ret; } private int getMaximumValForPreviousMonth(Calendar current) { Calendar cal = (Calendar) current.clone(); cal.add(Calendar.MONTH, -1); cal.getTime(); // For recomputation return cal.getActualMaximum(Calendar.DAY_OF_MONTH); } private Calendar getEarlierCalendar(Calendar dayOfMonthCalendar, Calendar dayOfWeekCalendar) throws Exception { Calendar withDayOfMonth = fillOutCalendar(dayOfMonthCalendar); if (LOG.isDebugEnabled()) { LOG.debug("dayOfMonthCalendar:[" + (withDayOfMonth != null ? withDayOfMonth.getTime() : null) + "]"); } Calendar withDayOfWeek = fillOutCalendar(dayOfWeekCalendar); if (LOG.isDebugEnabled()) { LOG.debug("dayOfWeekCalendar:[" + (withDayOfWeek != null ? withDayOfWeek.getTime() : null) + "]"); } if (withDayOfMonth != null && withDayOfWeek != null) { return withDayOfMonth.after(withDayOfWeek) ? withDayOfMonth : withDayOfWeek; } else if (withDayOfMonth == null) { return withDayOfWeek; } else { return withDayOfMonth; } } private Calendar fillOutCalendar(Calendar calendar) throws Exception { Calendar ret = null; if (calendar != null) { ValueWithBorrow input = new ValueWithBorrow(calendar.get(Calendar.MONTH)); ValueWithBorrow closestMonth = getPastFieldValueWithBorrow(RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec.month, months, input); input.setValue(calendar.get(Calendar.YEAR)); input.setBorrow(closestMonth.borrow); ValueWithBorrow closestYear = getPastFieldValueWithBorrow(RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec.year, years, input); // Build calendar ret = (Calendar) calendar.clone(); ret.set(Calendar.YEAR, closestYear.value); ret.set(Calendar.MONTH, closestMonth.value); ret.set(Calendar.SECOND, 0); ret.getTime(); // for recomputation if (LOG.isDebugEnabled()) { LOG.debug("Filled-out-Calendar:[" + ret.getTime() + "]"); } } return ret; } private ValueWithBorrow getPastFieldValueWithBorrow(RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec fieldSpec, List<ScheduledTimeMatcher> searchList, ValueWithBorrow input) throws Exception { return getPastFieldValueWithBorrow(fieldSpec, searchList, input, fieldSpec.maximum); } private ValueWithBorrow getPastFieldValueWithBorrow(RangerValidityRecurrence.RecurrenceSchedule.ScheduleFieldSpec fieldSpec, List<ScheduledTimeMatcher> searchList, ValueWithBorrow input, int maximum) throws Exception { ValueWithBorrow ret; boolean borrow = false; int value = input.value - (input.borrow ? 1 : 0); if (CollectionUtils.isNotEmpty(searchList)) { int range = fieldSpec.maximum - fieldSpec.minimum + 1; for (int i = 0; i < range; i++, value--) { if (value < fieldSpec.minimum) { value = maximum; borrow = true; } for (ScheduledTimeMatcher time : searchList) { if (time.isMatch(value)) { if (LOG.isDebugEnabled()) { LOG.debug("Found match in field:[" + fieldSpec + "], value:[" + value + "], borrow:[" + borrow + "], maximum:[" + maximum + "]"); } return new ValueWithBorrow(value, borrow); } } } // Not found throw new Exception("No match found in field:[" + fieldSpec + "] for [input=" + input + "]"); } else { if (value < fieldSpec.minimum) { value = maximum; } ret = new ValueWithBorrow(value, false); } return ret; } } }
apache-2.0
subhrajyotim/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/util/ParseUtil.java
2972
package org.camunda.bpm.engine.impl.util; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.camunda.bpm.engine.ProcessEngineException; import org.camunda.bpm.engine.exception.NotValidException; import org.camunda.bpm.engine.impl.ProcessEngineLogger; import org.camunda.bpm.engine.impl.bpmn.parser.FailedJobRetryConfiguration; import org.camunda.bpm.engine.impl.calendar.DurationHelper; import org.camunda.bpm.engine.impl.context.Context; import org.camunda.bpm.engine.impl.el.Expression; import org.camunda.bpm.engine.impl.el.ExpressionManager; public class ParseUtil { private static final EngineUtilLogger LOG = ProcessEngineLogger.UTIL_LOGGER; protected static final Pattern REGEX_TTL_ISO = Pattern.compile("^P(\\d+)D$"); /** * Parse History Time To Live in ISO-8601 format to integer and set into the given entity * @param historyTimeToLive */ public static Integer parseHistoryTimeToLive(String historyTimeToLive) { Integer timeToLive = null; if (historyTimeToLive != null && !historyTimeToLive.isEmpty()) { Matcher matISO = REGEX_TTL_ISO.matcher(historyTimeToLive); if (matISO.find()) { historyTimeToLive = matISO.group(1); } timeToLive = parseIntegerAttribute("historyTimeToLive", historyTimeToLive); } if (timeToLive != null && timeToLive < 0) { throw new NotValidException("Cannot parse historyTimeToLive: negative value is not allowed"); } return timeToLive; } protected static Integer parseIntegerAttribute(String attributeName, String text) { Integer result = null; if (text != null && !text.isEmpty()) { try { result = Integer.parseInt(text); } catch (NumberFormatException e) { throw new ProcessEngineException("Cannot parse " + attributeName + ": " + e.getMessage()); } } return result; } public static FailedJobRetryConfiguration parseRetryIntervals(String retryIntervals) { if (retryIntervals != null && !retryIntervals.isEmpty()) { if (StringUtil.isExpression(retryIntervals)) { ExpressionManager expressionManager = Context.getProcessEngineConfiguration().getExpressionManager(); Expression expression = expressionManager.createExpression(retryIntervals); return new FailedJobRetryConfiguration(expression); } String[] intervals = StringUtil.split(retryIntervals, ","); int retries = intervals.length + 1; if (intervals.length == 1) { try { DurationHelper durationHelper = new DurationHelper(intervals[0]); if (durationHelper.isRepeat()) { retries = durationHelper.getTimes(); } } catch (Exception e) { LOG.logParsingRetryIntervals(intervals[0], e); return null; } } return new FailedJobRetryConfiguration(retries, Arrays.asList(intervals)); } else { return null; } } }
apache-2.0
macosforge/ccs-calendarserver
twistedcaldav/datafilters/test/test_calendardata.py
9902
## # Copyright (c) 2009-2017 Apple 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. ## import twistedcaldav.test.util from twistedcaldav.datafilters.calendardata import CalendarDataFilter from twistedcaldav.caldavxml import CalendarData, CalendarComponent, \ AllComponents, AllProperties, Property from twistedcaldav.ical import Component class CalendarDataTest (twistedcaldav.test.util.TestCase): def test_empty(self): data = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN BEGIN:VEVENT UID:12345-67890 DTSTART:20080601T120000Z DTEND:20080601T130000Z ATTENDEE:mailto:user1@example.com ATTENDEE:mailto:user2@example.com ORGANIZER;CN=User 01:mailto:user1@example.com END:VEVENT END:VCALENDAR """.replace("\n", "\r\n") empty = CalendarData() for item in (data, Component.fromString(data),): self.assertEqual(str(CalendarDataFilter(empty).filter(item)), data) def test_vcalendar_no_effect(self): data = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN BEGIN:VEVENT UID:12345-67890 DTSTART:20080601T120000Z DTEND:20080601T130000Z ATTENDEE:mailto:user1@example.com ATTENDEE:mailto:user2@example.com ORGANIZER;CN=User 01:mailto:user1@example.com END:VEVENT END:VCALENDAR """.replace("\n", "\r\n") no_effect = CalendarData( CalendarComponent( name="VCALENDAR" ) ) for item in (data, Component.fromString(data),): self.assertEqual(str(CalendarDataFilter(no_effect).filter(item)), data) no_effect = CalendarData( CalendarComponent( AllComponents(), AllProperties(), name="VCALENDAR" ) ) for item in (data, Component.fromString(data),): self.assertEqual(str(CalendarDataFilter(no_effect).filter(item)), data) def test_vcalendar_no_props(self): data = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN X-WR-CALNAME:Help BEGIN:VEVENT UID:12345-67890 DTSTART:20080601T120000Z DTEND:20080601T130000Z ATTENDEE:mailto:user1@example.com ATTENDEE:mailto:user2@example.com ORGANIZER;CN=User 01:mailto:user1@example.com END:VEVENT END:VCALENDAR """.replace("\n", "\r\n") result = """BEGIN:VCALENDAR BEGIN:VEVENT UID:12345-67890 DTSTART:20080601T120000Z DTEND:20080601T130000Z ATTENDEE:mailto:user1@example.com ATTENDEE:mailto:user2@example.com ORGANIZER;CN=User 01:mailto:user1@example.com END:VEVENT END:VCALENDAR """.replace("\n", "\r\n") empty = CalendarData( CalendarComponent( AllComponents(), name="VCALENDAR" ) ) for item in (data, Component.fromString(data),): self.assertEqual(str(CalendarDataFilter(empty).filter(item)), result) def test_vcalendar_no_comp(self): data = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN X-WR-CALNAME:Help BEGIN:VEVENT UID:12345-67890 DTSTART:20080601T120000Z DTEND:20080601T130000Z ATTENDEE:mailto:user1@example.com ATTENDEE:mailto:user2@example.com ORGANIZER;CN=User 01:mailto:user1@example.com END:VEVENT END:VCALENDAR """.replace("\n", "\r\n") result = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN X-WR-CALNAME:Help END:VCALENDAR """.replace("\n", "\r\n") empty = CalendarData( CalendarComponent( AllProperties(), name="VCALENDAR" ) ) for item in (data, Component.fromString(data),): self.assertEqual(str(CalendarDataFilter(empty).filter(item)), result) def test_vevent_no_effect(self): data = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN BEGIN:VEVENT UID:12345-67890 DTSTART:20080601T120000Z DTEND:20080601T130000Z ATTENDEE:mailto:user1@example.com ATTENDEE:mailto:user2@example.com ORGANIZER;CN=User 01:mailto:user1@example.com END:VEVENT END:VCALENDAR """.replace("\n", "\r\n") no_effect = CalendarData( CalendarComponent( CalendarComponent( name="VEVENT" ), AllProperties(), name="VCALENDAR" ) ) for item in (data, Component.fromString(data),): self.assertEqual(str(CalendarDataFilter(no_effect).filter(item)), data) def test_vevent_other_component(self): data = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN BEGIN:VEVENT UID:12345-67890 DTSTART:20080601T120000Z DTEND:20080601T130000Z ATTENDEE:mailto:user1@example.com ATTENDEE:mailto:user2@example.com ORGANIZER;CN=User 01:mailto:user1@example.com END:VEVENT END:VCALENDAR """.replace("\n", "\r\n") result = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN END:VCALENDAR """.replace("\n", "\r\n") other_component = CalendarData( CalendarComponent( CalendarComponent( name="VTODO" ), AllProperties(), name="VCALENDAR" ) ) for item in (data, Component.fromString(data),): self.assertEqual(str(CalendarDataFilter(other_component).filter(item)), result) def test_vevent_no_props(self): data = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN BEGIN:VEVENT UID:12345-67890 DTSTART:20080601T120000Z DTEND:20080601T130000Z ATTENDEE:mailto:user1@example.com ATTENDEE:mailto:user2@example.com ORGANIZER;CN=User 01:mailto:user1@example.com BEGIN:VALARM ACTION:DISPLAY DESCRIPTION:Test TRIGGER;RELATED=START:-PT10M END:VALARM END:VEVENT END:VCALENDAR """.replace("\n", "\r\n") result = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN BEGIN:VEVENT BEGIN:VALARM ACTION:DISPLAY DESCRIPTION:Test TRIGGER;RELATED=START:-PT10M END:VALARM END:VEVENT END:VCALENDAR """.replace("\n", "\r\n") empty = CalendarData( CalendarComponent( CalendarComponent( AllComponents(), name="VEVENT" ), AllProperties(), name="VCALENDAR" ) ) for item in (data, Component.fromString(data),): filtered = str(CalendarDataFilter(empty).filter(item)) filtered = "".join([line for line in filtered.splitlines(True) if not line.startswith("UID:")]) self.assertEqual(filtered, result) def test_vevent_no_comp(self): data = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN BEGIN:VEVENT UID:12345-67890 DTSTART:20080601T120000Z DTEND:20080601T130000Z ATTENDEE:mailto:user1@example.com ATTENDEE:mailto:user2@example.com ORGANIZER;CN=User 01:mailto:user1@example.com BEGIN:VALARM ACTION:DISPLAY DESCRIPTION:Test TRIGGER;RELATED=START:-PT10M END:VALARM END:VEVENT END:VCALENDAR """.replace("\n", "\r\n") result = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN BEGIN:VEVENT UID:12345-67890 DTSTART:20080601T120000Z DTEND:20080601T130000Z ATTENDEE:mailto:user1@example.com ATTENDEE:mailto:user2@example.com ORGANIZER;CN=User 01:mailto:user1@example.com END:VEVENT END:VCALENDAR """.replace("\n", "\r\n") empty = CalendarData( CalendarComponent( CalendarComponent( AllProperties(), name="VEVENT" ), AllProperties(), name="VCALENDAR" ) ) for item in (data, Component.fromString(data),): self.assertEqual(str(CalendarDataFilter(empty).filter(item)), result) def test_vevent_some_props(self): data = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN BEGIN:VEVENT UID:12345-67890 DTSTART:20080601T120000Z DTEND:20080601T130000Z ATTENDEE:mailto:user1@example.com ATTENDEE:mailto:user2@example.com ORGANIZER;CN=User 01:mailto:user1@example.com BEGIN:VALARM ACTION:DISPLAY DESCRIPTION:Test TRIGGER;RELATED=START:-PT10M END:VALARM END:VEVENT END:VCALENDAR """.replace("\n", "\r\n") result = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN BEGIN:VEVENT UID:12345-67890 DTSTART:20080601T120000Z DTEND:20080601T130000Z BEGIN:VALARM ACTION:DISPLAY DESCRIPTION:Test TRIGGER;RELATED=START:-PT10M END:VALARM END:VEVENT END:VCALENDAR """.replace("\n", "\r\n") empty = CalendarData( CalendarComponent( CalendarComponent( AllComponents(), Property( name="UID", ), Property( name="DTSTART", ), Property( name="DTEND", ), name="VEVENT" ), AllProperties(), name="VCALENDAR" ) ) for item in (data, Component.fromString(data),): self.assertEqual(str(CalendarDataFilter(empty).filter(item)), result)
apache-2.0
matiu2/cdnalizer
src/apache/utils.hpp
2121
#pragma once /** * Utilitiies to help make the C more ++ier * * © Copyright 2014 Matthew Sherborne. All Rights Reserved. * License: Apache License, Version 2.0 (See LICENSE.txt) **/ #include <cassert> #include <stdexcept> #include <memory> extern "C" { #include <apr_buckets.h> } namespace cdnalizer { namespace apache { /** RAII guarded bucket brigade **/ class BrigadeGuard { private: apr_bucket_brigade* bb; void cleanup() { if (bb != nullptr) apr_brigade_destroy(bb); } void moveFromOther(BrigadeGuard&& other) { assert(other.bb != bb); // That would be weird // Delete our current bb cleanup(); // Steal our bro's brigade bb = other.bb; other.bb = nullptr; } public: BrigadeGuard(apr_pool_t* pool, apr_bucket_alloc_t* list) { bb = apr_brigade_create(pool, list); } /// Move a bb from a bro BrigadeGuard(BrigadeGuard&& other) { moveFromOther(std::move(other)); } ~BrigadeGuard() { cleanup(); } BrigadeGuard& operator =(BrigadeGuard&& other) { moveFromOther(std::move(other)); return *this; } apr_bucket_brigade& operator *() { return *bb; } apr_bucket_brigade& operator ->() { return *bb; } const apr_bucket_brigade& operator *() const { return *bb; } const apr_bucket_brigade& operator ->() const { return *bb; } operator apr_bucket_brigade*() { return bb; } operator apr_bucket_brigade&() { return *bb; } apr_bucket_brigade* brigade() { return bb; } }; /// Turns an apr status code into a c++ exception class ApacheException : public std::runtime_error { private: std::string static getMessage(apr_status_t code) { char data[256]; apr_strerror(code, data, 256); return std::string(data); } public: const apr_status_t code; ApacheException(apr_status_t code) : std::runtime_error(getMessage(code)), code(code) {} }; /// Throws an exception if the code is not APR_SUCCESS void checkStatusCode(apr_status_t code) { if (code != APR_SUCCESS) throw ApacheException(code); } } }
apache-2.0
ivannaranjo/google-api-dotnet-client
Src/Generated/Google.Apis.Reseller.v1/Google.Apis.Reseller.v1.cs
73275
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.14.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Enterprise Apps Reseller API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/google-apps/reseller/'>Enterprise Apps Reseller API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20160329 (453) * <tr><th>API Docs * <td><a href='https://developers.google.com/google-apps/reseller/'> * https://developers.google.com/google-apps/reseller/</a> * <tr><th>Discovery Name<td>reseller * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Enterprise Apps Reseller API can be found at * <a href='https://developers.google.com/google-apps/reseller/'>https://developers.google.com/google-apps/reseller/</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Reseller.v1 { /// <summary>The Reseller Service.</summary> public class ResellerService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public ResellerService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public ResellerService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { customers = new CustomersResource(this); subscriptions = new SubscriptionsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "reseller"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/apps/reseller/v1/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "apps/reseller/v1/"; } } /// <summary>Available OAuth 2.0 scopes for use with the Enterprise Apps Reseller API.</summary> public class Scope { /// <summary>Manage users on your domain</summary> public static string AppsOrder = "https://www.googleapis.com/auth/apps.order"; /// <summary>Manage users on your domain</summary> public static string AppsOrderReadonly = "https://www.googleapis.com/auth/apps.order.readonly"; } private readonly CustomersResource customers; /// <summary>Gets the Customers resource.</summary> public virtual CustomersResource Customers { get { return customers; } } private readonly SubscriptionsResource subscriptions; /// <summary>Gets the Subscriptions resource.</summary> public virtual SubscriptionsResource Subscriptions { get { return subscriptions; } } } ///<summary>A base abstract class for Reseller requests.</summary> public abstract class ResellerBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new ResellerBaseServiceRequest instance.</summary> protected ResellerBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user /// limits.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes Reseller parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "customers" collection of methods.</summary> public class CustomersResource { private const string Resource = "customers"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public CustomersResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Gets a customer resource if one exists and is owned by the reseller.</summary> /// <param name="customerId">Id of the Customer</param> public virtual GetRequest Get(string customerId) { return new GetRequest(service, customerId); } /// <summary>Gets a customer resource if one exists and is owned by the reseller.</summary> public class GetRequest : ResellerBaseServiceRequest<Google.Apis.Reseller.v1.Data.Customer> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string customerId) : base(service) { CustomerId = customerId; InitParameters(); } /// <summary>Id of the Customer</summary> [Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Path)] public virtual string CustomerId { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "customers/{customerId}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "customerId", new Google.Apis.Discovery.Parameter { Name = "customerId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Creates a customer resource if one does not already exist.</summary> /// <param name="body">The body of the request.</param> public virtual InsertRequest Insert(Google.Apis.Reseller.v1.Data.Customer body) { return new InsertRequest(service, body); } /// <summary>Creates a customer resource if one does not already exist.</summary> public class InsertRequest : ResellerBaseServiceRequest<Google.Apis.Reseller.v1.Data.Customer> { /// <summary>Constructs a new Insert request.</summary> public InsertRequest(Google.Apis.Services.IClientService service, Google.Apis.Reseller.v1.Data.Customer body) : base(service) { Body = body; InitParameters(); } /// <summary>An auth token needed for inserting a customer for which domain already exists. Can be generated /// at https://admin.google.com/TransferToken. Optional.</summary> [Google.Apis.Util.RequestParameterAttribute("customerAuthToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string CustomerAuthToken { get; set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Reseller.v1.Data.Customer Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "insert"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "customers"; } } /// <summary>Initializes Insert parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "customerAuthToken", new Google.Apis.Discovery.Parameter { Name = "customerAuthToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Update a customer resource if one it exists and is owned by the reseller. This method supports /// patch semantics.</summary> /// <param name="body">The body of the request.</param> /// <param name="customerId">Id of the Customer</param> public virtual PatchRequest Patch(Google.Apis.Reseller.v1.Data.Customer body, string customerId) { return new PatchRequest(service, body, customerId); } /// <summary>Update a customer resource if one it exists and is owned by the reseller. This method supports /// patch semantics.</summary> public class PatchRequest : ResellerBaseServiceRequest<Google.Apis.Reseller.v1.Data.Customer> { /// <summary>Constructs a new Patch request.</summary> public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Reseller.v1.Data.Customer body, string customerId) : base(service) { CustomerId = customerId; Body = body; InitParameters(); } /// <summary>Id of the Customer</summary> [Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Path)] public virtual string CustomerId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Reseller.v1.Data.Customer Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "patch"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "PATCH"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "customers/{customerId}"; } } /// <summary>Initializes Patch parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "customerId", new Google.Apis.Discovery.Parameter { Name = "customerId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Update a customer resource if one it exists and is owned by the reseller.</summary> /// <param name="body">The body of the request.</param> /// <param name="customerId">Id of the Customer</param> public virtual UpdateRequest Update(Google.Apis.Reseller.v1.Data.Customer body, string customerId) { return new UpdateRequest(service, body, customerId); } /// <summary>Update a customer resource if one it exists and is owned by the reseller.</summary> public class UpdateRequest : ResellerBaseServiceRequest<Google.Apis.Reseller.v1.Data.Customer> { /// <summary>Constructs a new Update request.</summary> public UpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.Reseller.v1.Data.Customer body, string customerId) : base(service) { CustomerId = customerId; Body = body; InitParameters(); } /// <summary>Id of the Customer</summary> [Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Path)] public virtual string CustomerId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Reseller.v1.Data.Customer Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "update"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "PUT"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "customers/{customerId}"; } } /// <summary>Initializes Update parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "customerId", new Google.Apis.Discovery.Parameter { Name = "customerId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "subscriptions" collection of methods.</summary> public class SubscriptionsResource { private const string Resource = "subscriptions"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public SubscriptionsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Activates a subscription previously suspended by the reseller</summary> /// <param name="customerId">Id of the Customer</param> /// <param name="subscriptionId">Id of the subscription, /// which is unique for a customer</param> public virtual ActivateRequest Activate(string customerId, string subscriptionId) { return new ActivateRequest(service, customerId, subscriptionId); } /// <summary>Activates a subscription previously suspended by the reseller</summary> public class ActivateRequest : ResellerBaseServiceRequest<Google.Apis.Reseller.v1.Data.Subscription> { /// <summary>Constructs a new Activate request.</summary> public ActivateRequest(Google.Apis.Services.IClientService service, string customerId, string subscriptionId) : base(service) { CustomerId = customerId; SubscriptionId = subscriptionId; InitParameters(); } /// <summary>Id of the Customer</summary> [Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Path)] public virtual string CustomerId { get; private set; } /// <summary>Id of the subscription, which is unique for a customer</summary> [Google.Apis.Util.RequestParameterAttribute("subscriptionId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SubscriptionId { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "activate"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "customers/{customerId}/subscriptions/{subscriptionId}/activate"; } } /// <summary>Initializes Activate parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "customerId", new Google.Apis.Discovery.Parameter { Name = "customerId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "subscriptionId", new Google.Apis.Discovery.Parameter { Name = "subscriptionId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Changes the plan of a subscription</summary> /// <param name="body">The body of the request.</param> /// <param name="customerId">Id of the Customer</param> /// <param name="subscriptionId">Id of the subscription, /// which is unique for a customer</param> public virtual ChangePlanRequest ChangePlan(Google.Apis.Reseller.v1.Data.ChangePlanRequest body, string customerId, string subscriptionId) { return new ChangePlanRequest(service, body, customerId, subscriptionId); } /// <summary>Changes the plan of a subscription</summary> public class ChangePlanRequest : ResellerBaseServiceRequest<Google.Apis.Reseller.v1.Data.Subscription> { /// <summary>Constructs a new ChangePlan request.</summary> public ChangePlanRequest(Google.Apis.Services.IClientService service, Google.Apis.Reseller.v1.Data.ChangePlanRequest body, string customerId, string subscriptionId) : base(service) { CustomerId = customerId; SubscriptionId = subscriptionId; Body = body; InitParameters(); } /// <summary>Id of the Customer</summary> [Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Path)] public virtual string CustomerId { get; private set; } /// <summary>Id of the subscription, which is unique for a customer</summary> [Google.Apis.Util.RequestParameterAttribute("subscriptionId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SubscriptionId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Reseller.v1.Data.ChangePlanRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "changePlan"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "customers/{customerId}/subscriptions/{subscriptionId}/changePlan"; } } /// <summary>Initializes ChangePlan parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "customerId", new Google.Apis.Discovery.Parameter { Name = "customerId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "subscriptionId", new Google.Apis.Discovery.Parameter { Name = "subscriptionId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Changes the renewal settings of a subscription</summary> /// <param name="body">The body of the request.</param> /// <param name="customerId">Id of the Customer</param> /// <param name="subscriptionId">Id of the subscription, /// which is unique for a customer</param> public virtual ChangeRenewalSettingsRequest ChangeRenewalSettings(Google.Apis.Reseller.v1.Data.RenewalSettings body, string customerId, string subscriptionId) { return new ChangeRenewalSettingsRequest(service, body, customerId, subscriptionId); } /// <summary>Changes the renewal settings of a subscription</summary> public class ChangeRenewalSettingsRequest : ResellerBaseServiceRequest<Google.Apis.Reseller.v1.Data.Subscription> { /// <summary>Constructs a new ChangeRenewalSettings request.</summary> public ChangeRenewalSettingsRequest(Google.Apis.Services.IClientService service, Google.Apis.Reseller.v1.Data.RenewalSettings body, string customerId, string subscriptionId) : base(service) { CustomerId = customerId; SubscriptionId = subscriptionId; Body = body; InitParameters(); } /// <summary>Id of the Customer</summary> [Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Path)] public virtual string CustomerId { get; private set; } /// <summary>Id of the subscription, which is unique for a customer</summary> [Google.Apis.Util.RequestParameterAttribute("subscriptionId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SubscriptionId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Reseller.v1.Data.RenewalSettings Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "changeRenewalSettings"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "customers/{customerId}/subscriptions/{subscriptionId}/changeRenewalSettings"; } } /// <summary>Initializes ChangeRenewalSettings parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "customerId", new Google.Apis.Discovery.Parameter { Name = "customerId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "subscriptionId", new Google.Apis.Discovery.Parameter { Name = "subscriptionId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Changes the seats configuration of a subscription</summary> /// <param name="body">The body of the request.</param> /// <param name="customerId">Id of the Customer</param> /// <param name="subscriptionId">Id of the subscription, /// which is unique for a customer</param> public virtual ChangeSeatsRequest ChangeSeats(Google.Apis.Reseller.v1.Data.Seats body, string customerId, string subscriptionId) { return new ChangeSeatsRequest(service, body, customerId, subscriptionId); } /// <summary>Changes the seats configuration of a subscription</summary> public class ChangeSeatsRequest : ResellerBaseServiceRequest<Google.Apis.Reseller.v1.Data.Subscription> { /// <summary>Constructs a new ChangeSeats request.</summary> public ChangeSeatsRequest(Google.Apis.Services.IClientService service, Google.Apis.Reseller.v1.Data.Seats body, string customerId, string subscriptionId) : base(service) { CustomerId = customerId; SubscriptionId = subscriptionId; Body = body; InitParameters(); } /// <summary>Id of the Customer</summary> [Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Path)] public virtual string CustomerId { get; private set; } /// <summary>Id of the subscription, which is unique for a customer</summary> [Google.Apis.Util.RequestParameterAttribute("subscriptionId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SubscriptionId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Reseller.v1.Data.Seats Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "changeSeats"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "customers/{customerId}/subscriptions/{subscriptionId}/changeSeats"; } } /// <summary>Initializes ChangeSeats parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "customerId", new Google.Apis.Discovery.Parameter { Name = "customerId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "subscriptionId", new Google.Apis.Discovery.Parameter { Name = "subscriptionId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Cancels/Downgrades a subscription.</summary> /// <param name="customerId">Id of the Customer</param> /// <param name="subscriptionId">Id of the subscription, /// which is unique for a customer</param> /// <param name="deletionType">Whether the subscription is to be fully /// cancelled or downgraded</param> public virtual DeleteRequest Delete(string customerId, string subscriptionId, DeleteRequest.DeletionTypeEnum deletionType) { return new DeleteRequest(service, customerId, subscriptionId, deletionType); } /// <summary>Cancels/Downgrades a subscription.</summary> public class DeleteRequest : ResellerBaseServiceRequest<string> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string customerId, string subscriptionId, DeleteRequest.DeletionTypeEnum deletionType) : base(service) { CustomerId = customerId; SubscriptionId = subscriptionId; DeletionType = deletionType; InitParameters(); } /// <summary>Id of the Customer</summary> [Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Path)] public virtual string CustomerId { get; private set; } /// <summary>Id of the subscription, which is unique for a customer</summary> [Google.Apis.Util.RequestParameterAttribute("subscriptionId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SubscriptionId { get; private set; } /// <summary>Whether the subscription is to be fully cancelled or downgraded</summary> [Google.Apis.Util.RequestParameterAttribute("deletionType", Google.Apis.Util.RequestParameterType.Query)] public virtual DeletionTypeEnum DeletionType { get; private set; } /// <summary>Whether the subscription is to be fully cancelled or downgraded</summary> public enum DeletionTypeEnum { /// <summary>Cancels the subscription immediately</summary> [Google.Apis.Util.StringValueAttribute("cancel")] Cancel, /// <summary>Downgrades a Google Apps for Business subscription to Google Apps</summary> [Google.Apis.Util.StringValueAttribute("downgrade")] Downgrade, /// <summary>Suspends the subscriptions for 4 days before cancelling it</summary> [Google.Apis.Util.StringValueAttribute("suspend")] Suspend, /// <summary>Transfers a subscription directly to Google</summary> [Google.Apis.Util.StringValueAttribute("transfer_to_direct")] TransferToDirect, } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "delete"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "DELETE"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "customers/{customerId}/subscriptions/{subscriptionId}"; } } /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "customerId", new Google.Apis.Discovery.Parameter { Name = "customerId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "subscriptionId", new Google.Apis.Discovery.Parameter { Name = "subscriptionId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "deletionType", new Google.Apis.Discovery.Parameter { Name = "deletionType", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Gets a subscription of the customer.</summary> /// <param name="customerId">Id of the Customer</param> /// <param name="subscriptionId">Id of the subscription, /// which is unique for a customer</param> public virtual GetRequest Get(string customerId, string subscriptionId) { return new GetRequest(service, customerId, subscriptionId); } /// <summary>Gets a subscription of the customer.</summary> public class GetRequest : ResellerBaseServiceRequest<Google.Apis.Reseller.v1.Data.Subscription> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string customerId, string subscriptionId) : base(service) { CustomerId = customerId; SubscriptionId = subscriptionId; InitParameters(); } /// <summary>Id of the Customer</summary> [Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Path)] public virtual string CustomerId { get; private set; } /// <summary>Id of the subscription, which is unique for a customer</summary> [Google.Apis.Util.RequestParameterAttribute("subscriptionId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SubscriptionId { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "customers/{customerId}/subscriptions/{subscriptionId}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "customerId", new Google.Apis.Discovery.Parameter { Name = "customerId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "subscriptionId", new Google.Apis.Discovery.Parameter { Name = "subscriptionId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Creates/Transfers a subscription for the customer.</summary> /// <param name="body">The body of the request.</param> /// <param name="customerId">Id of the Customer</param> public virtual InsertRequest Insert(Google.Apis.Reseller.v1.Data.Subscription body, string customerId) { return new InsertRequest(service, body, customerId); } /// <summary>Creates/Transfers a subscription for the customer.</summary> public class InsertRequest : ResellerBaseServiceRequest<Google.Apis.Reseller.v1.Data.Subscription> { /// <summary>Constructs a new Insert request.</summary> public InsertRequest(Google.Apis.Services.IClientService service, Google.Apis.Reseller.v1.Data.Subscription body, string customerId) : base(service) { CustomerId = customerId; Body = body; InitParameters(); } /// <summary>Id of the Customer</summary> [Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Path)] public virtual string CustomerId { get; private set; } /// <summary>An auth token needed for transferring a subscription. Can be generated at /// https://www.google.com/a/cpanel/customer-domain/TransferToken. Optional.</summary> [Google.Apis.Util.RequestParameterAttribute("customerAuthToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string CustomerAuthToken { get; set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Reseller.v1.Data.Subscription Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "insert"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "customers/{customerId}/subscriptions"; } } /// <summary>Initializes Insert parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "customerId", new Google.Apis.Discovery.Parameter { Name = "customerId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "customerAuthToken", new Google.Apis.Discovery.Parameter { Name = "customerAuthToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Lists subscriptions of a reseller, optionally filtered by a customer name prefix.</summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary>Lists subscriptions of a reseller, optionally filtered by a customer name prefix.</summary> public class ListRequest : ResellerBaseServiceRequest<Google.Apis.Reseller.v1.Data.Subscriptions> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>An auth token needed if the customer is not a resold customer of this reseller. Can be /// generated at https://www.google.com/a/cpanel/customer-domain/TransferToken.Optional.</summary> [Google.Apis.Util.RequestParameterAttribute("customerAuthToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string CustomerAuthToken { get; set; } /// <summary>Id of the Customer</summary> [Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Query)] public virtual string CustomerId { get; set; } /// <summary>Prefix of the customer's domain name by which the subscriptions should be filtered. /// Optional</summary> [Google.Apis.Util.RequestParameterAttribute("customerNamePrefix", Google.Apis.Util.RequestParameterType.Query)] public virtual string CustomerNamePrefix { get; set; } /// <summary>Maximum number of results to return</summary> /// [minimum: 1] /// [maximum: 100] [Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<long> MaxResults { get; set; } /// <summary>Token to specify next page in the list</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "subscriptions"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "customerAuthToken", new Google.Apis.Discovery.Parameter { Name = "customerAuthToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "customerId", new Google.Apis.Discovery.Parameter { Name = "customerId", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "customerNamePrefix", new Google.Apis.Discovery.Parameter { Name = "customerNamePrefix", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "maxResults", new Google.Apis.Discovery.Parameter { Name = "maxResults", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Starts paid service of a trial subscription</summary> /// <param name="customerId">Id of the Customer</param> /// <param name="subscriptionId">Id of the subscription, /// which is unique for a customer</param> public virtual StartPaidServiceRequest StartPaidService(string customerId, string subscriptionId) { return new StartPaidServiceRequest(service, customerId, subscriptionId); } /// <summary>Starts paid service of a trial subscription</summary> public class StartPaidServiceRequest : ResellerBaseServiceRequest<Google.Apis.Reseller.v1.Data.Subscription> { /// <summary>Constructs a new StartPaidService request.</summary> public StartPaidServiceRequest(Google.Apis.Services.IClientService service, string customerId, string subscriptionId) : base(service) { CustomerId = customerId; SubscriptionId = subscriptionId; InitParameters(); } /// <summary>Id of the Customer</summary> [Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Path)] public virtual string CustomerId { get; private set; } /// <summary>Id of the subscription, which is unique for a customer</summary> [Google.Apis.Util.RequestParameterAttribute("subscriptionId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SubscriptionId { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "startPaidService"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "customers/{customerId}/subscriptions/{subscriptionId}/startPaidService"; } } /// <summary>Initializes StartPaidService parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "customerId", new Google.Apis.Discovery.Parameter { Name = "customerId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "subscriptionId", new Google.Apis.Discovery.Parameter { Name = "subscriptionId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Suspends an active subscription</summary> /// <param name="customerId">Id of the Customer</param> /// <param name="subscriptionId">Id of the subscription, /// which is unique for a customer</param> public virtual SuspendRequest Suspend(string customerId, string subscriptionId) { return new SuspendRequest(service, customerId, subscriptionId); } /// <summary>Suspends an active subscription</summary> public class SuspendRequest : ResellerBaseServiceRequest<Google.Apis.Reseller.v1.Data.Subscription> { /// <summary>Constructs a new Suspend request.</summary> public SuspendRequest(Google.Apis.Services.IClientService service, string customerId, string subscriptionId) : base(service) { CustomerId = customerId; SubscriptionId = subscriptionId; InitParameters(); } /// <summary>Id of the Customer</summary> [Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Path)] public virtual string CustomerId { get; private set; } /// <summary>Id of the subscription, which is unique for a customer</summary> [Google.Apis.Util.RequestParameterAttribute("subscriptionId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SubscriptionId { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "suspend"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "customers/{customerId}/subscriptions/{subscriptionId}/suspend"; } } /// <summary>Initializes Suspend parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "customerId", new Google.Apis.Discovery.Parameter { Name = "customerId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "subscriptionId", new Google.Apis.Discovery.Parameter { Name = "subscriptionId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Reseller.v1.Data { /// <summary>JSON template for address of a customer.</summary> public class Address : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Address line 1 of the address.</summary> [Newtonsoft.Json.JsonPropertyAttribute("addressLine1")] public virtual string AddressLine1 { get; set; } /// <summary>Address line 2 of the address.</summary> [Newtonsoft.Json.JsonPropertyAttribute("addressLine2")] public virtual string AddressLine2 { get; set; } /// <summary>Address line 3 of the address.</summary> [Newtonsoft.Json.JsonPropertyAttribute("addressLine3")] public virtual string AddressLine3 { get; set; } /// <summary>Name of the contact person.</summary> [Newtonsoft.Json.JsonPropertyAttribute("contactName")] public virtual string ContactName { get; set; } /// <summary>ISO 3166 country code.</summary> [Newtonsoft.Json.JsonPropertyAttribute("countryCode")] public virtual string CountryCode { get; set; } /// <summary>Identifies the resource as a customer address.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Name of the locality. This is in accordance with - http://portablecontacts.net/draft- /// spec.html#address_element.</summary> [Newtonsoft.Json.JsonPropertyAttribute("locality")] public virtual string Locality { get; set; } /// <summary>Name of the organization.</summary> [Newtonsoft.Json.JsonPropertyAttribute("organizationName")] public virtual string OrganizationName { get; set; } /// <summary>The postal code. This is in accordance with - http://portablecontacts.net/draft- /// spec.html#address_element.</summary> [Newtonsoft.Json.JsonPropertyAttribute("postalCode")] public virtual string PostalCode { get; set; } /// <summary>Name of the region. This is in accordance with - http://portablecontacts.net/draft- /// spec.html#address_element.</summary> [Newtonsoft.Json.JsonPropertyAttribute("region")] public virtual string Region { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>JSON template for the ChangePlan rpc request.</summary> public class ChangePlanRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>External name of the deal code applicable for the subscription. This field is optional. If missing, /// the deal price plan won't be used.</summary> [Newtonsoft.Json.JsonPropertyAttribute("dealCode")] public virtual string DealCode { get; set; } /// <summary>Identifies the resource as a subscription change plan request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Name of the plan to change to.</summary> [Newtonsoft.Json.JsonPropertyAttribute("planName")] public virtual string PlanName { get; set; } /// <summary>Purchase order id for your order tracking purposes.</summary> [Newtonsoft.Json.JsonPropertyAttribute("purchaseOrderId")] public virtual string PurchaseOrderId { get; set; } /// <summary>Number/Limit of seats in the new plan.</summary> [Newtonsoft.Json.JsonPropertyAttribute("seats")] public virtual Seats Seats { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>JSON template for a customer.</summary> public class Customer : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The alternate email of the customer.</summary> [Newtonsoft.Json.JsonPropertyAttribute("alternateEmail")] public virtual string AlternateEmail { get; set; } /// <summary>The domain name of the customer.</summary> [Newtonsoft.Json.JsonPropertyAttribute("customerDomain")] public virtual string CustomerDomain { get; set; } /// <summary>Whether the customer's primary domain has been verified.</summary> [Newtonsoft.Json.JsonPropertyAttribute("customerDomainVerified")] public virtual System.Nullable<bool> CustomerDomainVerified { get; set; } /// <summary>The id of the customer.</summary> [Newtonsoft.Json.JsonPropertyAttribute("customerId")] public virtual string CustomerId { get; set; } /// <summary>Identifies the resource as a customer.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The phone number of the customer.</summary> [Newtonsoft.Json.JsonPropertyAttribute("phoneNumber")] public virtual string PhoneNumber { get; set; } /// <summary>The postal address of the customer.</summary> [Newtonsoft.Json.JsonPropertyAttribute("postalAddress")] public virtual Address PostalAddress { get; set; } /// <summary>Ui url for customer resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("resourceUiUrl")] public virtual string ResourceUiUrl { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>JSON template for a subscription renewal settings.</summary> public class RenewalSettings : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Identifies the resource as a subscription renewal setting.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Subscription renewal type.</summary> [Newtonsoft.Json.JsonPropertyAttribute("renewalType")] public virtual string RenewalType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>JSON template for subscription seats.</summary> public class Seats : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Identifies the resource as a subscription change plan request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Read-only field containing the current number of licensed seats for FLEXIBLE Google-Apps /// subscriptions and secondary subscriptions such as Google-Vault and Drive-storage.</summary> [Newtonsoft.Json.JsonPropertyAttribute("licensedNumberOfSeats")] public virtual System.Nullable<int> LicensedNumberOfSeats { get; set; } /// <summary>Maximum number of seats that can be purchased. This needs to be provided only for a non-commitment /// plan. For a commitment plan it is decided by the contract.</summary> [Newtonsoft.Json.JsonPropertyAttribute("maximumNumberOfSeats")] public virtual System.Nullable<int> MaximumNumberOfSeats { get; set; } /// <summary>Number of seats to purchase. This is applicable only for a commitment plan.</summary> [Newtonsoft.Json.JsonPropertyAttribute("numberOfSeats")] public virtual System.Nullable<int> NumberOfSeats { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>JSON template for a subscription.</summary> public class Subscription : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Billing method of this subscription.</summary> [Newtonsoft.Json.JsonPropertyAttribute("billingMethod")] public virtual string BillingMethod { get; set; } /// <summary>Creation time of this subscription in milliseconds since Unix epoch.</summary> [Newtonsoft.Json.JsonPropertyAttribute("creationTime")] public virtual System.Nullable<long> CreationTime { get; set; } /// <summary>Primary domain name of the customer</summary> [Newtonsoft.Json.JsonPropertyAttribute("customerDomain")] public virtual string CustomerDomain { get; set; } /// <summary>The id of the customer to whom the subscription belongs.</summary> [Newtonsoft.Json.JsonPropertyAttribute("customerId")] public virtual string CustomerId { get; set; } /// <summary>External name of the deal, if this subscription was provisioned under one. Otherwise this field /// will be empty.</summary> [Newtonsoft.Json.JsonPropertyAttribute("dealCode")] public virtual string DealCode { get; set; } /// <summary>Identifies the resource as a Subscription.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Plan details of the subscription</summary> [Newtonsoft.Json.JsonPropertyAttribute("plan")] public virtual Subscription.PlanData Plan { get; set; } /// <summary>Purchase order id for your order tracking purposes.</summary> [Newtonsoft.Json.JsonPropertyAttribute("purchaseOrderId")] public virtual string PurchaseOrderId { get; set; } /// <summary>Renewal settings of the subscription.</summary> [Newtonsoft.Json.JsonPropertyAttribute("renewalSettings")] public virtual RenewalSettings RenewalSettings { get; set; } /// <summary>Ui url for subscription resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("resourceUiUrl")] public virtual string ResourceUiUrl { get; set; } /// <summary>Number/Limit of seats in the new plan.</summary> [Newtonsoft.Json.JsonPropertyAttribute("seats")] public virtual Seats Seats { get; set; } /// <summary>Name of the sku for which this subscription is purchased.</summary> [Newtonsoft.Json.JsonPropertyAttribute("skuId")] public virtual string SkuId { get; set; } /// <summary>Status of the subscription.</summary> [Newtonsoft.Json.JsonPropertyAttribute("status")] public virtual string Status { get; set; } /// <summary>The id of the subscription.</summary> [Newtonsoft.Json.JsonPropertyAttribute("subscriptionId")] public virtual string SubscriptionId { get; set; } /// <summary>Read-only field containing an enumerable of all the current suspension reasons for a subscription. /// It is possible for a subscription to have many concurrent, overlapping suspension reasons. A subscription's /// STATUS is SUSPENDED until all pending suspensions are removed. Possible options include: - /// PENDING_TOS_ACCEPTANCE - The customer has not logged in and accepted the Google Apps Resold Terms of /// Services. - RENEWAL_WITH_TYPE_CANCEL - The customer's commitment ended and their service was cancelled at /// the end of their term. - RESELLER_INITIATED - A manual suspension invoked by a Reseller. - TRIAL_ENDED - The /// customer's trial expired without a plan selected. - OTHER - The customer is suspended for an internal Google /// reason (e.g. abuse or otherwise).</summary> [Newtonsoft.Json.JsonPropertyAttribute("suspensionReasons")] public virtual System.Collections.Generic.IList<string> SuspensionReasons { get; set; } /// <summary>Transfer related information for the subscription.</summary> [Newtonsoft.Json.JsonPropertyAttribute("transferInfo")] public virtual Subscription.TransferInfoData TransferInfo { get; set; } /// <summary>Trial Settings of the subscription.</summary> [Newtonsoft.Json.JsonPropertyAttribute("trialSettings")] public virtual Subscription.TrialSettingsData TrialSettings { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>Plan details of the subscription</summary> public class PlanData { /// <summary>Interval of the commitment if it is a commitment plan.</summary> [Newtonsoft.Json.JsonPropertyAttribute("commitmentInterval")] public virtual PlanData.CommitmentIntervalData CommitmentInterval { get; set; } /// <summary>Whether the plan is a commitment plan or not.</summary> [Newtonsoft.Json.JsonPropertyAttribute("isCommitmentPlan")] public virtual System.Nullable<bool> IsCommitmentPlan { get; set; } /// <summary>The plan name of this subscription's plan.</summary> [Newtonsoft.Json.JsonPropertyAttribute("planName")] public virtual string PlanName { get; set; } /// <summary>Interval of the commitment if it is a commitment plan.</summary> public class CommitmentIntervalData { /// <summary>End time of the commitment interval in milliseconds since Unix epoch.</summary> [Newtonsoft.Json.JsonPropertyAttribute("endTime")] public virtual System.Nullable<long> EndTime { get; set; } /// <summary>Start time of the commitment interval in milliseconds since Unix epoch.</summary> [Newtonsoft.Json.JsonPropertyAttribute("startTime")] public virtual System.Nullable<long> StartTime { get; set; } } } /// <summary>Transfer related information for the subscription.</summary> public class TransferInfoData { [Newtonsoft.Json.JsonPropertyAttribute("minimumTransferableSeats")] public virtual System.Nullable<int> MinimumTransferableSeats { get; set; } /// <summary>Time when transfer token or intent to transfer will expire.</summary> [Newtonsoft.Json.JsonPropertyAttribute("transferabilityExpirationTime")] public virtual System.Nullable<long> TransferabilityExpirationTime { get; set; } } /// <summary>Trial Settings of the subscription.</summary> public class TrialSettingsData { /// <summary>Whether the subscription is in trial.</summary> [Newtonsoft.Json.JsonPropertyAttribute("isInTrial")] public virtual System.Nullable<bool> IsInTrial { get; set; } /// <summary>End time of the trial in milliseconds since Unix epoch.</summary> [Newtonsoft.Json.JsonPropertyAttribute("trialEndTime")] public virtual System.Nullable<long> TrialEndTime { get; set; } } } /// <summary>JSON template for a subscription list.</summary> public class Subscriptions : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Identifies the resource as a collection of subscriptions.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The continuation token, used to page through large result sets. Provide this value in a subsequent /// request to return the next page of results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The subscriptions in this page of results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("subscriptions")] public virtual System.Collections.Generic.IList<Subscription> SubscriptionsValue { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
apache-2.0
hoangelos/Herd
bin/herd-manager.py
2454
#!/usr/bin/env python # -*- coding: utf-8 -*- ## Copyright 2012 Peter Halliday ## ## 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 argparse import gevent from herd.manager.server import HerdManager from herd import herd_config def manager1(args): #Get options from command-line manager = HerdManager(address=args.address, port=args.port, ip=args.ip, config=args.config, stream_ip=args.stream_ip, stream_port=args.stream_port) manager.start_listener() def main(args): gevent.joinall([ gevent.spawn(manager1, args) ]) if __name__ == "__main__": parser = argparse.ArgumentParser("Start a Herd Manager node") parser.add_argument("-a", "--address", dest="address", default=None, help="Address to connect to of existing node. In format of xxx.xxx.xxx.xxx[:nnnn].", metavar="ADDRESS") parser.add_argument('-p', "--port", dest="port", default=None, help="Port to connect to locally. Default:8339", metavar="PORT") parser.add_argument('-i', "--ip", dest="ip", default=None, metavar="IP_ADDRESS", help="IP address to connect to locally. Default: 127.0.0.1") parser.add_argument('-I', '--stream_ip', dest="stream_ip", default=None, metavar="IP_ADDRESS", help="IP address to connect the stream too. Default: 0.0.0.0") parser.add_argument('-P', '--stream_port', dest="stream_port", default=None, help="Port to connect the stream to. Default:8339", metavar="PORT") config_help = "Config file PATH if different than default. (Default: %s)" % herd_config.HERD_MANAGE_CONFIG parser.add_argument('-c', "--config", dest="config", default=None, metavar="FILE", help=config_help) args = parser.parse_args() main(args)
apache-2.0
darranl/directory-shared
ldap/extras/codec-api/src/main/java/org/apache/directory/api/ldap/extras/extended/gracefulShutdown/GracefulShutdownRequest.java
2414
/* * 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.directory.api.ldap.extras.extended.gracefulShutdown; import org.apache.directory.api.ldap.model.message.ExtendedRequest; /** * An extended operation requesting the server to shutdown it's LDAP service * port while allowing established clients to complete or abandon operations * already in progress. More information about this extended request is * available here: <a href="http://docs.safehaus.org:8080/x/GR">LDAP Extensions * for Graceful Shutdown</a>. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public interface GracefulShutdownRequest extends ExtendedRequest { /** The OID for the graceful shutdown extended operation request. */ String EXTENSION_OID = "1.3.6.1.4.1.18060.0.1.3"; /** Undetermined value used for offline time */ int UNDETERMINED = 0; /** The shutdown is immediate */ int NOW = 0; /** * Gets the delay before disconnection, in seconds. * * @return the delay before disconnection */ int getDelay(); /** * Sets the delay before disconnection, in seconds. * * @param delay the new delay before disconnection */ void setDelay( int delay ); /** * Gets the offline time after disconnection, in minutes. * * @return the offline time after disconnection */ int getTimeOffline(); /** * Sets the time offline after disconnection, in minutes. * * @param timeOffline the new time offline after disconnection */ void setTimeOffline( int timeOffline ); }
apache-2.0
Shockah/tModLoader-Mods
Shockah.ItemAffix/Content/Hidden Potential/HiddenPotentialHitRequirement.cs
1069
using Shockah.Affix.Utils; using Terraria; namespace Shockah.Affix.Content { public class HiddenPotentialHitRequirement : HiddenPotentialIntRequirement { public static readonly TagDeserializer<HiddenPotentialHitRequirement> DESERIALIZER = new TagDeserializer<HiddenPotentialHitRequirement>(tag => { HiddenPotentialHitRequirement requirement = new HiddenPotentialHitRequirement(tag.GetInt("required")); requirement.progress = tag.GetInt("progress"); return requirement; }); public HiddenPotentialHitRequirement(int required) : base(required) { } public override string GetRequirementTooltipName(Item item, HiddenPotentialAffix affix) { return "Hits"; } public override void OnHitNPC(Item item, Player player, NPC target, int damage, float knockBack, bool crit, HiddenPotentialAffix affix) { Progress(1, item, affix); } public override void OnHitNPC(Item item, Player player, Projectile projectile, NPC target, int damage, float knockBack, bool crit, HiddenPotentialAffix affix) { Progress(1, item, affix); } } }
apache-2.0
apptik/MultiView
galleryview/src/main/java/io/apptik/multiview/galleryview/scaleimage/gestures/VersionedGestureDetector.java
1554
package io.apptik.multiview.galleryview.scaleimage.gestures; /******************************************************************************* * Copyright 2011, 2012 Chris Banes. * * 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 android.content.Context; import android.os.Build; public final class VersionedGestureDetector { public static GestureDetector newInstance(Context context, OnGestureListener listener) { final int sdkVersion = Build.VERSION.SDK_INT; GestureDetector detector; if (sdkVersion < Build.VERSION_CODES.ECLAIR) { detector = new CupcakeGestureDetector(context); } else if (sdkVersion < Build.VERSION_CODES.FROYO) { detector = new EclairGestureDetector(context); } else { detector = new FroyoGestureDetector(context); } detector.setOnGestureListener(listener); return detector; } }
apache-2.0
dorzey/assertj-core
src/test/java/org/assertj/core/api/charsequence/CharSequenceAssert_containsSequence_Test.java
1370
/** * 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. * * Copyright 2012-2016 the original author or authors. */ package org.assertj.core.api.charsequence; import static org.mockito.Mockito.verify; import java.util.Arrays; import org.assertj.core.api.CharSequenceAssert; import org.assertj.core.api.CharSequenceAssertBaseTest; /** * Tests for <code>{@link CharSequenceAssert#containsSequence(Iterable)}</code>. * * @author André Diermann */ public class CharSequenceAssert_containsSequence_Test extends CharSequenceAssertBaseTest { @Override protected CharSequenceAssert invoke_api_method() { return assertions.containsSequence(Arrays.<CharSequence> asList("od", "do")); } @Override protected void verify_internal_effects() { verify(strings).assertContainsSequence(getInfo(assertions), getActual(assertions), new String[] { "od", "do" }); } }
apache-2.0
asterd/BootsFaces-OSP
src/main/java/net/bootsfaces/render/Tooltip.java
6033
/** * Copyright 2014-16 by Riccardo Massera (TheCoder4.Eu) and Stephan Rauh (http://www.beyondjava.net). * * This file is part of BootsFaces. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bootsfaces.render; import java.io.IOException; import java.util.Map; import javax.faces.FacesException; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import net.bootsfaces.C; import net.bootsfaces.listeners.AddResourcesListener; /** * Renders a tooltip. * * @author Stephan Rauh */ public class Tooltip { public static void generateTooltip(FacesContext context, UIComponent component, ResponseWriter rw) throws IOException { Map<String, Object> attrs = component.getAttributes(); String tooltip = (String) attrs.get("tooltip"); if (null != tooltip) { //set default values first, if not present String position = (String) attrs.get("tooltipPosition"); if (null == position) // compatibility for the HTML-style using "-" characters instead of camelcase position = (String) attrs.get("tooltip-position"); if (null == position) position = "auto"; String container = (String) attrs.get("tooltipContainer"); if (null == container) // compatibility for the HTML-style using "-" characters instead of camelcase container = (String) attrs.get("tooltip-container"); if (null == container || container.length() == 0) container = "body"; verifyAndWriteTooltip(context, rw, tooltip, position, container); } } private static void verifyAndWriteTooltip(FacesContext context, ResponseWriter rw, String tooltip, String position, String container) throws IOException { if (null == position) position="bottom"; boolean ok = "top".equals(position); ok |= "bottom".equals(position); ok |= "right".equals(position); ok |= "left".equals(position); ok |= "auto".equals(position); ok |= "auto top".equals(position); ok |= "auto bottom".equals(position); ok |= "auto right".equals(position); ok |= "auto left".equals(position); if (!ok) { position = "bottom"; context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Wrong JSF markup", "Tooltip position must either be 'auto', 'top', 'bottom', 'left' or 'right'.")); } rw.writeAttribute("data-toggle", "tooltip", null); rw.writeAttribute("data-placement", position, "data-placement"); rw.writeAttribute("data-container", container, "data-container"); rw.writeAttribute("title", tooltip, null); } private static String generateDelayAttributes(Map<String, Object> attrs) throws IOException { String json = ""; String delayShow = getAndCheckDelayAttribute("tooltip-delay-show", attrs, "show"); if (null == delayShow) { delayShow = getAndCheckDelayAttribute("tooltip-delay", attrs, "show"); } if (null != delayShow) json += delayShow + ","; String delayHide = getAndCheckDelayAttribute("tooltip-delay-hide", attrs, "hide"); if (null == delayHide) { delayHide = getAndCheckDelayAttribute("tooltip-delay", attrs, "hide"); } if (null != delayHide) json += delayHide + ","; if (!json.isEmpty()) { return "{" + json.substring(0, json.length() - 1) + "}"; } return null; } private static String getAndCheckDelayAttribute(String attributeName, Map<String, Object> attrs, String htmlAttributeName) throws FacesException { Object value = attrs.get(attributeName); if (null != value) { if ((value instanceof String) && ((String)value).length() > 0) { try { Integer.parseInt((String)value); return htmlAttributeName + ":" + value; } catch (NumberFormatException ex) { //throw exception later } } else if (value instanceof Integer) { return htmlAttributeName + ":" + value; } //if we reach this point, the value wasn't accepted as Integer throw new FacesException("The attribute " + attributeName + " has to be numeric. The value '" + value + "' is invalid."); } return null; } /** * Adds the required resource files for tooltips to the required resources list. */ public static void addResourceFiles() { // if (null != getAttributes().get("tooltip")) { //!bs-less//AddResourcesListener.addThemedCSSResource("tooltip.css"); AddResourcesListener.addResourceToHeadButAfterJQuery(C.BSF_LIBRARY, "js/tooltip.js"); // } } public static void activateTooltips(FacesContext context, UIComponent component) throws IOException { String id = component.getClientId(); activateTooltips(context, component, id); } public static void activateTooltips(FacesContext context, UIComponent component, String id) throws IOException { Map<String, Object> attributes = component.getAttributes(); if (attributes.get("tooltip") != null) { id = id.replace(":", "\\\\:"); // we need to escape the id for // jQuery String delayOptions = generateDelayAttributes(attributes); String options = ""; if (null != delayOptions) options = "'delay':" + delayOptions + ","; if (options.length() > 0) options = "{" + options.substring(0, options.length() - 1) + "}"; String js = "$(function () {\n" + "$('#" + id + "').tooltip(" + options + ")\n" + "});\n"; //destroy existing tooltips to prevent ajax bugs in some browsers and prevent memory leaks (see #323 and #220) js+="$('.tooltip').tooltip('destroy'); "; context.getResponseWriter().write("<script type='text/javascript'>" + js + "</script>"); } } }
apache-2.0
ChillingVan/android-openGL-canvas
canvasglsample/src/main/java/com/chillingvan/canvasglsample/text/DrawTextActivity.java
2750
package com.chillingvan.canvasglsample.text; import android.graphics.SurfaceTexture; import android.os.Bundle; import android.os.CountDownTimer; import android.support.v7.app.AppCompatActivity; import android.view.Surface; import android.view.View; import android.widget.TextView; import com.chillingvan.canvasgl.glcanvas.RawTexture; import com.chillingvan.canvasgl.glview.texture.GLSurfaceTextureProducerView; import com.chillingvan.canvasglsample.R; import com.chillingvan.canvasglsample.video.MediaPlayerHelper; public class DrawTextActivity extends AppCompatActivity { private MediaPlayerHelper mediaPlayer = new MediaPlayerHelper(); private Surface mediaSurface; private DrawTextTextureView drawTextTextureView; private CountDownTimer countDownTimer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_draw_text); initTextureView(); } private void initTextureView() { drawTextTextureView = findViewById(R.id.media_player_texture_view); final TextView frameRateTxt = findViewById(R.id.frame_rate_txt); drawTextTextureView.setOnSurfaceTextureSet(new GLSurfaceTextureProducerView.OnSurfaceTextureSet() { @Override public void onSet(SurfaceTexture surfaceTexture, RawTexture surfaceTextureRelatedTexture) { // No need to request draw because it is continues GL View. mediaSurface = new Surface(surfaceTexture); } }); countDownTimer = new CountDownTimer(1000 * 3600, 1000) { @Override public void onTick(long millisUntilFinished) { frameRateTxt.setText(String.valueOf(drawTextTextureView.getFrameRate())); } @Override public void onFinish() { } }; countDownTimer.start(); } @Override protected void onResume() { super.onResume(); drawTextTextureView.onResume(); } @Override protected void onPause() { super.onPause(); if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); } drawTextTextureView.onPause(); } @Override protected void onDestroy() { super.onDestroy(); countDownTimer.cancel(); if (mediaPlayer.isPlaying()) { mediaPlayer.release(); } } public void onClickStart(View view) { if ((mediaPlayer.isPlaying() || mediaPlayer.isLooping())) { return; } playMedia(); } private void playMedia() { mediaPlayer.playMedia(this, mediaSurface); drawTextTextureView.start(); } }
apache-2.0
stephanie-wang/ray
streaming/java/streaming-runtime/src/main/java/org/ray/streaming/runtime/core/graph/executiongraph/ExecutionJobVertex.java
4349
package org.ray.streaming.runtime.core.graph.executiongraph; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.ray.api.RayActor; import org.ray.streaming.jobgraph.JobVertex; import org.ray.streaming.jobgraph.VertexType; import org.ray.streaming.operator.StreamOperator; import org.ray.streaming.runtime.worker.JobWorker; /** * Physical job vertex. * * <p>Execution job vertex is the physical form of {@link JobVertex} and * every execution job vertex is corresponding to a group of {@link ExecutionVertex}. */ public class ExecutionJobVertex { /** * Unique id for execution job vertex. */ private final int jobVertexId; /** * Unique name generated by vertex name and index for execution job vertex. */ private final String jobVertexName; private final StreamOperator streamOperator; private final VertexType vertexType; private int parallelism; private List<ExecutionVertex> executionVertices; private List<ExecutionJobEdge> inputEdges = new ArrayList<>(); private List<ExecutionJobEdge> outputEdges = new ArrayList<>(); public ExecutionJobVertex(JobVertex jobVertex) { this.jobVertexId = jobVertex.getVertexId(); this.jobVertexName = generateVertexName(jobVertexId, jobVertex.getStreamOperator()); this.streamOperator = jobVertex.getStreamOperator(); this.vertexType = jobVertex.getVertexType(); this.parallelism = jobVertex.getParallelism(); this.executionVertices = createExecutionVertics(); } private String generateVertexName(int vertexId, StreamOperator streamOperator) { return vertexId + "-" + streamOperator.getName(); } private List<ExecutionVertex> createExecutionVertics() { List<ExecutionVertex> executionVertices = new ArrayList<>(); for (int index = 1; index <= parallelism; index++) { executionVertices.add(new ExecutionVertex(jobVertexId, index, this)); } return executionVertices; } public Map<Integer, RayActor<JobWorker>> getExecutionVertexWorkers() { Map<Integer, RayActor<JobWorker>> executionVertexWorkersMap = new HashMap<>(); Preconditions.checkArgument( executionVertices != null && !executionVertices.isEmpty(), "Empty execution vertex."); executionVertices.stream().forEach(vertex -> { Preconditions.checkArgument( vertex.getWorkerActor() != null, "Empty execution vertex worker actor."); executionVertexWorkersMap.put(vertex.getVertexId(), vertex.getWorkerActor()); }); return executionVertexWorkersMap; } public int getJobVertexId() { return jobVertexId; } public String getJobVertexName() { return jobVertexName; } public int getParallelism() { return parallelism; } public List<ExecutionVertex> getExecutionVertices() { return executionVertices; } public void setExecutionVertices( List<ExecutionVertex> executionVertex) { this.executionVertices = executionVertex; } public List<ExecutionJobEdge> getOutputEdges() { return outputEdges; } public void setOutputEdges( List<ExecutionJobEdge> outputEdges) { this.outputEdges = outputEdges; } public List<ExecutionJobEdge> getInputEdges() { return inputEdges; } public void setInputEdges( List<ExecutionJobEdge> inputEdges) { this.inputEdges = inputEdges; } public StreamOperator getStreamOperator() { return streamOperator; } public VertexType getVertexType() { return vertexType; } public boolean isSourceVertex() { return getVertexType() == VertexType.SOURCE; } public boolean isTransformationVertex() { return getVertexType() == VertexType.TRANSFORMATION; } public boolean isSinkVertex() { return getVertexType() == VertexType.SINK; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("jobVertexId", jobVertexId) .add("jobVertexName", jobVertexName) .add("streamOperator", streamOperator) .add("vertexType", vertexType) .add("parallelism", parallelism) .add("executionVertices", executionVertices) .add("inputEdges", inputEdges) .add("outputEdges", outputEdges) .toString(); } }
apache-2.0
AutomationRockstars/Design
design/gir-webdriver/src/main/java/com/automationrockstars/design/gir/webdriver/plugin/UiDriverPlugin.java
770
/* * <!-- * Copyright (c) 2015-2019 Automation RockStars Ltd. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License v2.0 * which accompanies this distribution, and is available at * http://www.apache.org/licenses/LICENSE-2.0 * * Contributors: * Automation RockStars * --> */ package com.automationrockstars.design.gir.webdriver.plugin; import org.openqa.selenium.WebDriver; public interface UiDriverPlugin { void beforeInstantiateDriver(); void afterInstantiateDriver(WebDriver driver); void beforeGetDriver(); void afterGetDriver(WebDriver driver); void beforeCloseDriver(WebDriver driver); void afterCloseDriver(); }
apache-2.0
apache/hadoop-mapreduce
src/java/org/apache/hadoop/mapreduce/QueueAclsInfo.java
2334
/** * 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.hadoop.mapreduce; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; /** * Class to encapsulate Queue ACLs for a particular * user. * */ public class QueueAclsInfo implements Writable { private String queueName; private String[] operations; /** * Default constructor for QueueAclsInfo. * */ public QueueAclsInfo() { } /** * Construct a new QueueAclsInfo object using the queue name and the * queue operations array * * @param queueName Name of the job queue * @param operations */ public QueueAclsInfo(String queueName, String[] operations) { this.queueName = queueName; this.operations = operations; } /** * Get queue name. * * @return name */ public String getQueueName() { return queueName; } protected void setQueueName(String queueName) { this.queueName = queueName; } /** * Get opearations allowed on queue. * * @return array of String */ public String[] getOperations() { return operations; } @Override public void readFields(DataInput in) throws IOException { queueName = Text.readString(in); operations = WritableUtils.readStringArray(in); } @Override public void write(DataOutput out) throws IOException { Text.writeString(out, queueName); WritableUtils.writeStringArray(out, operations); } }
apache-2.0
cogitate/twitter-zipkin-uuid
zipkin-common/src/main/scala/com/twitter/zipkin/storage/util/SpanStoreValidator.scala
9947
/* * Copyright 2014 Twitter Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.zipkin.storage.util import com.twitter.conversions.time._ import com.twitter.logging.Logger import com.twitter.util.{Await, Duration, NonFatal} import com.twitter.zipkin.common._ import com.twitter.zipkin.query.Trace import com.twitter.zipkin.storage.{TraceIdDuration, SpanStore} import java.nio.ByteBuffer import scala.language.reflectiveCalls class SpanStoreValidator( newSpanStore: => SpanStore, ignoreSortTests: Boolean = false, log: Logger = Logger.get("ValidateSpanStore") ) { val ep = Endpoint(123, 123, "service") implicit def long2String(l: Long): String = l.toString def binaryAnnotation(key: String, value: String) = BinaryAnnotation(key, ByteBuffer.wrap(value.getBytes), AnnotationType.String, Some(ep)) val spanId = 456 val ann1 = Annotation(1, "cs", Some(ep)) val ann2 = Annotation(2, "sr", None) val ann3 = Annotation(20, "custom", Some(ep)) val ann4 = Annotation(20, "custom", Some(ep)) val ann5 = Annotation(5, "custom", Some(ep)) val ann6 = Annotation(6, "custom", Some(ep)) val ann7 = Annotation(7, "custom", Some(ep)) val ann8 = Annotation(8, "custom", Some(ep)) val span1 = Span(123, "methodcall", spanId, None, List(ann1, ann3), List(binaryAnnotation("BAH", "BEH"))) val span2 = Span(456, "methodcall", spanId, None, List(ann2), List(binaryAnnotation("BAH2", "BEH2"))) val span3 = Span(789, "methodcall", spanId, None, List(ann2, ann3, ann4), List(binaryAnnotation("BAH2", "BEH2"))) val span4 = Span(999, "methodcall", spanId, None, List(ann6, ann7), List()) val span5 = Span(999, "methodcall", spanId, None, List(ann5, ann8), List(binaryAnnotation("BAH2", "BEH2"))) val spanEmptySpanName = Span(123, "", spanId, None, List(ann1, ann2), List()) val spanEmptyServiceName = Span(123, "spanname", spanId, None, List(), List()) val mergedSpan = Span(123, "methodcall", spanId, None, List(ann1, ann2), List(binaryAnnotation("BAH2", "BEH2"))) def resetAndLoadStore(spans: Seq[Span]): SpanStore = { val store = newSpanStore Await.result(store(spans)) store } private[this] var tests: Map[String, (() => Unit)] = Map.empty private[this] def test(name: String)(f: => Unit) { tests += (name -> f _) } def validate { val spanStoreName = newSpanStore.getClass.getName.split('.').last val results = tests map { case (name, f) => println("validating %s: %s".format(spanStoreName, name)) try { f(); println(" pass") true } catch { case NonFatal(e) => println(" fail") log.error(e, "validation failed") false } } val passedCount = results.count(x => x) println("%d / %d passed.".format(passedCount, tests.size)) if (passedCount < tests.size) { println("Failed tests for %s:".format(spanStoreName)) results.zip(tests) collect { case (result, (name, _)) if !result => println(name) } } assert(passedCount == tests.size) } // Test that we handle failures correctly. def validateFailures { val spanStoreName = newSpanStore.getClass.getName.split('.').last val results = tests map { case (name, f) => println("validating failures with %s: %s".format(spanStoreName, name)) try { f() println(" Fail: exception not thrown.") log.error("Validation failed: exception not thrown.") false } catch { case e: SpanStoreException => println(" Caught exception %s (expected)".format(e)) true case NonFatal(x) => println(" Error: caught exception %s (unexpected)".format(x)) false } } val passedCount = results.count(x => x) println("%d / %d passed.".format(passedCount, tests.size)) if (passedCount < tests.size) { println("Failed tests for %s:".format(spanStoreName)) results.zip(tests) collect { case (result, (name, _)) if !result => println(name) } } assert(passedCount == tests.size) } def eq(a: Any, b: Any): Boolean = if (a == b) true else { println("%s is not equal to %s".format(a, b)) false } def empty(v: { def isEmpty: Boolean }): Boolean = if (v.isEmpty) true else { println("%s is not empty".format(v)) false } def notEmpty(v: { def isEmpty: Boolean }): Boolean = if (!v.isEmpty) true else { println("%s is empty".format(v)) false } test("get by trace id") { val store = resetAndLoadStore(Seq(span1)) val spans = Await.result(store.getSpansByTraceId(span1.traceId)) assert(eq(spans.size, 1)) assert(eq(spans.head, span1)) } test("get by trace ids") { val span666 = Span(666, "methodcall2", spanId, None, List(ann2), List(binaryAnnotation("BAH2", "BEH2"))) val store = resetAndLoadStore(Seq(span1, span666)) val actual1 = Await.result(store.getSpansByTraceIds(Seq(span1.traceId))) assert(notEmpty(actual1)) val trace1 = Trace(actual1(0)) assert(notEmpty(trace1.spans)) assert(eq(trace1.spans(0), span1)) val actual2 = Await.result(store.getSpansByTraceIds(Seq(span1.traceId, span666.traceId))) assert(eq(actual2.size, 2)) val trace2 = Trace(actual2(0)) assert(notEmpty(trace2.spans)) assert(eq(trace2.spans(0), span1)) val trace3 = Trace(actual2(1)) assert(notEmpty(trace3.spans)) assert(eq(trace3.spans(0), span666)) } test("get by trace ids returns an empty list if nothing is found") { val store = resetAndLoadStore(Seq()) val spans = Await.result(store.getSpansByTraceIds(Seq(54321))) // Nonexistent span assert(empty(spans)) } test("alter TTL on a span") { val store = resetAndLoadStore(Seq(span1)) Await.result(store.setTimeToLive(span1.traceId, 1234.seconds)) // If a store doesn't use TTLs this should return Duration.Top val allowedVals = Seq(1234.seconds, Duration.Top) assert(allowedVals.contains(Await.result(store.getTimeToLive(span1.traceId)))) } test("check for existing traces") { val store = resetAndLoadStore(Seq(span1, span4)) val expected = Set(span1.traceId, span4.traceId) val result = Await.result(store.tracesExist(Seq(span1.traceId, span4.traceId, 111111))) assert(eq(result, expected)) } test("get spans by name") { val store = resetAndLoadStore(Seq(span1)) assert(eq(Await.result(store.getSpanNames("service")), Set(span1.name))) } test("get service names") { val store = resetAndLoadStore(Seq(span1)) assert(eq(Await.result(store.getAllServiceNames), span1.serviceNames)) } if (!ignoreSortTests) { test("get trace ids by name") { val store = resetAndLoadStore(Seq(span1)) assert(eq(Await.result(store.getTraceIdsByName("service", None, 100, 3)).head.traceId, span1.traceId)) assert(eq(Await.result(store.getTraceIdsByName("service", Some("methodcall"), 100, 3)).head.traceId, span1.traceId)) assert(empty(Await.result(store.getTraceIdsByName("badservice", None, 100, 3)))) assert(empty(Await.result(store.getTraceIdsByName("service", Some("badmethod"), 100, 3)))) assert(empty(Await.result(store.getTraceIdsByName("badservice", Some("badmethod"), 100, 3)))) } test("get traces duration") { val store = resetAndLoadStore(Seq(span1, span2, span3, span4)) val expected = Seq( TraceIdDuration(span1.traceId, 19, 1), TraceIdDuration(span2.traceId, 0, 2), TraceIdDuration(span3.traceId, 18, 2), TraceIdDuration(span4.traceId, 1, 6)) val result = Await.result(store.getTracesDuration( Seq(span1.traceId, span2.traceId, span3.traceId, span4.traceId))) assert(eq(result, expected)) val store2 = resetAndLoadStore(Seq(span4)) assert(eq(Await.result(store2.getTracesDuration(Seq(999))), Seq(TraceIdDuration(999, 1, 6)))) Await.result(store2(Seq(span5))) assert(eq(Await.result(store2.getTracesDuration(Seq(999))), Seq(TraceIdDuration(999, 3, 5)))) } } test("get trace ids by annotation") { val store = resetAndLoadStore(Seq(span1)) // fetch by time based annotation, find trace val res1 = Await.result(store.getTraceIdsByAnnotation("service", "custom", None, 100, 3)) assert(eq(res1.head.traceId, span1.traceId)) // should not find any traces since the core annotation doesn't exist in index val res2 = Await.result(store.getTraceIdsByAnnotation("service", "cs", None, 100, 3)) assert(empty(res2)) // should find traces by the key and value annotation val res3 = Await.result(store.getTraceIdsByAnnotation("service", "BAH", Some(ByteBuffer.wrap("BEH".getBytes)), 100, 3)) assert(eq(res3.head.traceId, span1.traceId)) } test("limit on annotations") { val store = resetAndLoadStore(Seq(span1, span4, span5)) val res1 = Await.result(store.getTraceIdsByAnnotation("service", "custom", None, 100, limit = 2)) assert(eq(res1.length, 2)) assert(eq(res1(0).traceId, span1.traceId)) assert(eq(res1(1).traceId, span5.traceId)) } test("wont index empty service names") { val store = resetAndLoadStore(Seq(spanEmptyServiceName)) assert(empty(Await.result(store.getAllServiceNames))) } test("wont index empty span names") { val store = resetAndLoadStore(Seq(spanEmptySpanName)) assert(empty(Await.result(store.getSpanNames(spanEmptySpanName.name)))) } }
apache-2.0
kagenonn/CTR_WEB
WebTemplate/WebTemplate/Controllers/SubmitBTRController.cs
319
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebTemplate.Controllers { public class SubmitBTRController : Controller { // GET: SubmitBTR public ActionResult Index() { return View(); } } }
apache-2.0
sfxcode/sapphire-extension
src/test/scala/com/sfxcode/sapphire/extension/property/BeanItemSpec.scala
2093
package com.sfxcode.sapphire.extension.property import java.util import com.sfxcode.sapphire.core.value.FXBean import com.sfxcode.sapphire.extension.test.{ Person, PersonDatabase } import com.typesafe.scalalogging.LazyLogging import org.specs2.mutable.Specification class BeanItemSpec extends Specification with LazyLogging { sequential "BeanItem" should { "be created with bean property" in { val person: FXBean[Person] = PersonDatabase.testPerson(1) person.bean.name must be equalTo "Bowen Leon" val nameItem = BeanItem(person, "name") nameItem.setValue("ABC") person.bean.name must be equalTo "ABC" nameItem.getType.toString must be equalTo "class java.lang.String" val ageItem = BeanItem(person, "age") ageItem.getType.toString must be equalTo "class java.lang.Integer" val activeItem = BeanItem(person, "isActive") activeItem.getType.toString must be equalTo "class java.lang.Boolean" } "be created with map property" in { val map = new util.HashMap[String, Any]() map.put("name", "name") map.put("age", 42) map.put("isActive", true) val person = FXBean(map) val nameItem = BeanItem(person, "name") nameItem.setValue("ABC") person.getValue("name") must be equalTo "ABC" nameItem.getType.toString must be equalTo "class java.lang.String" val ageItem = BeanItem(person, "age") ageItem.getType.toString must be equalTo "class java.lang.Integer" val activeItem = BeanItem(person, "isActive") activeItem.getType.toString must be equalTo "class java.lang.Boolean" } "be created with class" in { val map = new util.HashMap[String, Any]() map.put("name", "ABC") map.put("age", 42) map.put("isActive", true) val person = FXBean(map) val nameItem = BeanItem(FXBean(Map()), "name", clazz = classOf[String]) nameItem.getType.toString must be equalTo "class java.lang.String" nameItem.bean = person nameItem.getValue.toString must be equalTo "ABC" } } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-guardduty/src/main/java/com/amazonaws/services/guardduty/model/transform/CountryMarshaller.java
2204
/* * 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.guardduty.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.guardduty.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * CountryMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class CountryMarshaller { private static final MarshallingInfo<String> COUNTRYCODE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("countryCode").build(); private static final MarshallingInfo<String> COUNTRYNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("countryName").build(); private static final CountryMarshaller instance = new CountryMarshaller(); public static CountryMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(Country country, ProtocolMarshaller protocolMarshaller) { if (country == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(country.getCountryCode(), COUNTRYCODE_BINDING); protocolMarshaller.marshall(country.getCountryName(), COUNTRYNAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
wutongservice/virtualgoogdsman
marketfull/src/com/borqs/market/view/LightProgressDialog.java
2721
/* * Copyright 2012 GitHub Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.borqs.market.view; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.FROYO; import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; import com.borqs.market.R; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; /** * Progress dialog in Holo Light theme */ public class LightProgressDialog extends ProgressDialog { /** * Create progress dialog * * @param context * @param resId * @return dialog */ public static AlertDialog create(Context context, int resId) { return create(context, context.getResources().getString(resId)); } /** * Create progress dialog * * @param context * @param message * @return dialog */ public static AlertDialog create(Context context, CharSequence message) { if (SDK_INT > FROYO) { ProgressDialog dialog; if (SDK_INT >= ICE_CREAM_SANDWICH) dialog = new LightProgressDialog(context, message); else { dialog = new ProgressDialog(context); dialog.setInverseBackgroundForced(true); } dialog.setMessage(message); dialog.setIndeterminate(true); dialog.setProgressStyle(STYLE_SPINNER); dialog.setIndeterminateDrawable(context.getResources().getDrawable( R.drawable.spinner)); return dialog; } else { AlertDialog dialog = LightAlertDialog.create(context); dialog.setInverseBackgroundForced(true); View view = LayoutInflater.from(context).inflate( R.layout.progress_dialog, null); ((TextView) view.findViewById(R.id.tv_loading)).setText(message); dialog.setView(view); return dialog; } } private LightProgressDialog(Context context, CharSequence message) { super(context, THEME_HOLO_LIGHT); } }
apache-2.0
VHAINNOVATIONS/Telepathology
Source/Java/CoreRouterAnnotationProcessor/main/src/java/gov/va/med/imaging/core/annotations/FacadeRouterTesterAnnotationProcessor.java
1901
/** * Package: MAG - VistA Imaging WARNING: Per VHA Directive 2004-038, this routine should not be modified. Date Created: May 6, 2011 Site Name: Washington OI Field Office, Silver Spring, MD Developer: VHAISWWERFEJ Description: ;; +--------------------------------------------------------------------+ ;; Property of the US Government. ;; No permission to copy or redistribute this software is given. ;; Use of unreleased versions of this software requires the user ;; to execute a written test agreement with the VistA Imaging ;; Development Office of the Department of Veterans Affairs, ;; telephone (301) 734-0100. ;; ;; The Food and Drug Administration classifies this software as ;; a Class II medical device. As such, it may not be changed ;; in any way. Modifications to this software may result in an ;; adulterated medical device under 21CFR820, the use of which ;; is considered to be a violation of US Federal Statutes. ;; +--------------------------------------------------------------------+ */ package gov.va.med.imaging.core.annotations; import javax.annotation.processing.Processor; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedOptions; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; /** * @author VHAISWWERFEJ * */ @SupportedAnnotationTypes("gov.va.med.imaging.core.annotations.routerfacade.FacadeRouterInterfaceCommandTester") @SupportedSourceVersion(SourceVersion.RELEASE_6) @SupportedOptions("gov.va.med.imaging.mock") public class FacadeRouterTesterAnnotationProcessor extends FacadeRouterAnnotationProcessor implements Processor { public FacadeRouterTesterAnnotationProcessor() { super(); setGenerateTests(true); } }
apache-2.0
yangjunlin-const/WhileTrueCoding
JavaBase/src/main/java/com/yjl/javabase/thinkinjava/strings/Splitting.java
1006
package com.yjl.javabase.thinkinjava.strings;//: strings/Splitting.java import java.util.*; public class Splitting { public static String knights = "Then, when you have found the shrubbery, you must " + "cut down the mightiest tree in the forest... " + "with... a herring!"; public static void split(String regex) { System.out.println( Arrays.toString(knights.split(regex))); } public static void main(String[] args) { split(" "); // Doesn't have to contain regex chars split("\\W+"); // Non-word characters split("n\\W+"); // 'n' followed by non-word characters } } /* Output: [Then,, when, you, have, found, the, shrubbery,, you, must, cut, down, the, mightiest, tree, in, the, forest..., with..., a, herring!] [Then, when, you, have, found, the, shrubbery, you, must, cut, down, the, mightiest, tree, in, the, forest, with, a, herring] [The, whe, you have found the shrubbery, you must cut dow, the mightiest tree i, the forest... with... a herring!] *///:~
apache-2.0
mcxiaoke/python-labs
archives/fanfou/backup.py
2562
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: mcxiaoke # @Date: 2015-08-06 07:23:50 import fanfou import utils import time import sys from db import DB DEFAULT_COUNT = 60 def fetch_newer_statuses(api, uid): # first ,check new statuses db = DB('%s.db' % uid) head_status = db.get_latest_status() if head_status: while(True): head_status = db.get_latest_status() since_id = head_status['sid'] if head_status else None print 'fetch timeline, since_id: %s' % since_id timeline = api.get_user_timeline( uid, count=DEFAULT_COUNT, since_id=since_id) if not timeline: break print len(timeline) db.bulk_insert_status(timeline) time.sleep(2) if len(timeline) < DEFAULT_COUNT: break db.print_status() def fetch_older_statuses(api, uid): # then, check older status db = DB('%s.db' % uid) while(True): tail_status = db.get_oldest_status() max_id = tail_status['sid'] if tail_status else None print 'fetch timeline, max_id: %s' % max_id timeline = api.get_user_timeline( uid, count=DEFAULT_COUNT, max_id=max_id) if not timeline: break print len(timeline) db.bulk_insert_status(timeline) time.sleep(2) if len(timeline) < DEFAULT_COUNT: break db.print_status() def main(username, password, userid=None): api = fanfou.FanfouClient() token = utils.load_account_info(username) if token: print 'load account info: %s for %s' % ( token, username) api.set_oauth_token(token) else: print "no saved account info, get token from server..." if api.is_verified(): token = api.oauth_token user = api.user else: token = api.login(username, password) user = api.user print 'save new account_info: {0}'.format(token) utils.save_account_info(username, token) target_id = userid if userid else user['id'] target_user = api.get_user(target_id) if not target_user: print "target user: %s not exists" % target_id return print "prepare backup data for user: %s" % target_id # first ,check new statuses fetch_newer_statuses(api, target_id) # then, check older status fetch_older_statuses(api, target_id) if __name__ == '__main__': args = utils.parse_args() main(args.username, args.password, args.userid)
apache-2.0
azusa/hatunatu
hatunatu/src/main/java/jp/fieldnotes/hatunatu/dao/handler/BasicReturningRowsBatchHandler.java
4894
/* * Copyright 2004-2015 the Seasar Foundation and the Others. * * 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 jp.fieldnotes.hatunatu.dao.handler; import jp.fieldnotes.hatunatu.dao.ReturningRowsBatchHandler; import jp.fieldnotes.hatunatu.dao.StatementFactory; import jp.fieldnotes.hatunatu.dao.jdbc.QueryObject; import jp.fieldnotes.hatunatu.util.sql.PreparedStatementUtil; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; public class BasicReturningRowsBatchHandler extends BasicHandler implements ReturningRowsBatchHandler { private static final int[] EMPTY_ARRAY = new int[0]; private int batchSize = -1; /** * {@link BasicReturningRowsBatchHandler}を作成します。 */ public BasicReturningRowsBatchHandler() { } /** * {@link BasicReturningRowsBatchHandler}を作成します。 * * @param dataSource * データソース */ public BasicReturningRowsBatchHandler(final DataSource dataSource ) { this(dataSource, -1); } /** * {@link BasicReturningRowsBatchHandler}を作成します。 * * @param dataSource * データソース * @param batchSize * バッチ数 */ public BasicReturningRowsBatchHandler(final DataSource dataSource, final int batchSize) { this(dataSource, batchSize, StatementFactory.INSTANCE); } /** * {@link BasicReturningRowsBatchHandler}を作成します。 * * @param dataSource * データソース * @param batchSize * バッチ数 * @param statementFactory * ステートメントファクトリ */ public BasicReturningRowsBatchHandler(final DataSource dataSource, final int batchSize, final StatementFactory statementFactory) { setDataSource(dataSource); setBatchSize(batchSize); setStatementFactory(statementFactory); } /** * バッチ数を返します。 * * @return バッチ数 */ public int getBatchSize() { return batchSize; } /** * バッチ数を設定します。 * * @param batchSize * バッチ数 */ public void setBatchSize(final int batchSize) { this.batchSize = batchSize; } @Override public int[] execute(final QueryObject queryObject, final List<Object[]> list) throws Exception { if (list.size() == 0) { return EMPTY_ARRAY; } final Object[] args = list.get(0); return execute(queryObject, list, getArgTypes(args)); } protected int[] execute(final QueryObject queryObject, final List<Object[]> list, final Class[] argTypes) throws SQLException { try (Connection connection = getConnection()) { return execute(connection, queryObject, list, argTypes); } } /** * 更新を実行します。 * * @param connection * コネクション * @param list * バッチ対象のデータ * @param argTypes * 引数の型のリスト * @return バッチ内のコマンドごとに 1 つの要素が格納されている更新カウントの配列。 * 配列の要素はコマンドがバッチに追加された順序で並べられる */ protected int[] execute(final Connection connection, final QueryObject queryObject, final List<Object[]> list, final Class[] argTypes) throws SQLException { final int size = batchSize > 0 ? Math.min(batchSize, list.size()) : list.size(); if (size == 0) { return EMPTY_ARRAY; } try (PreparedStatement ps = prepareStatement(connection, queryObject)) { for (int i = 0; i < list.size(); ++i) { final Object[] args = list.get(i); logSql(queryObject); bindArgs(ps, args, argTypes); PreparedStatementUtil.addBatch(ps); } return PreparedStatementUtil.executeBatch(ps); } } }
apache-2.0
davidzchen/bazel
src/main/java/net/starlark/java/annot/processor/StarlarkMethodProcessor.java
21482
// Copyright 2018 The Bazel 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. package net.starlark.java.annot.processor; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.SetMultimap; import com.google.errorprone.annotations.FormatMethod; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.MirroredTypeException; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.WildcardType; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import net.starlark.java.annot.Param; import net.starlark.java.annot.ParamType; import net.starlark.java.annot.StarlarkBuiltin; import net.starlark.java.annot.StarlarkMethod; /** * Annotation processor for {@link StarlarkMethod}. See that class for requirements. * * <p>These properties can be relied upon at runtime without additional checks. */ @SupportedAnnotationTypes({ "net.starlark.java.annot.StarlarkMethod", "net.starlark.java.annot.StarlarkBuiltin" }) public class StarlarkMethodProcessor extends AbstractProcessor { private Types types; private Elements elements; private Messager messager; // A set containing a TypeElement for each class with a StarlarkMethod.selfCall annotation. private Set<Element> classesWithSelfcall; // A multimap where keys are class element, and values are the callable method names identified in // that class (where "method name" is StarlarkMethod.name). private SetMultimap<Element, String> processedClassMethods; @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } @Override public synchronized void init(ProcessingEnvironment env) { super.init(env); this.types = env.getTypeUtils(); this.elements = env.getElementUtils(); this.messager = env.getMessager(); this.classesWithSelfcall = new HashSet<>(); this.processedClassMethods = LinkedHashMultimap.create(); } private TypeMirror getType(String canonicalName) { return elements.getTypeElement(canonicalName).asType(); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { TypeMirror stringType = getType("java.lang.String"); TypeMirror integerType = getType("java.lang.Integer"); TypeMirror booleanType = getType("java.lang.Boolean"); TypeMirror listType = getType("java.util.List"); TypeMirror mapType = getType("java.util.Map"); TypeMirror starlarkValueType = getType("net.starlark.java.eval.StarlarkValue"); // Ensure StarlarkBuiltin-annotated classes implement StarlarkValue. for (Element cls : roundEnv.getElementsAnnotatedWith(StarlarkBuiltin.class)) { if (!types.isAssignable(cls.asType(), starlarkValueType)) { errorf( cls, "class %s has StarlarkBuiltin annotation but does not implement StarlarkValue", cls.getSimpleName()); } } for (Element element : roundEnv.getElementsAnnotatedWith(StarlarkMethod.class)) { // Only methods are annotated with StarlarkMethod. // This is ensured by the @Target(ElementType.METHOD) annotation. ExecutableElement method = (ExecutableElement) element; if (!method.getModifiers().contains(Modifier.PUBLIC)) { errorf(method, "StarlarkMethod-annotated methods must be public."); } if (method.getModifiers().contains(Modifier.STATIC)) { errorf(method, "StarlarkMethod-annotated methods cannot be static."); } // Check the annotation itself. StarlarkMethod annot = method.getAnnotation(StarlarkMethod.class); if (annot.name().isEmpty()) { errorf(method, "StarlarkMethod.name must be non-empty."); } Element cls = method.getEnclosingElement(); if (!processedClassMethods.put(cls, annot.name())) { errorf(method, "Containing class defines more than one method named '%s'.", annot.name()); } if (annot.documented() && annot.doc().isEmpty()) { errorf(method, "The 'doc' string must be non-empty if 'documented' is true."); } if (annot.structField()) { checkStructFieldAnnotation(method, annot); } else if (annot.useStarlarkSemantics()) { errorf( method, "a StarlarkMethod-annotated method with structField=false may not also specify" + " useStarlarkSemantics. (Instead, set useStarlarkThread and call" + " getSemantics().)"); } if (annot.selfCall() && !classesWithSelfcall.add(cls)) { errorf(method, "Containing class has more than one selfCall method defined."); } boolean hasFlag = false; if (!annot.enableOnlyWithFlag().isEmpty()) { if (!hasPlusMinusPrefix(annot.enableOnlyWithFlag())) { errorf(method, "enableOnlyWithFlag name must have a + or - prefix"); } hasFlag = true; } if (!annot.disableWithFlag().isEmpty()) { if (!hasPlusMinusPrefix(annot.disableWithFlag())) { errorf(method, "disableWithFlag name must have a + or - prefix"); } if (hasFlag) { errorf( method, "Only one of StarlarkMethod.enableOnlyWithFlag and StarlarkMethod.disableWithFlag" + " may be specified."); } hasFlag = true; } checkParameters(method, annot); // Verify that result type, if final, might satisfy Starlark.fromJava. // (If the type is non-final we can't prove that all subclasses are invalid.) TypeMirror ret = method.getReturnType(); if (ret.getKind() == TypeKind.DECLARED) { DeclaredType obj = (DeclaredType) ret; if (obj.asElement().getModifiers().contains(Modifier.FINAL) && !types.isSameType(ret, stringType) && !types.isSameType(ret, integerType) && !types.isSameType(ret, booleanType) && !types.isAssignable(obj, starlarkValueType) && !types.isAssignable(obj, listType) && !types.isAssignable(obj, mapType)) { errorf( method, "StarlarkMethod-annotated method %s returns %s, which has no legal Starlark values" + " (see Starlark.fromJava)", method.getSimpleName(), ret); } } } // Returning false allows downstream processors to work on the same annotations return false; } // TODO(adonovan): obviate these checks by separating field/method interfaces. private void checkStructFieldAnnotation(ExecutableElement method, StarlarkMethod annot) { // useStructField is incompatible with special thread-related parameters, // because unlike a method, which is actively called within a thread, // a field is a passive part of a data structure that may be accessed // from Java threads that don't have anything to do with Starlark threads. // However, the StarlarkSemantics is available even to fields, // because it is a required parameter for all attribute-selection // operations x.f. // // Not having a thread forces implementations to assume Mutability=null, // which is not quite right. Perhaps one day we can abolish Mutability // in favor of a tracing approach as in go.starlark.net. if (annot.useStarlarkThread()) { errorf( method, "a StarlarkMethod-annotated method with structField=true may not also specify" + " useStarlarkThread"); } if (!annot.extraPositionals().name().isEmpty()) { errorf( method, "a StarlarkMethod-annotated method with structField=true may not also specify" + " extraPositionals"); } if (!annot.extraKeywords().name().isEmpty()) { errorf( method, "a StarlarkMethod-annotated method with structField=true may not also specify" + " extraKeywords"); } if (annot.selfCall()) { errorf( method, "a StarlarkMethod-annotated method with structField=true may not also specify" + " selfCall=true"); } int nparams = annot.parameters().length; if (nparams > 0) { errorf( method, "method %s is annotated structField=true but also has %d Param annotations", method.getSimpleName(), nparams); } } private void checkParameters(ExecutableElement method, StarlarkMethod annot) { List<? extends VariableElement> params = method.getParameters(); TypeMirror objectType = getType("java.lang.Object"); boolean allowPositionalNext = true; boolean allowPositionalOnlyNext = true; boolean allowNonDefaultPositionalNext = true; // Check @Param annotations match parameters. Param[] paramAnnots = annot.parameters(); for (int i = 0; i < paramAnnots.length; i++) { Param paramAnnot = paramAnnots[i]; if (i >= params.size()) { errorf( method, "method %s has %d Param annotations but only %d parameters", method.getSimpleName(), paramAnnots.length, params.size()); return; } VariableElement param = params.get(i); checkParameter(param, paramAnnot, objectType); // Check parameter ordering. if (paramAnnot.positional()) { if (!allowPositionalNext) { errorf( param, "Positional parameter '%s' is specified after one or more non-positional parameters", paramAnnot.name()); } if (!paramAnnot.named() && !allowPositionalOnlyNext) { errorf( param, "Positional-only parameter '%s' is specified after one or more named parameters", paramAnnot.name()); } if (paramAnnot.defaultValue().isEmpty()) { // There is no default value. if (!allowNonDefaultPositionalNext) { errorf( param, "Positional parameter '%s' has no default value but is specified after one " + "or more positional parameters with default values", paramAnnot.name()); } } else { // There is a default value. // No positional parameters without a default value can come after this parameter. allowNonDefaultPositionalNext = false; } } else { // Not positional. // No positional parameters can come after this parameter. allowPositionalNext = false; if (!paramAnnot.named()) { errorf(param, "Parameter '%s' must be either positional or named", paramAnnot.name()); } } if (paramAnnot.named()) { // No positional-only parameters can come after this parameter. allowPositionalOnlyNext = false; } } checkSpecialParams(method, annot); } // Checks consistency of a single parameter with its Param annotation. private void checkParameter(Element param, Param paramAnnot, TypeMirror objectType) { TypeMirror paramType = param.asType(); // type of the Java method parameter // A "noneable" parameter variable must accept the value None. // A parameter whose default is None must be noneable. if (paramAnnot.noneable()) { if (!types.isSameType(paramType, objectType)) { errorf( param, "Expected type 'Object' but got type '%s' for noneable parameter '%s'. The argument" + " for a noneable parameter may be None, so the java parameter must be" + " compatible with the type of None as well as possible non-None values.", paramType, param.getSimpleName()); } } else if (paramAnnot.defaultValue().equals("None")) { errorf( param, "Parameter '%s' has 'None' default value but is not noneable. (If this is intended" + " as a mandatory parameter, leave the defaultValue field empty)", paramAnnot.name()); } // Check param.type. if (!types.isSameType(getParamType(paramAnnot), objectType)) { // Reject Param.type if not assignable to parameter variable. TypeMirror t = getParamType(paramAnnot); if (!types.isAssignable(t, types.erasure(paramType))) { errorf( param, "annotated type %s of parameter '%s' is not assignable to variable of type %s", t, paramAnnot.name(), paramType); } // Reject the combination of Param.type and Param.allowed_types. if (paramAnnot.allowedTypes().length > 0) { errorf( param, "Parameter '%s' has both 'type' and 'allowedTypes' specified. Only one may be" + " specified.", paramAnnot.name()); } } // Reject an Param.allowed_type if not assignable to parameter variable. for (ParamType paramTypeAnnot : paramAnnot.allowedTypes()) { TypeMirror t = getParamTypeType(paramTypeAnnot); if (!types.isAssignable(t, types.erasure(paramType))) { errorf( param, "annotated allowed_type %s of parameter '%s' is not assignable to variable of type %s", t, paramAnnot.name(), paramType); } } // Reject generic types C<T> other than C<?>, // since reflective calls check only the toplevel class. if (paramType instanceof DeclaredType) { DeclaredType declaredType = (DeclaredType) paramType; for (TypeMirror typeArg : declaredType.getTypeArguments()) { if (!(typeArg instanceof WildcardType)) { errorf( param, "parameter '%s' has generic type %s, but only wildcard type parameters are" + " allowed. Type inference in a Starlark-exposed method is unsafe. See" + " StarlarkMethod class documentation for details.", param.getSimpleName(), paramType); } } } // Check sense of flag-controlled parameters. boolean hasFlag = false; if (!paramAnnot.enableOnlyWithFlag().isEmpty()) { if (!hasPlusMinusPrefix(paramAnnot.enableOnlyWithFlag())) { errorf(param, "enableOnlyWithFlag name must have a + or - prefix"); } hasFlag = true; } if (!paramAnnot.disableWithFlag().isEmpty()) { if (!hasPlusMinusPrefix(paramAnnot.disableWithFlag())) { errorf(param, "disableWithFlag name must have a + or - prefix"); } if (hasFlag) { errorf( param, "Parameter '%s' has enableOnlyWithFlag and disableWithFlag set. At most one may be set", paramAnnot.name()); } hasFlag = true; } if (hasFlag == paramAnnot.valueWhenDisabled().isEmpty()) { errorf( param, hasFlag ? "Parameter '%s' may be disabled by semantic flag, thus valueWhenDisabled must be" + " set" : "Parameter '%s' has valueWhenDisabled set, but is always enabled", paramAnnot.name()); } } private static boolean hasPlusMinusPrefix(String s) { return s.charAt(0) == '-' || s.charAt(0) == '+'; } // Returns the logical type of Param.type. private static TypeMirror getParamType(Param param) { // See explanation of this hack at Element.getAnnotation // and at https://stackoverflow.com/a/10167558. try { param.type(); throw new IllegalStateException("unreachable"); } catch (MirroredTypeException ex) { return ex.getTypeMirror(); } } // Returns the logical type of ParamType.type. private static TypeMirror getParamTypeType(ParamType paramType) { // See explanation of this hack at Element.getAnnotation // and at https://stackoverflow.com/a/10167558. try { paramType.type(); throw new IllegalStateException("unreachable"); } catch (MirroredTypeException ex) { return ex.getTypeMirror(); } } private void checkSpecialParams(ExecutableElement method, StarlarkMethod annot) { if (!annot.extraPositionals().enableOnlyWithFlag().isEmpty() || !annot.extraPositionals().disableWithFlag().isEmpty()) { errorf(method, "The extraPositionals parameter may not be toggled by semantic flag"); } if (!annot.extraKeywords().enableOnlyWithFlag().isEmpty() || !annot.extraKeywords().disableWithFlag().isEmpty()) { errorf(method, "The extraKeywords parameter may not be toggled by semantic flag"); } List<? extends VariableElement> params = method.getParameters(); int index = annot.parameters().length; // insufficient parameters? int special = numExpectedSpecialParams(annot); if (index + special > params.size()) { errorf( method, "method %s is annotated with %d Params plus %d special parameters, but has only %d" + " parameter variables", method.getSimpleName(), index, special, params.size()); return; // not safe to proceed } if (!annot.extraPositionals().name().isEmpty()) { VariableElement param = params.get(index++); // Allow any supertype of Tuple<Object>. TypeMirror tupleOfObjectType = types.getDeclaredType( elements.getTypeElement("net.starlark.java.eval.Tuple"), getType("java.lang.Object")); if (!types.isAssignable(tupleOfObjectType, param.asType())) { errorf( param, "extraPositionals special parameter '%s' has type %s, to which Tuple<Object> cannot be" + " assigned", param.getSimpleName(), param.asType()); } } if (!annot.extraKeywords().name().isEmpty()) { VariableElement param = params.get(index++); // Allow any supertype of Dict<String, Object>. TypeMirror dictOfStringObjectType = types.getDeclaredType( elements.getTypeElement("net.starlark.java.eval.Dict"), getType("java.lang.String"), getType("java.lang.Object")); if (!types.isAssignable(dictOfStringObjectType, param.asType())) { errorf( param, "extraKeywords special parameter '%s' has type %s, to which Dict<String, Object>" + " cannot be assigned", param.getSimpleName(), param.asType()); } } if (annot.useStarlarkThread()) { VariableElement param = params.get(index++); TypeMirror threadType = getType("net.starlark.java.eval.StarlarkThread"); if (!types.isSameType(threadType, param.asType())) { errorf( param, "for useStarlarkThread special parameter '%s', got type %s, want StarlarkThread", param.getSimpleName(), param.asType()); } } if (annot.useStarlarkSemantics()) { VariableElement param = params.get(index++); TypeMirror semanticsType = getType("net.starlark.java.eval.StarlarkSemantics"); if (!types.isSameType(semanticsType, param.asType())) { errorf( param, "for useStarlarkSemantics special parameter '%s', got type %s, want StarlarkSemantics", param.getSimpleName(), param.asType()); } } // surplus parameters? if (index < params.size()) { errorf( params.get(index), // first surplus parameter "method %s is annotated with %d Params plus %d special parameters, yet has %d parameter" + " variables", method.getSimpleName(), annot.parameters().length, special, params.size()); } } private static int numExpectedSpecialParams(StarlarkMethod annot) { int n = 0; n += annot.extraPositionals().name().isEmpty() ? 0 : 1; n += annot.extraKeywords().name().isEmpty() ? 0 : 1; n += annot.useStarlarkThread() ? 1 : 0; n += annot.useStarlarkSemantics() ? 1 : 0; return n; } // Reports a (formatted) error and fails the compilation. @FormatMethod private void errorf(Element e, String format, Object... args) { messager.printMessage(Diagnostic.Kind.ERROR, String.format(format, args), e); } }
apache-2.0
force1267/minirush
js/graphic.js
1356
module.exports = ((objects) => { var graphic = {}; graphic.FPS = 0; graphic.objects = objects ? objects : []; var cvs = graphic.cvs = document.getElementById("cvs"); var ctx = graphic.ctx = cvs.getContext("2d"); graphic.sprite = ((obj) => { var spr = obj.sprite = {}; spr.object = obj; spr.draw = (() => { ctx.fillRect(obj.x, obj.y, obj.width, obj.height); }); spr.visible = true; return spr; }); var PAUSE = false; var loop = (() => { ctx.clearRect(0, 0, cvs.width, cvs.height); for (i in graphic.objects) { if (graphic.objects[i]) if (graphic.objects[i].sprite) if (graphic.objects[i].sprite.visible) graphic.objects[i].sprite.draw(); } if (!PAUSE) { if (window.requestAnimationFrame) { window.requestAnimationFrame(loop); } else { setTimeout(loop, 1000 / graphic.FPS); } } }); graphic.start = (() => { PAUSE = false; loop(); }); graphic.stop = (() => { PAUSE = true; }); return graphic; //exports.FPS //exports.objects //exports.cvs //exports.ctx //exports.sprite //exports.start //exports.stop });
apache-2.0
WIZARD-CXY/cf-cassandra-broker
spec/models/service_spec.rb
5093
require 'spec_helper' describe Service do describe '.build' do before do allow(Plan).to receive(:build) end it 'sets fields correct' do service = Service.build( 'id' => 'my-id', 'name' => 'my-name', 'description' => 'my description', 'tags' => ['tagA', 'tagB'], 'metadata' => { 'stuff' => 'goes here' }, 'plans' => [] ) expect(service.id).to eq('my-id') expect(service.name).to eq('my-name') expect(service.description).to eq('my description') expect(service.tags).to eq(['tagA', 'tagB']) expect(service.metadata).to eq({ 'stuff' => 'goes here' }) end it 'is bindable' do service = Service.build( 'id' => 'my-id', 'name' => 'my-name', 'description' => 'my description', 'tags' => ['tagA', 'tagB'], 'metadata' => { 'stuff' => 'goes here' }, 'plans' => [] ) expect(service).to be_bindable end it 'builds plans and sets the plans field' do plan_attrs = [double(:plan_attr1), double(:plan_attr2)] plan1 = double(:plan1) plan2 = double(:plan2) allow(Plan).to receive(:build).with(plan_attrs[0]).and_return(plan1) allow(Plan).to receive(:build).with(plan_attrs[1]).and_return(plan2) service = Service.build( 'plans' => plan_attrs, 'id' => 'my-id', 'name' => 'my-name', 'description' => 'my description', 'tags' => ['tagA', 'tagB'], 'metadata' => { 'stuff' => 'goes here' }, ) expect(service.plans).to eq([plan1, plan2]) end context 'when the metadata attr is missing' do let(:service) do Service.build( 'id' => 'my-id', 'name' => 'my-name', 'description' => 'my description', 'tags' => ['tagA', 'tagB'], 'plans' => [] ) end it 'sets the field to nil' do expect(service.metadata).to be_nil end end context 'when the tags attr is missing' do let(:service) do Service.build( 'id' => 'my-id', 'name' => 'my-name', 'description' => 'my description', 'metadata' => { 'stuff' => 'goes here' }, 'plans' => [] ) end it 'sets the field to an empty array' do expect(service.tags).to eq([]) end end end describe '#to_hash' do it 'contains the right values' do service = Service.new( 'id' => 'my-id', 'name' => 'my-name', 'description' => 'my-description', 'tags' => ['tagA', 'tagB'], 'metadata' => { 'meta' => 'data' }, 'plans' => [] ) expect(service.to_hash.fetch('id')).to eq('my-id') expect(service.to_hash.fetch('name')).to eq('my-name') expect(service.to_hash.fetch('bindable')).to eq(true) expect(service.to_hash.fetch('description')).to eq('my-description') expect(service.to_hash.fetch('tags')).to eq(['tagA', 'tagB']) expect(service.to_hash.fetch('metadata')).to eq({ 'meta' => 'data' }) expect(service.to_hash).to have_key('plans') end it 'includes the #to_hash for each plan' do plan_1 = double(:plan_1) plan_2 = double(:plan_2) plan_1_to_hash = double(:plan_1_to_hash) plan_2_to_hash = double(:plan_2_to_hash) expect(plan_1).to receive(:to_hash).and_return(plan_1_to_hash) expect(plan_2).to receive(:to_hash).and_return(plan_2_to_hash) service = Service.new( 'plans' => [plan_1, plan_2], 'id' => 'my-id', 'name' => 'my-name', 'description' => 'my-description', 'tags' => ['tagA', 'tagB'], 'metadata' => { 'meta' => 'data' }, ) expect(service.to_hash.fetch('plans')).to eq([plan_1_to_hash, plan_2_to_hash]) end context 'when there is no plans key' do let(:service) do Service.build( 'id' => 'my-id', 'name' => 'my-name', 'description' => 'my-description', 'tags' => ['tagA', 'tagB'], 'metadata' => { 'meta' => 'data' }, ) end it 'has an empty list of plans' do expect(service.to_hash.fetch('plans')).to eq([]) end end # There might be a dangling "plans:" in the yaml, which assigns a nil value context 'when the plans key is nil' do let(:service) do Service.build( 'id' => 'my-id', 'name' => 'my-name', 'description' => 'my-description', 'tags' => ['tagA', 'tagB'], 'metadata' => { 'meta' => 'data' }, 'plans' => nil, ) end it 'has an empty list of plans' do expect(service.to_hash.fetch('plans')).to eq([]) end end end end
apache-2.0
SergiusIW/ton
src/main/java/com/matthewmichelotti/ton/internal/parser/nodes/ParentNode.java
1266
/* * Copyright 2015-2016 Matthew D. Michelotti * * 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.matthewmichelotti.ton.internal.parser.nodes; import com.matthewmichelotti.ton.FileLoc; import com.matthewmichelotti.ton.internal.NodeType; public abstract class ParentNode extends Node { private FileLoc fullFileLoc; private boolean started = false; protected ParentNode(NodeType type, FileLoc loc) { super(type, loc); } public void setEndFileLoc(FileLoc loc) { if(fullFileLoc != null) throw new IllegalStateException(); fullFileLoc = new FileLoc(loc(), loc); } public FileLoc getFullLoc() { return fullFileLoc; } public void markStarted() { started = true; } public boolean getStarted() { return started; } }
apache-2.0
xfmysql/itouchstudio
index/Tpl/encodei/Public/static/hm.js
21317
(function(){var h={},mt={},c={id:"e23f8e2a52042baf776f12680f3b7cad",dm:["zmingcx.com"],js:"tongji.baidu.com/hm-web/js/",etrk:[],icon:'',ctrk:false,align:-1,nv:-1,vdur:1800000,age:31536000000,rec:1,rp:[],trust:0,vcard:0,qiao:0,lxb:0,conv:0,comm:0,apps:''};var p=!0,q=null,r=!1;mt.i={};mt.i.Ia=/msie (\d+\.\d+)/i.test(navigator.userAgent);mt.i.cookieEnabled=navigator.cookieEnabled;mt.i.javaEnabled=navigator.javaEnabled();mt.i.language=navigator.language||navigator.browserLanguage||navigator.systemLanguage||navigator.userLanguage||"";mt.i.ra=(window.screen.width||0)+"x"+(window.screen.height||0);mt.i.colorDepth=window.screen.colorDepth||0;mt.cookie={}; mt.cookie.set=function(a,b,e){var d;e.F&&(d=new Date,d.setTime(d.getTime()+e.F));document.cookie=a+"="+b+(e.domain?"; domain="+e.domain:"")+(e.path?"; path="+e.path:"")+(d?"; expires="+d.toGMTString():"")+(e.Ma?"; secure":"")};mt.cookie.get=function(a){return(a=RegExp("(^| )"+a+"=([^;]*)(;|$)").exec(document.cookie))?a[2]:q};mt.p={};mt.p.da=function(a){return document.getElementById(a)};mt.p.Ea=function(a,b){for(b=b.toUpperCase();(a=a.parentNode)&&1==a.nodeType;)if(a.tagName==b)return a;return q}; (mt.p.T=function(){function a(){if(!a.z){a.z=p;for(var b=0,e=d.length;b<e;b++)d[b]()}}function b(){try{document.documentElement.doScroll("left")}catch(d){setTimeout(b,1);return}a()}var e=r,d=[],k;document.addEventListener?k=function(){document.removeEventListener("DOMContentLoaded",k,r);a()}:document.attachEvent&&(k=function(){"complete"===document.readyState&&(document.detachEvent("onreadystatechange",k),a())});(function(){if(!e)if(e=p,"complete"===document.readyState)a.z=p;else if(document.addEventListener)document.addEventListener("DOMContentLoaded", k,r),window.addEventListener("load",a,r);else if(document.attachEvent){document.attachEvent("onreadystatechange",k);window.attachEvent("onload",a);var d=r;try{d=window.frameElement==q}catch(n){}document.documentElement.doScroll&&d&&b()}})();return function(b){a.z?b():d.push(b)}}()).z=r;mt.event={};mt.event.e=function(a,b,e){a.attachEvent?a.attachEvent("on"+b,function(b){e.call(a,b)}):a.addEventListener&&a.addEventListener(b,e,r)}; mt.event.preventDefault=function(a){a.preventDefault?a.preventDefault():a.returnValue=r};mt.l={};mt.l.parse=function(){return(new Function('return (" + source + ")'))()}; mt.l.stringify=function(){function a(a){/["\\\x00-\x1f]/.test(a)&&(a=a.replace(/["\\\x00-\x1f]/g,function(a){var b=e[a];if(b)return b;b=a.charCodeAt();return"\\u00"+Math.floor(b/16).toString(16)+(b%16).toString(16)}));return'"'+a+'"'}function b(a){return 10>a?"0"+a:a}var e={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};return function(d){switch(typeof d){case "undefined":return"undefined";case "number":return isFinite(d)?String(d):"null";case "string":return a(d);case "boolean":return String(d); default:if(d===q)return"null";if(d instanceof Array){var e=["["],l=d.length,n,f,g;for(f=0;f<l;f++)switch(g=d[f],typeof g){case "undefined":case "function":case "unknown":break;default:n&&e.push(","),e.push(mt.l.stringify(g)),n=1}e.push("]");return e.join("")}if(d instanceof Date)return'"'+d.getFullYear()+"-"+b(d.getMonth()+1)+"-"+b(d.getDate())+"T"+b(d.getHours())+":"+b(d.getMinutes())+":"+b(d.getSeconds())+'"';n=["{"];f=mt.l.stringify;for(l in d)if(Object.prototype.hasOwnProperty.call(d,l))switch(g= d[l],typeof g){case "undefined":case "unknown":case "function":break;default:e&&n.push(","),e=1,n.push(f(l)+":"+f(g))}n.push("}");return n.join("")}}}();mt.lang={};mt.lang.d=function(a,b){return"[object "+b+"]"==={}.toString.call(a)};mt.lang.Ja=function(a){return mt.lang.d(a,"Number")&&isFinite(a)};mt.lang.La=function(a){return mt.lang.d(a,"String")};mt.localStorage={}; mt.localStorage.C=function(){if(!mt.localStorage.f)try{mt.localStorage.f=document.createElement("input"),mt.localStorage.f.type="hidden",mt.localStorage.f.style.display="none",mt.localStorage.f.addBehavior("#default#userData"),document.getElementsByTagName("head")[0].appendChild(mt.localStorage.f)}catch(a){return r}return p}; mt.localStorage.set=function(a,b,e){var d=new Date;d.setTime(d.getTime()+e||31536E6);try{window.localStorage?(b=d.getTime()+"|"+b,window.localStorage.setItem(a,b)):mt.localStorage.C()&&(mt.localStorage.f.expires=d.toUTCString(),mt.localStorage.f.load(document.location.hostname),mt.localStorage.f.setAttribute(a,b),mt.localStorage.f.save(document.location.hostname))}catch(k){}}; mt.localStorage.get=function(a){if(window.localStorage){if(a=window.localStorage.getItem(a)){var b=a.indexOf("|"),e=a.substring(0,b)-0;if(e&&e>(new Date).getTime())return a.substring(b+1)}}else if(mt.localStorage.C())try{return mt.localStorage.f.load(document.location.hostname),mt.localStorage.f.getAttribute(a)}catch(d){}return q}; mt.localStorage.remove=function(a){if(window.localStorage)window.localStorage.removeItem(a);else if(mt.localStorage.C())try{mt.localStorage.f.load(document.location.hostname),mt.localStorage.f.removeAttribute(a),mt.localStorage.f.save(document.location.hostname)}catch(b){}};mt.sessionStorage={};mt.sessionStorage.set=function(a,b){if(window.sessionStorage)try{window.sessionStorage.setItem(a,b)}catch(e){}}; mt.sessionStorage.get=function(a){return window.sessionStorage?window.sessionStorage.getItem(a):q};mt.sessionStorage.remove=function(a){window.sessionStorage&&window.sessionStorage.removeItem(a)};mt.U={};mt.U.log=function(a,b){var e=new Image,d="mini_tangram_log_"+Math.floor(2147483648*Math.random()).toString(36);window[d]=e;e.onload=e.onerror=e.onabort=function(){e.onload=e.onerror=e.onabort=q;e=window[d]=q;b&&b(a)};e.src=a};mt.L={}; mt.L.ia=function(){var a="";if(navigator.plugins&&navigator.mimeTypes.length){var b=navigator.plugins["Shockwave Flash"];b&&b.description&&(a=b.description.replace(/^.*\s+(\S+)\s+\S+$/,"$1"))}else if(window.ActiveXObject)try{if(b=new ActiveXObject("ShockwaveFlash.ShockwaveFlash"))(a=b.GetVariable("$version"))&&(a=a.replace(/^.*\s+(\d+),(\d+).*$/,"$1.$2"))}catch(e){}return a}; mt.L.Ca=function(a,b,e,d,k){return'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" id="'+a+'" width="'+e+'" height="'+d+'"><param name="movie" value="'+b+'" /><param name="flashvars" value="'+(k||"")+'" /><param name="allowscriptaccess" value="always" /><embed type="application/x-shockwave-flash" name="'+a+'" width="'+e+'" height="'+d+'" src="'+b+'" flashvars="'+(k||"")+'" allowscriptaccess="always" /></object>'};mt.url={}; mt.url.h=function(a,b){var e=a.match(RegExp("(^|&|\\?|#)("+b+")=([^&#]*)(&|$|#)",""));return e?e[3]:q};mt.url.Ga=function(a){return(a=a.match(/^(https?:)\/\//))?a[1]:q};mt.url.fa=function(a){return(a=a.match(/^(https?:\/\/)?([^\/\?#]*)/))?a[2].replace(/.*@/,""):q};mt.url.O=function(a){return(a=mt.url.fa(a))?a.replace(/:\d+$/,""):a};mt.url.Fa=function(a){return(a=a.match(/^(https?:\/\/)?[^\/]*(.*)/))?a[2].replace(/[\?#].*/,"").replace(/^$/,"/"):q}; h.m={Ha:"http://tongji.baidu.com/hm-web/welcome/ico",S:"log.hm.baidu.com/hm.gif",X:"baidu.com",ma:"hmmd",na:"hmpl",la:"hmkw",ka:"hmci",oa:"hmsr",o:0,j:Math.round(+new Date/1E3),protocol:"https:"==document.location.protocol?"https:":"http:",Ka:0,za:6E5,Aa:10,Ba:1024,ya:1,A:2147483647,V:"cc cf ci ck cl cm cp cw ds ep et fl ja ln lo lt nv rnd si st su v cv lv api tt u".split(" ")}; (function(){var a={k:{},e:function(a,e){this.k[a]=this.k[a]||[];this.k[a].push(e)},s:function(a,e){this.k[a]=this.k[a]||[];for(var d=this.k[a].length,k=0;k<d;k++)this.k[a][k](e)}};return h.q=a})(); (function(){function a(a,d){var k=document.createElement("script");k.charset="utf-8";b.d(d,"Function")&&(k.readyState?k.onreadystatechange=function(){if("loaded"===k.readyState||"complete"===k.readyState)k.onreadystatechange=q,d()}:k.onload=function(){d()});k.src=a;var l=document.getElementsByTagName("script")[0];l.parentNode.insertBefore(k,l)}var b=mt.lang;return h.load=a})(); (function(){function a(){var a="";h.b.a.nv?(a=encodeURIComponent(document.referrer),window.sessionStorage?e.set("Hm_from_"+c.id,a):b.set("Hm_from_"+c.id,a,864E5)):a=(window.sessionStorage?e.get("Hm_from_"+c.id):b.get("Hm_from_"+c.id))||"";return a}var b=mt.localStorage,e=mt.sessionStorage;return h.M=a})(); (function(){var a=mt.p,b=h.m,e=h.load,d=h.M;h.q.e("pv-b",function(){c.rec&&a.T(function(){for(var k=0,l=c.rp.length;k<l;k++){var n=c.rp[k][0],f=c.rp[k][1],g=a.da("hm_t_"+n);if(f&&!(2==f&&!g||g&&""!==g.innerHTML))g="",g=Math.round(Math.random()*b.A),g=4==f?"http://crs.baidu.com/hl.js?"+["siteId="+c.id,"planId="+n,"rnd="+g].join("&"):"http://crs.baidu.com/t.js?"+["siteId="+c.id,"planId="+n,"from="+d(),"referer="+encodeURIComponent(document.referrer),"title="+encodeURIComponent(document.title),"rnd="+ g].join("&"),e(g)}})})})();(function(){var a=h.m,b=h.load,e=h.M;h.q.e("pv-b",function(){if(c.trust&&c.vcard){var d=a.protocol+"//trust.baidu.com/vcard/v.js?"+["siteid="+c.vcard,"url="+encodeURIComponent(document.location.href),"source="+e(),"rnd="+Math.round(Math.random()*a.A)].join("&");b(d)}})})(); (function(){function a(){return function(){h.b.a.nv=0;h.b.a.st=4;h.b.a.et=3;h.b.a.ep=h.D.ga()+","+h.D.ea();h.b.g()}}function b(){clearTimeout(x);var a;w&&(a="visible"==document[w]);y&&(a=!document[y]);f="undefined"==typeof a?p:a;if((!n||!g)&&f&&m)u=p,t=+new Date;else if(n&&g&&(!f||!m))u=r,s+=+new Date-t;n=f;g=m;x=setTimeout(b,100)}function e(a){var g=document,t="";if(a in g)t=a;else for(var s=["webkit","ms","moz","o"],b=0;b<s.length;b++){var m=s[b]+a.charAt(0).toUpperCase()+a.slice(1);if(m in g){t= m;break}}return t}function d(a){if(!("focus"==a.type||"blur"==a.type)||!(a.target&&a.target!=window))m="focus"==a.type||"focusin"==a.type?p:r,b()}var k=mt.event,l=h.q,n=p,f=p,g=p,m=p,v=+new Date,t=v,s=0,u=p,w=e("visibilityState"),y=e("hidden"),x;b();(function(){var a=w.replace(/[vV]isibilityState/,"visibilitychange");k.e(document,a,b);k.e(window,"pageshow",b);k.e(window,"pagehide",b);"object"==typeof document.onfocusin?(k.e(document,"focusin",d),k.e(document,"focusout",d)):(k.e(window,"focus",d), k.e(window,"blur",d))})();h.D={ga:function(){return+new Date-v},ea:function(){return u?+new Date-t+s:s}};l.e("pv-b",function(){k.e(window,"unload",a())});return h.D})(); (function(){var a=mt.lang,b=h.m,e=h.load,d={pa:function(d){if((void 0===window._dxt||a.d(window._dxt,"Array"))&&"undefined"!==typeof h.b){var l=h.b.G();e([b.protocol,"//datax.baidu.com/x.js?si=",c.id,"&dm=",encodeURIComponent(l)].join(""),d)}},xa:function(b){if(a.d(b,"String")||a.d(b,"Number"))window._dxt=window._dxt||[],window._dxt.push(["_setUserId",b])}};return h.$=d})(); (function(){function a(g){for(var b in g)if({}.hasOwnProperty.call(g,b)){var d=g[b];e.d(d,"Object")||e.d(d,"Array")?a(d):g[b]=String(d)}}function b(a){return a.replace?a.replace(/'/g,"'0").replace(/\*/g,"'1").replace(/!/g,"'2"):a}var e=mt.lang,d=mt.l,k=h.m,l=h.q,n=h.$,f={P:q,r:[],B:0,Q:r,init:function(){f.c=0;f.P={push:function(){f.J.apply(f,arguments)}};l.e("pv-b",function(){f.aa();f.ba()});l.e("pv-d",f.ca);l.e("stag-b",function(){h.b.a.api=f.c||f.B?f.c+"_"+f.B:""});l.e("stag-d",function(){h.b.a.api= 0;f.c=0;f.B=0})},aa:function(){var a=window._hmt;if(a&&a.length)for(var b=0;b<a.length;b++){var d=a[b];switch(d[0]){case "_setAccount":1<d.length&&/^[0-9a-z]{32}$/.test(d[1])&&(f.c|=1,window._bdhm_account=d[1]);break;case "_setAutoPageview":if(1<d.length&&(d=d[1],r===d||p===d))f.c|=2,window._bdhm_autoPageview=d}}},ba:function(){if("undefined"===typeof window._bdhm_account||window._bdhm_account===c.id){window._bdhm_account=c.id;var a=window._hmt;if(a&&a.length)for(var b=0,d=a.length;b<d;b++)e.d(a[b], "Array")&&"_trackEvent"!==a[b][0]&&"_trackRTEvent"!==a[b][0]?f.J(a[b]):f.r.push(a[b]);window._hmt=f.P}},ca:function(){if(0<f.r.length)for(var a=0,b=f.r.length;a<b;a++)f.J(f.r[a]);f.r=q},J:function(a){if(e.d(a,"Array")){var b=a[0];if(f.hasOwnProperty(b)&&e.d(f[b],"Function"))f[b](a)}},_trackPageview:function(a){if(1<a.length&&a[1].charAt&&"/"==a[1].charAt(0)){f.c|=4;h.b.a.et=0;h.b.a.ep="";h.b.H?(h.b.a.nv=0,h.b.a.st=4):h.b.H=p;var b=h.b.a.u,d=h.b.a.su;h.b.a.u=k.protocol+"//"+document.location.host+ a[1];f.Q||(h.b.a.su=document.location.href);h.b.g();h.b.a.u=b;h.b.a.su=d}},_trackEvent:function(a){2<a.length&&(f.c|=8,h.b.a.nv=0,h.b.a.st=4,h.b.a.et=4,h.b.a.ep=b(a[1])+"*"+b(a[2])+(a[3]?"*"+b(a[3]):"")+(a[4]?"*"+b(a[4]):""),h.b.g())},_setCustomVar:function(a){if(!(4>a.length)){var d=a[1],e=a[4]||3;if(0<d&&6>d&&0<e&&4>e){f.B++;for(var t=(h.b.a.cv||"*").split("!"),s=t.length;s<d-1;s++)t.push("*");t[d-1]=e+"*"+b(a[2])+"*"+b(a[3]);h.b.a.cv=t.join("!");a=h.b.a.cv.replace(/[^1](\*[^!]*){2}/g,"*").replace(/((^|!)\*)+$/g, "");""!==a?h.b.setData("Hm_cv_"+c.id,encodeURIComponent(a),c.age):h.b.qa("Hm_cv_"+c.id)}}},_setReferrerOverride:function(a){1<a.length&&(h.b.a.su=a[1].charAt&&"/"==a[1].charAt(0)?k.protocol+"//"+window.location.host+a[1]:a[1],f.Q=p)},_trackOrder:function(b){b=b[1];e.d(b,"Object")&&(a(b),f.c|=16,h.b.a.nv=0,h.b.a.st=4,h.b.a.et=94,h.b.a.ep=d.stringify(b),h.b.g())},_trackMobConv:function(a){if(a={webim:1,tel:2,map:3,sms:4,callback:5,share:6}[a[1]])f.c|=32,h.b.a.et=93,h.b.a.ep=a,h.b.g()},_trackRTPageview:function(b){b= b[1];e.d(b,"Object")&&(a(b),b=d.stringify(b),512>=encodeURIComponent(b).length&&(f.c|=64,h.b.a.rt=b))},_trackRTEvent:function(b){b=b[1];if(e.d(b,"Object")){a(b);b=encodeURIComponent(d.stringify(b));var m=function(a){var b=h.b.a.rt;f.c|=128;h.b.a.et=90;h.b.a.rt=a;h.b.g();h.b.a.rt=b},l=b.length;if(900>=l)m.call(this,b);else for(var l=Math.ceil(l/900),t="block|"+Math.round(Math.random()*k.A).toString(16)+"|"+l+"|",s=[],u=0;u<l;u++)s.push(u),s.push(b.substring(900*u,900*u+900)),m.call(this,t+s.join("|")), s=[]}},_setUserId:function(a){a=a[1];n.pa();n.xa(a)}};f.init();h.Y=f;return h.Y})(); (function(){function a(){"undefined"==typeof window["_bdhm_loaded_"+c.id]&&(window["_bdhm_loaded_"+c.id]=p,this.a={},this.H=r,this.init())}var b=mt.url,e=mt.U,d=mt.L,k=mt.lang,l=mt.cookie,n=mt.i,f=mt.localStorage,g=mt.sessionStorage,m=h.m,v=h.q;a.prototype={I:function(a,b){a="."+a.replace(/:\d+/,"");b="."+b.replace(/:\d+/,"");var d=a.indexOf(b);return-1<d&&d+b.length==a.length},R:function(a,b){a=a.replace(/^https?:\/\//,"");return 0===a.indexOf(b)},w:function(a){for(var d=0;d<c.dm.length;d++)if(-1< c.dm[d].indexOf("/")){if(this.R(a,c.dm[d]))return p}else{var e=b.O(a);if(e&&this.I(e,c.dm[d]))return p}return r},G:function(){for(var a=document.location.hostname,b=0,d=c.dm.length;b<d;b++)if(this.I(a,c.dm[b]))return c.dm[b].replace(/(:\d+)?[\/\?#].*/,"");return a},N:function(){for(var a=0,b=c.dm.length;a<b;a++){var d=c.dm[a];if(-1<d.indexOf("/")&&this.R(document.location.href,d))return d.replace(/^[^\/]+(\/.*)/,"$1")+"/"}return"/"},ha:function(){if(!document.referrer)return m.j-m.o>c.vdur?1:4;var a= r;this.w(document.referrer)&&this.w(document.location.href)?a=p:(a=b.O(document.referrer),a=this.I(a||"",document.location.hostname));return a?m.j-m.o>c.vdur?1:4:3},getData:function(a){try{return l.get(a)||g.get(a)||f.get(a)}catch(b){}},setData:function(a,b,d){try{l.set(a,b,{domain:this.G(),path:this.N(),F:d}),d?f.set(a,b,d):g.set(a,b)}catch(e){}},qa:function(a){try{l.set(a,"",{domain:this.G(),path:this.N(),F:-1}),g.remove(a),f.remove(a)}catch(b){}},va:function(){var a,b,d,e,f;m.o=this.getData("Hm_lpvt_"+ c.id)||0;13==m.o.length&&(m.o=Math.round(m.o/1E3));b=this.ha();a=4!=b?1:0;if(d=this.getData("Hm_lvt_"+c.id)){e=d.split(",");for(f=e.length-1;0<=f;f--)13==e[f].length&&(e[f]=""+Math.round(e[f]/1E3));for(;2592E3<m.j-e[0];)e.shift();f=4>e.length?2:3;for(1===a&&e.push(m.j);4<e.length;)e.shift();d=e.join(",");e=e[e.length-1]}else d=m.j,e="",f=1;this.setData("Hm_lvt_"+c.id,d,c.age);this.setData("Hm_lpvt_"+c.id,m.j);d=m.j==this.getData("Hm_lpvt_"+c.id)?"1":"0";if(0===c.nv&&this.w(document.location.href)&& (""===document.referrer||this.w(document.referrer)))a=0,b=4;this.a.nv=a;this.a.st=b;this.a.cc=d;this.a.lt=e;this.a.lv=f},ua:function(){for(var a=[],b=0,d=m.V.length;b<d;b++){var e=m.V[b],f=this.a[e];"undefined"!=typeof f&&""!==f&&a.push(e+"="+encodeURIComponent(f))}b=this.a.et;this.a.rt&&(0===b?a.push("rt="+encodeURIComponent(this.a.rt)):90===b&&a.push("rt="+this.a.rt));return a.join("&")},wa:function(){this.va();this.a.si=c.id;this.a.su=document.referrer;this.a.ds=n.ra;this.a.cl=n.colorDepth+"-bit"; this.a.ln=n.language;this.a.ja=n.javaEnabled?1:0;this.a.ck=n.cookieEnabled?1:0;this.a.lo="number"==typeof _bdhm_top?1:0;this.a.fl=d.ia();this.a.v="1.0.94";this.a.cv=decodeURIComponent(this.getData("Hm_cv_"+c.id)||"");1==this.a.nv&&(this.a.tt=document.title||"");var a=document.location.href;this.a.cm=b.h(a,m.ma)||"";this.a.cp=b.h(a,m.na)||"";this.a.cw=b.h(a,m.la)||"";this.a.ci=b.h(a,m.ka)||"";this.a.cf=b.h(a,m.oa)||""},init:function(){try{this.wa(),0===this.a.nv?this.ta():this.K(".*"),h.b=this,this.Z(), v.s("pv-b"),this.sa()}catch(a){var b=[];b.push("si="+c.id);b.push("n="+encodeURIComponent(a.name));b.push("m="+encodeURIComponent(a.message));b.push("r="+encodeURIComponent(document.referrer));e.log(m.protocol+"//"+m.S+"?"+b.join("&"))}},sa:function(){function a(){v.s("pv-d")}"undefined"===typeof window._bdhm_autoPageview||window._bdhm_autoPageview===p?(this.H=p,this.a.et=0,this.a.ep="",this.g(a)):a()},g:function(a){var b=this;b.a.rnd=Math.round(Math.random()*m.A);v.s("stag-b");var d=m.protocol+"//"+ m.S+"?"+b.ua();v.s("stag-d");b.W(d);e.log(d,function(d){b.K(d);k.d(a,"Function")&&a.call(b)})},Z:function(){var a=document.location.hash.substring(1),d=RegExp(c.id),e=-1<document.referrer.indexOf(m.X)?p:r,f=b.h(a,"jn"),k=/^heatlink$|^select$/.test(f);a&&(d.test(a)&&e&&k)&&(a=document.createElement("script"),a.setAttribute("type","text/javascript"),a.setAttribute("charset","utf-8"),a.setAttribute("src",m.protocol+"//"+c.js+f+".js?"+this.a.rnd),f=document.getElementsByTagName("script")[0],f.parentNode.insertBefore(a, f))},W:function(a){var b=g.get("Hm_unsent_"+c.id)||"",d=this.a.u?"":"&u="+encodeURIComponent(document.location.href),b=encodeURIComponent(a.replace(/^https?:\/\//,"")+d)+(b?","+b:"");g.set("Hm_unsent_"+c.id,b)},K:function(a){var b=g.get("Hm_unsent_"+c.id)||"";b&&((b=b.replace(RegExp(encodeURIComponent(a.replace(/^https?:\/\//,"")).replace(/([\*\(\)])/g,"\\$1")+"(%26u%3D[^,]*)?,?","g"),"").replace(/,$/,""))?g.set("Hm_unsent_"+c.id,b):g.remove("Hm_unsent_"+c.id))},ta:function(){var a=this,b=g.get("Hm_unsent_"+ c.id);if(b)for(var b=b.split(","),d=function(b){e.log(m.protocol+"//"+decodeURIComponent(b).replace(/^https?:\/\//,""),function(b){a.K(b)})},f=0,k=b.length;f<k;f++)d(b[f])}};return new a})(); (function(){var a=mt.p,b=mt.event,e=mt.url,d=mt.l;try{if(window.performance&&performance.timing&&"undefined"!==typeof h.b){var k=+new Date,l=function(a){var b=performance.timing,d=b[a+"Start"]?b[a+"Start"]:0;a=b[a+"End"]?b[a+"End"]:0;return{start:d,end:a,value:0<a-d?a-d:0}},n=q;a.T(function(){n=+new Date});var f=function(){var a,b,f;f=l("navigation");b=l("request");f={netAll:b.start-f.start,netDns:l("domainLookup").value,netTcp:l("connect").value,srv:l("response").start-b.start,dom:performance.timing.domInteractive- performance.timing.fetchStart,loadEvent:l("loadEvent").end-f.start};a=document.referrer;var s=q;b=q;if("www.baidu.com"===(a.match(/^(http[s]?:\/\/)?([^\/]+)(.*)/)||[])[2])s=e.h(a,"qid"),b=e.h(a,"click_t");a=s;f.qid=a!=q?a:"";b!=q?(f.bdDom=n?n-b:0,f.bdRun=k-b,f.bdDef=l("navigation").start-b):(f.bdDom=0,f.bdRun=0,f.bdDef=0);h.b.a.et=87;h.b.a.ep=d.stringify(f);h.b.g()};b.e(window,"load",function(){setTimeout(f,500)})}}catch(g){}})(); (function(){var a=h.m,b={init:function(){try{if("http:"===a.protocol){var b=document.createElement("IFRAME");b.setAttribute("src","http://boscdn.bpc.baidu.com/v1/holmes-moplus/mp-cdn.html");b.style.display="none";b.style.width="1";b.style.height="1";b.Da="0";document.body.appendChild(b)}}catch(e){}}},e=navigator.userAgent.toLowerCase();-1<e.indexOf("android")&&-1===e.indexOf("micromessenger")&&b.init()})(); (function(){var a=mt.lang,b=mt.event,e=mt.l;if(c.comm&&"undefined"!==typeof h.b){var d=function(a){if(a.item){for(var b=a.length,d=Array(b);b--;)d[b]=a[b];return d}return[].slice.call(a)},k=/.*\/swt(\/)?([\?|#].*)?$/i,l={click:function(){for(var a=[],b=d(document.getElementsByTagName("a")),b=[].concat.apply(b,d(document.getElementsByTagName("area"))),b=[].concat.apply(b,d(document.getElementsByTagName("img"))),e=/openZoosUrl\(|swt/,f=/\/LR\/Chatpre\.aspx/,g=0,m=b.length;g<m;g++){var l=b[g],n=l.getAttribute("onclick"), l=l.getAttribute("href");(e.test(n)||f.test(l)||k.test(l))&&a.push(b[g])}return a}},n=function(a,b){for(var d in a)if(a.hasOwnProperty(d)&&b.call(a,d,a[d])===r)return r},f=function(b,d){var f={n:"swt",t:"clk"};f.v=b;if(d){var g=d.getAttribute("href"),l=d.getAttribute("onclick")?""+d.getAttribute("onclick"):q;k.test(g)?(f.sn="mediate",f.snv=g):a.d(l,"String")&&(-1===l.indexOf("openZoosUrl")&&-1!==l.indexOf("swt"))&&(g=d.getAttribute("id")||"",f.sn="wrap",f.snv=l,f.id=g)}h.b.a.et=86;h.b.a.ep=e.stringify(f); h.b.g();for(f=+new Date;500>=+new Date-f;);},g,m="/zoosnet"+(/\/$/.test("/zoosnet")?"":"/"),v=function(b,d){if(g===d)return f(m+b,d),r;if(a.d(d,"Array")||a.d(d,"NodeList"))for(var e=0,k=d.length;e<k;e++)if(g===d[e])return f(m+b+"/"+(e+1),d[e]),r};b.e(document,"click",function(b){b=b||window.event;g=b.target||b.srcElement;var d={};for(n(l,function(b,e){d[b]=a.d(e,"Function")?e():document.getElementById(e)});g&&g!==document&&n(d,v)!==r;)g=g.parentNode})}})();})();
apache-2.0
u0hz/FineUI
src/FineUI/BaseWebControls/BoxComponent.Container.PanelBase/PanelBase.cs
38589
 #region Comment /* * Project: FineUI * * FileName: PanelBase.cs * CreatedOn: 2008-05-07 * CreatedBy: 30372245@qq.com * * * Description: * -> * * History: * -> * * * * */ #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Drawing; using System.Drawing.Design; using System.Web.UI.Design.WebControls; using Newtonsoft.Json; using System.Web.UI.HtmlControls; using System.Web.UI.Design; namespace FineUI { /// <summary> /// 面板控件基类(抽象类) /// </summary> public abstract class PanelBase : Container { #region Constructor /// <summary> /// 构造函数 /// </summary> public PanelBase() { AddServerAjaxProperties("IFrameUrl"); AddClientAjaxProperties(); } #endregion #region virtual properties ///// <summary> ///// 是否自动高度 ///// </summary> //[Category(CategoryName.LAYOUT)] //[DefaultValue(false)] //[Description("是否自动高度")] //public virtual bool AutoHeight //{ // get // { // object obj = FState["AutoHeight"]; // return obj == null ? false : (bool)obj; // } // set // { // FState["AutoHeight"] = value; // } //} ///// <summary> ///// 是否启用自动宽度,通过设置CSS属性height:auto来实现 ///// </summary> //[Category(CategoryName.LAYOUT)] //[DefaultValue(false)] //[Description("是否自动宽度,通过设置CSS属性height:auto来实现")] //public virtual bool AutoWidth //{ // get // { // object obj = FState["AutoWidth"]; // return obj == null ? false : (bool)obj; // } // set // { // FState["AutoWidth"] = value; // } //} /// <summary> /// 是否自动滚动 /// </summary> [Category(CategoryName.LAYOUT)] [DefaultValue(false)] [Description("是否自动滚动")] public bool AutoScroll { get { object obj = FState["AutoScroll"]; return obj == null ? false : (bool)obj; } set { FState["AutoScroll"] = value; } } #endregion #region Properties /// <summary> /// 最小高度 /// </summary> [Category(CategoryName.OPTIONS)] [DefaultValue(typeof(Unit), "")] [Description("最小高度")] public Unit MinHeight { get { object obj = FState["MinHeight"]; return obj == null ? Unit.Empty : (Unit)obj; } set { FState["MinHeight"] = value; } } /// <summary> /// 最小宽度 /// </summary> [Category(CategoryName.OPTIONS)] [DefaultValue(typeof(Unit), "")] [Description("最小宽度")] public Unit MinWidth { get { object obj = FState["MinWidth"]; return obj == null ? Unit.Empty : (Unit)obj; } set { FState["MinWidth"] = value; } } /// <summary> /// 最大高度 /// </summary> [Category(CategoryName.OPTIONS)] [DefaultValue(typeof(Unit), "")] [Description("最大高度")] public Unit MaxHeight { get { object obj = FState["MaxHeight"]; return obj == null ? Unit.Empty : (Unit)obj; } set { FState["MaxHeight"] = value; } } /// <summary> /// 最大宽度 /// </summary> [Category(CategoryName.OPTIONS)] [DefaultValue(typeof(Unit), "")] [Description("最大宽度")] public Unit MaxWidth { get { object obj = FState["MaxWidth"]; return obj == null ? Unit.Empty : (Unit)obj; } set { FState["MaxWidth"] = value; } } /// <summary> /// 启用自定义的圆角边框 /// </summary> [Category(CategoryName.BASEOPTIONS)] [DefaultValue(false)] [Description("启用自定义的圆角边框")] public bool EnableFrame { get { object obj = FState["EnableFrame"]; return obj == null ? false : (bool)obj; } set { FState["EnableFrame"] = value; } } ///// <summary> ///// 使用大的标题栏 ///// </summary> //[Category(CategoryName.BASEOPTIONS)] //[DefaultValue(false)] //[Description("使用大的标题栏")] //public bool EnableLargeHeader //{ // get // { // object obj = FState["EnableLargeHeader"]; // return obj == null ? false : (bool)obj; // } // set // { // FState["EnableLargeHeader"] = value; // } //} ///// <summary> ///// 是否显示浅色的背景色 ///// </summary> //[Category(CategoryName.BASEOPTIONS)] //[DefaultValue(false)] //[Description("是否显示浅色的背景色")] //public virtual bool EnableLightBackgroundColor //{ // get // { // object obj = FState["EnableLightBackgroundColor"]; // return obj == null ? false : (bool)obj; // } // set // { // FState["EnableLightBackgroundColor"] = value; // } //} ///// <summary> ///// 废弃EnableBackgroundColor属性,以便和ExtJS保持一致。 ///// </summary> //[Category(CategoryName.BASEOPTIONS)] //[DefaultValue(false)] //[Description("废弃EnableBackgroundColor属性,以便和ExtJS保持一致。")] //[Obsolete("此属性已废除,可以使用BodyStyle来达到想要的效果")] //public virtual bool EnableBackgroundColor //{ // get // { // object obj = FState["EnableBackgroundColor"]; // return obj == null ? false : (bool)obj; // } // set // { // FState["EnableBackgroundColor"] = value; // } //} //private bool RoundBorder_Default = false; //[Category(CategoryName.OPTIONS)] //[DefaultValue(false)] //[Description("是否圆角边框并")] //public virtual bool RoundBorder //{ // get // { // object obj = BoxState["RoundBorder"]; // return obj == null ? RoundBorder_Default : (bool)obj; // } // set // { // BoxState["RoundBorder"] = value; // } //} /// <summary> /// 内容区域的样式 /// </summary> [Category(CategoryName.BASEOPTIONS)] [DefaultValue("")] [Description("内容区域的样式")] public string BodyStyle { get { object obj = FState["BodyStyle"]; return obj == null ? "" : (string)obj; } set { FState["BodyStyle"] = value; } } /// <summary> /// 内容区域的内边距,字符串类型,可以设置上下左右的内边距,比如'0px 5px'或'5px 10px 2px 2px' /// </summary> [Category(CategoryName.LAYOUT)] [DefaultValue(typeof(String), "")] [Description("内容区域的内边距,字符串类型,可以设置上下左右的内边距,比如'0px 5px'或'5px 10px 2px 2px'")] public virtual string BodyPadding { get { object obj = FState["BodyPadding"]; return obj == null ? String.Empty : (string)obj; } set { FState["BodyPadding"] = value; } } /// <summary> /// 是否显示边框 /// </summary> [Category(CategoryName.BASEOPTIONS)] [DefaultValue(true)] [Description("是否显示边框")] public virtual bool ShowBorder { get { object obj = FState["ShowBorder"]; return obj == null ? true : (bool)obj; } set { FState["ShowBorder"] = value; } } #endregion #region old code //protected virtual bool IsIFramePanel //{ // get // { // return false; // } //} #endregion #region Toolbars private ToolbarCollection _toolbars; /// <summary> /// 工具栏控件 /// </summary> [Browsable(false)] [Category(CategoryName.OPTIONS)] [NotifyParentProperty(true)] [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Description("工具栏控件")] public virtual ToolbarCollection Toolbars { get { if (_toolbars == null) { _toolbars = new ToolbarCollection(this); } return _toolbars; } } #endregion #region Items private ControlBaseCollection items; /// <summary> /// 子控件 /// </summary> [Browsable(false)] [Category(CategoryName.OPTIONS)] [NotifyParentProperty(true)] [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Description("子控件")] [Editor(typeof(ControlBaseItemsEditor), typeof(System.Drawing.Design.UITypeEditor))] public virtual ControlBaseCollection Items { get { if (items == null) { items = new ControlBaseCollection(this); } return items; } } #endregion #region internal RenderChildrenAsContent private ITemplate content = null; /// <summary> /// 子控件 /// </summary> [Browsable(false)] [DefaultValue(null)] [NotifyParentProperty(true)] [PersistenceMode(PersistenceMode.InnerProperty)] [Description("子控件")] public virtual ITemplate Content { get { return content; } set { content = value; } } [Category(CategoryName.OPTIONS)] [DefaultValue(false)] [Description("渲染子控件为容器内容")] internal virtual bool RenderChildrenAsContent { get { object obj = FState["RenderChildrenAsContent"]; return obj == null ? false : (bool)obj; } set { FState["RenderChildrenAsContent"] = value; } } #endregion #region IFrameUrl/IFrameName/EnableIFrame /// <summary> /// [AJAX属性]IFrame的地址 /// </summary> [Category(CategoryName.BASEOPTIONS)] [DefaultValue("")] [Description("[AJAX属性]IFrame的地址")] public virtual string IFrameUrl { get { object obj = FState["IFrameUrl"]; if (obj == null) { return String.Empty; } else { string url = (string)obj; return ResolveIFrameUrl(url); } } set { FState["IFrameUrl"] = value; } } /// <summary> /// IFrame的名称 /// </summary> [Category(CategoryName.BASEOPTIONS)] [DefaultValue("")] [Description("IFrame的名称")] public virtual string IFrameName { get { object obj = FState["IFrameName"]; if (obj == null) { if (DesignMode) { return String.Empty; } else { return String.Format("{0}_iframe", XID); } } return (string)obj; } set { FState["IFrameName"] = value; } } /// <summary> /// 是否启用IFrame /// </summary> [Category(CategoryName.BASEOPTIONS)] [DefaultValue(false)] [Description("是否启用IFrame")] public virtual bool EnableIFrame { get { object obj = FState["EnableIFrame"]; return obj == null ? false : (bool)obj; } set { FState["EnableIFrame"] = value; } } #endregion #region ContentID [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] internal string ContentID { get { return String.Format("{0}_Content", ClientID); } } //protected string _childrenContentClass = String.Empty; //[Browsable(false)] //[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] //[Description("子控件的容器的样式类(Tab用到了)")] //protected virtual string ChildrenContentClass //{ // get // { // return _childrenContentClass; // } // set // { // _childrenContentClass = value; // } //} #endregion #region RenderBeginTag/RenderEndTag // 现在不需要这样处理Iframe了,用html属性 ///// <summary> ///// 是否向页面写iframe ///// </summary> //private bool _writeIframeToHtmlDocument = false; /// <summary> /// 渲染控件的开始标签 /// </summary> /// <param name="writer">输出流</param> protected override void RenderBeginTag(HtmlTextWriter writer) { base.RenderBeginTag(writer); if (RenderChildrenAsContent) { #region old code //HtmlNodeBuilder nodeBuilder = new HtmlNodeBuilder("div"); //nodeBuilder.SetProperty("id", ChildrenContentID); //nodeBuilder.SetProperty("style", "display:none;"); //if (!String.IsNullOrEmpty(ChildrenContentClass)) //{ // nodeBuilder.SetProperty("class", ChildrenContentClass); //} //string startDivHtml = nodeBuilder.ToString(); //if (startDivHtml.EndsWith("</div>")) //{ // startDivHtml = startDivHtml.Substring(0, startDivHtml.Length - "</div>".Length); //} //writer.Write(startDivHtml); #endregion #region ChildrenContentID StringBuilder sb = new StringBuilder(); sb.Append("<div"); sb.AppendFormat(" id=\"{0}\" ", ContentID); //sb.Append(" class=\"x-hide-display\" "); // 注意,这里不能用 display=none(ContentPanel中的其他FineUI控件的渲染就会有问题) // 一定要用visibility:hidden,The shape is not visible, but is still part of the flow of the objects in the browser. Mouse events are not processed. if (EnableIFrame) { sb.Append("style=\"width:100%;height:100%;\" "); } else { //sb.Append("style=\"visibility:hidden;\" "); //if (!String.IsNullOrEmpty(ChildrenContentClass)) //{ // sb.AppendFormat("class=\"{0}\" ", ChildrenContentClass); //} } sb.Append(">"); writer.Write(sb.ToString()); #endregion #region old code //if (EnableIFrame && _writeIframeToHtmlDocument) //{ // writer.Write(String.Format("<iframe src=\"{0}\" name=\"{1}\" frameborder=\"0\" style=\"height:100%;width:100%;overflow:auto;\"></iframe>", IFrameUrl, IFrameName)); //} #endregion } } /// <summary> /// 渲染控件的结束标签 /// </summary> /// <param name="writer">输出流</param> protected override void RenderEndTag(HtmlTextWriter writer) { if (RenderChildrenAsContent) { writer.Write("</div>"); } base.RenderEndTag(writer); } #endregion #region CreateChildControls /// <summary> /// 创建子控件 /// </summary> protected override void CreateChildControls() { base.CreateChildControls(); if (Content != null) { WebControl ctrl = new WebControl(HtmlTextWriterTag.Div); ctrl.ID = "Content"; Content.InstantiateIn(ctrl); Controls.Add(ctrl); } } #endregion #region OnPreRender /// <summary> /// 渲染 HTML 之前调用(AJAX回发) /// </summary> protected override void OnAjaxPreRender() { base.OnAjaxPreRender(); StringBuilder sb = new StringBuilder(); if (EnableIFrame) { if (PropertyModified("IFrameUrl")) { sb.AppendFormat("F.wnd.updateIFrameNode({0},{1});", XID, JsHelper.Enquote(IFrameUrl)); } } AddAjaxScript(sb); } /// <summary> /// 渲染 HTML 之前调用(页面第一次加载或者普通回发) /// </summary> protected override void OnFirstPreRender() { base.OnFirstPreRender(); if (EnableFrame) { OB.AddProperty("frame", true); } #region Items // 如果是 ContentPanel, 启用 IFrame 或者包含 Content, 则不生成 items if (RenderChildrenAsContent || EnableIFrame || (Content != null)) { if (RenderChildrenAsContent || (Content != null)) { OB.AddProperty("contentEl", String.Format("{0}", ContentID)); } } else { if (Items.Count > 0) { JsArrayBuilder ab = new JsArrayBuilder(); foreach (ControlBase item in Items) { if (item.Visible) { ab.AddProperty(String.Format("{0}", item.XID), true); } } OB.AddProperty("items", ab.ToString(), true); } } #endregion #region Toolbars //JsArrayBuilder dockItems = new JsArrayBuilder(); //foreach (Toolbar bar in Toolbars) //{ // dockItems.AddProperty(bar.XID, true); //} //if (this is Grid) //{ // Grid grid = this as Grid; // if (grid.AllowPaging) // { // dockItems.AddProperty(grid.Render_PagingID, true); // } //} Dictionary<string, JsArrayBuilder> bars = new Dictionary<string, JsArrayBuilder>(); foreach (Toolbar bar in Toolbars) { string barPosition = ToolbarPositionHelper.GetExtName(bar.Position); if (!bars.ContainsKey(barPosition)) { bars[barPosition] = new JsArrayBuilder(); } bars[barPosition].AddProperty(bar.XID, true); } // 将底部工具栏的顺序反转 if (bars.ContainsKey("bottom")) { bars["bottom"].Reverse(); } // 表格的分页工具栏 if (this is Grid) { Grid grid = this as Grid; if (grid.AllowPaging) { if (!bars.ContainsKey("bottom")) { bars["bottom"] = new JsArrayBuilder(); } bars["bottom"].AddProperty(grid.Render_PagingID, true); } } JsArrayBuilder dockItems = new JsArrayBuilder(); foreach (string barPosition in bars.Keys) { foreach (string barItem in bars[barPosition].Properties) { dockItems.AddProperty(barItem, true); } } OB.AddProperty("dockedItems", dockItems); #endregion #region BodyStyle/ShowBorder string bodyStyleStr = BodyStyle; if (!bodyStyleStr.Contains("padding")) { if (!String.IsNullOrEmpty(BodyPadding)) { bodyStyleStr += String.Format("padding:{0};", StyleUtil.GetMarginPaddingStyle(BodyPadding)); } } //if (EnableBackgroundColor) //{ // if (!bodyStyleStr.Contains("background-color")) // { // string backgroundColorStyleStr = GlobalConfig.GetDefaultBackgroundColor(); // if (!String.IsNullOrEmpty(backgroundColorStyleStr)) // { // bodyStyleStr += String.Format("background-color:{0};", backgroundColorStyleStr); // } // } //} OB.AddProperty("bodyStyle", bodyStyleStr); OB.AddProperty("border", ShowBorder); #endregion #region MinHeight/MinHeight if (MinHeight != Unit.Empty) { OB.AddProperty("minHeight", MinHeight.Value); } if (MinWidth != Unit.Empty) { OB.AddProperty("minWidth", MinWidth.Value); } if (MaxHeight != Unit.Empty) { OB.AddProperty("maxHeight", MaxHeight.Value); } if (MaxWidth != Unit.Empty) { OB.AddProperty("maxWidth", MaxWidth.Value); } //// 对于Panel,如果宽度/高度没有定义 //if (Width == Unit.Empty && AutoWidth) //{ // OB.AddProperty("autoWidth", true); //} //if (Height == Unit.Empty && AutoHeight) //{ // OB.AddProperty("autoHeight", true); //} //// 如果父控件是容器控件(不是ContentPanel),并且Layout != LayoutType.Container, //// 则设置AutoWidth/AutoHeight都为false //if (Parent is PanelBase) //{ // PanelBase parent = Parent as PanelBase; // if (!(parent is ContentPanel) && parent.Layout != Layout.Container) // { // OB.RemoveProperty("autoHeight"); // OB.RemoveProperty("autoWidth"); // } //} if (AutoScroll) { OB.AddProperty("autoScroll", true); } #region old code //// 如果是 PageLayout 中的Panel,不能设置AutoWidth //if (Parent is PageLayout) //{ // // region // if (Region != Region_Default) OB.AddProperty(OptionName.Region, RegionTypeName.GetName(Region.Value)); //} //else //{ // // 对于Panel,如果宽度/高度没有定义,则使用自动宽度和高度 // if (Width == Unit.Empty) // { // OB.AddProperty(OptionName.AutoWidth, true); // } // if (Height == Unit.Empty) // { // OB.AddProperty(OptionName.AutoHeight, true); // } //} //// 如果父控件是容器控件,并且Layout=Fit,则设置AutoWidth/AutoHeight都为false //if (Parent is PanelBase) //{ // PanelBase parentPanel = Parent as PanelBase; // if (parentPanel.Layout == LayoutType.Fit // || parentPanel.Layout == LayoutType.Anchor // || parentPanel.Layout == LayoutType.Border) // { // OB.RemoveProperty(OptionName.AutoHeight); // OB.RemoveProperty(OptionName.AutoWidth); // } //} #endregion #endregion #region EnableIFrame if (EnableIFrame) { #region old code //string iframeJsContent = String.Empty; //string frameUrl = ResolveUrl(IFrameUrl); //JsObjectBuilder iframeBuilder = new JsObjectBuilder(); //if (IFrameDelayLoad) //{ // iframeBuilder.AddProperty(OptionName.Src, "#"); //} //else //{ // iframeBuilder.AddProperty(OptionName.Src, frameUrl); //} //iframeBuilder.AddProperty(OptionName.LoadMask, false); //iframeJsContent += String.Format("var {0}=new Ext.ux.ManagedIFrame('{0}',{1});", IFrameID, iframeBuilder.ToString()); //if (IFrameDelayLoad) //{ // iframeJsContent += String.Format("{0}_url='{1}';", IFrameID, frameUrl); //} //iframeJsContent += "\r\n"; //AddStartupScript(this, iframeJsContent); #endregion // 注意: // 如下依附于现有对象的属性名称的定义规则:x_property1 // 存储于当前对象实例中 OB.AddProperty("f_iframe", true); OB.AddProperty("f_iframe_url", IFrameUrl); OB.AddProperty("f_iframe_name", IFrameName); // 如果定义了IFrameUrl,则直接写到页面中,否则先缓存到此对象中 if (!String.IsNullOrEmpty(IFrameUrl)) { //_writeIframeToHtmlDocument = true; OB.AddProperty("f_iframe_loaded", true); // 直接添加iframe属性 OB.AddProperty("html", String.Format("<iframe src=\"{0}\" name=\"{1}\" frameborder=\"0\" style=\"height:100%;width:100%;overflow:auto;\"></iframe>", IFrameUrl, IFrameName)); } else { //_writeIframeToHtmlDocument = false; OB.AddProperty("f_iframe_loaded", false); } #region old code //// If current panel is Tab, then process the IFrameDelayLoad property. //Tab tab = this as Tab; //if (tab != null && tab.IFrameDelayLoad) //{ // // 如果是Tab,并且此Tab不是激活的,则不添加iframe // //_writeIframeToHtmlDocument = false; // OB.AddProperty("box_property_iframe_loaded", false); //} //else //{ // // 如果定义了IFrameUrl,则直接写到页面中,否则先缓存到此对象中 // if (!String.IsNullOrEmpty(IFrameUrl)) // { // //_writeIframeToHtmlDocument = true; // OB.AddProperty("box_property_iframe_loaded", true); // // 直接添加iframe属性 // OB.AddProperty("html", String.Format("<iframe src=\"{0}\" name=\"{1}\" frameborder=\"0\" style=\"height:100%;width:100%;overflow:auto;\"></iframe>", IFrameUrl, IFrameName)); // } // else // { // //_writeIframeToHtmlDocument = false; // OB.AddProperty("box_property_iframe_loaded", false); // } //} #endregion } #endregion #region RoundBorder //if (RoundBorder) OB.AddProperty(OptionName.Frame, true); #endregion #region oldcode //if (EnableLargeHeader) //{ // OB.AddProperty("cls", "f-panel-big-header"); //} //OB.AddProperty("animCollapse", false); #endregion #region ContentEl //string finallyScript = String.Empty; if (RenderChildrenAsContent) { OB.AddProperty("contentEl", ContentID); // 在页面元素渲染完成后,才显示容器控件的内容 //string renderScript = String.Format("Ext.get('{0}').show();", ContentID); //OB.Listeners.AddProperty("render", JsHelper.GetFunction(renderScript), true); //string beforerenderScript = String.Format("Ext.get('{0}').setStyle('display','');", ChildrenContentID); //OB.Listeners.AddProperty("beforerender", "function(component){" + beforerenderScript + "}", true); // 这一段的逻辑(2008-9-1): // 如果是页面第一次加载 + 此Panel在Tab中 + 此Tab不是当前激活Tab + 此Tab的TabStrip启用了延迟加载 // 那么在页面加载完毕后,把此Panel给隐藏掉,等此Panel渲染到页面中时再显示出来 //Tab tab = ControlUtil.FindParentControl(this, typeof(Tab)) as Tab; //if (tab != null) //{ // TabStrip tabStrip = tab.Parent as TabStrip; // if (tabStrip.EnableDeferredRender && tabStrip.Tabs[tabStrip.ActiveTabIndex] != tab) // { // // 页面第一次加载时,在显示(控件的render事件)之前要先隐藏 // AddStartupAbsoluteScript(String.Format("Ext.get('{0}').setStyle('display','none');", ContentID)); // } //} } #endregion } #region oldcode //protected void AddItemsToOB() //{ // AddItemsToOB(Controls); //} ///// <summary> ///// 将controls添加到此控件的Items属性 ///// </summary> ///// <param name="controls"></param> //protected void AddItemsToOB(ControlCollection controls) //{ // // 运行到这里,Controls里全部是ControlBase类型了(在AddParsedSubObject中过滤的)。 // if (controls.Count > 0) // { // JsArrayBuilder ab = new JsArrayBuilder(); // foreach (Control item in controls) // { // // 再次检查是否ControlBase,并且只有Visible时才添加 // // 还有一个例外情况,Window控件不作为任何控件的子控件,Window的RenderImmediately一定为true // if (item is ControlBase && item.Visible && !(item is Window)) // { // string itemJSId = String.Format("{0}", (item as ControlBase).ClientJavascriptID); // if (item is Toolbar) // { // Toolbar bar = item as Toolbar; // if (bar.Position == ToolbarPosition.Top) // { // OB.AddProperty(OptionName.Tbar, itemJSId, true); // } // else // { // OB.AddProperty(OptionName.Bbar, itemJSId, true); // } // } // else // { // ab.AddProperty(itemJSId, true); // } // } // } // // 有内容时才添加items集合 // if (ab.Count > 0) // { // OB.AddProperty(OptionName.Items, ab.ToString(), true); // } // } //} #endregion #endregion #region ResolveIFrameUrl internal string ResolveIFrameUrl(string url) { if (String.IsNullOrEmpty(url)) { return String.Empty; } if (url == "#" || url == "about:blank") { return url; } //&& IFrameUrl != "#" && IFrameUrl != "about:blank" // 可能会通过<script></script>的方式传递js参数 if (url.Contains("<")) { url = url.Replace("<", "&lt;"); } if (url.Contains(">")) { url = url.Replace(">", "&gt;"); } // 这个在 v1.2.9 以后就不需要了 //// 加上后缀 //if (this is Window) //{ // if (!url.Contains("box_parent_client_id=")) // { // if (!url.Contains("?")) // { // url += "?"; // } // else // { // url += "&"; // } // url += "box_parent_client_id=" + ClientID; // } //} // 转换为客户端Url url = ResolveUrl(url); return url; } #endregion #region RefreshIFrame GetRefreshIFrameReference /// <summary> /// 刷新面板中的IFrame页面 /// </summary> public void RefreshIFrame() { PageContext.RegisterStartupScript(GetRefreshIFrameReference()); } /// <summary> /// 获取刷新面板中IFrame页面的客户端脚本 /// </summary> /// <returns>客户端脚本</returns> public string GetRefreshIFrameReference() { return String.Format("{0}.body.query('iframe')[0].contentWindow.location.reload();", ScriptID); } #endregion #region Reset /// <summary> /// 重置面板中所有字段 /// </summary> public virtual void Reset() { PageContext.RegisterStartupScript(GetResetReference()); } /// <summary> /// 获取重置面板中所有字段的客户端脚本 /// </summary> /// <returns></returns> public virtual string GetResetReference() { return String.Format("{0}.f_reset();", ScriptID); } #endregion #region GetClearDirtyReference /// <summary> /// 清空面板内表单字段的改变状态 /// </summary> /// <returns>客户端脚本</returns> public string GetClearDirtyReference() { return String.Format("{0}.f_clearDirty();", ScriptID); } #endregion } }
apache-2.0
justinmuller/buck
src/com/facebook/buck/jvm/java/KeystoreDescription.java
1826
/* * Copyright 2014-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.jvm.java; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.rules.AbstractDescriptionArg; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.Description; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.TargetGraph; import com.facebook.infer.annotation.SuppressFieldNotInitialized; import com.google.common.collect.ImmutableSortedSet; public class KeystoreDescription implements Description<KeystoreDescription.Arg> { @Override public Arg createUnpopulatedConstructorArg() { return new Arg(); } @Override public <A extends Arg> Keystore createBuildRule( TargetGraph targetGraph, BuildRuleParams params, BuildRuleResolver resolver, A args) { return new Keystore(params, new SourcePathResolver(resolver), args.store, args.properties); } @SuppressFieldNotInitialized public static class Arg extends AbstractDescriptionArg { public SourcePath store; public SourcePath properties; public ImmutableSortedSet<BuildTarget> deps = ImmutableSortedSet.of(); } }
apache-2.0
jfindley2/amazon-product
php/date-utils.php
1851
<?php /** * None of this is my code. * I found it at https://bootcamp-coders.cnm.edu/class-materials/object-oriented/object-oriented-php.php * With permission, of course. */ /** * custom filter for mySQL style dates * * Converts a string to a DateTime object or false if invalid. This is designed to be used within a mutator method. * * @param mixed $newDate date to validate * @return mixed DateTime object containing the validated date or false if invalid * @see http://php.net/manual/en/class.datetime.php PHP's DateTime class * @throws InvalidArgumentException if the date is in an invalid format * @throws RangeException if the date is not a Gregorian date **/ function validateDate($newDate) { // base case: if the date is a DateTime object, there's no work to be done if(is_object($newDate) === true && get_class($newDate) === "DateTime") { return($newDate); } // treat the date as a mySQL date string: Y-m-d H:i:s $newDate = trim($newDate); if((preg_match("/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/", $newDate, $matches)) !== 1) { throw(new InvalidArgumentException("date is not a valid date")); } // verify the date is really a valid calendar date $year = intval($matches[1]); $month = intval($matches[2]); $day = intval($matches[3]); $hour = intval($matches[4]); $minute = intval($matches[5]); $second = intval($matches[6]); if(checkdate($month, $day, $year) === false) { throw(new RangeException("date $newDate is not a Gregorian date")); } // verify the time is really a valid wall clock time if($hour < 0 || $hour >= 24 || $minute < 0 || $minute >= 60 || $second < 0 || $second >= 60) { throw(new RangeException("date $newDate is not a valid time")); } // if we got here, the date is clean $newDate = DateTime::createFromFormat("Y-m-d H:i:s", $newDate); return($newDate); }
apache-2.0
yunxao/JN-Sim
Simulador/src/drcl/ruv/RUVOutputManager.java
4876
// @(#)RUVOutputManager.java 11/2002 // Copyright (c) 1998-2002, Distributed Real-time Computing Lab (DRCL) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. Neither the name of "DRCL" nor the names of its contributors may be used // to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // package drcl.ruv; import java.io.OutputStream; import java.io.PrintStream; import java.io.IOException; /** */ public class RUVOutputManager extends OutputStream { public static final PrintStream SYSTEM_OUT = java.lang.System.out; public static final PrintStream SYSTEM_ERR = java.lang.System.err; static RUVOutput[] rout = null; static OutputStream[] sout= new OutputStream[]{SYSTEM_OUT, null}; public static final RUVOutputManager onlyManager = new RUVOutputManager(); public static void activate() { PrintStream ps_ = new PrintStream(onlyManager); java.lang.System.setOut(ps_); java.lang.System.setErr(ps_); } public static void deactivate() { java.lang.System.setOut(SYSTEM_OUT); java.lang.System.setErr(SYSTEM_ERR); } private RUVOutputManager() { super(); } public void write(int b) throws IOException { out(new String(new byte[]{(byte)b})); } public void write(byte b[]) throws IOException { out(new String(b)); } public void write(byte b[], int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) return; out(new String(b, off, len)); } void out(String msg_) { if (rout != null) for (int i=0; i<rout.length; i++) if (rout[i] != null) rout[i].RUVOutput(msg_); if (sout!= null) { byte[] bytes_ = msg_.getBytes(); for (int i=0; i<sout.length; i++) if (sout[i] != null) try { sout[i].write(bytes_); } catch (Exception e_) {} } } public static void addOutput(RUVOutput o_) { if (rout == null) rout = new RUVOutput[2]; for (int i=0; i<rout.length; i++) if (rout[i] == null) { rout[i] = o_; return; } RUVOutput[] tmp_ = new RUVOutput[rout.length + 2]; java.lang.System.arraycopy(rout, 0, tmp_, 0, rout.length); rout = tmp_; rout[rout.length-2] = o_; } public static void addOutput(OutputStream o_) { if (sout == null) sout = new OutputStream[2]; for (int i=0; i<sout.length; i++) if (sout[i] == null) { sout[i] = o_; return; } OutputStream[] tmp_ = new OutputStream[sout.length + 2]; java.lang.System.arraycopy(sout, 0, tmp_, 0, sout.length); sout = tmp_; sout[sout.length-2] = o_; } public static void removeOutput(OutputStream o_) { if (sout== null) return; for (int i=0; i<sout.length; i++) if (sout[i] == o_) { sout[i] = null; return; } } public static void removeOutput(RUVOutput o_) { if (rout == null) return; for (int i=0; i<rout.length; i++) if (rout[i] == o_) { rout[i] = null; return; } } /** Prints out the message on the standard output. */ public static void print(String s_) { SYSTEM_OUT.print(s_); } /** Prints out the message on the standard output. */ public static void println(String s_) { SYSTEM_OUT.println(s_); } /** Prints out the message on the standard err. */ public static void eprint(String s_) { SYSTEM_ERR.print(s_); } /** Prints out the message on the standard err. */ public static void eprintln(String s_) { SYSTEM_ERR.println(s_); } }
apache-2.0
unaccomplished/KaboodleMe
public/client/scripts/components/name/Name.js
328
(function() { var name = { templateUrl: 'client/scripts/components/name/name.html', bindings: { resolve: '<', close: '&', dismiss: '&' }, controller: nameCtrl } function nameCtrl() { var $ctrl = this; } angular .module('kaboodleme') .component('name', name); })();
apache-2.0
cs-au-dk/TAJS
src/dk/brics/tajs/lattice/FunctionPartitions.java
3571
/* * Copyright 2009-2020 Aarhus University * * 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 dk.brics.tajs.lattice; import dk.brics.tajs.flowgraph.Function; import dk.brics.tajs.util.Canonicalizer; import dk.brics.tajs.util.Collectors; import dk.brics.tajs.util.DeepImmutable; import javax.annotation.Nonnull; import java.util.Objects; import java.util.Set; import static dk.brics.tajs.util.Collections.newSet; import static dk.brics.tajs.util.Collections.singleton; /** * FunctionPartitions is a set of partitions that are sound to use for partitioned variables. */ public class FunctionPartitions implements DeepImmutable { @Nonnull private final Set<PartitionToken.FunctionPartitionToken> partitions; private final int hashcode; private FunctionPartitions(Set<PartitionToken.FunctionPartitionToken> partitions) { this.partitions = partitions; this.hashcode = Objects.hash(partitions); } private static FunctionPartitions makeAndCanonicalize(Set<PartitionToken.FunctionPartitionToken> partitionings) { return Canonicalizer.get().canonicalize(new FunctionPartitions(Canonicalizer.get().canonicalizeSet(partitionings))); } public static FunctionPartitions make(PartitionToken.FunctionPartitionToken q) { return makeAndCanonicalize(singleton(q)); } public Set<PartitionToken.FunctionPartitionToken> getPartitionings() { return partitions; } public FunctionPartitions join(FunctionPartitions other) { if (other == null) { return this; } Set<PartitionToken.FunctionPartitionToken> res = newSet(partitions); if (!res.addAll(other.partitions)) { // If no new partitionings added return this; } return FunctionPartitions.makeAndCanonicalize(res); } @Override public boolean equals(Object o) { if (!Canonicalizer.get().isCanonicalizing()) return this == o; if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FunctionPartitions that = (FunctionPartitions) o; return Objects.equals(partitions, that.partitions); } @Override public int hashCode() { return hashcode; } @Override public String toString() { return partitions.toString(); } /** * Removes partitions that are not relevant for the given function. */ public FunctionPartitions filterByFunction(ObjectLabel function) { Set<Function> outerFunctions = newSet(); Function fun = function.getFunction(); while (fun != null) { outerFunctions.add(fun); fun = fun.getOuterFunction(); } Set<PartitionToken.FunctionPartitionToken> partitions = this.partitions.stream().filter(q -> outerFunctions.contains(q.getNode().getBlock().getFunction())).collect(Collectors.toSet()); if (partitions.isEmpty()) return null; return FunctionPartitions.makeAndCanonicalize(partitions); } }
apache-2.0
kelely/Helios
src/Helios.Zero/Helios.Zero.Core/Authorization/Roles/RoleManager.cs
2449
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Abp.Authorization; using Abp.Authorization.Roles; using Abp.Domain.Uow; using Abp.Localization; using Abp.Runtime.Caching; using Abp.UI; using Abp.Zero.Configuration; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Helios.Authorization.Users; namespace Helios.Authorization.Roles { /// <summary> /// Role manager. /// Used to implement domain logic for roles. /// </summary> public class RoleManager : AbpRoleManager<Role, User> { private readonly ILocalizationManager _localizationManager; public RoleManager( RoleStore store, IEnumerable<IRoleValidator<Role>> roleValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, ILogger<RoleManager> logger, IPermissionManager permissionManager, IRoleManagementConfig roleManagementConfig, ICacheManager cacheManager, IUnitOfWorkManager unitOfWorkManager, ILocalizationManager localizationManager) : base( store, roleValidators, keyNormalizer, errors, logger, permissionManager, cacheManager, unitOfWorkManager, roleManagementConfig) { _localizationManager = localizationManager; } public override Task SetGrantedPermissionsAsync(Role role, IEnumerable<Permission> permissions) { CheckPermissionsToUpdate(role, permissions); return base.SetGrantedPermissionsAsync(role, permissions); } private void CheckPermissionsToUpdate(Role role, IEnumerable<Permission> permissions) { if (role.Name == StaticRoleNames.Host.Admin && (!permissions.Any(p => p.Name == AppPermissions.Pages_Administration_Roles_Edit) || !permissions.Any(p => p.Name == AppPermissions.Pages_Administration_Users_ChangePermissions))) { throw new UserFriendlyException(L("YouCannotRemoveUserRolePermissionsFromAdminRole")); } } private string L(string name) { return _localizationManager.GetString(HeliosZeroConsts.LocalizationSourceName, name); } } }
apache-2.0
KCBootcamp/KCMyRestaurant
app/src/main/java/es/bhavishchandnani/myrestaurant/model/Allergens.java
1515
package es.bhavishchandnani.myrestaurant.model; import java.util.Arrays; import java.util.LinkedList; import es.bhavishchandnani.myrestaurant.R; public enum Allergens { CELERY(R.string.allergen_celery, R.drawable.ic_allergen_celery), GLUTEN(R.string.allergen_gluten, R.drawable.ic_allergen_gluten), CRUSTACEAN(R.string.allergen_crustacean, R.drawable.ic_allergen_crustacean), EGG(R.string.allergen_egg, R.drawable.ic_allergen_egg), FISH(R.string.allergen_fish, R.drawable.ic_allergen_fish), LUPIN(R.string.allergen_lupin, R.drawable.ic_allergen_lupin), MILK(R.string.allergen_milk, R.drawable.ic_allergen_milk), MOLLUSC(R.string.allergen_mollusc, R.drawable.ic_allergen_mollusc), MUSTARD(R.string.allergen_mustard, R.drawable.ic_allergen_mustard), NUTS(R.string.allergen_nuts, R.drawable.ic_allergen_nuts), PEANUTS(R.string.allergen_peanuts, R.drawable.ic_allergen_peanuts), SESAMESEAD(R.string.allergen_sesame_seed, R.drawable.ic_allergen_sesame_seed), SOYA(R.string.allergen_soya, R.drawable.ic_allergen_soya), SULPHITES(R.string.allergen_sulphites, R.drawable.ic_allergen_sulphites); public final int stringId; public final int iconId; Allergens(int stringId, int iconId) { this.stringId = stringId; this.iconId = iconId; } public static LinkedList<Allergens> getAllergens(){ LinkedList<Allergens> allergensList = new LinkedList<>(Arrays.asList(Allergens.values())); return allergensList; } }
apache-2.0
telefonicaid/netphony-network-protocols
src/main/java/es/tid/pce/pcep/objects/tlvs/SRCapabilityTLV.java
3114
package es.tid.pce.pcep.objects.tlvs; import es.tid.pce.pcep.objects.MalformedPCEPObjectException; import es.tid.pce.pcep.objects.ObjectParameters; import es.tid.protocol.commons.ByteHandler; /** * SR-PCE-CAPABILITY (Type 26) (deprecated) [RFC8664] * The SR-PCE-CAPABILITY TLV is an optional TLV for use in the OPEN Object to negotiate Segment Routing capability on the PCEP session. @author ayk */ public class SRCapabilityTLV extends PCEPTLV { /* * The format of the SR-PCE-CAPABILITY TLV is shown in the following figure: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type=TBD | Length=4 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Reserved | Flags | MSD | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Figure 1: SR-PCE-CAPABILITY TLV format The code point for the TLV type is to be defined by IANA. The TLV length is 4 octets. The 32-bit value is formatted as follows. The "Maximum SID Depth" (1 octet) field (MSD) specifies the maximum number of SIDs that a PCC is capable of imposing on a packet. The "Flags" (1 octet) and "Reserved" (2 octets) fields are currently unused, and MUST be set to zero and ignored on receipt. */ protected int MSD; public SRCapabilityTLV(){ this.TLVType=ObjectParameters.PCEP_TLV_TYPE_SR_CAPABILITY; } public SRCapabilityTLV(byte[] bytes, int offset)throws MalformedPCEPObjectException{ super(bytes,offset); decode(); } @Override public void encode() { int length=4; this.setTLVValueLength(length); this.tlv_bytes=new byte[this.getTotalTLVLength()]; encodeHeader(); int Zero = 0; int offset = 4; log.debug("Encoding SRCapabilityTLV: MSD ="+MSD+" bytes: "+this.getTotalTLVLength()); ByteHandler.IntToBuffer(0,offset * 8, 32,Zero,this.tlv_bytes); //Last octet MSD byte[] aux = new byte[1]; aux[0] = (byte)(MSD & 0x000000ff); System.arraycopy(aux, 0, tlv_bytes, 7, 1); log.debug("finished Encoding SRCapabilityTLV: MSD ="+MSD); } public void decode() { log.debug("Decoding SRCapabilityTLV"); int offset = 7; //TODO: No se si lo hace bien byte[] aux = new byte[1]; System.arraycopy(this.tlv_bytes,offset, aux, 0, 1); MSD = (aux[0]&0xff); log.debug("MSD decoded, value: "+MSD); } public int getMSD() { return this.MSD; } public void setMSD(int MSD) { this.MSD = MSD; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + MSD; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SRCapabilityTLV other = (SRCapabilityTLV) obj; if (MSD != other.MSD) return false; return true; } }
apache-2.0
stellar/gateway-server
src/github.com/stellar/gateway/compliance/handlers/request_handler_auth_test.go
26192
package handlers import ( "encoding/base64" "encoding/json" "errors" "net/http" "net/http/httptest" "net/url" "strings" "testing" "time" "crypto/sha256" "github.com/facebookgo/inject" . "github.com/smartystreets/goconvey/convey" "github.com/stellar/gateway/compliance/config" "github.com/stellar/gateway/db/entities" "github.com/stellar/gateway/mocks" "github.com/stellar/gateway/net" "github.com/stellar/gateway/test" "github.com/stellar/go/build" "github.com/stellar/go/clients/stellartoml" "github.com/stellar/go/protocols/compliance" "github.com/stellar/go/xdr" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "github.com/zenazn/goji/web" ) func TestRequestHandlerAuth(t *testing.T) { c := &config.Config{ NetworkPassphrase: "Test SDF Network ; September 2015", Keys: config.Keys{ // GBYJZW5XFAI6XV73H5SAIUYK6XZI4CGGVBUBO3ANA2SV7KKDAXTV6AEB SigningSeed: "SDWTLFPALQSP225BSMX7HPZ7ZEAYSUYNDLJ5QI3YGVBNRUIIELWH3XUV", }, } mockHTTPClient := new(mocks.MockHTTPClient) mockEntityManager := new(mocks.MockEntityManager) mockRepository := new(mocks.MockRepository) mockFederationResolver := new(mocks.MockFederationResolver) mockSignerVerifier := new(mocks.MockSignerVerifier) mockStellartomlResolver := new(mocks.MockStellartomlResolver) requestHandler := RequestHandler{} // Inject mocks var g inject.Graph err := g.Provide( &inject.Object{Value: &requestHandler}, &inject.Object{Value: c}, &inject.Object{Value: mockHTTPClient}, &inject.Object{Value: mockEntityManager}, &inject.Object{Value: mockRepository}, &inject.Object{Value: mockFederationResolver}, &inject.Object{Value: mockSignerVerifier}, &inject.Object{Value: mockStellartomlResolver}, &inject.Object{Value: &TestNonceGenerator{}}, ) if err != nil { panic(err) } if err := g.Populate(); err != nil { panic(err) } httpHandle := func(w http.ResponseWriter, r *http.Request) { requestHandler.HandlerAuth(web.C{}, w, r) } testServer := httptest.NewServer(http.HandlerFunc(httpHandle)) defer testServer.Close() Convey("Given auth request (no sanctions check)", t, func() { Convey("When data param is missing", func() { statusCode, response := net.GetResponse(testServer, url.Values{}) responseString := strings.TrimSpace(string(response)) assert.Equal(t, 400, statusCode) expected := test.StringToJSONMap(`{ "code": "invalid_parameter", "message": "Invalid parameter." }`) assert.Equal(t, expected, test.StringToJSONMap(responseString, "more_info")) }) Convey("When data is invalid", func() { params := url.Values{ "data": {"hello world"}, "sig": {"bad sig"}, } statusCode, response := net.GetResponse(testServer, params) responseString := strings.TrimSpace(string(response)) assert.Equal(t, 400, statusCode) expected := test.StringToJSONMap(`{ "code": "invalid_parameter", "message": "Invalid parameter." }`) assert.Equal(t, expected, test.StringToJSONMap(responseString, "more_info")) }) Convey("When sender's stellar.toml does not contain signing key", func() { mockStellartomlResolver.On( "GetStellarTomlByAddress", "alice*stellar.org", ).Return(&stellartoml.Response{}, nil).Once() attachHash := sha256.Sum256([]byte("{}")) txBuilder, err := build.Transaction( build.SourceAccount{"GAW77Z6GPWXSODJOMF5L5BMX6VMYGEJRKUNBC2CZ725JTQZORK74HQQD"}, build.Sequence{0}, build.TestNetwork, build.MemoHash{attachHash}, build.Payment( build.Destination{"GAMVF7G4GJC4A7JMFJWLUAEIBFQD5RT3DCB5DC5TJDEKQBBACQ4JZVEE"}, build.CreditAmount{"USD", "GAMVF7G4GJC4A7JMFJWLUAEIBFQD5RT3DCB5DC5TJDEKQBBACQ4JZVEE", "20"}, ), ) require.NoError(t, err) txB64, err := xdr.MarshalBase64(txBuilder.TX) require.NoError(t, err) authData := compliance.AuthData{ Sender: "alice*stellar.org", NeedInfo: false, Tx: txB64, AttachmentJSON: "{}", } authDataJSON, err := authData.Marshal() require.NoError(t, err) params := url.Values{ "data": {string(authDataJSON)}, "sig": {"ACamNqa0dF8gf97URhFVKWSD7fmvZKc5At+8dCLM5ySR0HsHySF3G2WuwYP2nKjeqjKmu3U9Z3+u1P10w1KBCA=="}, } statusCode, response := net.GetResponse(testServer, params) responseString := strings.TrimSpace(string(response)) assert.Equal(t, 400, statusCode) expected := test.StringToJSONMap(`{ "code": "invalid_parameter", "message": "Invalid parameter.", "data": { "name": "data.sender" } }`) assert.Equal(t, expected, test.StringToJSONMap(responseString, "more_info")) }) Convey("When signature is invalid", func() { mockStellartomlResolver.On( "GetStellarTomlByAddress", "alice*stellar.org", ).Return(&stellartoml.Response{ SigningKey: "GBYJZW5XFAI6XV73H5SAIUYK6XZI4CGGVBUBO3ANA2SV7KKDAXTV6AEB", }, nil).Once() attachment := compliance.Attachment{} attachHash, err := attachment.Hash() require.NoError(t, err) attachmentJSON, err := attachment.Marshal() require.NoError(t, err) txBuilder, err := build.Transaction( build.SourceAccount{"GAW77Z6GPWXSODJOMF5L5BMX6VMYGEJRKUNBC2CZ725JTQZORK74HQQD"}, build.Sequence{0}, build.TestNetwork, build.MemoHash{attachHash}, build.Payment( build.Destination{"GAMVF7G4GJC4A7JMFJWLUAEIBFQD5RT3DCB5DC5TJDEKQBBACQ4JZVEE"}, build.CreditAmount{"USD", "GAMVF7G4GJC4A7JMFJWLUAEIBFQD5RT3DCB5DC5TJDEKQBBACQ4JZVEE", "20"}, ), ) require.NoError(t, err) txB64, err := xdr.MarshalBase64(txBuilder.TX) require.NoError(t, err) authData := compliance.AuthData{ Sender: "alice*stellar.org", NeedInfo: false, Tx: txB64, AttachmentJSON: string(attachmentJSON), } authDataJSON, err := authData.Marshal() require.NoError(t, err) params := url.Values{ "data": {string(authDataJSON)}, "sig": {"ACamNqa0dF8gf97URhFVKWSD7fmvZKc5At+8dCLM5ySR0HsHySF3G2WuwYP2nKjeqjKmu3U9Z3+u1P10w1KBCA=="}, } mockSignerVerifier.On( "Verify", "GBYJZW5XFAI6XV73H5SAIUYK6XZI4CGGVBUBO3ANA2SV7KKDAXTV6AEB", mock.AnythingOfType("[]uint8"), mock.AnythingOfType("[]uint8"), ).Return(errors.New("Verify error")).Once() statusCode, response := net.GetResponse(testServer, params) responseString := strings.TrimSpace(string(response)) assert.Equal(t, 400, statusCode) expected := test.StringToJSONMap(`{ "code": "invalid_parameter", "message": "Invalid parameter.", "data": { "name": "sig" } }`) assert.Equal(t, expected, test.StringToJSONMap(responseString, "more_info")) }) Convey("When all params are valid", func() { attachment := compliance.Attachment{} attachHash, err := attachment.Hash() require.NoError(t, err) attachHashB64 := base64.StdEncoding.EncodeToString(attachHash[:]) attachmentJSON, err := attachment.Marshal() require.NoError(t, err) txBuilder, err := build.Transaction( build.SourceAccount{"GAW77Z6GPWXSODJOMF5L5BMX6VMYGEJRKUNBC2CZ725JTQZORK74HQQD"}, build.Sequence{0}, build.TestNetwork, build.MemoHash{attachHash}, build.Payment( build.Destination{"GAMVF7G4GJC4A7JMFJWLUAEIBFQD5RT3DCB5DC5TJDEKQBBACQ4JZVEE"}, build.CreditAmount{"USD", "GAMVF7G4GJC4A7JMFJWLUAEIBFQD5RT3DCB5DC5TJDEKQBBACQ4JZVEE", "20"}, ), ) require.NoError(t, err) txB64, err := xdr.MarshalBase64(txBuilder.TX) require.NoError(t, err) txHash, err := txBuilder.HashHex() require.NoError(t, err) authData := compliance.AuthData{ Sender: "alice*stellar.org", NeedInfo: false, Tx: txB64, AttachmentJSON: string(attachmentJSON), } authDataJSON, err := authData.Marshal() require.NoError(t, err) params := url.Values{ "data": {string(authDataJSON)}, "sig": {"ACamNqa0dF8gf97URhFVKWSD7fmvZKc5At+8dCLM5ySR0HsHySF3G2WuwYP2nKjeqjKmu3U9Z3+u1P10w1KBCA=="}, } mockStellartomlResolver.On( "GetStellarTomlByAddress", "alice*stellar.org", ).Return(&stellartoml.Response{ SigningKey: "GBYJZW5XFAI6XV73H5SAIUYK6XZI4CGGVBUBO3ANA2SV7KKDAXTV6AEB", }, nil).Once() mockSignerVerifier.On( "Verify", "GBYJZW5XFAI6XV73H5SAIUYK6XZI4CGGVBUBO3ANA2SV7KKDAXTV6AEB", mock.AnythingOfType("[]uint8"), mock.AnythingOfType("[]uint8"), ).Return(nil).Once() Convey("it returns AuthResponse", func() { authorizedTransaction := &entities.AuthorizedTransaction{ TransactionID: txHash, Memo: attachHashB64, TransactionXdr: txB64, Data: params["data"][0], } mockEntityManager.On( "Persist", mock.AnythingOfType("*entities.AuthorizedTransaction"), ).Run(func(args mock.Arguments) { value := args.Get(0).(*entities.AuthorizedTransaction) assert.Equal(t, authorizedTransaction.TransactionID, value.TransactionID) assert.Equal(t, authorizedTransaction.Memo, value.Memo) assert.Equal(t, authorizedTransaction.TransactionXdr, value.TransactionXdr) assert.WithinDuration(t, time.Now(), value.AuthorizedAt, 2*time.Second) assert.Equal(t, authorizedTransaction.Data, value.Data) }).Return(nil).Once() statusCode, response := net.GetResponse(testServer, params) responseString := strings.TrimSpace(string(response)) assert.Equal(t, 200, statusCode) expected := test.StringToJSONMap(`{ "info_status": "ok", "tx_status": "ok" }`) assert.Equal(t, expected, test.StringToJSONMap(responseString)) }) }) }) Convey("Given auth request (sanctions check)", t, func() { c.Callbacks = config.Callbacks{ Sanctions: "http://sanctions", AskUser: "http://ask_user", FetchInfo: "http://fetch_info", } senderInfo := compliance.SenderInfo{FirstName: "John", LastName: "Doe"} senderInfoMap, err := senderInfo.Map() require.NoError(t, err) attachment := compliance.Attachment{ Transaction: compliance.Transaction{ Route: "bob*acme.com", Note: "Happy birthday", SenderInfo: senderInfoMap, Extra: "extra", }, } attachHash, err := attachment.Hash() require.NoError(t, err) attachHashB64 := base64.StdEncoding.EncodeToString(attachHash[:]) txBuilder, err := build.Transaction( build.SourceAccount{"GAW77Z6GPWXSODJOMF5L5BMX6VMYGEJRKUNBC2CZ725JTQZORK74HQQD"}, build.Sequence{0}, build.TestNetwork, build.MemoHash{attachHash}, build.Payment( build.Destination{"GAMVF7G4GJC4A7JMFJWLUAEIBFQD5RT3DCB5DC5TJDEKQBBACQ4JZVEE"}, build.CreditAmount{"USD", "GAMVF7G4GJC4A7JMFJWLUAEIBFQD5RT3DCB5DC5TJDEKQBBACQ4JZVEE", "20"}, ), ) require.NoError(t, err) txB64, _ := xdr.MarshalBase64(txBuilder.TX) txHash, _ := txBuilder.HashHex() attachmentJSON, err := attachment.Marshal() require.NoError(t, err) senderInfoJSON, err := json.Marshal(attachment.Transaction.SenderInfo) require.NoError(t, err) Convey("When all params are valid (NeedInfo = `false`)", func() { authData := compliance.AuthData{ Sender: "alice*stellar.org", NeedInfo: false, Tx: txB64, AttachmentJSON: string(attachmentJSON), } authDataJSON, err := authData.Marshal() require.NoError(t, err) params := url.Values{ "data": {string(authDataJSON)}, "sig": {"Q2cQVOn/A+aOxrLLeUPwHmBm3LMvlfXN8tDHo4Oi6SxWWueMTDfRkC4XvRX4emLij+Npo7/GfrZ82CnT5yB5Dg=="}, } mockStellartomlResolver.On( "GetStellarTomlByAddress", "alice*stellar.org", ).Return(&stellartoml.Response{ SigningKey: "GBYJZW5XFAI6XV73H5SAIUYK6XZI4CGGVBUBO3ANA2SV7KKDAXTV6AEB", }, nil).Once() mockSignerVerifier.On( "Verify", "GBYJZW5XFAI6XV73H5SAIUYK6XZI4CGGVBUBO3ANA2SV7KKDAXTV6AEB", mock.AnythingOfType("[]uint8"), mock.AnythingOfType("[]uint8"), ).Return(nil).Once() Convey("when sanctions server returns forbidden it returns tx_status `denied`", func() { mockHTTPClient.On( "PostForm", "http://sanctions", url.Values{"sender": {string(senderInfoJSON)}}, ).Return( net.BuildHTTPResponse(403, "forbidden"), nil, ).Once() statusCode, response := net.GetResponse(testServer, params) responseString := strings.TrimSpace(string(response)) assert.Equal(t, 403, statusCode) expected := test.StringToJSONMap(`{ "info_status": "ok", "tx_status": "denied" }`) assert.Equal(t, expected, test.StringToJSONMap(responseString)) }) Convey("when sanctions server returns bad request it returns tx_status `error`", func() { mockHTTPClient.On( "PostForm", "http://sanctions", url.Values{"sender": {string(senderInfoJSON)}}, ).Return( net.BuildHTTPResponse(400, "{\"error\": \"Invalid name\"}"), nil, ).Once() statusCode, response := net.GetResponse(testServer, params) responseString := strings.TrimSpace(string(response)) assert.Equal(t, 400, statusCode) expected := test.StringToJSONMap(`{ "info_status": "ok", "tx_status": "error", "error": "Invalid name" }`) assert.Equal(t, expected, test.StringToJSONMap(responseString)) }) Convey("when sanctions server returns accepted it returns tx_status `pending`", func() { mockHTTPClient.On( "PostForm", "http://sanctions", url.Values{"sender": {string(senderInfoJSON)}}, ).Return( net.BuildHTTPResponse(202, "pending"), nil, ).Once() statusCode, response := net.GetResponse(testServer, params) responseString := strings.TrimSpace(string(response)) assert.Equal(t, 202, statusCode) expected := test.StringToJSONMap(`{ "info_status": "ok", "tx_status": "pending", "pending": 600 }`) assert.Equal(t, expected, test.StringToJSONMap(responseString)) }) Convey("when sanctions server returns ok it returns tx_status `ok` and persists transaction", func() { mockHTTPClient.On( "PostForm", "http://sanctions", url.Values{"sender": {string(senderInfoJSON)}}, ).Return( net.BuildHTTPResponse(200, "ok"), nil, ).Once() authorizedTransaction := &entities.AuthorizedTransaction{ TransactionID: txHash, Memo: attachHashB64, TransactionXdr: txB64, Data: params["data"][0], } mockEntityManager.On( "Persist", mock.AnythingOfType("*entities.AuthorizedTransaction"), ).Run(func(args mock.Arguments) { value := args.Get(0).(*entities.AuthorizedTransaction) assert.Equal(t, authorizedTransaction.TransactionID, value.TransactionID) assert.Equal(t, authorizedTransaction.Memo, value.Memo) assert.Equal(t, authorizedTransaction.TransactionXdr, value.TransactionXdr) assert.WithinDuration(t, time.Now(), value.AuthorizedAt, 2*time.Second) assert.Equal(t, authorizedTransaction.Data, value.Data) }).Return(nil).Once() statusCode, response := net.GetResponse(testServer, params) responseString := strings.TrimSpace(string(response)) assert.Equal(t, 200, statusCode) expected := test.StringToJSONMap(`{ "info_status": "ok", "tx_status": "ok" }`) assert.Equal(t, expected, test.StringToJSONMap(responseString)) }) }) Convey("When all params are valid (NeedInfo = `true`)", func() { authData := compliance.AuthData{ Sender: "alice*stellar.org", NeedInfo: true, Tx: txB64, AttachmentJSON: string(attachmentJSON), } authDataJSON, err := authData.Marshal() require.NoError(t, err) params := url.Values{ "data": {string(authDataJSON)}, "sig": {"Q2cQVOn/A+aOxrLLeUPwHmBm3LMvlfXN8tDHo4Oi6SxWWueMTDfRkC4XvRX4emLij+Npo7/GfrZ82CnT5yB5Dg=="}, } mockStellartomlResolver.On( "GetStellarTomlByAddress", "alice*stellar.org", ).Return(&stellartoml.Response{ SigningKey: "GBYJZW5XFAI6XV73H5SAIUYK6XZI4CGGVBUBO3ANA2SV7KKDAXTV6AEB", }, nil).Once() mockSignerVerifier.On( "Verify", "GBYJZW5XFAI6XV73H5SAIUYK6XZI4CGGVBUBO3ANA2SV7KKDAXTV6AEB", mock.AnythingOfType("[]uint8"), mock.AnythingOfType("[]uint8"), ).Return(nil).Once() // Make sanctions checks successful (tested in the previous test case) mockHTTPClient.On( "PostForm", "http://sanctions", url.Values{ "sender": {string(senderInfoJSON)}, }, ).Return( net.BuildHTTPResponse(200, "ok"), nil, ).Once() Convey("when ask_user server returns forbidden it returns info_status `denied`", func() { mockHTTPClient.On( "PostForm", "http://ask_user", url.Values{ "sender": {string(senderInfoJSON)}, "note": {attachment.Transaction.Note}, "amount": {"20.0000000"}, "asset_code": {"USD"}, "asset_issuer": {"GAMVF7G4GJC4A7JMFJWLUAEIBFQD5RT3DCB5DC5TJDEKQBBACQ4JZVEE"}, }, ).Return( net.BuildHTTPResponse(403, "forbidden"), nil, ).Once() statusCode, response := net.GetResponse(testServer, params) responseString := strings.TrimSpace(string(response)) assert.Equal(t, 403, statusCode) expected := test.StringToJSONMap(`{ "info_status": "denied", "tx_status": "ok" }`) assert.Equal(t, expected, test.StringToJSONMap(responseString)) }) Convey("when ask_user server returns bad request it returns info_status `error`", func() { mockHTTPClient.On( "PostForm", "http://ask_user", url.Values{ "sender": {string(senderInfoJSON)}, "note": {attachment.Transaction.Note}, "amount": {"20.0000000"}, "asset_code": {"USD"}, "asset_issuer": {"GAMVF7G4GJC4A7JMFJWLUAEIBFQD5RT3DCB5DC5TJDEKQBBACQ4JZVEE"}, }, ).Return( net.BuildHTTPResponse(400, "{\"error\": \"Invalid name\"}"), nil, ).Once() statusCode, response := net.GetResponse(testServer, params) responseString := strings.TrimSpace(string(response)) assert.Equal(t, 400, statusCode) expected := test.StringToJSONMap(`{ "info_status": "error", "tx_status": "ok", "error": "Invalid name" }`) assert.Equal(t, expected, test.StringToJSONMap(responseString)) }) Convey("when ask_user server returns pending it returns info_status `pending`", func() { mockHTTPClient.On( "PostForm", "http://ask_user", url.Values{ "sender": {string(senderInfoJSON)}, "note": {attachment.Transaction.Note}, "amount": {"20.0000000"}, "asset_code": {"USD"}, "asset_issuer": {"GAMVF7G4GJC4A7JMFJWLUAEIBFQD5RT3DCB5DC5TJDEKQBBACQ4JZVEE"}, }, ).Return( net.BuildHTTPResponse(202, "{\"pending\": 300}"), nil, ).Once() statusCode, response := net.GetResponse(testServer, params) responseString := strings.TrimSpace(string(response)) assert.Equal(t, 202, statusCode) expected := test.StringToJSONMap(`{ "info_status": "pending", "tx_status": "ok", "pending": 300 }`) assert.Equal(t, expected, test.StringToJSONMap(responseString)) }) Convey("when ask_user server returns pending but invalid response body it returns info_status `pending` (600 seconds)", func() { mockHTTPClient.On( "PostForm", "http://ask_user", url.Values{ "sender": {string(senderInfoJSON)}, "note": {attachment.Transaction.Note}, "amount": {"20.0000000"}, "asset_code": {"USD"}, "asset_issuer": {"GAMVF7G4GJC4A7JMFJWLUAEIBFQD5RT3DCB5DC5TJDEKQBBACQ4JZVEE"}, }, ).Return( net.BuildHTTPResponse(202, "pending"), nil, ).Once() statusCode, response := net.GetResponse(testServer, params) responseString := strings.TrimSpace(string(response)) assert.Equal(t, 202, statusCode) expected := test.StringToJSONMap(`{ "info_status": "pending", "tx_status": "ok", "pending": 600 }`) assert.Equal(t, expected, test.StringToJSONMap(responseString)) }) Convey("when ask_user server returns ok it returns info_status `ok` and DestInfo and persists transaction", func() { mockHTTPClient.On( "PostForm", "http://ask_user", url.Values{ "sender": {string(senderInfoJSON)}, "note": {attachment.Transaction.Note}, "amount": {"20.0000000"}, "asset_code": {"USD"}, "asset_issuer": {"GAMVF7G4GJC4A7JMFJWLUAEIBFQD5RT3DCB5DC5TJDEKQBBACQ4JZVEE"}, }, ).Return( net.BuildHTTPResponse(200, "ok"), nil, ).Once() mockHTTPClient.On( "PostForm", "http://fetch_info", url.Values{"address": {"bob*acme.com"}}, ).Return( net.BuildHTTPResponse(200, "user data"), nil, ).Once() authorizedTransaction := &entities.AuthorizedTransaction{ TransactionID: txHash, Memo: attachHashB64, TransactionXdr: txB64, Data: params["data"][0], } mockEntityManager.On( "Persist", mock.AnythingOfType("*entities.AuthorizedTransaction"), ).Run(func(args mock.Arguments) { value := args.Get(0).(*entities.AuthorizedTransaction) assert.Equal(t, authorizedTransaction.TransactionID, value.TransactionID) assert.Equal(t, authorizedTransaction.Memo, value.Memo) assert.Equal(t, authorizedTransaction.TransactionXdr, value.TransactionXdr) assert.WithinDuration(t, time.Now(), value.AuthorizedAt, 2*time.Second) assert.Equal(t, authorizedTransaction.Data, value.Data) }).Return(nil).Once() statusCode, response := net.GetResponse(testServer, params) responseString := strings.TrimSpace(string(response)) assert.Equal(t, 200, statusCode) expected := test.StringToJSONMap(`{ "info_status": "ok", "tx_status": "ok", "dest_info": "user data" }`) assert.Equal(t, expected, test.StringToJSONMap(responseString)) }) Convey("When no callbacks.ask_user server", func() { c.Callbacks.AskUser = "" Convey("when FI allowed it returns info_status = `ok` and DestInfo and persists transaction", func() { mockRepository.On( "GetAllowedFiByDomain", "stellar.org", // sender = `alice*stellar.org` ).Return( &entities.AllowedFi{}, // It just returns existing record nil, ).Once() mockHTTPClient.On( "PostForm", "http://fetch_info", url.Values{"address": {"bob*acme.com"}}, ).Return( net.BuildHTTPResponse(200, "user data"), nil, ).Once() authorizedTransaction := &entities.AuthorizedTransaction{ TransactionID: txHash, Memo: attachHashB64, TransactionXdr: txB64, Data: params["data"][0], } mockEntityManager.On( "Persist", mock.AnythingOfType("*entities.AuthorizedTransaction"), ).Run(func(args mock.Arguments) { value := args.Get(0).(*entities.AuthorizedTransaction) assert.Equal(t, authorizedTransaction.TransactionID, value.TransactionID) assert.Equal(t, authorizedTransaction.Memo, value.Memo) assert.Equal(t, authorizedTransaction.TransactionXdr, value.TransactionXdr) assert.WithinDuration(t, time.Now(), value.AuthorizedAt, 2*time.Second) assert.Equal(t, authorizedTransaction.Data, value.Data) }).Return(nil).Once() statusCode, response := net.GetResponse(testServer, params) responseString := strings.TrimSpace(string(response)) assert.Equal(t, 200, statusCode) expected := test.StringToJSONMap(`{ "info_status": "ok", "tx_status": "ok", "dest_info": "user data" }`) assert.Equal(t, expected, test.StringToJSONMap(responseString)) }) Convey("when FI not allowed but User is allowed it returns info_status = `ok` and DestInfo and persists transaction", func() { mockRepository.On( "GetAllowedFiByDomain", "stellar.org", // sender = `alice*stellar.org` ).Return( nil, nil, ).Once() mockRepository.On( "GetAllowedUserByDomainAndUserID", "stellar.org", // sender = `alice*stellar.org` "alice", ).Return( &entities.AllowedUser{}, nil, ).Once() mockHTTPClient.On( "PostForm", "http://fetch_info", url.Values{"address": {"bob*acme.com"}}, ).Return( net.BuildHTTPResponse(200, "user data"), nil, ).Once() authorizedTransaction := &entities.AuthorizedTransaction{ TransactionID: txHash, Memo: attachHashB64, TransactionXdr: txB64, Data: params["data"][0], } mockEntityManager.On( "Persist", mock.AnythingOfType("*entities.AuthorizedTransaction"), ).Run(func(args mock.Arguments) { value := args.Get(0).(*entities.AuthorizedTransaction) assert.Equal(t, authorizedTransaction.TransactionID, value.TransactionID) assert.Equal(t, authorizedTransaction.Memo, value.Memo) assert.Equal(t, authorizedTransaction.TransactionXdr, value.TransactionXdr) assert.WithinDuration(t, time.Now(), value.AuthorizedAt, 2*time.Second) assert.Equal(t, authorizedTransaction.Data, value.Data) }).Return(nil).Once() statusCode, response := net.GetResponse(testServer, params) responseString := strings.TrimSpace(string(response)) assert.Equal(t, 200, statusCode) expected := test.StringToJSONMap(`{ "info_status": "ok", "tx_status": "ok", "dest_info": "user data" }`) assert.Equal(t, expected, test.StringToJSONMap(responseString)) }) Convey("when neither FI nor User is allowed it returns info_status = `denied`", func() { mockRepository.On( "GetAllowedFiByDomain", "stellar.org", // sender = `alice*stellar.org` ).Return( nil, nil, ).Once() mockRepository.On( "GetAllowedUserByDomainAndUserID", "stellar.org", // sender = `alice*stellar.org` "alice", ).Return( nil, nil, ).Once() statusCode, response := net.GetResponse(testServer, params) responseString := strings.TrimSpace(string(response)) assert.Equal(t, 403, statusCode) expected := test.StringToJSONMap(`{ "info_status": "denied", "tx_status": "ok" }`) assert.Equal(t, expected, test.StringToJSONMap(responseString)) }) }) }) }) }
apache-2.0
cedral/aws-sdk-cpp
aws-cpp-sdk-ec2/source/model/LaunchTemplateElasticInferenceAcceleratorResponse.cpp
2860
/* * 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. */ #include <aws/ec2/model/LaunchTemplateElasticInferenceAcceleratorResponse.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace EC2 { namespace Model { LaunchTemplateElasticInferenceAcceleratorResponse::LaunchTemplateElasticInferenceAcceleratorResponse() : m_typeHasBeenSet(false), m_count(0), m_countHasBeenSet(false) { } LaunchTemplateElasticInferenceAcceleratorResponse::LaunchTemplateElasticInferenceAcceleratorResponse(const XmlNode& xmlNode) : m_typeHasBeenSet(false), m_count(0), m_countHasBeenSet(false) { *this = xmlNode; } LaunchTemplateElasticInferenceAcceleratorResponse& LaunchTemplateElasticInferenceAcceleratorResponse::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode typeNode = resultNode.FirstChild("type"); if(!typeNode.IsNull()) { m_type = Aws::Utils::Xml::DecodeEscapedXmlText(typeNode.GetText()); m_typeHasBeenSet = true; } XmlNode countNode = resultNode.FirstChild("count"); if(!countNode.IsNull()) { m_count = StringUtils::ConvertToInt32(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(countNode.GetText()).c_str()).c_str()); m_countHasBeenSet = true; } } return *this; } void LaunchTemplateElasticInferenceAcceleratorResponse::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_typeHasBeenSet) { oStream << location << index << locationValue << ".Type=" << StringUtils::URLEncode(m_type.c_str()) << "&"; } if(m_countHasBeenSet) { oStream << location << index << locationValue << ".Count=" << m_count << "&"; } } void LaunchTemplateElasticInferenceAcceleratorResponse::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_typeHasBeenSet) { oStream << location << ".Type=" << StringUtils::URLEncode(m_type.c_str()) << "&"; } if(m_countHasBeenSet) { oStream << location << ".Count=" << m_count << "&"; } } } // namespace Model } // namespace EC2 } // namespace Aws
apache-2.0
snsv88/beta_lps
js/home.js
770
$(document).ready(function() { /**** GESTIONE SLIDER ORIZZONTALE ****/ //$('.cont-slider').flexslider({ $('#sliderhome').flexslider({ animation: "slide", animationLoop: true, directionNav: true, controlNav: false, itemWidth: 0, itemMargin : 0, smoothHeight: true, controlsContainer: ".flex-container", start: function(slider) { $('.total-slides').text(slider.count); $('.current-slide').text(slider.currentSlide + 1); }, after: function(slider) { $('.current-slide').text(slider.currentSlide + 1); } }); /**** FINE GESTIONE SLIDER ORIZZONTALE ****/ });
apache-2.0
brutella/hc
characteristic/relative_humidity_humidifier_threshold.go
563
// THIS FILE IS AUTO-GENERATED package characteristic const TypeRelativeHumidityHumidifierThreshold = "CA" type RelativeHumidityHumidifierThreshold struct { *Float } func NewRelativeHumidityHumidifierThreshold() *RelativeHumidityHumidifierThreshold { char := NewFloat(TypeRelativeHumidityHumidifierThreshold) char.Format = FormatFloat char.Perms = []string{PermRead, PermWrite, PermEvents} char.SetMinValue(0) char.SetMaxValue(100) char.SetStepValue(1) char.SetValue(0) char.Unit = UnitPercentage return &RelativeHumidityHumidifierThreshold{char} }
apache-2.0
SandishKumarHN/datacollector
basic-lib/src/main/java/com/streamsets/pipeline/lib/microservice/ResponseConfigBean.java
1759
/* * Copyright 2018 StreamSets Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.streamsets.pipeline.lib.microservice; import com.streamsets.pipeline.api.ConfigDef; import com.streamsets.pipeline.api.ConfigDefBean; import com.streamsets.pipeline.api.ValueChooserModel; import com.streamsets.pipeline.config.DataFormat; import com.streamsets.pipeline.stage.destination.lib.DataGeneratorFormatConfig; public class ResponseConfigBean { @ConfigDef( required = false, type = ConfigDef.Type.BOOLEAN, defaultValue = "false", label = "Send Raw Response", description = "Send raw response back to the originating client without an envelope", displayPosition = 210, group = "#0" ) public boolean sendRawResponse; @ConfigDef( required = true, type = ConfigDef.Type.MODEL, label = "Data Format", defaultValue = "JSON", description = "HTTP payload data format", displayPosition = 220, group = "#0" ) @ValueChooserModel(ResponseDataFormatChooserValues.class) public DataFormat dataFormat = DataFormat.JSON; @ConfigDefBean(groups = {"#0"}) public DataGeneratorFormatConfig dataGeneratorFormatConfig = new DataGeneratorFormatConfig(); }
apache-2.0
josdem/client-control
appControl/src/main/java/com/all/app/AppModule.java
13180
/** Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2011 Eric Haddad Koenig 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.all.app; /** * A phase is a simple process that runs linearly and is controlled by an * Application.<br> * * The idea is that a phase runs and does some work optionally will put more * phases in the Application and at the end of its execution just returns and * then the next phase would be launched. <br> * * If threading this phase is required or if a window is shown and we require * user to close the window to continue the phases then we need to add some * manual JooJoo This is easily done using either semaphores or old java. * * Example: * * <code> * public void doPhase(){ * final Object lock = new Object(); * JFrame frame = new JFrame(); * frame.setVisible(true); * ... * frame.addWindowListener(new WindowAdapter(){ * public void windowClosed(WindowEvent evt){ * synchronized(lock){ * lock.notifyAll(); * } * } * }); * synchronized(lock){ * try{ * lock.wait(); * }catch(InterruptedException e){} * } * } * </code> * * Or same shit less code: * * <code> * public void doPhase(){ * final Semaphore lock = new Semaphore(0); * JFrame frame = new JFrame(); * frame.setVisible(true); * ... * frame.addWindowListener(new WindowAdapter(){ * public void windowClosed(WindowEvent evt){ * semaphore.release(); * } * }); * try{ * semaphore.aquire(); * }catch(InterruptedException e){} * } * </code> * */ public interface AppModule { void load(); void activate(); void destroy(); }
apache-2.0
iraupph/tictactoe-android
AndEngineGLES2/src/org/andengine/util/time/TimeConstants.java
2196
package org.andengine.util.time; /** * (c) 2010 Nicolas Gramlich (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:49:25 - 26.07.2010 */ public interface TimeConstants { // =========================================================== // Constants // =========================================================== public static final int MONTHS_PER_YEAR = 12; public static final int DAYS_PER_WEEK = 7; public static final int DAYS_PER_MONTH = 30; public static final int HOURS_PER_DAY = 24; public static final int MINUTES_PER_HOUR = 60; public static final int MILLISECONDS_PER_SECOND = 1000; public static final int MICROSECONDS_PER_SECOND = 1000 * 1000; public static final long NANOSECONDS_PER_SECOND = 1000 * 1000 * 1000; public static final long MICROSECONDS_PER_MILLISECOND = MICROSECONDS_PER_SECOND / MILLISECONDS_PER_SECOND; public static final long NANOSECONDS_PER_MICROSECOND = NANOSECONDS_PER_SECOND / MICROSECONDS_PER_SECOND; public static final long NANOSECONDS_PER_MILLISECOND = NANOSECONDS_PER_SECOND / MILLISECONDS_PER_SECOND; public static final float SECONDS_PER_NANOSECOND = 1f / NANOSECONDS_PER_SECOND; public static final float MICROSECONDS_PER_NANOSECOND = 1f / NANOSECONDS_PER_MICROSECOND; public static final float MILLISECONDS_PER_NANOSECOND = 1f / NANOSECONDS_PER_MILLISECOND; public static final float SECONDS_PER_MICROSECOND = 1f / MICROSECONDS_PER_SECOND; public static final float MILLISECONDS_PER_MICROSECOND = 1f / MICROSECONDS_PER_MILLISECOND; public static final float SECONDS_PER_MILLISECOND = 1f / MILLISECONDS_PER_SECOND; public static final int SECONDS_PER_MINUTE = 60; public static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR; public static final int SECONDS_PER_DAY = SECONDS_PER_HOUR * HOURS_PER_DAY; public static final int SECONDS_PER_WEEK = SECONDS_PER_DAY * DAYS_PER_WEEK; public static final int SECONDS_PER_MONTH = SECONDS_PER_DAY * DAYS_PER_MONTH; public static final int SECONDS_PER_YEAR = SECONDS_PER_MONTH * MONTHS_PER_YEAR; // =========================================================== // Methods // =========================================================== }
apache-2.0
iryndin/lunchapp
src/main/java/net/iryndin/lunchapp/error/EntityDeletedException.java
241
package net.iryndin.lunchapp.error; /** * This exception is thrown when entity is deleted */ public class EntityDeletedException extends LunchAppBasicException { public EntityDeletedException(String msg) { super(msg); } }
apache-2.0
lukaciko/cropper
cropper/src/main/java/com/cropper/lib/HighlightView.java
13934
/* * The contents of this file have been modified. * * Copyright (C) 2007 The Android Open Source Project * Copyright 2015 Luka Cindro * * 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.cropper.lib; import android.content.res.Resources; import android.graphics.*; import android.graphics.drawable.Drawable; import android.view.View; // This class is used by CropImageActivity to display a highlighted cropping rectangle // overlayed with the image. There are two coordinate spaces in use. One is // image, another is screen. computeLayout() uses mMatrix to map from image // space to screen space. class HighlightView { @SuppressWarnings("unused") private static final String TAG = "HighlightView"; View mContext; // The View displaying the image. @SuppressWarnings("PointlessBitwiseExpression") public static final int GROW_NONE = (1 << 0); public static final int GROW_LEFT_EDGE = (1 << 1); public static final int GROW_RIGHT_EDGE = (1 << 2); public static final int GROW_TOP_EDGE = (1 << 3); public static final int GROW_BOTTOM_EDGE = (1 << 4); public static final int MOVE = (1 << 5); enum ModifyMode { None, Move, Grow } private ModifyMode mMode = ModifyMode.None; Rect mDrawRect; // in screen space private RectF mImageRect; // in image space RectF mCropRect; // in image space Matrix mMatrix; private boolean mMaintainAspectRatio = false; private float mInitialAspectRatio; private boolean mCircle = false; private Drawable mResizeDrawableWidth; private Drawable mResizeDrawableHeight; private Drawable mResizeDrawableDiagonal; private final Paint mFocusPaint = new Paint(); private final Paint mNoFocusPaint = new Paint(); private final Paint mOutlinePaint = new Paint(); private int highlightColor; private int highlightSelectedColor; public HighlightView(View ctx) { mContext = ctx; } private void init(int highlightColor, int highlightSelectedColor, int verticalIcon, int horizontalIcon) { Resources resources = mContext.getResources(); mResizeDrawableWidth = resources.getDrawable(verticalIcon); mResizeDrawableHeight = resources.getDrawable(horizontalIcon); mResizeDrawableDiagonal = resources.getDrawable(horizontalIcon); this.highlightColor = mContext.getResources().getColor(highlightColor); this.highlightSelectedColor = mContext.getResources().getColor(highlightSelectedColor); } boolean mIsFocused; boolean mHidden; public boolean hasFocus() { return mIsFocused; } public void setFocus(boolean f) { mIsFocused = f; } public void setHidden(boolean hidden) { mHidden = hidden; } protected void draw(Canvas canvas) { if (mHidden) { return; } Path path = new Path(); if (!hasFocus()) { mOutlinePaint.setColor(highlightColor); canvas.drawRect(mDrawRect, mOutlinePaint); } else { Rect viewDrawingRect = new Rect(); mContext.getDrawingRect(viewDrawingRect); if (mCircle) { canvas.save(); float width = mDrawRect.width(); float height = mDrawRect.height(); path.addCircle(mDrawRect.left + (width / 2), mDrawRect.top + (height / 2), width / 2, Path.Direction.CW); mOutlinePaint.setColor(highlightSelectedColor); canvas.clipPath(path, Region.Op.DIFFERENCE); canvas.drawRect(viewDrawingRect, hasFocus() ? mFocusPaint : mNoFocusPaint); canvas.restore(); } else { Rect topRect = new Rect(viewDrawingRect.left, viewDrawingRect.top, viewDrawingRect.right, mDrawRect.top); if (topRect.width() > 0 && topRect.height() > 0) { canvas.drawRect(topRect, hasFocus() ? mFocusPaint : mNoFocusPaint); } Rect bottomRect = new Rect(viewDrawingRect.left, mDrawRect.bottom, viewDrawingRect.right, viewDrawingRect.bottom); if (bottomRect.width() > 0 && bottomRect.height() > 0) { canvas.drawRect(bottomRect, hasFocus() ? mFocusPaint : mNoFocusPaint); } Rect leftRect = new Rect(viewDrawingRect.left, topRect.bottom, mDrawRect.left, bottomRect.top); if (leftRect.width() > 0 && leftRect.height() > 0) { canvas.drawRect(leftRect, hasFocus() ? mFocusPaint : mNoFocusPaint); } Rect rightRect = new Rect(mDrawRect.right, topRect.bottom, viewDrawingRect.right, bottomRect.top); if (rightRect.width() > 0 && rightRect.height() > 0) { canvas.drawRect(rightRect, hasFocus() ? mFocusPaint : mNoFocusPaint); } path.addRect(new RectF(mDrawRect), Path.Direction.CW); mOutlinePaint.setColor(highlightSelectedColor); } canvas.drawPath(path, mOutlinePaint); if (mMode == ModifyMode.Move || mMode == ModifyMode.Grow) { if (mCircle) { int width = mResizeDrawableDiagonal.getIntrinsicWidth(); int height = mResizeDrawableDiagonal.getIntrinsicHeight(); int d = (int) Math.round(Math.cos(/*45deg*/Math.PI / 4D) * (mDrawRect.width() / 2D)); int x = mDrawRect.left + (mDrawRect.width() / 2) + d - width / 2; int y = mDrawRect.top + (mDrawRect.height() / 2) - d - height / 2; mResizeDrawableDiagonal.setBounds(x, y, x + mResizeDrawableDiagonal.getIntrinsicWidth(), y + mResizeDrawableDiagonal.getIntrinsicHeight()); mResizeDrawableDiagonal.draw(canvas); } else { int left = mDrawRect.left + 1; int right = mDrawRect.right + 1; int top = mDrawRect.top + 4; int bottom = mDrawRect.bottom + 3; int widthWidth = mResizeDrawableWidth.getIntrinsicWidth() / 2; int widthHeight = mResizeDrawableWidth.getIntrinsicHeight() / 2; int heightHeight = mResizeDrawableHeight.getIntrinsicHeight() / 2; int heightWidth = mResizeDrawableHeight.getIntrinsicWidth() / 2; int xMiddle = mDrawRect.left + ((mDrawRect.right - mDrawRect.left) / 2); int yMiddle = mDrawRect.top + ((mDrawRect.bottom - mDrawRect.top) / 2); mResizeDrawableWidth.setBounds(left - widthWidth, yMiddle - widthHeight, left + widthWidth, yMiddle + widthHeight); mResizeDrawableWidth.draw(canvas); mResizeDrawableWidth.setBounds(right - widthWidth, yMiddle - widthHeight, right + widthWidth, yMiddle + widthHeight); mResizeDrawableWidth.draw(canvas); mResizeDrawableHeight.setBounds(xMiddle - heightWidth, top - heightHeight, xMiddle + heightWidth, top + heightHeight); mResizeDrawableHeight.draw(canvas); mResizeDrawableHeight.setBounds(xMiddle - heightWidth, bottom - heightHeight, xMiddle + heightWidth, bottom + heightHeight); mResizeDrawableHeight.draw(canvas); } } } } public void setMode(ModifyMode mode) { if (mode != mMode) { mMode = mode; mContext.invalidate(); } } // Determines which edges are hit by touching at (x, y). public int getHit(float x, float y) { Rect r = computeLayout(); final float hysteresis = 20F; int retval = GROW_NONE; if (mCircle) { float distX = x - r.centerX(); float distY = y - r.centerY(); int distanceFromCenter = (int) Math.sqrt(distX * distX + distY * distY); int radius = mDrawRect.width() / 2; int delta = distanceFromCenter - radius; if (Math.abs(delta) <= hysteresis) { if (Math.abs(distY) > Math.abs(distX)) { if (distY < 0) { retval = GROW_TOP_EDGE; } else { retval = GROW_BOTTOM_EDGE; } } else { if (distX < 0) { retval = GROW_LEFT_EDGE; } else { retval = GROW_RIGHT_EDGE; } } } else if (distanceFromCenter < radius) { retval = MOVE; } else { retval = GROW_NONE; } } else { // verticalCheck makes sure the position is between the top and // the bottom edge (with some tolerance). Similar for horizCheck. boolean verticalCheck = (y >= r.top - hysteresis) && (y < r.bottom + hysteresis); boolean horizCheck = (x >= r.left - hysteresis) && (x < r.right + hysteresis); // Check whether the position is near some edge(s). if ((Math.abs(r.left - x) < hysteresis) && verticalCheck) { retval |= GROW_LEFT_EDGE; } if ((Math.abs(r.right - x) < hysteresis) && verticalCheck) { retval |= GROW_RIGHT_EDGE; } if ((Math.abs(r.top - y) < hysteresis) && horizCheck) { retval |= GROW_TOP_EDGE; } if ((Math.abs(r.bottom - y) < hysteresis) && horizCheck) { retval |= GROW_BOTTOM_EDGE; } // Not near any edge but inside the rectangle: move. if (retval == GROW_NONE && r.contains((int) x, (int) y)) { retval = MOVE; } } return retval; } // Handles motion (dx, dy) in screen space. // The "edge" parameter specifies which edges the user is dragging. void handleMotion(int edge, float dx, float dy) { Rect r = computeLayout(); if (edge == GROW_NONE) { return; } else if (edge == MOVE) { // Convert to image space before sending to moveBy(). moveBy(dx * (mCropRect.width() / r.width()), dy * (mCropRect.height() / r.height())); } else { if (((GROW_LEFT_EDGE | GROW_RIGHT_EDGE) & edge) == 0) { dx = 0; } if (((GROW_TOP_EDGE | GROW_BOTTOM_EDGE) & edge) == 0) { dy = 0; } // Convert to image space before sending to growBy(). float xDelta = dx * (mCropRect.width() / r.width()); float yDelta = dy * (mCropRect.height() / r.height()); growBy((((edge & GROW_LEFT_EDGE) != 0) ? -1 : 1) * xDelta, (((edge & GROW_TOP_EDGE) != 0) ? -1 : 1) * yDelta); } } // Grows the cropping rectange by (dx, dy) in image space. void moveBy(float dx, float dy) { Rect invalRect = new Rect(mDrawRect); mCropRect.offset(dx, dy); // Put the cropping rectangle inside image rectangle. mCropRect.offset( Math.max(0, mImageRect.left - mCropRect.left), Math.max(0, mImageRect.top - mCropRect.top)); mCropRect.offset( Math.min(0, mImageRect.right - mCropRect.right), Math.min(0, mImageRect.bottom - mCropRect.bottom)); mDrawRect = computeLayout(); invalRect.union(mDrawRect); invalRect.inset(-10, -10); mContext.invalidate(invalRect); } // Grows the cropping rectange by (dx, dy) in image space. public void growBy(float dx, float dy) { if (mMaintainAspectRatio) { if (dx != 0) { dy = dx / mInitialAspectRatio; } else if (dy != 0) { dx = dy * mInitialAspectRatio; } } // Don't let the cropping rectangle grow too fast. // Grow at most half of the difference between the image rectangle and // the cropping rectangle. RectF r = new RectF(mCropRect); if (dx > 0F && r.width() + 2 * dx > mImageRect.width()) { float adjustment = (mImageRect.width() - r.width()) / 2F; dx = adjustment; if (mMaintainAspectRatio) { dy = dx / mInitialAspectRatio; } } if (dy > 0F && r.height() + 2 * dy > mImageRect.height()) { float adjustment = (mImageRect.height() - r.height()) / 2F; dy = adjustment; if (mMaintainAspectRatio) { dx = dy * mInitialAspectRatio; } } r.inset(-dx, -dy); // Don't let the cropping rectangle shrink too fast. final float widthCap = 25F; if (r.width() < widthCap) { r.inset(-(widthCap - r.width()) / 2F, 0F); } float heightCap = mMaintainAspectRatio ? (widthCap / mInitialAspectRatio) : widthCap; if (r.height() < heightCap) { r.inset(0F, -(heightCap - r.height()) / 2F); } // Put the cropping rectangle inside the image rectangle. if (r.left < mImageRect.left) { r.offset(mImageRect.left - r.left, 0F); } else if (r.right > mImageRect.right) { r.offset(-(r.right - mImageRect.right), 0); } if (r.top < mImageRect.top) { r.offset(0F, mImageRect.top - r.top); } else if (r.bottom > mImageRect.bottom) { r.offset(0F, -(r.bottom - mImageRect.bottom)); } mCropRect.set(r); mDrawRect = computeLayout(); mContext.invalidate(); } // Returns the cropping rectangle in image space. public Rect getCropRect() { return new Rect((int) mCropRect.left, (int) mCropRect.top, (int) mCropRect.right, (int) mCropRect.bottom); } // Maps the cropping rectangle from image space to screen space. private Rect computeLayout() { RectF r = new RectF(mCropRect.left, mCropRect.top, mCropRect.right, mCropRect.bottom); mMatrix.mapRect(r); return new Rect(Math.round(r.left), Math.round(r.top), Math.round(r.right), Math.round(r.bottom)); } public void invalidate() { mDrawRect = computeLayout(); } public void setup(Matrix m, Rect imageRect, RectF cropRect, boolean circle, boolean maintainAspectRatio, int highlightColorResId, int highlightSelectedColorResId, int verticalIconResId, int horizontalIconResId, int borderSizeResId) { if (circle) { maintainAspectRatio = true; } mMatrix = new Matrix(m); mCropRect = cropRect; mImageRect = new RectF(imageRect); mMaintainAspectRatio = maintainAspectRatio; mCircle = circle; mInitialAspectRatio = mCropRect.width() / mCropRect.height(); mDrawRect = computeLayout(); mFocusPaint.setARGB(125, 50, 50, 50); mNoFocusPaint.setARGB(125, 50, 50, 50); mOutlinePaint.setStyle(Paint.Style.STROKE); mOutlinePaint.setAntiAlias(true); mOutlinePaint.setStrokeWidth(mContext.getResources().getDimension(borderSizeResId)); mMode = ModifyMode.None; init(highlightColorResId, highlightSelectedColorResId, verticalIconResId, horizontalIconResId); } }
apache-2.0
angcyo/RLibrary
zxingzbar/src/main/java/com/angcyo/zxingzbar/camera/open/OpenCameraInterface.java
3455
/* * Copyright (C) 2012 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.angcyo.zxingzbar.camera.open; import android.hardware.Camera; import android.util.Log; /** * Abstraction over the {@link Camera} API that helps open them and return their metadata. */ @SuppressWarnings("deprecation") // camera APIs public final class OpenCameraInterface { /** * For {@link #open(int)}, means no preference for which camera to open. */ public static final int NO_REQUESTED_CAMERA = -1; private static final String TAG = OpenCameraInterface.class.getName(); private OpenCameraInterface() { } /** * Opens the requested camera with {@link Camera#open(int)}, if one exists. * * @param cameraId camera ID of the camera to use. A negative value * or {@link #NO_REQUESTED_CAMERA} means "no preference", in which case a rear-facing * camera is returned if possible or else any camera * @return handle to {@link OpenCamera} that was opened */ public static OpenCamera open(int cameraId) { int numCameras = Camera.getNumberOfCameras(); if (numCameras == 0) { Log.w(TAG, "No cameras!"); return null; } boolean explicitRequest = cameraId >= 0; Camera.CameraInfo selectedCameraInfo = null; int index; if (explicitRequest) { index = cameraId; selectedCameraInfo = new Camera.CameraInfo(); Camera.getCameraInfo(index, selectedCameraInfo); } else { index = 0; while (index < numCameras) { Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); Camera.getCameraInfo(index, cameraInfo); CameraFacing reportedFacing = CameraFacing.values()[cameraInfo.facing]; if (reportedFacing == CameraFacing.BACK) { selectedCameraInfo = cameraInfo; break; } index++; } } Camera camera; if (index < numCameras) { Log.i(TAG, "Opening camera #" + index); camera = Camera.open(index); } else { if (explicitRequest) { Log.w(TAG, "Requested camera does not exist: " + cameraId); camera = null; } else { Log.i(TAG, "No camera facing " + CameraFacing.BACK + "; returning camera #0"); camera = Camera.open(0); selectedCameraInfo = new Camera.CameraInfo(); Camera.getCameraInfo(0, selectedCameraInfo); } } if (camera == null) { return null; } return new OpenCamera(index, camera, CameraFacing.values()[selectedCameraInfo.facing], selectedCameraInfo.orientation); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-sns/src/main/java/com/amazonaws/services/sns/model/transform/SubscribeResultStaxUnmarshaller.java
2395
/* * 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.sns.model.transform; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.sns.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * SubscribeResult StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class SubscribeResultStaxUnmarshaller implements Unmarshaller<SubscribeResult, StaxUnmarshallerContext> { public SubscribeResult unmarshall(StaxUnmarshallerContext context) throws Exception { SubscribeResult subscribeResult = new SubscribeResult(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 2; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return subscribeResult; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("SubscriptionArn", targetDepth)) { subscribeResult.setSubscriptionArn(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return subscribeResult; } } } } private static SubscribeResultStaxUnmarshaller instance; public static SubscribeResultStaxUnmarshaller getInstance() { if (instance == null) instance = new SubscribeResultStaxUnmarshaller(); return instance; } }
apache-2.0
marques-work/gocd
server/src/test-integration/java/com/thoughtworks/go/server/messaging/JobStatusListenerIntegrationTest.java
6688
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.server.messaging; import com.thoughtworks.go.config.GoConfigDao; import com.thoughtworks.go.config.PipelineConfig; import com.thoughtworks.go.domain.*; import com.thoughtworks.go.domain.buildcause.BuildCause; import com.thoughtworks.go.remote.AgentIdentifier; import com.thoughtworks.go.server.cache.GoCache; import com.thoughtworks.go.server.dao.DatabaseAccessHelper; import com.thoughtworks.go.server.dao.JobInstanceSqlMapDao; import com.thoughtworks.go.server.scheduling.ScheduleHelper; import com.thoughtworks.go.server.service.ElasticAgentPluginService; import com.thoughtworks.go.server.service.JobInstanceService; import com.thoughtworks.go.server.service.StageService; import com.thoughtworks.go.util.GoConfigFileHelper; import com.thoughtworks.go.util.GoConstants; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static com.thoughtworks.go.helper.BuildPlanMother.withBuildPlans; import static com.thoughtworks.go.helper.ModificationsMother.modifyOneFile; import static com.thoughtworks.go.helper.PipelineMother.withSingleStageWithMaterials; import static org.mockito.Mockito.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:/applicationContext-global.xml", "classpath:/applicationContext-dataLocalAccess.xml", "classpath:/testPropertyConfigurer.xml", "classpath:/spring-all-servlet.xml", }) public class JobStatusListenerIntegrationTest { @Autowired private StageService stageService; @Autowired private DatabaseAccessHelper dbHelper; @Autowired private ScheduleHelper scheduleHelper; @Autowired private GoConfigDao goConfigDao; @Autowired private GoCache goCache; @Autowired private ElasticAgentPluginService elasticAgentPluginService; @Autowired private JobInstanceSqlMapDao jobInstanceSqlMapDao; @Autowired private JobInstanceService jobInstanceService; private static final String PIPELINE_NAME = "mingle"; private static final String STAGE_NAME = "dev"; private static final String JOB_NAME = "unit"; private static final String UUID = "AGENT1"; private Pipeline savedPipeline; JobIdentifier jobIdentifier = new JobIdentifier(PIPELINE_NAME, "1", STAGE_NAME, "1", JOB_NAME); private static final AgentIdentifier AGENT1 = new AgentIdentifier(UUID, "IPADDRESS", UUID); private JobStatusListener listener; private StageStatusTopic stageStatusTopic; private static GoConfigFileHelper configHelper = new GoConfigFileHelper(); @Before public void setUp() throws Exception { goCache.clear(); dbHelper.onSetUp(); configHelper.usingCruiseConfigDao(goConfigDao); configHelper.onSetUp(); PipelineConfig pipelineConfig = withSingleStageWithMaterials(PIPELINE_NAME, STAGE_NAME, withBuildPlans(JOB_NAME)); configHelper.addPipeline(PIPELINE_NAME, STAGE_NAME); savedPipeline = scheduleHelper.schedule(pipelineConfig, BuildCause.createWithModifications(modifyOneFile(pipelineConfig), ""), GoConstants.DEFAULT_APPROVED_BY); JobInstance job = savedPipeline.getStages().first().getJobInstances().first(); job.setAgentUuid(UUID); stageStatusTopic = mock(StageStatusTopic.class); } @After public void teardown() throws Exception { dbHelper.onTearDown(); goCache.clear(); configHelper.onTearDown(); } @Test public void shouldSendStageCompletedMessage() { final ElasticAgentPluginService spyOfElasticAgentPluginService = spy(this.elasticAgentPluginService); dbHelper.pass(savedPipeline); jobIdentifier.setBuildId(savedPipeline.getFirstStage().getJobInstances().get(0).getId()); listener = new JobStatusListener(new JobStatusTopic(null), stageService, stageStatusTopic, spyOfElasticAgentPluginService, jobInstanceSqlMapDao, jobInstanceService); final StageStatusMessage stagePassed = new StageStatusMessage(jobIdentifier.getStageIdentifier(), StageState.Passed, StageResult.Passed); listener.onMessage(new JobStatusMessage(jobIdentifier, JobState.Completed, AGENT1.getUuid())); verify(stageStatusTopic).post(stagePassed); verify(spyOfElasticAgentPluginService).jobCompleted(any(JobInstance.class)); } @Test public void shouldNotSendStageCompletedMessage() { final ElasticAgentPluginService spyOfElasticAgentPluginService = spy(this.elasticAgentPluginService); dbHelper.pass(savedPipeline); jobIdentifier.setBuildId(savedPipeline.getFirstStage().getJobInstances().get(0).getId()); listener = new JobStatusListener(new JobStatusTopic(null), stageService, stageStatusTopic, spyOfElasticAgentPluginService, jobInstanceSqlMapDao, jobInstanceService); listener.onMessage(new JobStatusMessage(jobIdentifier, JobState.Building, AGENT1.getUuid())); verify(stageStatusTopic, never()).post(any(StageStatusMessage.class)); verify(spyOfElasticAgentPluginService, never()).jobCompleted(any(JobInstance.class)); } @Test public void shouldSendStageCompletedMessageForCancelledStage() { dbHelper.cancelStage(savedPipeline.getStages().get(0)); jobIdentifier.setBuildId(savedPipeline.getFirstStage().getJobInstances().get(0).getId()); listener = new JobStatusListener(new JobStatusTopic(null), stageService, stageStatusTopic, mock(ElasticAgentPluginService.class), jobInstanceSqlMapDao, jobInstanceService); final StageStatusMessage stageCancelled = new StageStatusMessage(jobIdentifier.getStageIdentifier(), StageState.Cancelled, StageResult.Cancelled); listener.onMessage(new JobStatusMessage(jobIdentifier, JobState.Completed, AGENT1.getUuid())); verify(stageStatusTopic).post(stageCancelled); } }
apache-2.0
nzinfo/my-kfs-022
src/cc/tools/MonUtils.cc
6967
//---------------------------------------------------------- -*- Mode: C++ -*- // $Id: MonUtils.cc 149 2008-09-10 05:31:35Z sriramsrao $ // // Created 2006/07/18 // Author: Sriram Rao // // Copyright 2008 Quantcast Corp. // Copyright 2006-2008 Kosmix Corp. // // This file is part of Kosmos File System (KFS). // // 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. // // \brief Utilities for monitoring/stat extraction from meta/chunk servers. //---------------------------------------------------------------------------- #include "MonUtils.h" #include "common/kfstypes.h" #include <cassert> #include <cerrno> #include <sstream> #include <boost/scoped_array.hpp> using std::istringstream; using std::ostringstream; using std::string; using namespace KFS; using namespace KFS_MON; static const char *KFS_VERSION_STR = "KFS/1.0"; // use a big buffer so we don't have issues about server responses not fitting in static const int CMD_BUF_SIZE = 1 << 20; void KfsMonOp::ParseResponseCommon(string &resp, Properties &prop) { istringstream ist(resp); kfsSeq_t resSeq; const char separator = ':'; prop.loadProperties(ist, separator, false); resSeq = prop.getValue("Cseq", -1); this->status = prop.getValue("Status", -1); } void MetaPingOp::Request(ostringstream &os) { os << "PING\r\n"; os << "Version: " << KFS_VERSION_STR << "\r\n"; os << "Cseq: " << seq << "\r\n\r\n"; } void MetaPingOp::ParseResponse(const char *resp, int len) { string respStr(resp, len); Properties prop; string serv; const char delim = '\t'; string::size_type start, end; ParseResponseCommon(respStr, prop); serv = prop.getValue("Servers", ""); start = serv.find_first_of("s="); if (start == string::npos) { return; } string serverInfo; while (start != string::npos) { end = serv.find_first_of(delim, start); if (end != string::npos) serverInfo.assign(serv, start, end - start); else serverInfo.assign(serv, start, serv.size() - start); this->upServers.push_back(serverInfo); start = serv.find_first_of("s=", end); } serv = prop.getValue("Down Servers", ""); start = serv.find_first_of("s="); if (start == string::npos) { return; } while (start != string::npos) { end = serv.find_first_of(delim, start); if (end != string::npos) serverInfo.assign(serv, start, end - start); else serverInfo.assign(serv, start, serv.size() - start); this->downServers.push_back(serverInfo); start = serv.find_first_of("s=", end); } } void ChunkPingOp::Request(ostringstream &os) { os << "PING\r\n"; os << "Version: " << KFS_VERSION_STR << "\r\n"; os << "Cseq: " << seq << "\r\n\r\n"; } void ChunkPingOp::ParseResponse(const char *resp, int len) { string respStr(resp, len); Properties prop; ParseResponseCommon(respStr, prop); location.hostname = prop.getValue("Meta-server-host", ""); location.port = prop.getValue("Meta-server-port", 0); totalSpace = prop.getValue("Total-space", (long long) 0); usedSpace = prop.getValue("Used-space", (long long) 0); } void MetaStatsOp::Request(ostringstream &os) { os << "STATS\r\n"; os << "Version: " << KFS_VERSION_STR << "\r\n"; os << "Cseq: " << seq << "\r\n\r\n"; } void ChunkStatsOp::Request(ostringstream &os) { os << "STATS\r\n"; os << "Version: " << KFS_VERSION_STR << "\r\n"; os << "Cseq: " << seq << "\r\n\r\n"; } void MetaStatsOp::ParseResponse(const char *resp, int len) { string respStr(resp, len); ParseResponseCommon(respStr, stats); } void ChunkStatsOp::ParseResponse(const char *resp, int len) { string respStr(resp, len); ParseResponseCommon(respStr, stats); } void RetireChunkserverOp::Request(ostringstream &os) { os << "RETIRE_CHUNKSERVER\r\n"; os << "Version: " << KFS_VERSION_STR << "\r\n"; os << "Cseq: " << seq << "\r\n"; os << "Downtime: " << downtime << "\r\n"; os << "Chunk-server-name: " << chunkLoc.hostname << "\r\n"; os << "Chunk-server-port: " << chunkLoc.port << "\r\n\r\n"; } void RetireChunkserverOp::ParseResponse(const char *resp, int len) { string respStr(resp, len); Properties prop; ParseResponseCommon(respStr, prop); } int KFS_MON::DoOpCommon(KfsMonOp *op, TcpSocket *sock) { int numIO; boost::scoped_array<char> buf; int len; ostringstream os; op->Request(os); numIO = sock->DoSynchSend(os.str().c_str(), os.str().length()); if (numIO <= 0) { op->status = -1; return -1; } buf.reset(new char[CMD_BUF_SIZE]); numIO = GetResponse(buf.get(), CMD_BUF_SIZE, &len, sock); if (numIO <= 0) { op->status = -1; return -1; } assert(len > 0); op->ParseResponse(buf.get(), len); return numIO; } /// /// Get a response from the server. The response is assumed to /// terminate with "\r\n\r\n". /// @param[in/out] buf that should be filled with data from server /// @param[in] bufSize size of the buffer /// /// @param[out] delims the position in the buffer where "\r\n\r\n" /// occurs; in particular, the length of the response string that ends /// with last "\n" character. If the buffer got full and we couldn't /// find "\r\n\r\n", delims is set to -1. /// /// @param[in] sock the socket from which data should be read /// @retval # of bytes that were read; 0/-1 if there was an error /// int KFS_MON::GetResponse(char *buf, int bufSize, int *delims, TcpSocket *sock) { int nread; int i; *delims = -1; while (1) { struct timeval timeout; timeout.tv_sec = 300; timeout.tv_usec = 0; nread = sock->DoSynchPeek(buf, bufSize, timeout); if (nread <= 0) return nread; for (i = 4; i <= nread; i++) { if (i < 4) break; if ((buf[i - 3] == '\r') && (buf[i - 2] == '\n') && (buf[i - 1] == '\r') && (buf[i] == '\n')) { // valid stuff is from 0..i; so, length of resulting // string is i+1. memset(buf, '\0', bufSize); *delims = (i + 1); nread = sock->Recv(buf, *delims); return nread; } } } return -1; }
apache-2.0
camilesing/zstack
sdk/src/main/java/org/zstack/sdk/LogInByUserAction.java
2771
package org.zstack.sdk; import java.util.HashMap; import java.util.Map; import org.zstack.sdk.*; public class LogInByUserAction extends AbstractAction { private static final HashMap<String, Parameter> parameterMap = new HashMap<>(); private static final HashMap<String, Parameter> nonAPIParameterMap = new HashMap<>(); public static class Result { public ErrorCode error; public org.zstack.sdk.LogInResult value; public Result throwExceptionIfError() { if (error != null) { throw new ApiException( String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details) ); } return this; } } @Param(required = false, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String accountUuid; @Param(required = false, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String accountName; @Param(required = true, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String userName; @Param(required = true, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String password; @Param(required = false) public java.util.List systemTags; @Param(required = false) public java.util.List userTags; private Result makeResult(ApiResult res) { Result ret = new Result(); if (res.error != null) { ret.error = res.error; return ret; } org.zstack.sdk.LogInResult value = res.getResult(org.zstack.sdk.LogInResult.class); ret.value = value == null ? new org.zstack.sdk.LogInResult() : value; return ret; } public Result call() { ApiResult res = ZSClient.call(this); return makeResult(res); } public void call(final Completion<Result> completion) { ZSClient.call(this, new InternalCompletion() { @Override public void complete(ApiResult res) { completion.complete(makeResult(res)); } }); } protected Map<String, Parameter> getParameterMap() { return parameterMap; } protected Map<String, Parameter> getNonAPIParameterMap() { return nonAPIParameterMap; } protected RestInfo getRestInfo() { RestInfo info = new RestInfo(); info.httpMethod = "PUT"; info.path = "/accounts/users/login"; info.needSession = false; info.needPoll = false; info.parameterName = "logInByUser"; return info; } }
apache-2.0
jamiepg1/jetty.project
jetty-spdy/spdy-jetty-http/src/test/java/org/eclipse/jetty/spdy/http/ProtocolNegotiationTest.java
8694
/* * Copyright (c) 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.eclipse.jetty.spdy.http; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetSocketAddress; import java.util.List; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import org.eclipse.jetty.npn.NextProtoNego; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.spdy.SPDYServerConnector; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestWatchman; import org.junit.runners.model.FrameworkMethod; public class ProtocolNegotiationTest { @Rule public final TestWatchman testName = new TestWatchman() { @Override public void starting(FrameworkMethod method) { super.starting(method); System.err.printf("Running %s.%s()%n", method.getMethod().getDeclaringClass().getName(), method.getName()); } }; protected Server server; protected SPDYServerConnector connector; protected InetSocketAddress startServer(SPDYServerConnector connector) throws Exception { server = new Server(); if (connector == null) connector = new SPDYServerConnector(null, newSslContextFactory()); connector.setPort(0); this.connector = connector; server.addConnector(connector); server.start(); return new InetSocketAddress("localhost", connector.getLocalPort()); } protected SslContextFactory newSslContextFactory() { SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath("src/test/resources/keystore.jks"); sslContextFactory.setKeyStorePassword("storepwd"); sslContextFactory.setTrustStore("src/test/resources/truststore.jks"); sslContextFactory.setTrustStorePassword("storepwd"); sslContextFactory.setProtocol("TLSv1"); sslContextFactory.setIncludeProtocols("TLSv1"); return sslContextFactory; } @Test public void testServerAdvertisingHTTPSpeaksHTTP() throws Exception { InetSocketAddress address = startServer(null); connector.removeAsyncConnectionFactory("spdy/2"); connector.putAsyncConnectionFactory("http/1.1", new ServerHTTPAsyncConnectionFactory(connector)); SslContextFactory sslContextFactory = newSslContextFactory(); sslContextFactory.start(); SSLContext sslContext = sslContextFactory.getSslContext(); SSLSocket client = (SSLSocket)sslContext.getSocketFactory().createSocket(address.getAddress(), address.getPort()); client.setUseClientMode(true); client.setSoTimeout(5000); NextProtoNego.put(client, new NextProtoNego.ClientProvider() { @Override public boolean supports() { return true; } @Override public void unsupported() { } @Override public String selectProtocol(List<String> strings) { Assert.assertNotNull(strings); String protocol = "http/1.1"; Assert.assertTrue(strings.contains(protocol)); return protocol; } }); client.startHandshake(); // Verify that the server really speaks http/1.1 OutputStream output = client.getOutputStream(); output.write(("" + "GET / HTTP/1.1\r\n" + "Host: localhost:" + address.getPort() + "\r\n" + "\r\n" + "").getBytes("UTF-8")); output.flush(); InputStream input = client.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); String line = reader.readLine(); Assert.assertTrue(line.contains(" 404 ")); client.close(); } @Test public void testServerAdvertisingSPDYAndHTTPSpeaksHTTPWhenNegotiated() throws Exception { InetSocketAddress address = startServer(null); connector.putAsyncConnectionFactory("http/1.1", new ServerHTTPAsyncConnectionFactory(connector)); SslContextFactory sslContextFactory = newSslContextFactory(); sslContextFactory.start(); SSLContext sslContext = sslContextFactory.getSslContext(); SSLSocket client = (SSLSocket)sslContext.getSocketFactory().createSocket(address.getAddress(), address.getPort()); client.setUseClientMode(true); client.setSoTimeout(5000); NextProtoNego.put(client, new NextProtoNego.ClientProvider() { @Override public boolean supports() { return true; } @Override public void unsupported() { } @Override public String selectProtocol(List<String> strings) { Assert.assertNotNull(strings); String spdyProtocol = "spdy/2"; Assert.assertTrue(strings.contains(spdyProtocol)); String httpProtocol = "http/1.1"; Assert.assertTrue(strings.contains(httpProtocol)); Assert.assertTrue(strings.indexOf(spdyProtocol) < strings.indexOf(httpProtocol)); return httpProtocol; } }); client.startHandshake(); // Verify that the server really speaks http/1.1 OutputStream output = client.getOutputStream(); output.write(("" + "GET / HTTP/1.1\r\n" + "Host: localhost:" + address.getPort() + "\r\n" + "\r\n" + "").getBytes("UTF-8")); output.flush(); InputStream input = client.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); String line = reader.readLine(); Assert.assertTrue(line.contains(" 404 ")); client.close(); } @Test public void testServerAdvertisingSPDYAndHTTPSpeaksDefaultProtocolWhenNPNMissing() throws Exception { SPDYServerConnector connector = new SPDYServerConnector(null, newSslContextFactory()); connector.setDefaultAsyncConnectionFactory(new ServerHTTPAsyncConnectionFactory(connector)); InetSocketAddress address = startServer(connector); connector.putAsyncConnectionFactory("http/1.1", new ServerHTTPAsyncConnectionFactory(connector)); SslContextFactory sslContextFactory = newSslContextFactory(); sslContextFactory.start(); SSLContext sslContext = sslContextFactory.getSslContext(); SSLSocket client = (SSLSocket)sslContext.getSocketFactory().createSocket(address.getAddress(), address.getPort()); client.setUseClientMode(true); client.setSoTimeout(5000); NextProtoNego.put(client, new NextProtoNego.ClientProvider() { @Override public boolean supports() { return false; } @Override public void unsupported() { } @Override public String selectProtocol(List<String> strings) { return null; } }); client.startHandshake(); // Verify that the server really speaks http/1.1 OutputStream output = client.getOutputStream(); output.write(("" + "GET / HTTP/1.1\r\n" + "Host: localhost:" + address.getPort() + "\r\n" + "\r\n" + "").getBytes("UTF-8")); output.flush(); InputStream input = client.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); String line = reader.readLine(); Assert.assertTrue(line.contains(" 404 ")); client.close(); } }
apache-2.0
atsid/permissive
app/client/src/modules/common/directives/repodetails/repodetails.js
2762
'use strict'; let links = require('../../../links'), permissions = require('../../../permissions'), buttonConfig = require('../config/permission-buttons'); module.exports = /*@ngInject*/ () => { return { templateUrl: 'common/directives/repodetails/repodetails.html', scope: { repo: '=repodetails', user: '=repouser' }, controllerAs: 'ctrl', bindToController: true, controller: /*@ngInject*/ function (linkService, identityService, $mdDialog) { console.log('binding repo details controller', this); this.editLink = links.findByRel(this.repo.links, 'edit-user-permission'); this.buttons = angular.copy(buttonConfig); this.permission = this.repo.permission; //buttons display but are not clickable if the link isn't there if (!this.editLink) { this.buttons.forEach((btn) => btn.disabled = true); } this.handlePermissionChange = (value) => { console.log('permission change', value); if (!this.identity) { this.identity = identityService.get(() => { this.validateChange(value); }); } else { this.validateChange(value); } }; this.validateChange = (value) => { // confirmation for users trying to remove their own admin perms if (this.identity.username === this.user.username && this.permission === 'admin') { let confirm = $mdDialog.confirm() .title('Warning!') .content('Are you sure you want to remove your own admin permissions from this repo?') .cancel('Cancel') .ok('Confirm'); $mdDialog.show(confirm).then(() => { this.executeChange(value); }); } else { this.executeChange(value); } }; this.executeChange = (value) => { this.permission = value; linkService.exec(this.editLink, { permission: this.permission }); }; } }; };
apache-2.0
hong1012/FreePay
node_modules/antd/lib/locale-provider/ru_RU.d.ts
813
import 'moment/locale/ru'; declare var _default: { Pagination: any; DatePicker: { lang: any; timePickerLocale: any; }; TimePicker: { placeholder: string; }; Calendar: { lang: any; timePickerLocale: any; }; Table: { filterTitle: string; filterConfirm: string; filterReset: string; emptyText: string; }; Modal: { okText: string; cancelText: string; justOkText: string; }; Popconfirm: { okText: string; cancelText: string; }; Transfer: { notFoundContent: string; searchPlaceholder: string; itemUnit: string; itemsUnit: string; }; Select: { notFoundContent: string; }; }; export default _default;
apache-2.0
dcngmbh/moox_address
Classes/Domain/Model/Address.php
11596
<?php namespace DCNGmbH\MooxAddress\Domain\Model; /** * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use TYPO3\CMS\Extbase\Persistence\ObjectStorage; use TYPO3\CMS\Extbase\DomainObject\AbstractEntity; class Address extends AbstractEntity { /** * @var DateTime */ protected $crdate; /** * @var DateTime */ protected $tstamp; /** * @var int */ protected $hidden; /** * @var int */ protected $gender; /** * @var string */ protected $title; /** * @var string * @validate NotEmpty */ protected $forename; /** * @var string */ protected $surname; /** * @var string */ protected $company; /** * @var string */ protected $department; /** * @var string */ protected $street; /** * @var string */ protected $zip; /** * @var string */ protected $city; /** * @var string */ protected $region; /** * @var string */ protected $country; /** * @var string */ protected $phone; /** * @var string */ protected $mobile; /** * @var string */ protected $fax; /** * @var string */ protected $email; /** * @var string */ protected $www; /** * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\DCNGmbH\MooxAddress\Domain\Model\FileReference> * @lazy */ protected $images; /** * @var int */ protected $mailingAllowed; /** * @var int */ protected $registered; /** * @var int */ protected $unregistered; /** * @var string */ protected $registerHash; /** * @var int */ protected $registerTstamp; /** * @var int */ protected $quality; /** * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\DCNGmbH\MooxMailer\Domain\Model\Bounce> */ protected $bounces = NULL; /** * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\DCNGmbH\MooxMailer\Domain\Model\Error> */ protected $errors = NULL; /** * initialize object */ public function initializeObject() { //Do not remove the next line: It would break the functionality $this->initStorageObjects(); } /** * Initializes all ObjectStorage properties * Do not modify this method! * It will be rewritten on each save in the extension builder * You may modify the constructor of this class instead * * @return void */ protected function initStorageObjects() { $this->bounces = new ObjectStorage(); $this->errors = new ObjectStorage(); $this->images = new ObjectStorage(); } /** * Get creation date * * @return int */ public function getCrdate() { return $this->crdate; } /** * Set creation date * * @param int $crdate * @return void */ public function setCrdate($crdate) { $this->crdate = $crdate; } /** * Get year of crdate * * @return int */ public function getYearOfCrdate() { return $this->getCrdate()->format('Y'); } /** * Get month of crdate * * @return int */ public function getMonthOfCrdate() { return $this->getCrdate()->format('m'); } /** * Get day of crdate * * @return int */ public function getDayOfCrdate() { return (int)$this->crdate->format('d'); } /** * Get timestamp * * @return int */ public function getTstamp() { return $this->tstamp; } /** * Set time stamp * * @param int $tstamp time stamp * @return void */ public function setTstamp($tstamp) { $this->tstamp = $tstamp; } /** * Returns the hidden * * @return int $hidden */ public function getHidden() { return $this->hidden; } /** * Sets the hidden * * @param int $hidden * @return void */ public function setHidden($hidden) { $this->hidden = $hidden; } /** * Returns the gender * * @return int $gender */ public function getGender() { return $this->gender; } /** * Sets the gender * * @param int $gender * @return void */ public function setGender($gender) { $this->gender = $gender; } /** * Returns the title * * @return string $title */ public function getTitle() { return $this->title; } /** * Sets the title * * @param string $title * @return void */ public function setTitle($title) { $this->title = $title; } /** * Returns the forename * * @return string $forename */ public function getForename() { return $this->forename; } /** * Sets the forename * * @param string $forename * @return void */ public function setForename($forename) { $this->forename = $forename; } /** * Returns the surname * * @return string $surname */ public function getSurname() { return $this->surname; } /** * Sets the surname * * @param string $surname * @return void */ public function setSurname($surname) { $this->surname = $surname; } /** * Returns the company * * @return string $company */ public function getCompany() { return $this->company; } /** * Sets the company * * @param string $company * @return void */ public function setCompany($company) { $this->company = $company; } /** * Returns the department * * @return string $department */ public function getDepartment() { return $this->department; } /** * Sets the department * * @param string $department * @return void */ public function setDepartment($department) { $this->department = $department; } /** * Returns the street * * @return string $street */ public function getStreet() { return $this->street; } /** * Sets the street * * @param string $street * @return void */ public function setStreet($street) { $this->street = $street; } /** * Returns the zip * * @return string $zip */ public function getZip() { return $this->zip; } /** * Sets the zip * * @param string $zip * @return void */ public function setZip($zip) { $this->zip = $zip; } /** * Returns the city * * @return string $city */ public function getCity() { return $this->city; } /** * Sets the city * * @param string $city * @return void */ public function setCity($city) { $this->city = $city; } /** * Returns the region * * @return string $region */ public function getRegion() { return $this->region; } /** * Sets the region * * @param string $region * @return void */ public function setRegion($region) { $this->region = $region; } /** * Returns the country * * @return string $country */ public function getCountry() { return $this->country; } /** * Sets the country * * @param string $country * @return void */ public function setCountry($country) { $this->country = $country; } /** * Returns the phone * * @return string $phone */ public function getPhone() { return $this->phone; } /** * Sets the phone * * @param string $phone * @return void */ public function setPhone($phone) { $this->phone = $phone; } /** * Returns the mobile * * @return string $mobile */ public function getMobile() { return $this->mobile; } /** * Sets the mobile * * @param string $mobile * @return void */ public function setMobile($mobile) { $this->mobile = $mobile; } /** * Returns the fax * * @return string $fax */ public function getFax() { return $this->fax; } /** * Sets the fax * * @param string $fax * @return void */ public function setFax($fax) { $this->fax = $fax; } /** * Returns the email * * @return string $email */ public function getEmail() { return $this->email; } /** * Sets the email * * @param string $email * @return void */ public function setEmail($email) { $this->email = $email; } /** * Returns the www * * @return string $www */ public function getWww() { return $this->www; } /** * Sets the www * * @param string $www * @return void */ public function setWww($www) { $this->www = $www; } /** * sets the Images * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage $images * * @return void */ public function setImages($images) { $this->images = $images; } /** * get the Images * * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage */ public function getImages() { return $this->images; } /** * adds a image * * @param \DCNGmbH\MooxAddress\Domain\Model\FileReference $image * * @return void */ public function addImage(\DCNGmbH\MooxAddress\Domain\Model\FileReference $image) { $this->images->attach($image); } /** * remove a image * * @param \DCNGmbH\MooxAddress\Domain\Model\FileReference $image * * @return void */ public function removeImage(\DCNGmbH\MooxAddress\Domain\Model\FileReference $image) { $this->images->detach($image); } /** * Returns the mailing allowed * * @return bool $mailingAllowed */ public function getMailingAllowed() { return $this->mailingAllowed; } /** * Sets the mailing allowed * * @param bool $mailingAllowed * @return void */ public function setMailingAllowed($mailingAllowed) { $this->mailingAllowed = $mailingAllowed; } /** * Returns the registered * * @return int $registered */ public function getRegistered() { return $this->registered; } /** * Sets the registered * * @param int $registered * @return void */ public function setRegistered($registered) { $this->registered = $registered; } /** * Returns the unregistered * * @return int $unregistered */ public function getUnregistered() { return $this->unregistered; } /** * Sets the unregistered * * @param int $unregistered * @return void */ public function setUnregistered($unregistered) { $this->unregistered = $unregistered; } /** * get register hash * * @return int $registerHash register hash */ public function getRegisterHash() { return $this->registerHash; } /** * set register hash * * @param int $registerRecoveryHash register hash * @return void */ public function setRegisterHash($registerHash) { $this->registerHash = $registerHash; } /** * get register timestamp * * @return int $registerTstamp register timestamp */ public function getRegisterTstamp() { return $this->registerTstamp; } /** * set register timestamp * * @param int $registerTstamp register timestamp * @return void */ public function setRegisterTstamp($registerTstamp) { $this->registerTstamp = $registerTstamp; } /** * get quality * * @return int $quality quality */ public function getQuality() { return $this->quality; } /** * Returns the bounces * * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\DCNGmbH\MooxMailer\Domain\Model\Bounce> $bounces */ public function getBounces() { return $this->bounces; } /** * Returns the errors * * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\DCNGmbH\MooxMailer\Domain\Model\Error> $errors */ public function getErrors() { return $this->errors; } } ?>
apache-2.0
ljcservice/autumnprogram
src/main/java/com/ts/entity/pdss/pdss/Beans/DrugUseAuth/TCkDrugUserAuth.java
3927
package com.ts.entity.pdss.pdss.Beans.DrugUseAuth; import java.io.Serializable; import java.util.Date; /** * 药物使用授权 实体bean * @author autumn * */ public class TCkDrugUserAuth implements Serializable { private static final long serialVersionUID = 1L; /* 主键 */ private String ID; /* 药品 */ private String DRUG_CODE; /* 药品名称 */ private String DRUG_NAME; /* 科室 */ private String DEPT_NAME; /* 医生 */ private String DOCTOR_NAME; /* 规格 */ private String DRUG_SPEC; /* 剂型 */ private String DRUG_FORM; /* 控制类型 */ private String CONTROL_TYPE; /* 阀值 */ private Integer T_VALUE; /* 当前累计值 */ private Integer TOTAL_VALUE; /* 更新人 */ private String UPDATE_PERSION; /* 更新时间 */ private String UPDATE_DATE; /* 诊断名称 */ private String DIAG_NAME; /* 诊断编码 */ private String DIAG_CODE; /* 医保类型 */ private String H_TYPE; /* 科室 代码*/ private String DEPT_CODE; public String getID() { return ID; } public void setID(String iD) { ID = iD; } public String getDRUG_CODE() { return DRUG_CODE; } public void setDRUG_CODE(String dRUG_CODE) { DRUG_CODE = dRUG_CODE; } public String getDRUG_NAME() { return DRUG_NAME; } public void setDRUG_NAME(String dRUG_NAME) { DRUG_NAME = dRUG_NAME; } public String getDEPT_NAME() { return DEPT_NAME; } public void setDEPT_NAME(String dEPT_NAME) { DEPT_NAME = dEPT_NAME; } public String getDOCTOR_NAME() { return DOCTOR_NAME; } public void setDOCTOR_NAME(String dOCTOR_NAME) { DOCTOR_NAME = dOCTOR_NAME; } public String getDRUG_SPEC() { return DRUG_SPEC; } public void setDRUG_SPEC(String dRUG_SPEC) { DRUG_SPEC = dRUG_SPEC; } public String getDRUG_FORM() { return DRUG_FORM; } public void setDRUG_FORM(String dRUG_FORM) { DRUG_FORM = dRUG_FORM; } public String getCONTROL_TYPE() { return CONTROL_TYPE; } public void setCONTROL_TYPE(String cONTROL_TYPE) { CONTROL_TYPE = cONTROL_TYPE; } public Integer getT_VALUE() { return T_VALUE; } public void setT_VALUE(Integer t_VALUE) { T_VALUE = t_VALUE; } public Integer getTOTAL_VALUE() { return TOTAL_VALUE; } public void setTOTAL_VALUE(Integer tOTAL_VALUE) { TOTAL_VALUE = tOTAL_VALUE; } public String getUPDATE_PERSION() { return UPDATE_PERSION; } public void setUPDATE_PERSION(String uPDATE_PERSION) { UPDATE_PERSION = uPDATE_PERSION; } public String getUPDATE_DATE() { return UPDATE_DATE; } public void setUPDATE_DATE(String uPDATE_DATE) { UPDATE_DATE = uPDATE_DATE; } public String getDIAG_NAME() { return DIAG_NAME; } public void setDIAG_NAME(String dIAG_NAME) { DIAG_NAME = dIAG_NAME; } public String getDIAG_CODE() { return DIAG_CODE; } public void setDIAG_CODE(String dIAG_CODE) { DIAG_CODE = dIAG_CODE; } public String getH_TYPE() { return H_TYPE; } public void setH_TYPE(String h_TYPE) { H_TYPE = h_TYPE; } public String getDEPT_CODE() { return DEPT_CODE; } public void setDEPT_CODE(String dEPT_CODE) { DEPT_CODE = dEPT_CODE; } }
apache-2.0
rh-s/heat
heat/tests/aws/test_loadbalancer.py
13775
# # 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 copy import mock from oslo_config import cfg from heat.common import exception from heat.common import template_format from heat.engine.clients.os import nova from heat.engine.resources.aws.lb import loadbalancer as lb from heat.engine import rsrc_defn from heat.tests import common from heat.tests.nova import fakes as fakes_nova from heat.tests import utils lb_template = ''' { "AWSTemplateFormatVersion": "2010-09-09", "Description": "LB Template", "Parameters" : { "KeyName" : { "Description" : "KeyName", "Type" : "String", "Default" : "test" }, "LbFlavor" : { "Description" : "Flavor to use for LoadBalancer instance", "Type": "String", "Default": "m1.heat" } }, "Resources": { "WikiServerOne": { "Type": "AWS::EC2::Instance", "Properties": { "ImageId": "F17-x86_64-gold", "InstanceType" : "m1.large", "KeyName" : "test", "UserData" : "some data" } }, "LoadBalancer" : { "Type" : "AWS::ElasticLoadBalancing::LoadBalancer", "Properties" : { "AvailabilityZones" : ["nova"], "SecurityGroups": ["sg_1"], "Instances" : [{"Ref": "WikiServerOne"}], "Listeners" : [ { "LoadBalancerPort" : "80", "InstancePort" : "80", "Protocol" : "HTTP" }] } } } } ''' class LoadBalancerTest(common.HeatTestCase): def setUp(self): super(LoadBalancerTest, self).setUp() self.fc = fakes_nova.FakeClient() def test_loadbalancer(self): t = template_format.parse(lb_template) s = utils.parse_stack(t) s.store() resource_name = 'LoadBalancer' lb_defn = s.t.resource_definitions(s)[resource_name] rsrc = lb.LoadBalancer(resource_name, lb_defn, s) nova.NovaClientPlugin._create = mock.Mock(return_value=self.fc) initial_md = {'AWS::CloudFormation::Init': {'config': {'files': {'/etc/haproxy/haproxy.cfg': {'content': 'initial'}}}}} ha_cfg = '\n'.join(['\nglobal', ' daemon', ' maxconn 256', ' stats socket /tmp/.haproxy-stats', '\ndefaults', ' mode http\n timeout connect 5000ms', ' timeout client 50000ms', ' timeout server 50000ms\n\nfrontend http', ' bind *:80\n default_backend servers', '\nbackend servers\n balance roundrobin', ' option http-server-close', ' option forwardfor\n option httpchk', '\n server server1 1.2.3.4:80', ' server server2 0.0.0.0:80\n']) expected_md = {'AWS::CloudFormation::Init': {'config': {'files': {'/etc/haproxy/haproxy.cfg': { 'content': ha_cfg}}}}} md = mock.Mock() md.metadata_get.return_value = copy.deepcopy(initial_md) rsrc.nested = mock.Mock(return_value={'LB_instance': md}) prop_diff = {'Instances': ['WikiServerOne1', 'WikiServerOne2']} props = copy.copy(rsrc.properties.data) props.update(prop_diff) update_defn = rsrc_defn.ResourceDefinition(rsrc.name, rsrc.type(), props) rsrc.handle_update(update_defn, {}, prop_diff) self.assertIsNone(rsrc.handle_update(rsrc.t, {}, {})) md.metadata_get.assert_called_once_with() md.metadata_set.assert_called_once_with(expected_md) def test_loadbalancer_validate_hchk_good(self): rsrc = self.setup_loadbalancer() rsrc._parse_nested_stack = mock.Mock() hc = { 'Target': 'HTTP:80/', 'HealthyThreshold': '3', 'UnhealthyThreshold': '5', 'Interval': '30', 'Timeout': '5'} rsrc.t['Properties']['HealthCheck'] = hc self.assertIsNone(rsrc.validate()) def test_loadbalancer_validate_hchk_int_gt_tmo(self): rsrc = self.setup_loadbalancer() rsrc._parse_nested_stack = mock.Mock() hc = { 'Target': 'HTTP:80/', 'HealthyThreshold': '3', 'UnhealthyThreshold': '5', 'Interval': '30', 'Timeout': '35'} rsrc.t['Properties']['HealthCheck'] = hc self.assertEqual( {'Error': 'Interval must be larger than Timeout'}, rsrc.validate()) def test_loadbalancer_validate_badtemplate(self): cfg.CONF.set_override('loadbalancer_template', '/a/noexist/x.y') rsrc = self.setup_loadbalancer() self.assertRaises(exception.StackValidationFailed, rsrc.validate) def setup_loadbalancer(self, include_magic=True): template = template_format.parse(lb_template) if not include_magic: del template['Parameters']['KeyName'] del template['Parameters']['LbFlavor'] self.stack = utils.parse_stack(template) resource_name = 'LoadBalancer' lb_defn = self.stack.t.resource_definitions(self.stack)[resource_name] return lb.LoadBalancer(resource_name, lb_defn, self.stack) def test_loadbalancer_refid(self): rsrc = self.setup_loadbalancer() rsrc.resource_id = mock.Mock(return_value='not-this') self.assertEqual('LoadBalancer', rsrc.FnGetRefId()) def test_loadbalancer_attr_dnsname(self): rsrc = self.setup_loadbalancer() rsrc.get_output = mock.Mock(return_value='1.3.5.7') self.assertEqual('1.3.5.7', rsrc.FnGetAtt('DNSName')) rsrc.get_output.assert_called_once_with('PublicIp') def test_loadbalancer_attr_not_supported(self): rsrc = self.setup_loadbalancer() for attr in ['CanonicalHostedZoneName', 'CanonicalHostedZoneNameID', 'SourceSecurityGroup.GroupName', 'SourceSecurityGroup.OwnerAlias']: self.assertEqual('', rsrc.FnGetAtt(attr)) def test_loadbalancer_attr_invalid(self): rsrc = self.setup_loadbalancer() self.assertRaises(exception.InvalidTemplateAttribute, rsrc.FnGetAtt, 'Foo') def test_child_params_without_key_name(self): rsrc = self.setup_loadbalancer(False) self.assertNotIn('KeyName', rsrc.child_params()) def test_child_params_with_key_name(self): rsrc = self.setup_loadbalancer() params = rsrc.child_params() self.assertEqual('test', params['KeyName']) def test_child_template_without_key_name(self): rsrc = self.setup_loadbalancer(False) parsed_template = { 'Resources': {'LB_instance': {'Properties': {'KeyName': 'foo'}}}, 'Parameters': {'KeyName': 'foo'} } rsrc.get_parsed_template = mock.Mock(return_value=parsed_template) tmpl = rsrc.child_template() self.assertNotIn('KeyName', tmpl['Parameters']) self.assertNotIn('KeyName', tmpl['Resources']['LB_instance']['Properties']) def test_child_template_with_key_name(self): rsrc = self.setup_loadbalancer() rsrc.get_parsed_template = mock.Mock(return_value='foo') self.assertEqual('foo', rsrc.child_template()) def test_child_params_with_flavor(self): rsrc = self.setup_loadbalancer() params = rsrc.child_params() self.assertEqual('m1.heat', params['LbFlavor']) def test_child_params_without_flavor(self): rsrc = self.setup_loadbalancer(False) params = rsrc.child_params() self.assertNotIn('LbFlavor', params) def test_child_params_with_sec_gr(self): rsrc = self.setup_loadbalancer(False) params = rsrc.child_params() expected = {'SecurityGroups': ['sg_1']} self.assertEqual(expected, params) def test_child_params_default_sec_gr(self): template = template_format.parse(lb_template) del template['Parameters']['KeyName'] del template['Parameters']['LbFlavor'] del template['Resources']['LoadBalancer']['Properties'][ 'SecurityGroups'] stack = utils.parse_stack(template) resource_name = 'LoadBalancer' lb_defn = stack.t.resource_definitions(stack)[resource_name] rsrc = lb.LoadBalancer(resource_name, lb_defn, stack) params = rsrc.child_params() # None value means, that will be used default [] for parameter expected = {'SecurityGroups': None} self.assertEqual(expected, params) class HaProxyConfigTest(common.HeatTestCase): def setUp(self): super(HaProxyConfigTest, self).setUp() self.stack = utils.parse_stack(template_format.parse(lb_template)) resource_name = 'LoadBalancer' lb_defn = self.stack.t.resource_definitions(self.stack)[resource_name] self.lb = lb.LoadBalancer(resource_name, lb_defn, self.stack) self.lb.client_plugin = mock.Mock() def _mock_props(self, props): def get_props(name): return props[name] self.lb.properties = mock.MagicMock() self.lb.properties.__getitem__.side_effect = get_props def test_combined(self): self.lb._haproxy_config_global = mock.Mock(return_value='one,') self.lb._haproxy_config_frontend = mock.Mock(return_value='two,') self.lb._haproxy_config_backend = mock.Mock(return_value='three,') self.lb._haproxy_config_servers = mock.Mock(return_value='four') actual = self.lb._haproxy_config([3, 5]) self.assertEqual('one,two,three,four\n', actual) self.lb._haproxy_config_global.assert_called_once_with() self.lb._haproxy_config_frontend.assert_called_once_with() self.lb._haproxy_config_backend.assert_called_once_with() self.lb._haproxy_config_servers.assert_called_once_with([3, 5]) def test_global(self): exp = ''' global daemon maxconn 256 stats socket /tmp/.haproxy-stats defaults mode http timeout connect 5000ms timeout client 50000ms timeout server 50000ms ''' actual = self.lb._haproxy_config_global() self.assertEqual(exp, actual) def test_frontend(self): props = {'HealthCheck': {}, 'Listeners': [{'LoadBalancerPort': 4014}]} self._mock_props(props) exp = ''' frontend http bind *:4014 default_backend servers ''' actual = self.lb._haproxy_config_frontend() self.assertEqual(exp, actual) def test_backend_with_timeout(self): props = {'HealthCheck': {'Timeout': 43}} self._mock_props(props) actual = self.lb._haproxy_config_backend() exp = ''' backend servers balance roundrobin option http-server-close option forwardfor option httpchk timeout check 43s ''' self.assertEqual(exp, actual) def test_backend_no_timeout(self): self._mock_props({'HealthCheck': None}) be = self.lb._haproxy_config_backend() exp = ''' backend servers balance roundrobin option http-server-close option forwardfor option httpchk ''' self.assertEqual(exp, be) def test_servers_none(self): props = {'HealthCheck': {}, 'Listeners': [{'InstancePort': 1234}]} self._mock_props(props) actual = self.lb._haproxy_config_servers([]) exp = '' self.assertEqual(exp, actual) def test_servers_no_check(self): props = {'HealthCheck': {}, 'Listeners': [{'InstancePort': 4511}]} self._mock_props(props) def fake_to_ipaddr(inst): return '192.168.1.%s' % inst to_ip = self.lb.client_plugin.return_value.server_to_ipaddress to_ip.side_effect = fake_to_ipaddr actual = self.lb._haproxy_config_servers(range(1, 3)) exp = ''' server server1 192.168.1.1:4511 server server2 192.168.1.2:4511''' self.assertEqual(exp.replace('\n', '', 1), actual) def test_servers_servers_and_check(self): props = {'HealthCheck': {'HealthyThreshold': 1, 'Interval': 2, 'Target': 'HTTP:80/', 'Timeout': 45, 'UnhealthyThreshold': 5 }, 'Listeners': [{'InstancePort': 1234}]} self._mock_props(props) def fake_to_ipaddr(inst): return '192.168.1.%s' % inst to_ip = self.lb.client_plugin.return_value.server_to_ipaddress to_ip.side_effect = fake_to_ipaddr actual = self.lb._haproxy_config_servers(range(1, 3)) exp = ''' server server1 192.168.1.1:1234 check inter 2s fall 5 rise 1 server server2 192.168.1.2:1234 check inter 2s fall 5 rise 1''' self.assertEqual(exp.replace('\n', '', 1), actual)
apache-2.0
Seddryck/NBi
NBi.genbiL/Action/Case/GroupCaseAction.cs
3592
using NBi.GenbiL.Stateful; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; namespace NBi.GenbiL.Action.Case { public class GroupCaseAction : ISingleCaseAction { public List<string> ColumnNames { get; } public GroupCaseAction(IEnumerable<string> variableNames) { this.ColumnNames = new List<string>(variableNames); } public void Execute(GenerationState state) => Execute(state.CaseCollection.CurrentScope); public void Execute(CaseSet testCases) { var dataTable = testCases.Content; dataTable.AcceptChanges(); foreach (var columnName in ColumnNames) dataTable.Columns.Add($"_{columnName}", typeof(List<string>)); int i = 0; var firstRow = 0; while(i < dataTable.Rows.Count) { var isIdentical = true; for (int j = 0; j < dataTable.Columns.Count - ColumnNames.Count; j++) { if (!ColumnNames.Contains(dataTable.Columns[j].ColumnName) && !(dataTable.Rows[i][j] is IEnumerable<string>)) isIdentical &= dataTable.Rows[i][j].ToString() == dataTable.Rows[firstRow][j].ToString(); } if (!isIdentical) firstRow = i; foreach (var columnName in ColumnNames) { var columnListId = dataTable.Columns[$"_{columnName}"].Ordinal; var columnId = dataTable.Columns[columnName].Ordinal; if (dataTable.Rows[firstRow][columnListId] == DBNull.Value) dataTable.Rows[firstRow][columnListId] = new List<string>(); var list = dataTable.Rows[firstRow][columnListId] as List<string>; if (dataTable.Rows[i][columnId] is IEnumerable<string>) list.AddRange(dataTable.Rows[i][columnId] as IEnumerable<string>); else list.Add(dataTable.Rows[i][columnId].ToString()); } if (isIdentical && i != 0) dataTable.Rows[i].Delete(); i++; } foreach (var columnName in ColumnNames) dataTable.Columns.Add($"_{columnName}_", typeof(string[])); foreach (DataRow row in dataTable.Rows.Cast<DataRow>().Where(x => x.RowState!=DataRowState.Deleted)) foreach (var columnName in ColumnNames) row[$"_{columnName}_"] = (row[$"_{columnName}"] as List<string>).ToArray(); foreach (var columnName in ColumnNames) { var columnId = dataTable.Columns[columnName].Ordinal; dataTable.Columns[$"_{columnName}_"].SetOrdinal(columnId); dataTable.Columns.Remove(columnName); dataTable.Columns.Remove($"_{columnName}"); dataTable.Columns[$"_{columnName}_"].ColumnName = columnName; } dataTable.AcceptChanges(); } public string Display { get { if (ColumnNames.Count == 1) return string.Format("Grouping rows for content of column '{0}'", ColumnNames[0]); else return string.Format("Grouping rows for content of columns '{0}'", String.Join("', '", ColumnNames)); } } } }
apache-2.0
voho/web
examples/patterns/src/gof/adapter/Adaptee.java
347
package gof.adapter; /** * Vnořená třída, která má zpravidla zastaralé, nekompatibilní, nebo jinak * nevyhovujícím rozhraní. Proto k ní bude vytvořen odpovídající adaptér. * @author Vojtěch Hordějčuk */ public class Adaptee { /** * Provede požadavek. */ public void oldRequest() { // ... } }
apache-2.0
tiborvass/docker
pkg/parsers/operatingsystem/operatingsystem_linux.go
2364
// Package operatingsystem provides helper function to get the operating system // name for different platforms. package operatingsystem // import "github.com/tiborvass/docker/pkg/parsers/operatingsystem" import ( "bufio" "bytes" "fmt" "io/ioutil" "os" "strings" ) var ( // file to use to detect if the daemon is running in a container proc1Cgroup = "/proc/1/cgroup" // file to check to determine Operating System etcOsRelease = "/etc/os-release" // used by stateless systems like Clear Linux altOsRelease = "/usr/lib/os-release" ) // GetOperatingSystem gets the name of the current operating system. func GetOperatingSystem() (string, error) { if prettyName, err := getValueFromOsRelease("PRETTY_NAME"); err != nil { return "", err } else if prettyName != "" { return prettyName, nil } // If not set, defaults to PRETTY_NAME="Linux" // c.f. http://www.freedesktop.org/software/systemd/man/os-release.html return "Linux", nil } // GetOperatingSystemVersion gets the version of the current operating system, as a string. func GetOperatingSystemVersion() (string, error) { return getValueFromOsRelease("VERSION_ID") } // parses the os-release file and returns the value associated with `key` func getValueFromOsRelease(key string) (string, error) { osReleaseFile, err := os.Open(etcOsRelease) if err != nil { if !os.IsNotExist(err) { return "", fmt.Errorf("Error opening %s: %v", etcOsRelease, err) } osReleaseFile, err = os.Open(altOsRelease) if err != nil { return "", fmt.Errorf("Error opening %s: %v", altOsRelease, err) } } defer osReleaseFile.Close() var value string keyWithTrailingEqual := key + "=" scanner := bufio.NewScanner(osReleaseFile) for scanner.Scan() { line := scanner.Text() if strings.HasPrefix(line, keyWithTrailingEqual) { data := strings.SplitN(line, "=", 2) value = strings.Trim(data[1], `"' `) // remove leading/trailing quotes and whitespace } } return value, nil } // IsContainerized returns true if we are running inside a container. func IsContainerized() (bool, error) { b, err := ioutil.ReadFile(proc1Cgroup) if err != nil { return false, err } for _, line := range bytes.Split(b, []byte{'\n'}) { if len(line) > 0 && !bytes.HasSuffix(line, []byte(":/")) && !bytes.HasSuffix(line, []byte(":/init.scope")) { return true, nil } } return false, nil }
apache-2.0
outbrain/ob1k
ob1k-cache/src/main/java/com/outbrain/ob1k/cache/metrics/MonitoringCacheDelegate.java
3909
package com.outbrain.ob1k.cache.metrics; import com.google.common.collect.Iterables; import com.outbrain.ob1k.cache.EntryMapper; import com.outbrain.ob1k.cache.TypedCache; import com.outbrain.ob1k.concurrent.ComposableFuture; import com.outbrain.swinfra.metrics.api.Counter; import com.outbrain.swinfra.metrics.api.MetricFactory; import java.util.Map; import java.util.function.Function; import static com.google.common.base.Preconditions.checkNotNull; /** * A decorator adding metric monitoring to TypedCache. * * @author hunchback */ public class MonitoringCacheDelegate<K, V> implements TypedCache<K, V> { protected final TypedCache<K, V> delegate; /* interface call metrics */ private final AsyncOperationMetrics<V> getAsyncMetrics; private final AsyncOperationMetrics<Map<K, V>> getBulkAsyncMetrics; private final AsyncOperationMetrics<Boolean> setAsyncMetrics; private final AsyncOperationMetrics<Boolean> setIfAbsentAsyncMetrics; private final AsyncOperationMetrics<Map<K, Boolean>> setBulkAsyncMetrics; private final AsyncOperationMetrics<Boolean> deleteAsyncMetrics; /* cache metrics */ private final Counter total; private final Counter hits; private final Function<V, V> getCacheMetricsUpdater = new Function<V, V>() { @Override public V apply(final V result) { total.inc(); if (result != null) { hits.inc(); } return result; } }; public MonitoringCacheDelegate(final TypedCache<K, V> delegate, final String cacheName, final MetricFactory metricFactory) { checkNotNull(metricFactory, "metricFactory may not be null"); this.delegate = checkNotNull(delegate, "delegate may not be null"); final String component = delegate.getClass().getSimpleName() + "." + cacheName; getAsyncMetrics = new AsyncOperationMetrics<>(metricFactory, component + ".getAsync"); getBulkAsyncMetrics = new AsyncOperationMetrics<>(metricFactory, component + ".getBulkAsync"); setAsyncMetrics = new AsyncOperationMetrics<>(metricFactory, component + ".setAsync"); setIfAbsentAsyncMetrics = new AsyncOperationMetrics<>(metricFactory, component + ".setIfAbsentAsync"); setBulkAsyncMetrics = new AsyncOperationMetrics<>(metricFactory, component + ".setBulkAsync"); deleteAsyncMetrics = new AsyncOperationMetrics<>(metricFactory, component + ".deleteAsync"); final String componentCache = component + ".Cache"; hits = metricFactory.createCounter(componentCache, "hits"); total = metricFactory.createCounter(componentCache, "total"); } @Override public ComposableFuture<V> getAsync(final K key) { return getAsyncMetrics.update(delegate.getAsync(key)) .map(getCacheMetricsUpdater); } @Override public ComposableFuture<Map<K, V>> getBulkAsync(final Iterable<? extends K> keys) { return getBulkAsyncMetrics.update(delegate.getBulkAsync(keys)) .map(result -> { total.inc(Iterables.size(keys)); hits.inc(result.size()); return result; }); } @Override public ComposableFuture<Boolean> setAsync(final K key, final V value) { return setAsyncMetrics.update(delegate.setAsync(key, value)); } @Override public ComposableFuture<Boolean> setIfAbsentAsync(final K key, final V value) { return setIfAbsentAsyncMetrics.update(delegate.setIfAbsentAsync(key, value)); } @Override public ComposableFuture<Boolean> setAsync(final K key, final EntryMapper<K, V> mapper, final int maxIterations) { return setAsyncMetrics.update(delegate.setAsync(key, mapper, maxIterations)); } @Override public ComposableFuture<Map<K, Boolean>> setBulkAsync(final Map<? extends K, ? extends V> entries) { return setBulkAsyncMetrics.update(delegate.setBulkAsync(entries)); } @Override public ComposableFuture<Boolean> deleteAsync(final K key) { return deleteAsyncMetrics.update(delegate.deleteAsync(key)); } }
apache-2.0
google/jsinterop-generator
java/jsinterop/generator/model/AnnotationType.java
1800
/* * Copyright 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package jsinterop.generator.model; /** A list of annotations we use in our JsInterop code generation. */ public enum AnnotationType { JS_ENUM(PredefinedTypeReference.JS_ENUM, true), JS_TYPE(PredefinedTypeReference.JS_TYPE, true), JS_PROPERTY(PredefinedTypeReference.JS_PROPERTY, false), JS_METHOD(PredefinedTypeReference.JS_METHOD, false), JS_PACKAGE(PredefinedTypeReference.JS_PACKAGE, false), JS_FUNCTION(PredefinedTypeReference.JS_FUNCTION, false), JS_OVERLAY(PredefinedTypeReference.JS_OVERLAY, false), DEPRECATED(PredefinedTypeReference.DEPRECATED, false), FUNCTIONAL_INTERFACE(PredefinedTypeReference.FUNCTIONAL_INTERFACE, false); private final PredefinedTypeReference type; private final boolean isJsInteropTypeAnnotation; AnnotationType(PredefinedTypeReference type, boolean isJsInteropTypeAnnotation) { this.type = type; this.isJsInteropTypeAnnotation = isJsInteropTypeAnnotation; } public TypeReference getType() { return type; } /** * Returns {@code true} if the annotation is a JsInterop annotation targeting a type, {@code * false} otherwise. */ public boolean isJsInteropTypeAnnotation() { return isJsInteropTypeAnnotation; } }
apache-2.0
java110/MicroCommunity
service-user/src/main/java/com/java110/user/bmo/rentingAppointment/IUpdateRentingAppointmentBMO.java
404
package com.java110.user.bmo.rentingAppointment; import com.java110.po.rentingAppointment.RentingAppointmentPo; import org.springframework.http.ResponseEntity; public interface IUpdateRentingAppointmentBMO { /** * 修改租赁预约 * add by wuxw * @param rentingAppointmentPo * @return */ ResponseEntity<String> update(RentingAppointmentPo rentingAppointmentPo); }
apache-2.0
brettwooldridge/buck
test/com/facebook/buck/rules/coercer/SourceSortedSetTest.java
8139
/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.rules.coercer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import com.facebook.buck.core.cell.CellPathResolver; import com.facebook.buck.core.cell.TestCellPathResolver; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.BuildTargetFactory; import com.facebook.buck.core.parser.buildtargetparser.BuildTargetPattern; import com.facebook.buck.core.parser.buildtargetparser.BuildTargetPatternParser; import com.facebook.buck.core.sourcepath.DefaultBuildTargetSourcePath; import com.facebook.buck.core.sourcepath.SourcePath; import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem; import com.facebook.buck.rules.coercer.AbstractSourceSortedSet.Type; import com.facebook.buck.versions.FixedTargetNodeTranslator; import com.facebook.buck.versions.TargetNodeTranslator; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedSet; import java.util.Arrays; import java.util.Collections; import java.util.Optional; import org.hamcrest.Matchers; import org.junit.Test; public class SourceSortedSetTest { private static final CellPathResolver CELL_PATH_RESOLVER = TestCellPathResolver.get(new FakeProjectFilesystem()); private static final BuildTargetPatternParser<BuildTargetPattern> PATTERN = BuildTargetPatternParser.fullyQualified(); @Test public void translatedNamedSourcesTargets() { BuildTarget target = BuildTargetFactory.newInstance("//:rule"); BuildTarget newTarget = BuildTargetFactory.newInstance("//something:else"); TargetNodeTranslator translator = new FixedTargetNodeTranslator( new DefaultTypeCoercerFactory(), ImmutableMap.of(target, newTarget)); assertThat( translator.translate( CELL_PATH_RESOLVER, PATTERN, SourceSortedSet.ofNamedSources( ImmutableSortedMap.of("name", DefaultBuildTargetSourcePath.of(target)))), Matchers.equalTo( Optional.of( SourceSortedSet.ofNamedSources( ImmutableSortedMap.of("name", DefaultBuildTargetSourcePath.of(newTarget)))))); } @Test public void untranslatedNamedSourcesTargets() { BuildTarget target = BuildTargetFactory.newInstance("//:rule"); TargetNodeTranslator translator = new FixedTargetNodeTranslator(new DefaultTypeCoercerFactory(), ImmutableMap.of()); SourceSortedSet list = SourceSortedSet.ofNamedSources( ImmutableSortedMap.of("name", DefaultBuildTargetSourcePath.of(target))); assertThat( translator.translate(CELL_PATH_RESOLVER, PATTERN, list), Matchers.equalTo(Optional.empty())); } @Test public void translatedUnnamedSourcesTargets() { BuildTarget target = BuildTargetFactory.newInstance("//:rule"); BuildTarget newTarget = BuildTargetFactory.newInstance("//something:else"); TargetNodeTranslator translator = new FixedTargetNodeTranslator( new DefaultTypeCoercerFactory(), ImmutableMap.of(target, newTarget)); assertThat( translator.translate( CELL_PATH_RESOLVER, PATTERN, SourceSortedSet.ofUnnamedSources( ImmutableSortedSet.of(DefaultBuildTargetSourcePath.of(target)))), Matchers.equalTo( Optional.of( SourceSortedSet.ofUnnamedSources( ImmutableSortedSet.of(DefaultBuildTargetSourcePath.of(newTarget)))))); } @Test public void untranslatedUnnamedSourcesTargets() { BuildTarget target = BuildTargetFactory.newInstance("//:rule"); TargetNodeTranslator translator = new FixedTargetNodeTranslator(new DefaultTypeCoercerFactory(), ImmutableMap.of()); SourceSortedSet list = SourceSortedSet.ofUnnamedSources( ImmutableSortedSet.of(DefaultBuildTargetSourcePath.of(target))); assertThat( translator.translate(CELL_PATH_RESOLVER, PATTERN, list), Matchers.equalTo(Optional.empty())); } @Test public void testConcatOfEmptyListCreatesEmptyList() { assertTrue(SourceSortedSet.concat(Collections.emptyList()).isEmpty()); } @Test public void testConcatOfDifferentTypesThrowsExceptionForUnnamed() { BuildTarget target = BuildTargetFactory.newInstance("//:rule"); SourceSortedSet unnamedList = SourceSortedSet.ofUnnamedSources( ImmutableSortedSet.of(DefaultBuildTargetSourcePath.of(target))); SourceSortedSet namedList = SourceSortedSet.ofNamedSources( ImmutableSortedMap.of("name", DefaultBuildTargetSourcePath.of(target))); try { SourceSortedSet.concat(Arrays.asList(unnamedList, namedList)); } catch (IllegalStateException e) { assertEquals("Expected unnamed source list, got: NAMED", e.getMessage()); } } @Test public void testConcatOfDifferentTypesThrowsExceptionForNamed() { BuildTarget target = BuildTargetFactory.newInstance("//:rule"); SourceSortedSet unnamedList = SourceSortedSet.ofUnnamedSources( ImmutableSortedSet.of(DefaultBuildTargetSourcePath.of(target))); SourceSortedSet namedList = SourceSortedSet.ofNamedSources( ImmutableSortedMap.of("name", DefaultBuildTargetSourcePath.of(target))); try { SourceSortedSet.concat(Arrays.asList(namedList, unnamedList)); } catch (IllegalStateException e) { assertEquals("Expected named source list, got: UNNAMED", e.getMessage()); } } @Test public void testConcatOfSameTypesReturnsCompleteListForUnnamed() { BuildTarget target1 = BuildTargetFactory.newInstance("//:rule1"); BuildTarget target2 = BuildTargetFactory.newInstance("//:rule2"); SourcePath sourcePath1 = DefaultBuildTargetSourcePath.of(target1); SourcePath sourcePath2 = DefaultBuildTargetSourcePath.of(target2); SourceSortedSet unnamedList1 = SourceSortedSet.ofUnnamedSources(ImmutableSortedSet.of(sourcePath1)); SourceSortedSet unnamedList2 = SourceSortedSet.ofUnnamedSources(ImmutableSortedSet.of(sourcePath2)); SourceSortedSet result = SourceSortedSet.concat(Arrays.asList(unnamedList1, unnamedList2)); assertEquals(Type.UNNAMED, result.getType()); assertEquals(2, result.getUnnamedSources().get().size()); assertEquals(sourcePath1, result.getUnnamedSources().get().first()); assertEquals(sourcePath2, result.getUnnamedSources().get().last()); } @Test public void testConcatOfSameTypesReturnsCompleteListForNamed() { BuildTarget target1 = BuildTargetFactory.newInstance("//:rule1"); BuildTarget target2 = BuildTargetFactory.newInstance("//:rule2"); SourcePath sourcePath1 = DefaultBuildTargetSourcePath.of(target1); SourcePath sourcePath2 = DefaultBuildTargetSourcePath.of(target2); SourceSortedSet namedList1 = SourceSortedSet.ofNamedSources(ImmutableSortedMap.of("name1", sourcePath1)); SourceSortedSet namedList2 = SourceSortedSet.ofNamedSources(ImmutableSortedMap.of("name2", sourcePath2)); SourceSortedSet result = SourceSortedSet.concat(Arrays.asList(namedList1, namedList2)); assertEquals(Type.NAMED, result.getType()); assertEquals(2, result.getNamedSources().get().size()); assertEquals(sourcePath1, result.getNamedSources().get().get("name1")); assertEquals(sourcePath2, result.getNamedSources().get().get("name2")); } }
apache-2.0
bobo159357456/bobo
android_project/MyFirstApp/app/src/main/java/com/example/myfirstapp/MainActivity.java
2012
package com.example.myfirstapp; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; public class MainActivity extends ActionBarActivity { public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_main); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_activity_actions,menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case R.id.action_search: openSearch(); return true; case R.id.action_settings: openSettings(); return true; default: return super.onOptionsItemSelected(item); } } /** Called when the user clicks the Send button */ public void sendMessage(View view) { // Do something in response to button Intent intent = new Intent(this, DisplayMessageActivity.class); EditText editText = (EditText) findViewById(R.id.edit_message); String message = editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent); } }
apache-2.0
aldeka/oppia
extensions/widgets/interactive/InteractiveMap/InteractiveMap.py
2179
from core.domain import widget_domain from extensions.value_generators.models import generators class InteractiveMap(widget_domain.BaseWidget): """Definition of a widget. Do NOT make any changes to this widget definition while the Oppia app is running, otherwise things will break. This class represents a widget, whose id is the name of the class. It is auto-discovered when the default widgets are refreshed. """ # The human-readable name of the widget. name = 'Interactive map' # The category the widget falls under in the widget repository. category = 'Custom' # A description of the widget. description = ( 'A map input widget for users to specify a position.') # Customization parameters and their descriptions, types and default # values. This attribute name MUST be prefixed by '_'. _params = [{ 'name': 'latitude', 'description': 'Starting map center latitude (-90 to 90).', 'generator': generators.RangeRestrictedCopier, 'init_args': { 'min_value': -90.0, 'max_value': 90.0 }, 'customization_args': { 'value': 0.0 }, 'obj_type': 'Real' }, { 'name': 'longitude', 'description': 'Starting map center longitude (-180 to 180).', 'generator': generators.RangeRestrictedCopier, 'init_args': { 'min_value': -180.0, 'max_value': 180.0 }, 'customization_args': { 'value': 0.0 }, 'obj_type': 'Real' }, { 'name': 'zoom', 'description': 'Starting map zoom level (0 shows the entire earth).', 'generator': generators.Copier, 'init_args': {}, 'customization_args': { 'value': 0.0 }, 'obj_type': 'Real' }] # Actions that the reader can perform on this widget which trigger a # feedback interaction, and the associated input types. Interactive widgets # must have at least one of these. This attribute name MUST be prefixed by # '_'. _handlers = [{ 'name': 'submit', 'obj_type': 'CoordTwoDim' }]
apache-2.0
850759383/ZhihuDailyNews
app/src/main/java/com/yininghuang/zhihudailynews/detail/ZhihuNewsDetailActivity.java
1885
package com.yininghuang.zhihudailynews.detail; import android.os.Bundle; import android.support.annotation.Nullable; import com.yininghuang.zhihudailynews.BaseActivity; import com.yininghuang.zhihudailynews.R; import com.yininghuang.zhihudailynews.net.Api; import com.yininghuang.zhihudailynews.net.RetrofitHelper; import com.yininghuang.zhihudailynews.net.ZhihuDailyService; import com.yininghuang.zhihudailynews.settings.UserSettingConstants; import com.yininghuang.zhihudailynews.utils.CacheManager; import com.yininghuang.zhihudailynews.utils.DBManager; /** * Created by Yining Huang on 2016/10/18. */ public class ZhihuNewsDetailActivity extends BaseActivity { private static final int LIGHT_THEME = R.style.AppTheme_NoActionBar_TranslucentStatusBar; private static final int DARK_THEME = R.style.AppThemeDark_NoActionBar_TranslucentStatusBar; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (UserSettingConstants.DARK_THEME) setTheme(DARK_THEME); else setTheme(LIGHT_THEME); setContentView(R.layout.activity_zhihu_news_detail); ZhihuNewsDetailFragment fragment = (ZhihuNewsDetailFragment) getSupportFragmentManager() .findFragmentById(R.id.mainFrameLayout); if (fragment == null) { fragment = ZhihuNewsDetailFragment.newInstance(getIntent().getIntExtra("id", -1)); getSupportFragmentManager().beginTransaction() .replace(R.id.mainFrameLayout, fragment) .commit(); } new ZhihuNewsDetailPresenter( fragment, RetrofitHelper.getInstance().createRetrofit(ZhihuDailyService.class, Api.ZHIHU_BASE_URL), new DBManager(this), CacheManager.getInstance(this) ); } }
apache-2.0
amarbarik/iPayPrepaidVendor
src/za/co/ipay/prepaid/vendor/client/IPayPrepaidElectricity.java
995
package za.co.ipay.prepaid.vendor.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.*; import za.co.ipay.prepaid.vendor.client.dto.MeterDTO; import za.co.ipay.prepaid.vendor.client.dto.PayTypeDTO; import java.util.ArrayList; import java.util.List; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class IPayPrepaidElectricity implements EntryPoint { /** * This is the entry point method. */ public void onModuleLoad() { PrepaidElectricityForm prepaidElectricityForm = new PrepaidElectricityForm(); RootPanel.get().add(prepaidElectricityForm); } }
apache-2.0
HuangLS/neo4j
community/kernel/src/test/java/org/neo4j/unsafe/impl/batchimport/staging/QuantizedProjectionTest.java
1552
/* * Copyright (c) 2002-2018 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.unsafe.impl.batchimport.staging; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class QuantizedProjectionTest { @Test public void shouldProjectSteps() throws Exception { // GIVEN QuantizedProjection projection = new QuantizedProjection( 9, 7 ); // WHEN/THEN assertTrue( projection.next( 3 ) ); assertEquals( 2, projection.step() ); assertTrue( projection.next( 3 ) ); assertEquals( 3, projection.step() ); assertTrue( projection.next( 3 ) ); assertEquals( 2, projection.step() ); assertFalse( projection.next( 1 ) ); } }
apache-2.0
open-orchestra/open-orchestra-front-bundle
FrontBundle/SubQuery/Strategies/RequestSubQueryStrategy.php
813
<?php namespace OpenOrchestra\FrontBundle\SubQuery\Strategies; /** * Class RequestSubQueryStrategy */ class RequestSubQueryStrategy extends AbstractRequestSubQueryStrategy { /** * @param string $blockParameter * * @return bool */ public function support($blockParameter) { return strpos($blockParameter, 'request.') === 0; } /** * @param string $blockParameter * * @return array */ public function generate($blockParameter) { $parameter = str_replace('request.', '', $blockParameter); $request = $this->requestStack->getMasterRequest(); return array($parameter => $request->get($parameter)); } /** * @return string */ public function getName() { return 'request'; } }
apache-2.0
InstaList/instalist-android-backend
src/main/java/org/noorganization/instalist/presenter/IListController.java
8092
/* * Copyright 2016 Tino Siegmund, Michael Wodniok * * 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.noorganization.instalist.presenter; import android.support.annotation.NonNull; import org.noorganization.instalist.model.Category; import org.noorganization.instalist.model.ListEntry; import org.noorganization.instalist.model.Product; import org.noorganization.instalist.model.ShoppingList; import java.util.List; /** * IListController is the (by software engineering created) interface for modifying * shopping lists. If there is no documentation for the methods, following is always valid: * - for parameters, null's are not allowed. If set to null, no modification will be made and false * will be returned. * - it will be always returned whether the modification worked. * Created by michi on 20.04.2015. */ public interface IListController { /** * Shortcut for {@link #addOrChangeItem(ShoppingList, Product, float, int)} with priority set to * 0 and replacing amount of an existing item. */ ListEntry addOrChangeItem(ShoppingList _list, Product _product, float _amount); /** * Shortcut for {@link #addOrChangeItem(ShoppingList, Product, float, int, boolean)}, replacing * amount of an existing item. */ ListEntry addOrChangeItem(ShoppingList _list, Product _product, float _amount, int _prio); /** * Shortcut for {@link #addOrChangeItem(ShoppingList, Product, float, int, boolean)}, not * updating any priority (if creating, then set to 0) */ ListEntry addOrChangeItem(ShoppingList _list, Product _product, float _amount, boolean _addAmount); /** * * Adds or updates an item to an existing list. The amount will be updated (not added) if the * corresponding ListEntry already exists. * @param _list A valid ShoppingList, not null. * @param _product A valid Product, not null. * @param _amount The amount of the product. Not +infty, NaN or lesser than 0.001f. * @param _prio The priority of the ListEntry. 0 does mean neutral, higher values mean higher * priority. * @param _addAmount Whether to add the amount if ListEntry exits (= true) or to replace it * (= false). * @return The created or updated ListEntry. If not worked, null or the old item will be * returned. */ ListEntry addOrChangeItem(ShoppingList _list, Product _product, float _amount, int _prio, boolean _addAmount); List<ShoppingList> getAllLists(); /** * Searches a ListEntry. * @param _UUID The UUID identifying the entry. * @return The found ListEntry or null if something went wrong or not found. */ ListEntry getEntryById(@NonNull String _UUID); /** * Searchess a ListEntry. * @param _list The list as parameter for the search. Not null. * @param _product The product as parameter for the search. Not null. * @return Either the found entry or null if nothing found or something went wrong. */ ListEntry getEntryByListAndProduct(@NonNull ShoppingList _list, @NonNull Product _product); int getEntryCount(@NonNull ShoppingList _list); /** * Searches a ShoppingList. * @param _UUID The UUID identifying the list. * @return The found ShoppingList or null if something went wrong or not found. */ ShoppingList getListById(@NonNull String _UUID); /** * Searches ShoppingLists with given ids. * @param _category The category, to use as parameter. If null, lists will be searched, which * don't belong to a category. * @return Either a list with results (may be also empty) or null if category does not exist (if * set) or an error occurs. */ List<ShoppingList> getListsByCategory(Category _category); /** * Strikes all items on a list. * @param _list The valid shopping list to strike. Not null. */ void strikeAllItems(ShoppingList _list); /** * Unstrikes all items on a list. * @param _list The valid shopping list to strike. Not null. */ void unstrikeAllItems(ShoppingList _list); /** * Strikes a ListEntry. * @param _list A valid ShoppingList, not null. * @param _product A valid Product, not null. * @return The changed item or null, if not found or parameters invalid. */ ListEntry strikeItem(ShoppingList _list, Product _product); /** * Removes the virtual stroke from a ListEntry. * @param _list A valid ShoppingList, not null. * @param _product A valid Product, not null. * @return The changed item or null, if not found or parameters invalid. */ ListEntry unstrikeItem(ShoppingList _list, Product _product); /** * Alias for {@link #strikeItem(org.noorganization.instalist.model.ShoppingList, org.noorganization.instalist.model.Product)}. * @param _item A valid ListEntry, not null. * @return The changed item or null, if _item was invalid. */ ListEntry strikeItem(ListEntry _item); /** * Alias for {@link #unstrikeItem(org.noorganization.instalist.model.ShoppingList, org.noorganization.instalist.model.Product)}. * @param _item A valid ListEntry, not null. * @return The changed item or null if _item was invalid. */ ListEntry unstrikeItem(ListEntry _item); boolean removeItem(ShoppingList _list, Product _product); boolean removeItem(ListEntry _item); /** * Set a new priority for an item. * @param _item The item to priorize, not null, saved. * @param _newPrio A new priority (0 = neutral, less = lower priority, more = higher priority). * @return The changed ListEntry or null if not found. */ ListEntry setItemPriority(ListEntry _item, int _newPrio); /** * Creates a list and returns it. * @param _name The name of the new list. Not null, not empty. * @return The new list or null, if creation failed. */ ShoppingList addList(String _name); /** * Creates a list in a specific category. * @param _name The name of the category. Not null, not empty. * @param _category The specific, already saved category. Null is possible if no category. * @return The created list or null if creation failed. */ ShoppingList addList(String _name, Category _category); boolean removeList(ShoppingList _list); /** * Renames a list and returns it. The name must be unique or the rename will fail. * @param _list A valid ShoppingList, not null. * @param _newName A new name for the list. Not null, not empty. * @return The modified list or the old list. */ ShoppingList renameList(ShoppingList _list, String _newName); /** * Moves a list to a category. * @param _list The list to move (saved, not null). * @param _category The saved category or null, if no category. If category can't be found and * is not null, moving fails. * @return The changed ShoppingList or null if moving failed. */ ShoppingList moveToCategory(ShoppingList _list, Category _category); /** * List all entries of a given shoppinglist * @param _shoppingListUUID the uuid of the shoppingList * @param _categoryUUID * @return an empty list or a filled list with corresponding {@link ListEntry}s. Or null if an error occured. */ List<ListEntry> listAllListEntries(String _shoppingListUUID, String _categoryUUID); }
apache-2.0
jfiala/swagger-spring-demo
archive/user-rest-service-1.0.2-client-php-codegen-2.1.2-M1/UsergettworeadApi.php
2080
<?php /** * Copyright 2015 Reverb Technologies, 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. */ /** * * NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. */ class UsergettworeadApi { function __construct($apiClient) { $this->apiClient = $apiClient; } /** * getUser * * read User by ID * id, int: id (required) * * @return User */ public function getUser($id) { // parse inputs $resourcePath = "/user_get_two_read1"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "GET"; $queryParams = array(); $headerParams = array(); $formParams = array(); $headerParams['Accept'] = '*/*'; $headerParams['Content-Type'] = 'application/json'; // query params if($id !== null) { $queryParams['id'] = $this->apiClient->toQueryValue($id); } $body = $body ?: $formParams; if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { $body = http_build_query($body); } // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $body, $headerParams); if(! $response) { return null; } $responseObject = $this->apiClient->deserialize($response, 'User'); return $responseObject; } }
apache-2.0
pdxrunner/geode
geode-core/src/main/java/org/apache/geode/internal/cache/tx/RemoteGetMessage.java
14706
/* * 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.geode.internal.cache.tx; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Set; import org.apache.logging.log4j.Logger; import org.apache.geode.DataSerializer; import org.apache.geode.distributed.DistributedSystemDisconnectedException; import org.apache.geode.distributed.internal.ClusterDistributionManager; import org.apache.geode.distributed.internal.DirectReplyProcessor; import org.apache.geode.distributed.internal.DistributionManager; import org.apache.geode.distributed.internal.DistributionMessage; import org.apache.geode.distributed.internal.DistributionStats; import org.apache.geode.distributed.internal.InternalDistributedSystem; import org.apache.geode.distributed.internal.ReplyException; import org.apache.geode.distributed.internal.ReplyMessage; import org.apache.geode.distributed.internal.ReplyProcessor21; import org.apache.geode.distributed.internal.ReplySender; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.internal.Assert; import org.apache.geode.internal.InternalDataSerializer; import org.apache.geode.internal.Version; import org.apache.geode.internal.cache.BucketRegion.RawValue; import org.apache.geode.internal.cache.CachedDeserializableFactory; import org.apache.geode.internal.cache.DataLocationException; import org.apache.geode.internal.cache.EntryEventImpl; import org.apache.geode.internal.cache.KeyInfo; import org.apache.geode.internal.cache.LocalRegion; import org.apache.geode.internal.cache.RemoteOperationException; import org.apache.geode.internal.cache.TXManagerImpl; import org.apache.geode.internal.cache.TXStateProxy; import org.apache.geode.internal.cache.tier.sockets.ClientProxyMembershipID; import org.apache.geode.internal.logging.LogService; import org.apache.geode.internal.logging.log4j.LogMarker; import org.apache.geode.internal.offheap.OffHeapHelper; import org.apache.geode.internal.util.BlobHelper; /** * This message is used as the request for a get operation done in a transaction that is hosted on a * remote member. This messsage sends the get to the remote member. * * @since GemFire 6.5 */ public class RemoteGetMessage extends RemoteOperationMessageWithDirectReply { private static final Logger logger = LogService.getLogger(); private Object key; /** The callback arg of the operation */ private Object cbArg; private ClientProxyMembershipID context; /** * Empty constructor to satisfy {@link DataSerializer} requirements */ public RemoteGetMessage() {} private RemoteGetMessage(InternalDistributedMember recipient, String regionPath, DirectReplyProcessor processor, final Object key, final Object aCallbackArgument, ClientProxyMembershipID context) { super(recipient, regionPath, processor); this.key = key; this.cbArg = aCallbackArgument; this.context = context; } @Override protected boolean operateOnRegion(final ClusterDistributionManager dm, LocalRegion r, long startTime) throws RemoteOperationException { if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) { logger.trace(LogMarker.DM_VERBOSE, "RemoteGetMessage operateOnRegion: {}", r.getFullPath()); } if (this.getTXUniqId() != TXManagerImpl.NOTX) { assert r.getDataView() instanceof TXStateProxy; } r.waitOnInitialization(); // bug #43371 - accessing a region before it's initialized RawValue valueBytes; Object val = null; try { KeyInfo keyInfo = r.getKeyInfo(key, cbArg); val = r.getDataView().getSerializedValue(r, keyInfo, false, this.context, null, false /* for replicate regions */); valueBytes = val instanceof RawValue ? (RawValue) val : new RawValue(val); if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) { logger.trace(LogMarker.DM_VERBOSE, "GetMessage sending serialized value {} back via GetReplyMessage using processorId: {}", valueBytes, getProcessorId()); } GetReplyMessage.send(getSender(), getProcessorId(), valueBytes, getReplySender(dm)); // Unless an exception was thrown, this message handles sending the response return false; } catch (DistributedSystemDisconnectedException sde) { sendReply(getSender(), this.processorId, dm, new ReplyException(new RemoteOperationException( "Operation got interrupted due to shutdown in progress on remote VM.", sde)), r, startTime); return false; } catch (DataLocationException e) { sendReply(getSender(), getProcessorId(), dm, new ReplyException(e), r, startTime); return false; } finally { OffHeapHelper.release(val); } } @Override protected void appendFields(StringBuffer buff) { super.appendFields(buff); buff.append("; key=").append(this.key).append("; callback arg=").append(this.cbArg); } public int getDSFID() { return R_GET_MESSAGE; } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { super.fromData(in); this.key = DataSerializer.readObject(in); this.cbArg = DataSerializer.readObject(in); this.context = DataSerializer.readObject(in); } @Override public void toData(DataOutput out) throws IOException { super.toData(out); DataSerializer.writeObject(this.key, out); DataSerializer.writeObject(this.cbArg, out); DataSerializer.writeObject(this.context, out); } public void setKey(Object key) { this.key = key; } /** * Sends a ReplicateRegion {@link org.apache.geode.cache.Region#get(Object)} message * * @param recipient the member that the get message is sent to * @param r the ReplicateRegion for which get was performed upon * @param key the object to which the value should be feteched * @param requestingClient the client requesting the value * @return the processor used to fetch the returned value associated with the key */ public static RemoteGetResponse send(InternalDistributedMember recipient, LocalRegion r, final Object key, final Object aCallbackArgument, ClientProxyMembershipID requestingClient) throws RemoteOperationException { Assert.assertTrue(recipient != null, "RemoteGetMessage NULL recipient"); RemoteGetResponse p = new RemoteGetResponse(r.getSystem(), recipient); RemoteGetMessage m = new RemoteGetMessage(recipient, r.getFullPath(), p, key, aCallbackArgument, requestingClient); Set<?> failures = r.getDistributionManager().putOutgoing(m); if (failures != null && failures.size() > 0) { throw new RemoteOperationException( String.format("Failed sending < %s >", m)); } return p; } /** * This message is used for the reply to a * {@link org.apache.geode.cache.Region#get(Object)}operation This is the reply to a * {@link RemoteGetMessage}. * * Since the {@link org.apache.geode.cache.Region#get(Object)}operation is used <bold>very </bold> * frequently the performance of this class is critical. * * @since GemFire 6.5 */ public static class GetReplyMessage extends ReplyMessage { /** * The raw value in the cache which may be serialized to the output stream, if it is NOT already * a byte array */ private transient RawValue rawVal; /** * Indicates that the value already a byte array (aka user blob) and does not need * de-serialization */ public boolean valueIsByteArray; /* * Used on the fromData side to transfer the value bytes to the requesting thread */ public transient byte[] valueInBytes; public transient Version remoteVersion; /** * Empty constructor to conform to DataSerializable interface */ public GetReplyMessage() {} private GetReplyMessage(int processorId, RawValue val) { setProcessorId(processorId); this.rawVal = val; this.valueIsByteArray = val.isValueByteArray(); } /** GetReplyMessages are always processed in-line */ @Override public boolean getInlineProcess() { return true; } /** * Return the value from the get operation, serialize it bytes as late as possible to avoid * making un-neccesary byte[] copies. De-serialize those same bytes as late as possible to avoid * using precious threads (aka P2P readers). * * @param recipient the origin VM that performed the get * @param processorId the processor on which the origin thread is waiting * @param val the raw value that will eventually be serialized * @param replySender distribution manager used to send the reply */ public static void send(InternalDistributedMember recipient, int processorId, RawValue val, ReplySender replySender) throws RemoteOperationException { Assert.assertTrue(recipient != null, "PRDistribuedGetReplyMessage NULL reply message"); GetReplyMessage m = new GetReplyMessage(processorId, val); m.setRecipient(recipient); replySender.putOutgoing(m); } /** * Processes this message. This method is invoked by the receiver of the message. * * @param dm the distribution manager that is processing the message. */ @Override public void process(final DistributionManager dm, ReplyProcessor21 processor) { final boolean isDebugEnabled = logger.isTraceEnabled(LogMarker.DM_VERBOSE); final long startTime = getTimestamp(); if (isDebugEnabled) { logger.trace(LogMarker.DM_VERBOSE, "GetReplyMessage process invoking reply processor with processorId:{}", this.processorId); } if (processor == null) { if (isDebugEnabled) { logger.trace(LogMarker.DM_VERBOSE, "GetReplyMessage processor not found"); } return; } processor.process(this); if (isDebugEnabled) { logger.trace(LogMarker.DM_VERBOSE, "{} Processed {}", processor, this); } dm.getStats().incReplyMessageTime(DistributionStats.getStatTime() - startTime); } @Override public int getDSFID() { return R_GET_REPLY_MESSAGE; } @Override public void toData(DataOutput out) throws IOException { super.toData(out); out.writeByte(this.valueIsByteArray ? 1 : 0); this.rawVal.writeAsByteArray(out); } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { super.fromData(in); this.valueIsByteArray = (in.readByte() == 1); this.valueInBytes = DataSerializer.readByteArray(in); if (!this.valueIsByteArray) { this.remoteVersion = InternalDataSerializer.getVersionForDataStreamOrNull(in); } } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("GetReplyMessage ").append("processorid=").append(this.processorId) .append(" reply to sender ").append(this.getSender()) .append(" returning serialized value=").append(this.rawVal); return sb.toString(); } } /** * A processor to capture the value returned by * {@link org.apache.geode.internal.cache.tx.RemoteGetMessage.GetReplyMessage} * * @since GemFire 5.0 */ public static class RemoteGetResponse extends RemoteOperationResponse { private volatile GetReplyMessage getReply; private volatile boolean returnValueReceived; private volatile long start; public RemoteGetResponse(InternalDistributedSystem ds, InternalDistributedMember recipient) { super(ds, recipient, false); } @Override public void process(DistributionMessage msg) { if (DistributionStats.enableClockStats) { this.start = DistributionStats.getStatTime(); } if (msg instanceof GetReplyMessage) { GetReplyMessage reply = (GetReplyMessage) msg; // De-serialization needs to occur in the requesting thread, not a P2P thread // (or some other limited resource) if (reply.valueInBytes != null) { this.getReply = reply; } this.returnValueReceived = true; } super.process(msg); } /** * De-seralize the value, if the value isn't already a byte array, this method should be called * in the context of the requesting thread for the best scalability * * @see EntryEventImpl#deserialize(byte[]) * @return the value object */ public Object getValue(boolean preferCD) throws RemoteOperationException { final GetReplyMessage reply = this.getReply; try { if (reply != null) { if (reply.valueIsByteArray) { return reply.valueInBytes; } else if (preferCD) { return CachedDeserializableFactory.create(reply.valueInBytes, getDistributionManager().getCache()); } else { return BlobHelper.deserializeBlob(reply.valueInBytes, reply.remoteVersion, null); } } return null; } catch (IOException e) { throw new RemoteOperationException( "Unable to deserialize value (IOException)", e); } catch (ClassNotFoundException e) { throw new RemoteOperationException( "Unable to deserialize value (ClassNotFoundException)", e); } } /** * @return Object associated with the key that was sent in the get message */ public Object waitForResponse(boolean preferCD) throws RemoteOperationException { waitForRemoteResponse(); if (DistributionStats.enableClockStats) { getDistributionManager().getStats().incReplyHandOffTime(this.start); } if (!this.returnValueReceived) { throw new RemoteOperationException( "no return value received"); } return getValue(preferCD); } } }
apache-2.0
alibaba/fastjson
src/test/java/com/alibaba/json/bvt/issue_1800/Issue1879.java
1582
package com.alibaba.json.bvt.issue_1800; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONCreator; import com.alibaba.fastjson.annotation.JSONField; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List; public class Issue1879 extends TestCase { // public void test_for_issue() throws Exception { // String json = "{\n" + // " \"ids\" : \"1,2,3\"\n" + // "}"; // M1 m = JSON.parseObject(json, M1.class); // } public void test_for_issue_2() throws Exception { String json = "{\n" + " \"ids\" : \"1,2,3\"\n" + "}"; M2 m = JSON.parseObject(json, M2.class); } public static class M1 { private List<Long> ids; @JSONCreator public M1(@JSONField(name = "ids") String ids) { this.ids = new ArrayList<Long>(); for(String id : ids.split(",")) { this.ids.add(Long.valueOf(id)); } } public List<Long> getIds() { return ids; } public void setIds(List<Long> ids) { this.ids = ids; } } public static class M2 { private List<Long> ids; @JSONCreator public M2(@JSONField(name = "ids") Long id) { this.ids = new ArrayList<Long>(); this.ids.add(id); } public List<Long> getIds() { return ids; } public void setIds(List<Long> ids) { this.ids = ids; } } }
apache-2.0
reflectsoftware/Plato.NET
src/Plato.Messaging.AMQ/AMQReceiverText.cs
1638
// Plato.NET // Copyright (c) 2018 ReflectSoftware Inc. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Apache.NMS; using Plato.Messaging.AMQ.Interfaces; using Plato.Messaging.AMQ.Settings; using Plato.Messaging.Interfaces; using System.Threading; namespace Plato.Messaging.AMQ { /// <summary> /// /// </summary> /// <seealso cref="Plato.Messaging.AMQ.AMQReceiver" /> /// <seealso cref="Plato.Messaging.AMQ.Interfaces.IAMQReceiverText" /> public class AMQReceiverText : AMQReceiver, IAMQReceiverText { /// <summary> /// Initializes a new instance of the <see cref="AMQReceiverText" /> class. /// </summary> /// <param name="connectionFactory">The connection factory.</param> /// <param name="connectionSettings">The connection settings.</param> /// <param name="destination">The destination.</param> public AMQReceiverText(IAMQConnectionFactory connectionFactory, AMQConnectionSettings connectionSettings, AMQDestinationSettings destination) : base(connectionFactory, connectionSettings, destination) { } /// <summary> /// Receives the specified msec timeout. /// </summary> /// <param name="msecTimeout">The msec timeout.</param> /// <returns></returns> public IMessageReceiveResult<string> Receive(int msecTimeout = Timeout.Infinite) { var message = ReceiveMessage(msecTimeout); return message != null ?new AMQReceiverTextResult((ITextMessage)message) : null; } } }
apache-2.0
darenegade/Apollon
Frontend/components/SongListEntry.js
3207
var React = require('react'); const ImageStyle = { height: '123px', width: '110px', }; const CountStyle = { fontSize: '1.1em', fontWeight: 'bold', paddingTop: '5px' }; function IconVoteStyle(a, b) { return { margin: '5px', fontSize: '2.5em', color: arguments.length && a == b ? 'red' : '' }; } var SongListEntry = React.createClass({ makeClickHandler(value) { return (e) => { e.preventDefault(); this.props.handle(this.props.song.id, value); }; }, render(){ return ( <div className="panel panel-default"> <div className="panel-body"> <div className="col-xs-4 col-md-4 col-lg-7 no-padding"> <img src={this.props.song.imageUrl} style={ImageStyle} /> </div> <div className="col-xs-8 col-s-8 col-md-8 cd-lg-5 no-padding"> <div className="col-xs-7 col-md-7 col-lg-7 no-padding"> <div className="artist-name">{this.props.song.artistName}</div> <div className="song-name">{this.props.song.name}</div> <div className="smalltext">{this.props.song.albumName}</div> { this.props.view == 'wish' || this.props.view == 'wish-admin' ? <div> <span style={CountStyle}>{(this.props.score > 0 ? "+" : "") + this.props.score}</span> </div> : <span></span> } </div> { this.props.view == "wish" ? <div className="col-xs-4 col-s-4 col-md-4 col-lg-7"> <button className="icon-button" onClick={this.makeClickHandler(+1)}> <i className="fa fa-heart-o fa-2x" style={IconVoteStyle(this.props.voted, "UP")} aria-hidden="true"></i> </button> <button className="icon-button" onClick={this.makeClickHandler(-1)}> <i className="fa fa-thumbs-o-down fa-2x" style={IconVoteStyle(this.props.voted, "DOWN")} aria-hidden="true"></i> </button> </div> : this.props.view == "wish-admin" ? <div className="col-xs-4 col-s-4 col-md-4 col-xs-4 col-md-4 col-lg-7"> <button className="icon-button" onClick={this.makeClickHandler(+1)}> <i className="fa fa-heart-o fa-2x" style={IconVoteStyle(this.props.voted, "UP")} aria-hidden="true"></i> </button> <button className="icon-button" onClick={this.makeClickHandler(-1)}> <i className="fa fa-thumbs-o-down fa-2x" style={IconVoteStyle(this.props.voted, "DOWN")} aria-hidden="true"></i> </button> </div> : this.props.view == "browse" ? <div className="col-xs-4 col-s-4 col-md-4 col-xs-4 col-md-4 col-lg-7"> <button className="icon-button" onClick={this.makeClickHandler(+1)}> <i className="fa fa-heart-o fa-2x" style={IconVoteStyle(this.props.voted, "UP")} aria-hidden="true"></i> </button> </div> : this.props.view == "browse-admin" ? <div className="col-xs-4 col-s-4 col-md-4 col-xs-4 col-md-4 col-lg-7"> <button className="icon-button" onClick={this.makeClickHandler(+1)}> <i className="fa fa-heart-o fa-2x" style={IconVoteStyle(this.props.voted, "UP")} aria-hidden="true"></i> </button> </div> : <div className="col-xs-4 col-s-4 col-md-4 col-xs-4 col-md-4 col-lg-7"></div> } </div> </div> </div> ) } }); module.exports = SongListEntry;
apache-2.0
asakusafw/asakusafw
windgate-project/asakusa-windgate-core/src/main/java/com/asakusafw/windgate/core/resource/package-info.java
718
/** * Copyright 2011-2021 Asakusa Framework Team. * * 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. */ /** * Abstract implementations of WindGate resources. */ package com.asakusafw.windgate.core.resource;
apache-2.0
xgqfrms/JavaWeb
DesignPattern_Homework/src/strategy_2/Monkey.java
1532
package strategy_2; //============================== // // A subclass of the strategy hierarchy //==============================// import java.awt.Color; import javax.swing.ImageIcon; public class Monkey implements ChineseZodiac { public String say(){ String description ="You have a zodiac Monkey. \n"+ "Monkey people are intelligent, witty and possess an general attractive personality. They are "+ "talktive and very easy to communicate with. Monkeys are also fast learners. Some "+ "people don't like the Monkey personality, such as restless, sly, inquistive behaviour. "+ "Sometimes a monkey don't know why some other people don't like them. With a wide range "+ "of interests, monkeys can perform very well in many kinds of jobs, but are reluctant to work from 9 - 5. "+ "Personality: \n"+ "Eloquent, smart, quick-witted, sociable, agile mentally and physically, creative, innovative and "+ "competitive. An inventor, motivator and problem solver. Can be snobbish, egotistical, overly "+ "optimistic, impatient, reckless, inquisitive and vain."+ "Most Compatible With: Dragon, Rat\n"+ "Most Incompatible With: Snake, Pig, Tiger\n"+ "The following occupations best suit the Monkey personality."+ "Scientist, Journalist, Editor, Filem director, Jeweller, Actor, Writer, "+ "Air traffic controller, Engineer, Market trader \n"; return description; } public ImageIcon setImgIcon(){ ImageIcon angryFace = new ImageIcon("images/monkey.jpg"); return angryFace; } }
apache-2.0