repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
dongjiaqiang/tez
tez-runtime-library/src/main/java/org/apache/tez/runtime/library/common/shuffle/orderedgrouped/ShuffleInputEventHandlerOrderedGrouped.java
8132
/** * 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.tez.runtime.library.common.shuffle.orderedgrouped; import java.io.IOException; import java.net.URI; import java.util.BitSet; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.ByteString; import org.apache.tez.runtime.library.common.shuffle.ShuffleEventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.tez.common.TezCommonUtils; import org.apache.tez.common.TezUtilsInternal; import org.apache.tez.dag.api.TezUncheckedException; import org.apache.tez.runtime.api.Event; import org.apache.tez.runtime.api.InputContext; import org.apache.tez.runtime.api.events.DataMovementEvent; import org.apache.tez.runtime.api.events.InputFailedEvent; import org.apache.tez.runtime.library.common.InputAttemptIdentifier; import org.apache.tez.runtime.library.common.InputIdentifier; import org.apache.tez.runtime.library.common.shuffle.ShuffleUtils; import org.apache.tez.runtime.library.shuffle.impl.ShuffleUserPayloads.DataMovementEventPayloadProto; import com.google.protobuf.InvalidProtocolBufferException; public class ShuffleInputEventHandlerOrderedGrouped implements ShuffleEventHandler { private static final Logger LOG = LoggerFactory.getLogger(ShuffleInputEventHandlerOrderedGrouped.class); private final ShuffleScheduler scheduler; private final InputContext inputContext; private int maxMapRuntime = 0; private final boolean sslShuffle; private final AtomicInteger nextToLogEventCount = new AtomicInteger(0); private final AtomicInteger numDmeEvents = new AtomicInteger(0); private final AtomicInteger numObsoletionEvents = new AtomicInteger(0); private final AtomicInteger numDmeEventsNoData = new AtomicInteger(0); public ShuffleInputEventHandlerOrderedGrouped(InputContext inputContext, ShuffleScheduler scheduler, boolean sslShuffle) { this.inputContext = inputContext; this.scheduler = scheduler; this.sslShuffle = sslShuffle; } @Override public void handleEvents(List<Event> events) throws IOException { for (Event event : events) { handleEvent(event); } } @Override public void logProgress(boolean updateOnClose) { LOG.info(inputContext.getSourceVertexName() + ": " + "numDmeEventsSeen=" + numDmeEvents.get() + ", numDmeEventsSeenWithNoData=" + numDmeEventsNoData.get() + ", numObsoletionEventsSeen=" + numObsoletionEvents.get() + (updateOnClose == true ? ", updateOnClose" : "")); } private void handleEvent(Event event) throws IOException { if (event instanceof DataMovementEvent) { numDmeEvents.incrementAndGet(); processDataMovementEvent((DataMovementEvent) event); scheduler.updateEventReceivedTime(); } else if (event instanceof InputFailedEvent) { numObsoletionEvents.incrementAndGet(); processTaskFailedEvent((InputFailedEvent) event); } if (numDmeEvents.get() + numObsoletionEvents.get() > nextToLogEventCount.get()) { logProgress(false); // Log every 50 events seen. nextToLogEventCount.addAndGet(50); } } private void processDataMovementEvent(DataMovementEvent dmEvent) throws IOException { DataMovementEventPayloadProto shufflePayload; try { shufflePayload = DataMovementEventPayloadProto.parseFrom(ByteString.copyFrom(dmEvent.getUserPayload())); } catch (InvalidProtocolBufferException e) { throw new TezUncheckedException("Unable to parse DataMovementEvent payload", e); } int partitionId = dmEvent.getSourceIndex(); if (LOG.isDebugEnabled()) { LOG.debug("DME srcIdx: " + partitionId + ", targetIdx: " + dmEvent.getTargetIndex() + ", attemptNum: " + dmEvent.getVersion() + ", payload: " + ShuffleUtils.stringify(shufflePayload)); } // TODO NEWTEZ See if this duration hack can be removed. int duration = shufflePayload.getRunDuration(); if (duration > maxMapRuntime) { maxMapRuntime = duration; scheduler.informMaxMapRunTime(maxMapRuntime); } if (shufflePayload.hasEmptyPartitions()) { try { byte[] emptyPartitions = TezCommonUtils.decompressByteStringToByteArray(shufflePayload.getEmptyPartitions()); BitSet emptyPartitionsBitSet = TezUtilsInternal.fromByteArray(emptyPartitions); if (emptyPartitionsBitSet.get(partitionId)) { InputAttemptIdentifier srcAttemptIdentifier = constructInputAttemptIdentifier(dmEvent, shufflePayload); if (LOG.isDebugEnabled()) { LOG.debug( "Source partition: " + partitionId + " did not generate any data. SrcAttempt: [" + srcAttemptIdentifier + "]. Not fetching."); } numDmeEventsNoData.incrementAndGet(); scheduler.copySucceeded(srcAttemptIdentifier, null, 0, 0, 0, null); return; } } catch (IOException e) { throw new TezUncheckedException("Unable to set " + "the empty partition to succeeded", e); } } InputAttemptIdentifier srcAttemptIdentifier = constructInputAttemptIdentifier(dmEvent, shufflePayload); URI baseUri = getBaseURI(shufflePayload.getHost(), shufflePayload.getPort(), partitionId); scheduler.addKnownMapOutput(shufflePayload.getHost(), shufflePayload.getPort(), partitionId, baseUri.toString(), srcAttemptIdentifier); } private void processTaskFailedEvent(InputFailedEvent ifEvent) { InputAttemptIdentifier taIdentifier = new InputAttemptIdentifier(ifEvent.getTargetIndex(), ifEvent.getVersion()); scheduler.obsoleteInput(taIdentifier); if (LOG.isDebugEnabled()) { LOG.debug("Obsoleting output of src-task: " + taIdentifier); } } @VisibleForTesting URI getBaseURI(String host, int port, int partitionId) { StringBuilder sb = ShuffleUtils.constructBaseURIForShuffleHandler(host, port, partitionId, inputContext.getApplicationId().toString(), inputContext.getDagIdentifier(), sslShuffle); URI u = URI.create(sb.toString()); return u; } /** * Helper method to create InputAttemptIdentifier * * @param dmEvent * @param shufflePayload * @return InputAttemptIdentifier */ private InputAttemptIdentifier constructInputAttemptIdentifier(DataMovementEvent dmEvent, DataMovementEventPayloadProto shufflePayload) { String pathComponent = (shufflePayload.hasPathComponent()) ? shufflePayload.getPathComponent() : null; int spillEventId = shufflePayload.getSpillId(); InputAttemptIdentifier srcAttemptIdentifier = null; if (shufflePayload.hasSpillId()) { boolean lastEvent = shufflePayload.getLastEvent(); InputAttemptIdentifier.SPILL_INFO info = (lastEvent) ? InputAttemptIdentifier.SPILL_INFO .FINAL_UPDATE : InputAttemptIdentifier.SPILL_INFO.INCREMENTAL_UPDATE; srcAttemptIdentifier = new InputAttemptIdentifier(new InputIdentifier(dmEvent.getTargetIndex()), dmEvent .getVersion(), pathComponent, false, info, spillEventId); } else { srcAttemptIdentifier = new InputAttemptIdentifier(dmEvent.getTargetIndex(), dmEvent.getVersion(), pathComponent); } return srcAttemptIdentifier; } }
apache-2.0
ened/ExoPlayer
extensions/flac/src/androidTest/java/com/google/android/exoplayer2/ext/flac/FlacPlaybackTest.java
5082
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.ext.flac; import static org.junit.Assert.fail; import android.content.Context; import android.net.Uri; import android.os.Looper; import androidx.annotation.Nullable; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.MediaItem; import com.google.android.exoplayer2.PlaybackException; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.Renderer; import com.google.android.exoplayer2.RenderersFactory; import com.google.android.exoplayer2.audio.AudioProcessor; import com.google.android.exoplayer2.audio.AudioSink; import com.google.android.exoplayer2.audio.DefaultAudioSink; import com.google.android.exoplayer2.extractor.mkv.MatroskaExtractor; import com.google.android.exoplayer2.source.MediaSource; import com.google.android.exoplayer2.source.ProgressiveMediaSource; import com.google.android.exoplayer2.testutil.CapturingAudioSink; import com.google.android.exoplayer2.testutil.DumpFileAsserts; import com.google.android.exoplayer2.upstream.DefaultDataSource; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** Playback tests using {@link LibflacAudioRenderer}. */ @RunWith(AndroidJUnit4.class) public class FlacPlaybackTest { private static final String BEAR_FLAC_16BIT = "mka/bear-flac-16bit.mka"; private static final String BEAR_FLAC_24BIT = "mka/bear-flac-24bit.mka"; @Before public void setUp() { if (!FlacLibrary.isAvailable()) { fail("Flac library not available."); } } @Test public void test16BitPlayback() throws Exception { playAndAssertAudioSinkInput(BEAR_FLAC_16BIT); } @Test public void test24BitPlayback() throws Exception { playAndAssertAudioSinkInput(BEAR_FLAC_24BIT); } private static void playAndAssertAudioSinkInput(String fileName) throws Exception { CapturingAudioSink audioSink = new CapturingAudioSink( new DefaultAudioSink(/* audioCapabilities= */ null, new AudioProcessor[0])); TestPlaybackRunnable testPlaybackRunnable = new TestPlaybackRunnable( Uri.parse("asset:///media/" + fileName), ApplicationProvider.getApplicationContext(), audioSink); Thread thread = new Thread(testPlaybackRunnable); thread.start(); thread.join(); if (testPlaybackRunnable.playbackException != null) { throw testPlaybackRunnable.playbackException; } DumpFileAsserts.assertOutput( ApplicationProvider.getApplicationContext(), audioSink, "audiosinkdumps/" + fileName + ".audiosink.dump"); } private static class TestPlaybackRunnable implements Player.Listener, Runnable { private final Context context; private final Uri uri; private final AudioSink audioSink; @Nullable private ExoPlayer player; @Nullable private PlaybackException playbackException; public TestPlaybackRunnable(Uri uri, Context context, AudioSink audioSink) { this.uri = uri; this.context = context; this.audioSink = audioSink; } @Override public void run() { Looper.prepare(); RenderersFactory renderersFactory = (eventHandler, videoRendererEventListener, audioRendererEventListener, textRendererOutput, metadataRendererOutput) -> new Renderer[] { new LibflacAudioRenderer(eventHandler, audioRendererEventListener, audioSink) }; player = new ExoPlayer.Builder(context, renderersFactory).build(); player.addListener(this); MediaSource mediaSource = new ProgressiveMediaSource.Factory( new DefaultDataSource.Factory(context), MatroskaExtractor.FACTORY) .createMediaSource(MediaItem.fromUri(uri)); player.setMediaSource(mediaSource); player.prepare(); player.play(); Looper.loop(); } @Override public void onPlayerError(PlaybackException error) { playbackException = error; } @Override public void onPlaybackStateChanged(@Player.State int playbackState) { if (playbackState == Player.STATE_ENDED || (playbackState == Player.STATE_IDLE && playbackException != null)) { player.release(); Looper.myLooper().quit(); } } } }
apache-2.0
OHDSI/RcppBoostCompute
inst/include/boost.new/compute/iterator/function_input_iterator.hpp
4730
//---------------------------------------------------------------------------// // Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com> // // Distributed under the Boost Software License, Version 1.0 // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // // See http://kylelutz.github.com/compute for more information. //---------------------------------------------------------------------------// #ifndef BOOST_COMPUTE_ITERATOR_FUNCTION_INPUT_ITERATOR_HPP #define BOOST_COMPUTE_ITERATOR_FUNCTION_INPUT_ITERATOR_HPP #include <cstddef> #include <iterator> #include <boost/config.hpp> #include <boost/iterator/iterator_facade.hpp> #include <boost/compute/detail/meta_kernel.hpp> #include <boost/compute/detail/is_device_iterator.hpp> #include <boost/compute/type_traits/result_of.hpp> namespace boost { namespace compute { // forward declaration for function_input_iterator<Function> template<class Function> class function_input_iterator; namespace detail { // helper class which defines the iterator_facade super-class // type for function_input_iterator<Function> template<class Function> class function_input_iterator_base { public: typedef ::boost::iterator_facade< ::boost::compute::function_input_iterator<Function>, typename ::boost::compute::result_of<Function()>::type, ::std::random_access_iterator_tag, typename ::boost::compute::result_of<Function()>::type > type; }; template<class Function> struct function_input_iterator_expr { typedef typename ::boost::compute::result_of<Function()>::type result_type; function_input_iterator_expr(const Function &function) : m_function(function) { } Function m_function; }; template<class Function> inline meta_kernel& operator<<(meta_kernel &kernel, const function_input_iterator_expr<Function> &expr) { return kernel << expr.m_function(); } } // end detail namespace template<class Function> class function_input_iterator : public detail::function_input_iterator_base<Function>::type { public: typedef typename detail::function_input_iterator_base<Function>::type super_type; typedef typename super_type::reference reference; typedef typename super_type::difference_type difference_type; typedef Function function; function_input_iterator(const Function &function, size_t index = 0) : m_function(function), m_index(index) { } function_input_iterator(const function_input_iterator<Function> &other) : m_function(other.m_function), m_index(other.m_index) { } function_input_iterator<Function>& operator=(const function_input_iterator<Function> &other) { if(this != &other){ m_function = other.m_function; m_index = other.m_index; } return *this; } ~function_input_iterator() { } size_t get_index() const { return m_index; } template<class Expr> detail::function_input_iterator_expr<Function> operator[](const Expr &expr) const { (void) expr; return detail::function_input_iterator_expr<Function>(m_function); } private: friend class ::boost::iterator_core_access; reference dereference() const { return reference(); } bool equal(const function_input_iterator<Function> &other) const { return m_function == other.m_function && m_index == other.m_index; } void increment() { m_index++; } void decrement() { m_index--; } void advance(difference_type n) { m_index = static_cast<size_t>(static_cast<difference_type>(m_index) + n); } difference_type distance_to(const function_input_iterator<Function> &other) const { return static_cast<difference_type>(other.m_index - m_index); } private: Function m_function; size_t m_index; }; template<class Function> inline function_input_iterator<Function> make_function_input_iterator(const Function &function, size_t index = 0) { return function_input_iterator<Function>(function, index); } namespace detail { // is_device_iterator specialization for function_input_iterator template<class Iterator> struct is_device_iterator< Iterator, typename boost::enable_if< boost::is_same< function_input_iterator<typename Iterator::function>, typename boost::remove_const<Iterator>::type > >::type > : public boost::true_type {}; } // end detail namespace } // end compute namespace } // end boost namespace #endif // BOOST_COMPUTE_ITERATOR_FUNCTION_INPUT_ITERATOR_HPP
apache-2.0
cloudera/hadoop-hdfs
src/test/hdfs/org/apache/hadoop/hdfs/server/namenode/TestCheckPointForSecurityTokens.java
6895
/** * 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.hdfs.server.namenode; import junit.framework.Assert; import java.io.*; import java.net.URI; import java.util.Collection; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.protocol.FSConstants.SafeModeAction; import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier; import org.apache.hadoop.hdfs.server.common.HdfsConstants.StartupOption; import org.apache.hadoop.hdfs.tools.DFSAdmin; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.io.Text; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.junit.Test; /** * This class tests the creation and validation of a checkpoint. */ public class TestCheckPointForSecurityTokens { static final long seed = 0xDEADBEEFL; static final int blockSize = 4096; static final int fileSize = 8192; static final int numDatanodes = 3; short replication = 3; MiniDFSCluster cluster = null; NameNode startNameNode( Configuration conf, String imageDirs, String editsDirs, StartupOption start) throws IOException { conf.set(DFSConfigKeys.FS_DEFAULT_NAME_KEY, "hdfs://localhost:0"); conf.set(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY, "0.0.0.0:0"); conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY, imageDirs); conf.set(DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_KEY, editsDirs); String[] args = new String[]{start.getName()}; NameNode nn = NameNode.createNameNode(args, conf); Assert.assertTrue(nn.isInSafeMode()); return nn; } private void cancelToken(Token<DelegationTokenIdentifier> token) throws IOException { cluster.getNamesystem().cancelDelegationToken(token); } private void renewToken(Token<DelegationTokenIdentifier> token) throws IOException { cluster.getNamesystem().renewDelegationToken(token); } /** * Tests save namepsace. */ @Test public void testSaveNamespace() throws IOException { DistributedFileSystem fs = null; try { Configuration conf = new HdfsConfiguration(); cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDatanodes).build(); cluster.waitActive(); fs = (DistributedFileSystem)(cluster.getFileSystem()); FSNamesystem namesystem = cluster.getNamesystem(); namesystem.getDelegationTokenSecretManager().startThreads(); String renewer = UserGroupInformation.getLoginUser().getUserName(); Token<DelegationTokenIdentifier> token1 = namesystem .getDelegationToken(new Text(renewer)); Token<DelegationTokenIdentifier> token2 = namesystem .getDelegationToken(new Text(renewer)); // Saving image without safe mode should fail DFSAdmin admin = new DFSAdmin(conf); String[] args = new String[]{"-saveNamespace"}; // verify that the edits file is NOT empty Collection<URI> editsDirs = cluster.getNameEditsDirs(); for(URI uri : editsDirs) { File ed = new File(uri.getPath()); Assert.assertTrue(new File(ed, "current/edits").length() > Integer.SIZE/Byte.SIZE); } // Saving image in safe mode should succeed fs.setSafeMode(SafeModeAction.SAFEMODE_ENTER); try { admin.run(args); } catch(Exception e) { throw new IOException(e.getMessage()); } // verify that the edits file is empty for(URI uri : editsDirs) { File ed = new File(uri.getPath()); Assert.assertTrue(new File(ed, "current/edits").length() == Integer.SIZE/Byte.SIZE); } // restart cluster cluster.shutdown(); cluster = null; cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDatanodes).format(false).build(); cluster.waitActive(); //Should be able to renew & cancel the delegation token after cluster restart try { renewToken(token1); renewToken(token2); } catch (IOException e) { Assert.fail("Could not renew or cancel the token"); } namesystem = cluster.getNamesystem(); namesystem.getDelegationTokenSecretManager().startThreads(); Token<DelegationTokenIdentifier> token3 = namesystem .getDelegationToken(new Text(renewer)); Token<DelegationTokenIdentifier> token4 = namesystem .getDelegationToken(new Text(renewer)); // restart cluster again cluster.shutdown(); cluster = null; cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDatanodes).format(false).build(); cluster.waitActive(); namesystem = cluster.getNamesystem(); namesystem.getDelegationTokenSecretManager().startThreads(); Token<DelegationTokenIdentifier> token5 = namesystem .getDelegationToken(new Text(renewer)); try { renewToken(token1); renewToken(token2); renewToken(token3); renewToken(token4); renewToken(token5); } catch (IOException e) { Assert.fail("Could not renew or cancel the token"); } // restart cluster again cluster.shutdown(); cluster = null; cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDatanodes).format(false).build(); cluster.waitActive(); namesystem = cluster.getNamesystem(); namesystem.getDelegationTokenSecretManager().startThreads(); try { renewToken(token1); cancelToken(token1); renewToken(token2); cancelToken(token2); renewToken(token3); cancelToken(token3); renewToken(token4); cancelToken(token4); renewToken(token5); cancelToken(token5); } catch (IOException e) { Assert.fail("Could not renew or cancel the token"); } } finally { if(fs != null) fs.close(); if(cluster!= null) cluster.shutdown(); } } }
apache-2.0
ggalancs/one
src/sunstone/public/app/tabs/vms-tab/panels/log.js
2034
define(function(require) { /* DEPENDENCIES */ var Locale = require('utils/locale'); var Notifier = require('utils/notifier'); var OpenNebulaVM = require('opennebula/vm'); /* CONSTANTS */ var TAB_ID = require('../tabId'); var PANEL_ID = require('./log/panelId'); var RESOURCE = "VM" var XML_ROOT = "VM" /* CONSTRUCTOR */ function Panel(info) { this.panelId = PANEL_ID; this.title = Locale.tr("Log"); this.icon = "fa-file-text"; this.element = info[XML_ROOT]; return this; }; Panel.PANEL_ID = PANEL_ID; Panel.prototype.html = _html; Panel.prototype.setup = _setup; Panel.prototype.onShow = _onShow; return Panel; /* FUNCTION DEFINITIONS */ function _html() { return '<div class="row">' + '<div class="large-12 columns vm_log_container">' + '<div class="text-center" style="height: 100px;">' + '<span id="provision_dashboard_total" style="font-size:80px">' + '<i class="fa fa-spinner fa-spin"></i>' + '</span>' + '</div>' + '</div>' + '</div>'; } function _setup(context) { } function _onShow(context) { var that = this; OpenNebulaVM.log({ data: {id: that.element.ID}, success: function(req, response) { var log_lines = response['vm_log'].split("\n"); var colored_log = ''; for (var i = 0; i < log_lines.length; i++) { var line = log_lines[i]; if (line.match(/\[E\]/)) { line = '<span class="vm_log_error">' + line + '</span>'; } colored_log += line + "<br>"; } $('.vm_log_container', context).html( '<div class="row">' + '<div class="large-11 small-centered columns log-tab">' + colored_log + '</div>' + '</div>') }, error: function(request, error_json) { $('.vm_log_container', context).html(''); Notifier.onError(request, error_json); } }); } });
apache-2.0
kingargyle/turmeric-wsdldoctool
wsdl-doc-tool/src/main/java/org/ebayopensource/turmeric/tools/annoparser/dataobjects/PortType.java
2861
/******************************************************************************* * Copyright (c) 2006-2010 eBay 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 *******************************************************************************/ package org.ebayopensource.turmeric.tools.annoparser.dataobjects; import java.util.ArrayList; import java.util.List; /** * Models the lightweight wsdl Porttypes to capture primarily * association with operations, name and documentation information. * * @author sdaripelli */ public class PortType { /** * captures the name of the PortType */ private String name; private ParsedAnnotationInfo annotations; /** * Captures association with Operations */ private List<OperationHolder> operations; /** * Gets the name. * * @return name */ public String getName() { return name; } /** * Sets the name. * * @param name the new name */ public void setName(String name) { this.name = name; } /** * Gets the operations. * * @return operations */ public List<OperationHolder> getOperations() { return operations; } /** * Sets the operations. * * @param operations the new operations */ public void setOperations(List<OperationHolder> operations) { this.operations = operations; } /** * Adds the operation. * * @param operation utility for adding to the collection */ public void addOperation(OperationHolder operation){ if(operations==null){ operations=new ArrayList<OperationHolder>(); } operations.add(operation); } public ParsedAnnotationInfo getAnnotations() { return annotations; } public void setAnnotations(ParsedAnnotationInfo annotations) { this.annotations = annotations; } @Override public String toString() { StringBuffer retVal=new StringBuffer(); retVal.append("=========================================================\n"); retVal.append("PortType Name: " +name + "\n"); retVal.append("Operations : " + "\n"); if(annotations!=null){ retVal.append(name +" Port Type Annotations: \n"); retVal.append("=========================================================\n"); retVal.append(annotations.toString()); retVal.append("=========================================================\n"); } if(operations!=null){ for(OperationHolder attr:operations) { if(attr != null) { retVal.append(attr.toString()+ "\n"); } } } retVal.append("=========================================================\n"); return retVal.toString(); } }
apache-2.0
Frouk/zulip
zerver/views/webhooks/github.py
10744
from __future__ import absolute_import from django.conf import settings from zerver.models import get_client from zerver.lib.response import json_success from zerver.lib.validator import check_dict from zerver.decorator import authenticated_api_view, REQ, has_request_variables, to_non_negative_int, flexible_boolean from zerver.views.messages import send_message_backend import logging import re import ujson COMMITS_IN_LIST_LIMIT = 10 ZULIP_TEST_REPO_NAME = 'zulip-test' ZULIP_TEST_REPO_ID = 6893087 def is_test_repository(repository): return repository['name'] == ZULIP_TEST_REPO_NAME and repository['id'] == ZULIP_TEST_REPO_ID class UnknownEventType(Exception): pass def github_generic_subject(noun, topic_focus, blob): # issue and pull_request objects have the same fields we're interested in return '%s: %s %d: %s' % (topic_focus, noun, blob['number'], blob['title']) def github_generic_content(noun, payload, blob): action = 'synchronized' if payload['action'] == 'synchronize' else payload['action'] # issue and pull_request objects have the same fields we're interested in content = ('%s %s [%s %s](%s)' % (payload['sender']['login'], action, noun, blob['number'], blob['html_url'])) if payload['action'] in ('opened', 'reopened'): content += '\n\n~~~ quote\n%s\n~~~' % (blob['body'],) return content def api_github_v1(user_profile, event, payload, branches, stream, **kwargs): """ processes github payload with version 1 field specification `payload` comes in unmodified from github `stream` is set to 'commits' if otherwise unset """ commit_stream = stream issue_stream = 'issues' return api_github_v2(user_profile, event, payload, branches, stream, commit_stream, issue_stream, **kwargs) def api_github_v2(user_profile, event, payload, branches, default_stream, commit_stream, issue_stream, topic_focus = None): """ processes github payload with version 2 field specification `payload` comes in unmodified from github `default_stream` is set to what `stream` is in v1 above `commit_stream` and `issue_stream` fall back to `default_stream` if they are empty This and allowing alternative endpoints is what distinguishes v1 from v2 of the github configuration """ target_stream = commit_stream if commit_stream else default_stream issue_stream = issue_stream if issue_stream else default_stream repository = payload['repository'] topic_focus = topic_focus if topic_focus else repository['name'] # Event Handlers if event == 'pull_request': pull_req = payload['pull_request'] subject = github_generic_subject('pull request', topic_focus, pull_req) content = github_generic_content('pull request', payload, pull_req) elif event == 'issues': # in v1, we assume that this stream exists since it is # deprecated and the few realms that use it already have the # stream target_stream = issue_stream issue = payload['issue'] subject = github_generic_subject('issue', topic_focus, issue) content = github_generic_content('issue', payload, issue) elif event == 'issue_comment': # Comments on both issues and pull requests come in as issue_comment events issue = payload['issue'] if 'pull_request' not in issue or issue['pull_request']['diff_url'] is None: # It's an issues comment target_stream = issue_stream noun = 'issue' else: # It's a pull request comment noun = 'pull request' subject = github_generic_subject(noun, topic_focus, issue) comment = payload['comment'] content = ('%s [commented](%s) on [%s %d](%s)\n\n~~~ quote\n%s\n~~~' % (comment['user']['login'], comment['html_url'], noun, issue['number'], issue['html_url'], comment['body'])) elif event == 'push': subject, content = build_message_from_gitlog(user_profile, topic_focus, payload['ref'], payload['commits'], payload['before'], payload['after'], payload['compare'], payload['pusher']['name'], forced=payload['forced'], created=payload['created']) elif event == 'commit_comment': comment = payload['comment'] subject = '%s: commit %s' % (topic_focus, comment['commit_id']) content = ('%s [commented](%s)' % (comment['user']['login'], comment['html_url'])) if comment['line'] is not None: content += ' on `%s`, line %d' % (comment['path'], comment['line']) content += '\n\n~~~ quote\n%s\n~~~' % (comment['body'],) else: raise UnknownEventType(u'Event %s is unknown and cannot be handled' % (event,)) return target_stream, subject, content @authenticated_api_view @has_request_variables def api_github_landing(request, user_profile, event=REQ, payload=REQ(validator=check_dict([])), branches=REQ(default=''), stream=REQ(default=''), version=REQ(converter=to_non_negative_int, default=1), commit_stream=REQ(default=''), issue_stream=REQ(default=''), exclude_pull_requests=REQ(converter=flexible_boolean, default=False), exclude_issues=REQ(converter=flexible_boolean, default=False), exclude_commits=REQ(converter=flexible_boolean, default=False), emphasize_branch_in_topic=REQ(converter=flexible_boolean, default=False), ): repository = payload['repository'] # Special hook for capturing event data. If we see our special test repo, log the payload from github. try: if is_test_repository(repository) and settings.PRODUCTION: with open('/var/log/zulip/github-payloads', 'a') as f: f.write(ujson.dumps({'event': event, 'payload': payload, 'branches': branches, 'stream': stream, 'version': version, 'commit_stream': commit_stream, 'issue_stream': issue_stream, 'exclude_pull_requests': exclude_pull_requests, 'exclude_issues': exclude_issues, 'exclude_commits': exclude_commits, 'emphasize_branch_in_topic': emphasize_branch_in_topic, })) f.write('\n') except Exception: logging.exception('Error while capturing Github event') if not stream: stream = 'commits' short_ref = re.sub(r'^refs/heads/', '', payload.get('ref', '')) kwargs = dict() if emphasize_branch_in_topic and short_ref: kwargs['topic_focus'] = short_ref allowed_events = set() if not exclude_pull_requests: allowed_events.add('pull_request') if not exclude_issues: allowed_events.add('issues') allowed_events.add('issue_comment') if not exclude_commits: allowed_events.add('push') allowed_events.add('commit_comment') if event not in allowed_events: return json_success() # We filter issue_comment events for issue creation events if event == 'issue_comment' and payload['action'] != 'created': return json_success() if event == 'push': # If we are given a whitelist of branches, then we silently ignore # any push notification on a branch that is not in our whitelist. if branches and short_ref not in re.split('[\s,;|]+', branches): return json_success() # Map payload to the handler with the right version if version == 2: target_stream, subject, content = api_github_v2(user_profile, event, payload, branches, stream, commit_stream, issue_stream, **kwargs) else: target_stream, subject, content = api_github_v1(user_profile, event, payload, branches, stream, **kwargs) request.client = get_client('ZulipGitHubWebhook') return send_message_backend(request, user_profile, message_type_name='stream', message_to=[target_stream], forged=False, subject_name=subject, message_content=content) def build_commit_list_content(commits, branch, compare_url, pusher): if compare_url is not None: push_text = '[pushed](%s)' % (compare_url,) else: push_text = 'pushed' content = ('%s %s to branch %s\n\n' % (pusher, push_text, branch)) num_commits = len(commits) truncated_commits = commits[:COMMITS_IN_LIST_LIMIT] for commit in truncated_commits: short_id = commit['id'][:7] (short_commit_msg, _, _) = commit['message'].partition('\n') content += '* [%s](%s): %s\n' % (short_id, commit['url'], short_commit_msg) if num_commits > COMMITS_IN_LIST_LIMIT: content += ('\n[and %d more commits]' % (num_commits - COMMITS_IN_LIST_LIMIT,)) return content def build_message_from_gitlog(user_profile, name, ref, commits, before, after, url, pusher, forced=None, created=None): short_ref = re.sub(r'^refs/heads/', '', ref) subject = name if re.match(r'^0+$', after): content = '%s deleted branch %s' % (pusher, short_ref) # 'created' and 'forced' are github flags; the second check is for beanstalk elif (forced and not created) or (forced is None and len(commits) == 0): content = ('%s [force pushed](%s) to branch %s. Head is now %s' % (pusher, url, short_ref, after[:7])) else: content = build_commit_list_content(commits, short_ref, url, pusher) return subject, content
apache-2.0
roxolan/nakamura
bundles/files/impl/src/main/java/org/sakaiproject/nakamura/files/SparseContentInternalFileHandler.java
2196
/** * Licensed to the Sakai Foundation (SF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The SF 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.sakaiproject.nakamura.files; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.sakaiproject.nakamura.api.files.LinkHandler; import java.io.IOException; import javax.servlet.ServletException; /** * */ @Component(immediate = true, label = "JcrInternalFileHandler") @Service(value = LinkHandler.class) @Properties({ @Property(name = "service.vendor", value = "The Sakai Foundation"), @Property(name = "sakai.files.handler", value = "sparseinternal") }) public class SparseContentInternalFileHandler implements LinkHandler { /** * {@inheritDoc} * * @see org.sakaiproject.nakamura.api.files.LinkHandler#handleFile(org.apache.sling.api.SlingHttpServletRequest, * org.apache.sling.api.SlingHttpServletResponse, java.lang.String) */ public void handleFile(SlingHttpServletRequest request, SlingHttpServletResponse response, String to) throws ServletException, IOException { // JcrInternalFileHandler converted a node ID to a path then redirected. // TODO check that it is safe to assume "to" is the path since sparse content is path based -CFH response.sendRedirect(to); } }
apache-2.0
mglukhikh/intellij-community
platform/platform-tests/testSrc/com/intellij/openapi/editor/NullGraphics2D.java
10668
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.editor; import java.awt.*; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.awt.image.ImageObserver; import java.awt.image.RenderedImage; import java.awt.image.renderable.RenderableImage; import java.text.AttributedCharacterIterator; import java.util.Map; import java.util.Objects; /** * For use in painting tests. To make sure drawing method calls are not optimized away on execution, they all change an internal state, * which should be retrieved on painting finish using {@link #getResult()} method. */ public class NullGraphics2D extends Graphics2D { private final FontRenderContext myFontRenderContext = new FontRenderContext(null, false, false); private Rectangle myClip; private Composite myComposite = AlphaComposite.SrcOver; private RenderingHints myRenderingHints = new RenderingHints(null); private Color myColor = Color.black; private Font myFont = Font.decode(null); private Stroke myStroke = new BasicStroke(); private int myResult; public NullGraphics2D(Rectangle clip) { myClip = clip; } public int getResult() { return myResult; } @Override public void draw(Shape s) { throw new UnsupportedOperationException(); } @Override public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs) { throw new UnsupportedOperationException(); } @Override public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) { throw new UnsupportedOperationException(); } @Override public void drawRenderedImage(RenderedImage img, AffineTransform xform) { throw new UnsupportedOperationException(); } @Override public void drawRenderableImage(RenderableImage img, AffineTransform xform) { throw new UnsupportedOperationException(); } @Override public void drawString(String str, int x, int y) { myResult += x; myResult += y; for (int i = 0; i < str.length(); i++) { myResult += str.charAt(i); } } @Override public void drawString(String str, float x, float y) { throw new UnsupportedOperationException(); } @Override public void drawString(AttributedCharacterIterator iterator, int x, int y) { throw new UnsupportedOperationException(); } @Override public boolean drawImage(Image img, int x, int y, ImageObserver observer) { throw new UnsupportedOperationException(); } @Override public boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) { throw new UnsupportedOperationException(); } @Override public boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) { throw new UnsupportedOperationException(); } @Override public boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) { throw new UnsupportedOperationException(); } @Override public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) { throw new UnsupportedOperationException(); } @Override public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer) { throw new UnsupportedOperationException(); } @Override public void dispose() { throw new UnsupportedOperationException(); } @Override public void drawString(AttributedCharacterIterator iterator, float x, float y) { throw new UnsupportedOperationException(); } @Override public void drawGlyphVector(GlyphVector g, float x, float y) { myResult += x; myResult += y; for (int i = 0; i < g.getNumGlyphs(); i++) { myResult += g.getGlyphCode(i); Point2D position = g.getGlyphPosition(i); myResult += position.getX(); myResult += position.getY(); } } @Override public void fill(Shape s) { Rectangle bounds = s.getBounds(); myResult += bounds.x; myResult += bounds.y; myResult += bounds.width; myResult += bounds.height; } @Override public boolean hit(Rectangle rect, Shape s, boolean onStroke) { throw new UnsupportedOperationException(); } @Override public GraphicsConfiguration getDeviceConfiguration() { throw new UnsupportedOperationException(); } @Override public void setComposite(Composite comp) { myComposite = comp; myResult += Objects.hashCode(comp); } @Override public void setPaint(Paint paint) { throw new UnsupportedOperationException(); } @Override public void setRenderingHint(RenderingHints.Key hintKey, Object hintValue) { myRenderingHints.put(hintKey, hintValue); myResult += Objects.hashCode(hintKey); myResult += Objects.hashCode(hintValue); } @Override public Object getRenderingHint(RenderingHints.Key hintKey) { return myRenderingHints.get(hintKey); } @Override public void setRenderingHints(Map<?, ?> hints) { myRenderingHints.clear(); addRenderingHints(hints); myResult += Objects.hashCode(hints); } @Override public void addRenderingHints(Map<?, ?> hints) { for (Map.Entry<?, ?> entry : hints.entrySet()) { myRenderingHints.put(entry.getKey(), entry.getValue()); } myResult += Objects.hashCode(hints); } @Override public RenderingHints getRenderingHints() { return (RenderingHints)myRenderingHints.clone(); } @Override public Graphics create() { throw new UnsupportedOperationException(); } @Override public void translate(int x, int y) { myResult += x; myResult += y; } @Override public Color getColor() { return myColor; } @Override public void setColor(Color c) { myColor = c; myResult += Objects.hashCode(c); } @Override public void setPaintMode() { throw new UnsupportedOperationException(); } @Override public void setXORMode(Color c1) { throw new UnsupportedOperationException(); } @Override public Font getFont() { return myFont; } @Override public void setFont(Font font) { myFont = font; myResult += Objects.hashCode(font); } @Override public void setStroke(Stroke s) { myStroke = s; myResult += Objects.hashCode(s); } @Override public Stroke getStroke() { return myStroke; } @Override public FontMetrics getFontMetrics(Font f) { throw new UnsupportedOperationException(); } @Override public Rectangle getClipBounds() { return myClip == null ? null : new Rectangle(myClip); } @Override public void clipRect(int x, int y, int width, int height) { throw new UnsupportedOperationException(); } @Override public void setClip(int x, int y, int width, int height) { throw new UnsupportedOperationException(); } @Override public Shape getClip() { return myClip == null ? null : new Rectangle(myClip); } @Override public void setClip(Shape clip) { throw new UnsupportedOperationException(); } @Override public void copyArea(int x, int y, int width, int height, int dx, int dy) { throw new UnsupportedOperationException(); } @Override public void drawLine(int x1, int y1, int x2, int y2) { myResult += x1; myResult += x2; myResult += y1; myResult += y2; } @Override public void fillRect(int x, int y, int width, int height) { myResult += x; myResult += y; myResult += width; myResult += height; } @Override public void clearRect(int x, int y, int width, int height) { throw new UnsupportedOperationException(); } @Override public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { throw new UnsupportedOperationException(); } @Override public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { throw new UnsupportedOperationException(); } @Override public void drawOval(int x, int y, int width, int height) { throw new UnsupportedOperationException(); } @Override public void fillOval(int x, int y, int width, int height) { throw new UnsupportedOperationException(); } @Override public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) { throw new UnsupportedOperationException(); } @Override public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) { throw new UnsupportedOperationException(); } @Override public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) { throw new UnsupportedOperationException(); } @Override public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) { throw new UnsupportedOperationException(); } @Override public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) { throw new UnsupportedOperationException(); } @Override public void translate(double tx, double ty) { throw new UnsupportedOperationException(); } @Override public void rotate(double theta) { throw new UnsupportedOperationException(); } @Override public void rotate(double theta, double x, double y) { throw new UnsupportedOperationException(); } @Override public void scale(double sx, double sy) { throw new UnsupportedOperationException(); } @Override public void shear(double shx, double shy) { throw new UnsupportedOperationException(); } @Override public void transform(AffineTransform Tx) { throw new UnsupportedOperationException(); } @Override public void setTransform(AffineTransform Tx) { throw new UnsupportedOperationException(); } @Override public AffineTransform getTransform() { throw new UnsupportedOperationException(); } @Override public Paint getPaint() { throw new UnsupportedOperationException(); } @Override public Composite getComposite() { return myComposite; } @Override public void setBackground(Color color) { throw new UnsupportedOperationException(); } @Override public Color getBackground() { throw new UnsupportedOperationException(); } @Override public void clip(Shape s) { throw new UnsupportedOperationException(); } @Override public FontRenderContext getFontRenderContext() { return myFontRenderContext; } }
apache-2.0
LARS-robotics/lars-ros
src/vision_based_adaptive_following/src/vision_based_adaptive_following_node.cpp
4306
#include "vision_based_localization/VisionBasedLocalizationMsgs.h" #include "ros/ros.h" #include <vision_based_adaptive_following/AdaptiveControlVariablesConfig.h> #include "geometry_msgs/Twist.h" #include "dynamic_reconfigure/server.h" #include <math.h> #include <algorithm> #include "ros/console.h" #include "stdio.h" //#include <LinearMath/btQuaternion.h> //#include <LinearMath/btMatrix3x3.h> //#include "nav_msgs/Odometry.h" #define PI 3.1415926535 //double vl = 0.2; // Leader Linear Velocity //double wl = 0.108; // Leader Angular Velocity double k = 1; double kv = 1.0; // Velocity Gain double kw = 1.2; // Rotation Gain double ksigma = 0.0; // Estimator Gain double vmax = 0.5; // Maximum Velocity double epsilon = 0.25; // Angle Bound double rho_min = 0.3; // Minimum Distance double rhod = 0.9*1000; // Rho Desired double psid = PI/8.0; // Psi Desired double rd = 1.2; // Radius Desired double alpha = 1.0; // Radius Desired bool power = true; // ON/OFF double rho = 0.0; double psi = 0.0; double gamm = 0.0; void Callbackzero(const vision_based_localization::VisionBasedLocalizationMsgs::ConstPtr& msg) { psi = msg->psi; gamm = msg->gamma; rho = msg->rho; } void reconfigureCallback(vision_based_adaptive_following::AdaptiveControlVariablesConfig &config, uint32_t level) { //wl = config.wl; kv = config.kv; kw = config.kw; ksigma = config.ksigma; vmax = config.vmax; epsilon = config.epsilon; rho_min = config.rho_min; rhod = config.rhod; psid = config.psid; power = config.power; } double sigmaIntegrator(double gamma, double psi, double rho, double dT) { static double rhs_old = 0.0; static double sigma_old = 0.0; if ( fabs(rho-0.0) < 1e-10 && fabs(psi-0.0) < 1e-10 && fabs(gamma-0.0) < 1e-10 ) { rhs_old = 0.8*rhs_old; sigma_old = 0.8*sigma_old; } else { double rhs = (ksigma/4.0)*cos(gamma - psi)*(rho - rhod); double sigma = sigma_old + (dT/2)*(rhs_old + rhs); rhs_old = rhs; sigma_old = sigma; } return sigma_old; } int main(int argc, char **argv) { ros::init(argc, argv, "vision_based_adaptive_following_node"); ros::NodeHandle n; ros::NodeHandle private_n("~"); dynamic_reconfigure::Server<vision_based_adaptive_following::AdaptiveControlVariablesConfig> server; dynamic_reconfigure::Server<vision_based_adaptive_following::AdaptiveControlVariablesConfig>::CallbackType f; f = boost::bind(&reconfigureCallback, _1, _2); server.setCallback(f); ros::Subscriber subzero = n.subscribe( "localization", 1, Callbackzero); ros::Publisher cmd_vel = n.advertise<geometry_msgs::Twist>("cmd_vel", 10); double begin; do { begin = ros::Time::now().toSec(); } while ( begin == 0 ); ros::Rate loop_rate(30); // 100 Hz ros::spinOnce(); bool firstExecution = true; bool firstExecutiond = true; double t = ros::Time::now().toSec() - begin; double t_old = t; double v = 0.0; double w = 0.0; while (ros::ok()) { t = ros::Time::now().toSec() - begin; double dT = t - t_old; t_old = t; double sigma = sigmaIntegrator( gamm, psi, rho, dT ); if ( fabs(rho-0.0) < 1e-10 && fabs(psi-0.0) < 1e-10 && fabs(gamm-0.0) < 1e-10 ) { v = 0.8*fmod(v, 500.0); w = 0.8*w; } else { v = (kv*(rho - rhod) + sigma*cos(gamm - psi))/cos(psi); w = (v*sin(psi))/rho + sigma*sin(gamm - psi)/rho + kw*(psi - psid); } if ( v != v || w != w ) { ROS_INFO("rho = %f", rho); ROS_INFO("psi = %f", psi); ROS_INFO("gamma = %f", gamm); } //ROS_INFO("rho = %f", rho); //ROS_INFO("psi = %f", psi); //ROS_INFO("gamma = %f", gamm); //ROS_INFO("v = %f", v); //ROS_INFO("kv*(rho - rhod) = %f", kv*(rho - rhod)); //ROS_INFO("sigma*cos(gamm - psi) = %f", sigma*cos(gamm - psi)); //ROS_INFO("cos(psi) = %f", cos(psi)); if ( power ) { //&& !isnan(v) && !isnan(w) ) { // Send wheel velocities to driver geometry_msgs::Twist msg; msg.linear.x = v/1000.0; msg.linear.y = 0; msg.linear.z = sigma; msg.angular.x = 0; msg.angular.y = 0; msg.angular.z = -w; cmd_vel.publish(msg); } else { geometry_msgs::Twist msg; msg.linear.x = 0; msg.linear.y = 0; msg.linear.z = sigma; msg.angular.x = 0; msg.angular.y = 0; msg.angular.z = 0; cmd_vel.publish(msg); } ros::spinOnce(); loop_rate.sleep(); } }
apache-2.0
MCDong/barbican
barbican/tests/plugin/test_resource.py
8764
# Copyright (c) 2014 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import base64 import mock import testtools from barbican.model import models from barbican.plugin.interface import secret_store from barbican.plugin import resources from barbican.plugin import store_crypto from barbican.tests import utils @utils.parameterized_test_case class WhenTestingPluginResource(testtools.TestCase, utils.MockModelRepositoryMixin): def setUp(self): super(WhenTestingPluginResource, self).setUp() self.plugin_resource = resources self.spec = {'algorithm': 'RSA', 'bit_length': 1024, 'passphrase': 'changeit' } self.content_type = 'application/octet-stream' self.project_model = mock.MagicMock() asymmetric_meta_dto = secret_store.AsymmetricKeyMetadataDTO() # Mock plug-in self.moc_plugin = mock.MagicMock() self.moc_plugin.generate_asymmetric_key.return_value = ( asymmetric_meta_dto) self.moc_plugin.store_secret.return_value = {} moc_plugin_config = { 'return_value.get_plugin_generate.return_value': self.moc_plugin, 'return_value.get_plugin_store.return_value': self.moc_plugin, 'return_value.get_plugin_retrieve_delete.return_value': self.moc_plugin } self.moc_plugin_patcher = mock.patch( 'barbican.plugin.interface.secret_store.get_manager', **moc_plugin_config ) self.moc_plugin_manager = self.moc_plugin_patcher.start() self.addCleanup(self.moc_plugin_patcher.stop) self.setup_project_repository_mock() self.secret_repo = mock.MagicMock() self.secret_repo.create_from.return_value = None self.setup_secret_repository_mock(self.secret_repo) self.container_repo = mock.MagicMock() self.container_repo.create_from.return_value = None self.setup_container_repository_mock(self.container_repo) self.container_secret_repo = mock.MagicMock() self.container_secret_repo.create_from.return_value = None self.setup_container_secret_repository_mock( self.container_secret_repo) self.secret_meta_repo = mock.MagicMock() self.secret_meta_repo.create_from.return_value = None self.setup_secret_meta_repository_mock(self.secret_meta_repo) def tearDown(self): super(WhenTestingPluginResource, self).tearDown() def test_store_secret_dto(self): spec = {'algorithm': 'AES', 'bit_length': 256, 'secret_type': 'symmetric'} secret = base64.b64encode('ABCDEFABCDEFABCDEFABCDEF') self.plugin_resource.store_secret( unencrypted_raw=secret, content_type_raw=self.content_type, content_encoding='base64', secret_model=models.Secret(spec), project_model=self.project_model) dto = self.moc_plugin.store_secret.call_args_list[0][0][0] self.assertEqual("symmetric", dto.type) self.assertEqual(secret, dto.secret) self.assertEqual(spec['algorithm'], dto.key_spec.alg) self.assertEqual(spec['bit_length'], dto.key_spec.bit_length) self.assertEqual(self.content_type, dto.content_type) @utils.parameterized_dataset({ 'general_secret_store': { 'moc_plugin': None }, 'store_crypto': { 'moc_plugin': mock.MagicMock(store_crypto.StoreCryptoAdapterPlugin) } }) def test_get_secret_dto(self, moc_plugin): def mock_secret_store_store_secret(dto): self.secret_dto = dto def mock_secret_store_get_secret(secret_type, secret_metadata): return self.secret_dto def mock_store_crypto_store_secret(dto, context): self.secret_dto = dto def mock_store_crypto_get_secret( secret_type, secret_metadata, context): return self.secret_dto if moc_plugin: self.moc_plugin = moc_plugin self.moc_plugin.store_secret.return_value = {} self.moc_plugin.store_secret.side_effect = ( mock_store_crypto_store_secret) self.moc_plugin.get_secret.side_effect = ( mock_store_crypto_get_secret) moc_plugin_config = { 'return_value.get_plugin_store.return_value': self.moc_plugin, 'return_value.get_plugin_retrieve_delete.return_value': self.moc_plugin } self.moc_plugin_manager.configure_mock(**moc_plugin_config) else: self.moc_plugin.store_secret.side_effect = ( mock_secret_store_store_secret) self.moc_plugin.get_secret.side_effect = ( mock_secret_store_get_secret) raw_secret = 'ABCDEFABCDEFABCDEFABCDEF' spec = {'name': 'testsecret', 'algorithm': 'AES', 'bit_length': 256, 'secret_type': 'symmetric'} self.plugin_resource.store_secret( unencrypted_raw=base64.b64encode(raw_secret), content_type_raw=self.content_type, content_encoding='base64', secret_model=models.Secret(spec), project_model=self.project_model) secret = self.plugin_resource.get_secret( 'application/octet-stream', models.Secret(spec), None) self.assertEqual(raw_secret, secret) def test_generate_asymmetric_with_passphrase(self): """test asymmetric secret generation with passphrase.""" secret_container = self.plugin_resource.generate_asymmetric_secret( self.spec, self.content_type, self.project_model, ) self.assertEqual("rsa", secret_container.type) self.assertEqual(self.moc_plugin. generate_asymmetric_key.call_count, 1) self.assertEqual(self.container_repo. create_from.call_count, 1) self.assertEqual(self.container_secret_repo. create_from.call_count, 3) def test_generate_asymmetric_without_passphrase(self): """test asymmetric secret generation without passphrase.""" del self.spec['passphrase'] secret_container = self.plugin_resource.generate_asymmetric_secret( self.spec, self.content_type, self.project_model, ) self.assertEqual("rsa", secret_container.type) self.assertEqual(self.moc_plugin.generate_asymmetric_key. call_count, 1) self.assertEqual(self.container_repo.create_from. call_count, 1) self.assertEqual(self.container_secret_repo.create_from. call_count, 2) def test_delete_secret_w_metadata(self): project_id = "some_id" secret_model = mock.MagicMock() secret_meta = mock.MagicMock() self.secret_meta_repo.get_metadata_for_secret.return_value = ( secret_meta) self.plugin_resource.delete_secret(secret_model=secret_model, project_id=project_id) self.secret_meta_repo.get_metadata_for_secret.assert_called_once_with( secret_model.id) self.moc_plugin.delete_secret.assert_called_once_with(secret_meta) self.secret_repo.delete_entity_by_id.assert_called_once_with( entity_id=secret_model.id, external_project_id=project_id) def test_delete_secret_w_out_metadata(self): project_id = "some_id" secret_model = mock.MagicMock() self.secret_meta_repo.get_metadata_for_secret.return_value = None self.plugin_resource.delete_secret(secret_model=secret_model, project_id=project_id) self.secret_meta_repo.get_metadata_for_secret.assert_called_once_with( secret_model.id) self.secret_repo.delete_entity_by_id.assert_called_once_with( entity_id=secret_model.id, external_project_id=project_id)
apache-2.0
nickperez1285/truck-hunt-hackathon
client/stemapp/widgets/LayerList/nls/zh-cn/strings.js
497
define( ({ _widgetLabel: "图层列表", titleBasemap: "底图", titleLayers: "业务图层", labelLayer: "图层名称", itemZoomTo: "缩放至", itemTransparency: "透明度", itemTransparent: "透明", itemOpaque: "不透明", itemMoveUp: "上移", itemMoveDown: "下移", itemDesc: "描述", itemDownload: "下载", itemToAttributeTable: "打开属性表", itemShowItemDetails: "显示项目详细信息" }) );
apache-2.0
OpenBEL/kam-nav
tools/groovy/src/src/main/org/codehaus/groovy/runtime/Reflector.java
1502
/** * 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.codehaus.groovy.runtime; import groovy.lang.MissingMethodException; import org.codehaus.groovy.reflection.CachedMethod; /** * Provides as alternative to reflection using bytecode generation. * * @author <a href="mailto:james@coredevelopers.net">James Strachan</a> */ public class Reflector { public Object invoke(CachedMethod method, Object object, Object[] arguments) { return noSuchMethod(method, object, arguments); } protected Object noSuchMethod(CachedMethod method, Object object, Object[] arguments) { throw new MissingMethodException(method.getName(), method.getDeclaringClass().getTheClass(), arguments, false); } }
apache-2.0
amirsojoodi/tez
tez-ui/src/main/webapp/app/scripts/controllers/vertex_controller.js
3056
/** * 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. */ App.VertexController = Em.ObjectController.extend(App.Helpers.DisplayHelper, App.ModelRefreshMixin, { controllerName: 'VertexController', pageTitle: 'Vertex', loading: true, loadAdditional: function(vertex) { var loaders = [], that = this, applicationId = vertex.get('applicationId'); if (vertex.get('status') == 'RUNNING') { var vertexIdx = vertex.get('id').split('_').splice(-1).pop(); App.Helpers.misc.removeRecord(this.store, 'vertexProgress', vertexIdx); var progressLoader = this.store.find('vertexProgress', vertexIdx, { appId: applicationId, dagIdx: vertex.get('dagIdx') }).then(function(vertexProgressInfo) { if (vertexProgressInfo) { vertex.set('progress', vertexProgressInfo.get('progress')); } }).catch(function(error) { Em.Logger.error("Failed to fetch vertexProgress" + error) }); loaders.push(progressLoader); } App.Helpers.misc.removeRecord(that.store, 'appDetail', applicationId); var appDetailFetcher = that.store.find('appDetail', applicationId).then(function(appDetail) { var appState = appDetail.get('appState'); if (appState) { vertex.set('yarnAppState', appState); } vertex.set('status', App.Helpers.misc.getRealStatus(vertex.get('status'), appDetail.get('appState'), appDetail.get('finalAppStatus'))); }).catch(function(){}); loaders.push(appDetailFetcher); var dagFetcher = that.store.find('dag', vertex.get('dagID')).then(function (dag) { vertex.set('dag', dag); }); loaders.push(dagFetcher); Em.RSVP.allSettled(loaders).then(function(){ that.set('loading', false); }); return Em.RSVP.all(loaders); }, childDisplayViews: [ Ember.Object.create({title: 'Vertex Details', linkTo: 'vertex.index'}), Ember.Object.create({title: 'Vertex Counters', linkTo: 'vertex.counters'}), Ember.Object.create({title: 'Tasks', linkTo: 'vertex.tasks'}), Ember.Object.create({title: 'Task Attempts', linkTo: 'vertex.taskAttempts'}), Ember.Object.create({title: 'Swimlane', linkTo: 'vertex.swimlane'}), Ember.Object.create({title: 'Sources & Sinks', linkTo: 'vertex.additionals'}), ], });
apache-2.0
knative-sandbox/kn-plugin-func
vendor/github.com/google/cel-go/checker/checker.go
19027
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package checker defines functions to type-checked a parsed expression // against a set of identifier and function declarations. package checker import ( "fmt" "reflect" "github.com/google/cel-go/checker/decls" "github.com/google/cel-go/common" "github.com/google/cel-go/common/containers" "github.com/google/cel-go/common/types/ref" "google.golang.org/protobuf/proto" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" ) type checker struct { env *Env errors *typeErrors mappings *mapping freeTypeVarCounter int sourceInfo *exprpb.SourceInfo types map[int64]*exprpb.Type references map[int64]*exprpb.Reference } // Check performs type checking, giving a typed AST. // The input is a ParsedExpr proto and an env which encapsulates // type binding of variables, declarations of built-in functions, // descriptions of protocol buffers, and a registry for errors. // Returns a CheckedExpr proto, which might not be usable if // there are errors in the error registry. func Check(parsedExpr *exprpb.ParsedExpr, source common.Source, env *Env) (*exprpb.CheckedExpr, *common.Errors) { c := checker{ env: env, errors: &typeErrors{common.NewErrors(source)}, mappings: newMapping(), freeTypeVarCounter: 0, sourceInfo: parsedExpr.GetSourceInfo(), types: make(map[int64]*exprpb.Type), references: make(map[int64]*exprpb.Reference), } c.check(parsedExpr.GetExpr()) // Walk over the final type map substituting any type parameters either by their bound value or // by DYN. m := make(map[int64]*exprpb.Type) for k, v := range c.types { m[k] = substitute(c.mappings, v, true) } return &exprpb.CheckedExpr{ Expr: parsedExpr.GetExpr(), SourceInfo: parsedExpr.GetSourceInfo(), TypeMap: m, ReferenceMap: c.references, }, c.errors.Errors } func (c *checker) check(e *exprpb.Expr) { if e == nil { return } switch e.ExprKind.(type) { case *exprpb.Expr_ConstExpr: literal := e.GetConstExpr() switch literal.ConstantKind.(type) { case *exprpb.Constant_BoolValue: c.checkBoolLiteral(e) case *exprpb.Constant_BytesValue: c.checkBytesLiteral(e) case *exprpb.Constant_DoubleValue: c.checkDoubleLiteral(e) case *exprpb.Constant_Int64Value: c.checkInt64Literal(e) case *exprpb.Constant_NullValue: c.checkNullLiteral(e) case *exprpb.Constant_StringValue: c.checkStringLiteral(e) case *exprpb.Constant_Uint64Value: c.checkUint64Literal(e) } case *exprpb.Expr_IdentExpr: c.checkIdent(e) case *exprpb.Expr_SelectExpr: c.checkSelect(e) case *exprpb.Expr_CallExpr: c.checkCall(e) case *exprpb.Expr_ListExpr: c.checkCreateList(e) case *exprpb.Expr_StructExpr: c.checkCreateStruct(e) case *exprpb.Expr_ComprehensionExpr: c.checkComprehension(e) default: panic(fmt.Sprintf("Unrecognized ast type: %v", reflect.TypeOf(e))) } } func (c *checker) checkInt64Literal(e *exprpb.Expr) { c.setType(e, decls.Int) } func (c *checker) checkUint64Literal(e *exprpb.Expr) { c.setType(e, decls.Uint) } func (c *checker) checkStringLiteral(e *exprpb.Expr) { c.setType(e, decls.String) } func (c *checker) checkBytesLiteral(e *exprpb.Expr) { c.setType(e, decls.Bytes) } func (c *checker) checkDoubleLiteral(e *exprpb.Expr) { c.setType(e, decls.Double) } func (c *checker) checkBoolLiteral(e *exprpb.Expr) { c.setType(e, decls.Bool) } func (c *checker) checkNullLiteral(e *exprpb.Expr) { c.setType(e, decls.Null) } func (c *checker) checkIdent(e *exprpb.Expr) { identExpr := e.GetIdentExpr() // Check to see if the identifier is declared. if ident := c.env.LookupIdent(identExpr.GetName()); ident != nil { c.setType(e, ident.GetIdent().Type) c.setReference(e, newIdentReference(ident.GetName(), ident.GetIdent().Value)) // Overwrite the identifier with its fully qualified name. identExpr.Name = ident.GetName() return } c.setType(e, decls.Error) c.errors.undeclaredReference( c.location(e), c.env.container.Name(), identExpr.GetName()) } func (c *checker) checkSelect(e *exprpb.Expr) { sel := e.GetSelectExpr() // Before traversing down the tree, try to interpret as qualified name. qname, found := containers.ToQualifiedName(e) if found { ident := c.env.LookupIdent(qname) if ident != nil { if sel.TestOnly { c.errors.expressionDoesNotSelectField(c.location(e)) c.setType(e, decls.Bool) return } // Rewrite the node to be a variable reference to the resolved fully-qualified // variable name. c.setType(e, ident.GetIdent().Type) c.setReference(e, newIdentReference(ident.GetName(), ident.GetIdent().Value)) identName := ident.GetName() e.ExprKind = &exprpb.Expr_IdentExpr{ IdentExpr: &exprpb.Expr_Ident{ Name: identName, }, } return } } // Interpret as field selection, first traversing down the operand. c.check(sel.Operand) targetType := c.getType(sel.Operand) // Assume error type by default as most types do not support field selection. resultType := decls.Error switch kindOf(targetType) { case kindMap: // Maps yield their value type as the selection result type. mapType := targetType.GetMapType() resultType = mapType.ValueType case kindObject: // Objects yield their field type declaration as the selection result type, but only if // the field is defined. messageType := targetType if fieldType, found := c.lookupFieldType( c.location(e), messageType.GetMessageType(), sel.Field); found { resultType = fieldType.Type } case kindTypeParam: // Set the operand type to DYN to prevent assignment to a potentionally incorrect type // at a later point in type-checking. The isAssignable call will update the type // substitutions for the type param under the covers. c.isAssignable(decls.Dyn, targetType) // Also, set the result type to DYN. resultType = decls.Dyn default: // Dynamic / error values are treated as DYN type. Errors are handled this way as well // in order to allow forward progress on the check. if isDynOrError(targetType) { resultType = decls.Dyn } else { c.errors.typeDoesNotSupportFieldSelection(c.location(e), targetType) } } if sel.TestOnly { resultType = decls.Bool } c.setType(e, resultType) } func (c *checker) checkCall(e *exprpb.Expr) { // Note: similar logic exists within the `interpreter/planner.go`. If making changes here // please consider the impact on planner.go and consolidate implementations or mirror code // as appropriate. call := e.GetCallExpr() target := call.GetTarget() args := call.GetArgs() fnName := call.GetFunction() // Traverse arguments. for _, arg := range args { c.check(arg) } // Regular static call with simple name. if target == nil { // Check for the existence of the function. fn := c.env.LookupFunction(fnName) if fn == nil { c.errors.undeclaredReference( c.location(e), c.env.container.Name(), fnName) c.setType(e, decls.Error) return } // Overwrite the function name with its fully qualified resolved name. call.Function = fn.GetName() // Check to see whether the overload resolves. c.resolveOverloadOrError(c.location(e), e, fn, nil, args) return } // If a receiver 'target' is present, it may either be a receiver function, or a namespaced // function, but not both. Given a.b.c() either a.b.c is a function or c is a function with // target a.b. // // Check whether the target is a namespaced function name. qualifiedPrefix, maybeQualified := containers.ToQualifiedName(target) if maybeQualified { maybeQualifiedName := qualifiedPrefix + "." + fnName fn := c.env.LookupFunction(maybeQualifiedName) if fn != nil { // The function name is namespaced and so preserving the target operand would // be an inaccurate representation of the desired evaluation behavior. // Overwrite with fully-qualified resolved function name sans receiver target. call.Target = nil call.Function = fn.GetName() c.resolveOverloadOrError(c.location(e), e, fn, nil, args) return } } // Regular instance call. c.check(call.Target) fn := c.env.LookupFunction(fnName) // Function found, attempt overload resolution. if fn != nil { c.resolveOverloadOrError(c.location(e), e, fn, target, args) return } // Function name not declared, record error. c.errors.undeclaredReference(c.location(e), c.env.container.Name(), fnName) } func (c *checker) resolveOverloadOrError( loc common.Location, e *exprpb.Expr, fn *exprpb.Decl, target *exprpb.Expr, args []*exprpb.Expr) { // Attempt to resolve the overload. resolution := c.resolveOverload(loc, fn, target, args) // No such overload, error noted in the resolveOverload call, type recorded here. if resolution == nil { c.setType(e, decls.Error) return } // Overload found. c.setType(e, resolution.Type) c.setReference(e, resolution.Reference) } func (c *checker) resolveOverload( loc common.Location, fn *exprpb.Decl, target *exprpb.Expr, args []*exprpb.Expr) *overloadResolution { var argTypes []*exprpb.Type if target != nil { argTypes = append(argTypes, c.getType(target)) } for _, arg := range args { argTypes = append(argTypes, c.getType(arg)) } var resultType *exprpb.Type var checkedRef *exprpb.Reference for _, overload := range fn.GetFunction().Overloads { if (target == nil && overload.IsInstanceFunction) || (target != nil && !overload.IsInstanceFunction) { // not a compatible call style. continue } overloadType := decls.NewFunctionType(overload.ResultType, overload.Params...) if len(overload.TypeParams) > 0 { // Instantiate overload's type with fresh type variables. substitutions := newMapping() for _, typePar := range overload.TypeParams { substitutions.add(decls.NewTypeParamType(typePar), c.newTypeVar()) } overloadType = substitute(substitutions, overloadType, false) } candidateArgTypes := overloadType.GetFunction().ArgTypes if c.isAssignableList(argTypes, candidateArgTypes) { if checkedRef == nil { checkedRef = newFunctionReference(overload.OverloadId) } else { checkedRef.OverloadId = append(checkedRef.OverloadId, overload.OverloadId) } // First matching overload, determines result type. fnResultType := substitute(c.mappings, overloadType.GetFunction().ResultType, false) if resultType == nil { resultType = fnResultType } else if !isDyn(resultType) && !proto.Equal(fnResultType, resultType) { resultType = decls.Dyn } } } if resultType == nil { c.errors.noMatchingOverload(loc, fn.GetName(), argTypes, target != nil) resultType = decls.Error return nil } return newResolution(checkedRef, resultType) } func (c *checker) checkCreateList(e *exprpb.Expr) { create := e.GetListExpr() var elemType *exprpb.Type for _, e := range create.Elements { c.check(e) elemType = c.joinTypes(c.location(e), elemType, c.getType(e)) } if elemType == nil { // If the list is empty, assign free type var to elem type. elemType = c.newTypeVar() } c.setType(e, decls.NewListType(elemType)) } func (c *checker) checkCreateStruct(e *exprpb.Expr) { str := e.GetStructExpr() if str.MessageName != "" { c.checkCreateMessage(e) } else { c.checkCreateMap(e) } } func (c *checker) checkCreateMap(e *exprpb.Expr) { mapVal := e.GetStructExpr() var keyType *exprpb.Type var valueType *exprpb.Type for _, ent := range mapVal.GetEntries() { key := ent.GetMapKey() c.check(key) keyType = c.joinTypes(c.location(key), keyType, c.getType(key)) c.check(ent.Value) valueType = c.joinTypes(c.location(ent.Value), valueType, c.getType(ent.Value)) } if keyType == nil { // If the map is empty, assign free type variables to typeKey and value type. keyType = c.newTypeVar() valueType = c.newTypeVar() } c.setType(e, decls.NewMapType(keyType, valueType)) } func (c *checker) checkCreateMessage(e *exprpb.Expr) { msgVal := e.GetStructExpr() // Determine the type of the message. messageType := decls.Error decl := c.env.LookupIdent(msgVal.MessageName) if decl == nil { c.errors.undeclaredReference( c.location(e), c.env.container.Name(), msgVal.MessageName) return } // Ensure the type name is fully qualified in the AST. msgVal.MessageName = decl.GetName() c.setReference(e, newIdentReference(decl.GetName(), nil)) ident := decl.GetIdent() identKind := kindOf(ident.Type) if identKind != kindError { if identKind != kindType { c.errors.notAType(c.location(e), ident.Type) } else { messageType = ident.Type.GetType() if kindOf(messageType) != kindObject { c.errors.notAMessageType(c.location(e), messageType) messageType = decls.Error } } } if isObjectWellKnownType(messageType) { c.setType(e, getObjectWellKnownType(messageType)) } else { c.setType(e, messageType) } // Check the field initializers. for _, ent := range msgVal.GetEntries() { field := ent.GetFieldKey() value := ent.Value c.check(value) fieldType := decls.Error if t, found := c.lookupFieldType( c.locationByID(ent.Id), messageType.GetMessageType(), field); found { fieldType = t.Type } if !c.isAssignable(fieldType, c.getType(value)) { c.errors.fieldTypeMismatch( c.locationByID(ent.Id), field, fieldType, c.getType(value)) } } } func (c *checker) checkComprehension(e *exprpb.Expr) { comp := e.GetComprehensionExpr() c.check(comp.IterRange) c.check(comp.AccuInit) accuType := c.getType(comp.AccuInit) rangeType := c.getType(comp.IterRange) var varType *exprpb.Type switch kindOf(rangeType) { case kindList: varType = rangeType.GetListType().ElemType case kindMap: // Ranges over the keys. varType = rangeType.GetMapType().KeyType case kindDyn, kindError, kindTypeParam: // Set the range type to DYN to prevent assignment to a potentionally incorrect type // at a later point in type-checking. The isAssignable call will update the type // substitutions for the type param under the covers. c.isAssignable(decls.Dyn, rangeType) // Set the range iteration variable to type DYN as well. varType = decls.Dyn default: c.errors.notAComprehensionRange(c.location(comp.IterRange), rangeType) varType = decls.Error } // Create a scope for the comprehension since it has a local accumulation variable. // This scope will contain the accumulation variable used to compute the result. c.env = c.env.enterScope() c.env.Add(decls.NewVar(comp.AccuVar, accuType)) // Create a block scope for the loop. c.env = c.env.enterScope() c.env.Add(decls.NewVar(comp.IterVar, varType)) // Check the variable references in the condition and step. c.check(comp.LoopCondition) c.assertType(comp.LoopCondition, decls.Bool) c.check(comp.LoopStep) c.assertType(comp.LoopStep, accuType) // Exit the loop's block scope before checking the result. c.env = c.env.exitScope() c.check(comp.Result) // Exit the comprehension scope. c.env = c.env.exitScope() c.setType(e, c.getType(comp.Result)) } // Checks compatibility of joined types, and returns the most general common type. func (c *checker) joinTypes(loc common.Location, previous *exprpb.Type, current *exprpb.Type) *exprpb.Type { if previous == nil { return current } if c.isAssignable(previous, current) { return mostGeneral(previous, current) } if c.dynAggregateLiteralElementTypesEnabled() { return decls.Dyn } c.errors.typeMismatch(loc, previous, current) return decls.Error } func (c *checker) dynAggregateLiteralElementTypesEnabled() bool { return c.env.aggLitElemType == dynElementType } func (c *checker) newTypeVar() *exprpb.Type { id := c.freeTypeVarCounter c.freeTypeVarCounter++ return decls.NewTypeParamType(fmt.Sprintf("_var%d", id)) } func (c *checker) isAssignable(t1 *exprpb.Type, t2 *exprpb.Type) bool { subs := isAssignable(c.mappings, t1, t2) if subs != nil { c.mappings = subs return true } return false } func (c *checker) isAssignableList(l1 []*exprpb.Type, l2 []*exprpb.Type) bool { subs := isAssignableList(c.mappings, l1, l2) if subs != nil { c.mappings = subs return true } return false } func (c *checker) lookupFieldType(l common.Location, messageType string, fieldName string) (*ref.FieldType, bool) { if _, found := c.env.provider.FindType(messageType); !found { // This should not happen, anyway, report an error. c.errors.unexpectedFailedResolution(l, messageType) return nil, false } if ft, found := c.env.provider.FindFieldType(messageType, fieldName); found { return ft, found } c.errors.undefinedField(l, fieldName) return nil, false } func (c *checker) setType(e *exprpb.Expr, t *exprpb.Type) { if old, found := c.types[e.Id]; found && !proto.Equal(old, t) { panic(fmt.Sprintf("(Incompatible) Type already exists for expression: %v(%d) old:%v, new:%v", e, e.Id, old, t)) } c.types[e.Id] = t } func (c *checker) getType(e *exprpb.Expr) *exprpb.Type { return c.types[e.Id] } func (c *checker) setReference(e *exprpb.Expr, r *exprpb.Reference) { if old, found := c.references[e.Id]; found && !proto.Equal(old, r) { panic(fmt.Sprintf("Reference already exists for expression: %v(%d) old:%v, new:%v", e, e.Id, old, r)) } c.references[e.Id] = r } func (c *checker) assertType(e *exprpb.Expr, t *exprpb.Type) { if !c.isAssignable(t, c.getType(e)) { c.errors.typeMismatch(c.location(e), t, c.getType(e)) } } type overloadResolution struct { Reference *exprpb.Reference Type *exprpb.Type } func newResolution(checkedRef *exprpb.Reference, t *exprpb.Type) *overloadResolution { return &overloadResolution{ Reference: checkedRef, Type: t, } } func (c *checker) location(e *exprpb.Expr) common.Location { return c.locationByID(e.Id) } func (c *checker) locationByID(id int64) common.Location { positions := c.sourceInfo.GetPositions() var line = 1 if offset, found := positions[id]; found { col := int(offset) for _, lineOffset := range c.sourceInfo.LineOffsets { if lineOffset < offset { line++ col = int(offset - lineOffset) } else { break } } return common.NewLocation(line, col) } return common.NoLocation } func newIdentReference(name string, value *exprpb.Constant) *exprpb.Reference { return &exprpb.Reference{Name: name, Value: value} } func newFunctionReference(overloads ...string) *exprpb.Reference { return &exprpb.Reference{OverloadId: overloads} }
apache-2.0
aws/aws-sdk-cpp
aws-cpp-sdk-s3-crt/source/model/ServerSideEncryptionByDefault.cpp
2237
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/s3-crt/model/ServerSideEncryptionByDefault.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 S3Crt { namespace Model { ServerSideEncryptionByDefault::ServerSideEncryptionByDefault() : m_sSEAlgorithm(ServerSideEncryption::NOT_SET), m_sSEAlgorithmHasBeenSet(false), m_kMSMasterKeyIDHasBeenSet(false) { } ServerSideEncryptionByDefault::ServerSideEncryptionByDefault(const XmlNode& xmlNode) : m_sSEAlgorithm(ServerSideEncryption::NOT_SET), m_sSEAlgorithmHasBeenSet(false), m_kMSMasterKeyIDHasBeenSet(false) { *this = xmlNode; } ServerSideEncryptionByDefault& ServerSideEncryptionByDefault::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode sSEAlgorithmNode = resultNode.FirstChild("SSEAlgorithm"); if(!sSEAlgorithmNode.IsNull()) { m_sSEAlgorithm = ServerSideEncryptionMapper::GetServerSideEncryptionForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(sSEAlgorithmNode.GetText()).c_str()).c_str()); m_sSEAlgorithmHasBeenSet = true; } XmlNode kMSMasterKeyIDNode = resultNode.FirstChild("KMSMasterKeyID"); if(!kMSMasterKeyIDNode.IsNull()) { m_kMSMasterKeyID = Aws::Utils::Xml::DecodeEscapedXmlText(kMSMasterKeyIDNode.GetText()); m_kMSMasterKeyIDHasBeenSet = true; } } return *this; } void ServerSideEncryptionByDefault::AddToNode(XmlNode& parentNode) const { Aws::StringStream ss; if(m_sSEAlgorithmHasBeenSet) { XmlNode sSEAlgorithmNode = parentNode.CreateChildElement("SSEAlgorithm"); sSEAlgorithmNode.SetText(ServerSideEncryptionMapper::GetNameForServerSideEncryption(m_sSEAlgorithm)); } if(m_kMSMasterKeyIDHasBeenSet) { XmlNode kMSMasterKeyIDNode = parentNode.CreateChildElement("KMSMasterKeyID"); kMSMasterKeyIDNode.SetText(m_kMSMasterKeyID); } } } // namespace Model } // namespace S3Crt } // namespace Aws
apache-2.0
glyptodon/guacamole-client
extensions/guacamole-auth-sso/modules/guacamole-auth-sso-base/src/main/java/org/apache/guacamole/auth/sso/user/SSOAuthenticatedUser.java
3886
/* * 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.guacamole.auth.sso.user; import com.google.inject.Inject; import java.util.Collections; import java.util.Map; import java.util.Set; import org.apache.guacamole.net.auth.AbstractAuthenticatedUser; import org.apache.guacamole.net.auth.AuthenticationProvider; import org.apache.guacamole.net.auth.Credentials; /** * An AuthenticatedUser whose identity has been supplied by an arbitrary SSO * service. An SSOAuthenticatedUser may additionally be associated with a set * of user-specific parameter tokens to be injected into any connections used * by that user. */ public class SSOAuthenticatedUser extends AbstractAuthenticatedUser { /** * Reference to the authentication provider associated with this * authenticated user. */ @Inject private AuthenticationProvider authProvider; /** * The credentials provided when this user was authenticated. */ private Credentials credentials; /** * The groups that this user belongs to. */ private Set<String> effectiveGroups; /** * Parameter tokens to be automatically injected for any connections used * by this user. */ private Map<String, String> tokens; /** * Initializes this SSOAuthenticatedUser, associating it with the given * username, credentials, groups, and parameter tokens. This function must * be invoked for every SSOAuthenticatedUser created. * * @param username * The username of the user that was authenticated. * * @param credentials * The credentials provided when this user was authenticated. * * @param effectiveGroups * The groups that the authenticated user belongs to. * * @param tokens * A map of all the name/value pairs that should be available * as tokens when connections are established by this user. */ public void init(String username, Credentials credentials, Set<String> effectiveGroups, Map<String, String> tokens) { this.credentials = credentials; this.effectiveGroups = Collections.unmodifiableSet(effectiveGroups); this.tokens = Collections.unmodifiableMap(tokens); setIdentifier(username); } /** * Returns a Map of the parameter tokens that should be automatically * injected into connections used by this user during their session. If * there are no parameter tokens applicable to the SSO implementation, this * may simply be an empty map. * * @return * A map of the parameter token name/value pairs that should be * automatically injected into connections used by this user. */ public Map<String, String> getTokens() { return tokens; } @Override public AuthenticationProvider getAuthenticationProvider() { return authProvider; } @Override public Credentials getCredentials() { return credentials; } @Override public Set<String> getEffectiveUserGroups() { return effectiveGroups; } }
apache-2.0
smanvi-pivotal/geode
geode-core/src/main/java/org/apache/geode/cache/server/internal/ServerMetricsImpl.java
2162
/* * 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.cache.server.internal; import java.util.concurrent.atomic.AtomicInteger; import org.apache.geode.cache.server.ServerMetrics; /** * Metrics describing the load on a bridge server. * * @since GemFire 5.7 * */ public class ServerMetricsImpl implements ServerMetrics { private final AtomicInteger clientCount = new AtomicInteger(); private final AtomicInteger connectionCount = new AtomicInteger(); private final AtomicInteger queueCount = new AtomicInteger(); private final int maxConnections; public ServerMetricsImpl(int maxConnections) { this.maxConnections = maxConnections; } public int getClientCount() { return clientCount.get(); } public int getConnectionCount() { return connectionCount.get(); } public int getMaxConnections() { return maxConnections; } public int getSubscriptionConnectionCount() { return queueCount.get(); } public void incClientCount() { clientCount.incrementAndGet(); } public void decClientCount() { clientCount.decrementAndGet(); } public void incConnectionCount() { connectionCount.incrementAndGet(); } public void decConnectionCount() { connectionCount.decrementAndGet(); } public void incQueueCount() { queueCount.incrementAndGet(); } public void decQueueCount() { queueCount.decrementAndGet(); } }
apache-2.0
weaveworks/flux
pkg/http/websocket/ping.go
2817
package websocket import ( "io" "sync" "time" "github.com/gorilla/websocket" ) const ( // Time allowed to write a message to the peer. writeWait = 10 * time.Second // Time allowed to read the next pong message from the peer. Needs to be less // than the idle timeout on whatever frontend server is proxying the // websocket connections (e.g. nginx). pongWait = 30 * time.Second // Send pings to peer with this period. Must be less than pongWait. The peer // must respond with a pong in < pongWait. But it may take writeWait for the // pong to be sent. Therefore we want to allow time for that, and a bit of // delay/round-trip in case the peer is busy. 1/3 of pongWait seems like a // reasonable amount of time to respond to a ping. pingPeriod = ((pongWait - writeWait) * 2 / 3) ) type pingingWebsocket struct { pinger *time.Timer readLock sync.Mutex writeLock sync.Mutex reader io.Reader conn *websocket.Conn } // Ping adds a periodic ping to a websocket connection. func Ping(c *websocket.Conn) Websocket { p := &pingingWebsocket{conn: c} p.conn.SetPongHandler(p.pong) p.conn.SetReadDeadline(time.Now().Add(pongWait)) p.pinger = time.AfterFunc(pingPeriod, p.ping) return p } func (p *pingingWebsocket) ping() { p.writeLock.Lock() defer p.writeLock.Unlock() if err := p.conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(writeWait)); err != nil { p.conn.Close() return } p.pinger.Reset(pingPeriod) } func (p *pingingWebsocket) pong(string) error { p.conn.SetReadDeadline(time.Now().Add(pongWait)) return nil } func (p *pingingWebsocket) Read(b []byte) (int, error) { p.readLock.Lock() defer p.readLock.Unlock() for p.reader == nil { msgType, r, err := p.conn.NextReader() if err != nil { if IsExpectedWSCloseError(err) { return 0, io.EOF } return 0, err } if msgType != websocket.BinaryMessage { // Ignore non-binary messages for now. continue } p.reader = r } n, err := p.reader.Read(b) if err == io.EOF { p.reader = nil err = nil } p.conn.SetReadDeadline(time.Now().Add(pongWait)) return n, err } func (p *pingingWebsocket) Write(b []byte) (int, error) { p.writeLock.Lock() defer p.writeLock.Unlock() if err := p.conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil { return 0, err } w, err := p.conn.NextWriter(websocket.BinaryMessage) if err != nil { return 0, err } n, err := w.Write(b) if err != nil { return n, err } return n, w.Close() } func (p *pingingWebsocket) Close() error { p.writeLock.Lock() defer p.writeLock.Unlock() p.pinger.Stop() if err := p.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "ok"), time.Now().Add(writeWait)); err != nil { p.conn.Close() return err } return p.conn.Close() }
apache-2.0
kevinykuo/sparklyr
java/spark-2.0.0/repartition.scala
546
package sparklyr import org.apache.spark.sql._ object Repartition { def repartition(df: DataFrame, numPartitions: Int, partitionCols: String*): DataFrame = { val partitionExprs = partitionCols.map(df.col(_)) (numPartitions, partitionExprs.length) match { case (0, l) if l > 0 => df.repartition(partitionExprs: _*) case (n, 0) if n > 0 => df.repartition(numPartitions) case (n, l) if n > 0 && l > 0 => df.repartition(numPartitions, partitionExprs: _*) case _ => throw new IllegalArgumentException } } }
apache-2.0
jskeet/gcloud-dotnet
apis/Google.Cloud.Speech.V1/Google.Cloud.Speech.V1/CloudSpeech.g.cs
255400
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/speech/v1/cloud_speech.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.Speech.V1 { /// <summary>Holder for reflection information generated from google/cloud/speech/v1/cloud_speech.proto</summary> public static partial class CloudSpeechReflection { #region Descriptor /// <summary>File descriptor for google/cloud/speech/v1/cloud_speech.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static CloudSpeechReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cilnb29nbGUvY2xvdWQvc3BlZWNoL3YxL2Nsb3VkX3NwZWVjaC5wcm90bxIW", "Z29vZ2xlLmNsb3VkLnNwZWVjaC52MRocZ29vZ2xlL2FwaS9hbm5vdGF0aW9u", "cy5wcm90bxoXZ29vZ2xlL2FwaS9jbGllbnQucHJvdG8aH2dvb2dsZS9hcGkv", "ZmllbGRfYmVoYXZpb3IucHJvdG8aI2dvb2dsZS9sb25ncnVubmluZy9vcGVy", "YXRpb25zLnByb3RvGhlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvGh5nb29n", "bGUvcHJvdG9idWYvZHVyYXRpb24ucHJvdG8aH2dvb2dsZS9wcm90b2J1Zi90", "aW1lc3RhbXAucHJvdG8aHmdvb2dsZS9wcm90b2J1Zi93cmFwcGVycy5wcm90", "bxoXZ29vZ2xlL3JwYy9zdGF0dXMucHJvdG8ikAEKEFJlY29nbml6ZVJlcXVl", "c3QSPgoGY29uZmlnGAEgASgLMikuZ29vZ2xlLmNsb3VkLnNwZWVjaC52MS5S", "ZWNvZ25pdGlvbkNvbmZpZ0ID4EECEjwKBWF1ZGlvGAIgASgLMiguZ29vZ2xl", "LmNsb3VkLnNwZWVjaC52MS5SZWNvZ25pdGlvbkF1ZGlvQgPgQQIi5wEKG0xv", "bmdSdW5uaW5nUmVjb2duaXplUmVxdWVzdBI+CgZjb25maWcYASABKAsyKS5n", "b29nbGUuY2xvdWQuc3BlZWNoLnYxLlJlY29nbml0aW9uQ29uZmlnQgPgQQIS", "PAoFYXVkaW8YAiABKAsyKC5nb29nbGUuY2xvdWQuc3BlZWNoLnYxLlJlY29n", "bml0aW9uQXVkaW9CA+BBAhJKCg1vdXRwdXRfY29uZmlnGAQgASgLMi4uZ29v", "Z2xlLmNsb3VkLnNwZWVjaC52MS5UcmFuc2NyaXB0T3V0cHV0Q29uZmlnQgPg", "QQEiOgoWVHJhbnNjcmlwdE91dHB1dENvbmZpZxIRCgdnY3NfdXJpGAEgASgJ", "SABCDQoLb3V0cHV0X3R5cGUimQEKGVN0cmVhbWluZ1JlY29nbml6ZVJlcXVl", "c3QSTgoQc3RyZWFtaW5nX2NvbmZpZxgBIAEoCzIyLmdvb2dsZS5jbG91ZC5z", "cGVlY2gudjEuU3RyZWFtaW5nUmVjb2duaXRpb25Db25maWdIABIXCg1hdWRp", "b19jb250ZW50GAIgASgMSABCEwoRc3RyZWFtaW5nX3JlcXVlc3QijwEKGlN0", "cmVhbWluZ1JlY29nbml0aW9uQ29uZmlnEj4KBmNvbmZpZxgBIAEoCzIpLmdv", "b2dsZS5jbG91ZC5zcGVlY2gudjEuUmVjb2duaXRpb25Db25maWdCA+BBAhIY", "ChBzaW5nbGVfdXR0ZXJhbmNlGAIgASgIEhcKD2ludGVyaW1fcmVzdWx0cxgD", "IAEoCCLfBQoRUmVjb2duaXRpb25Db25maWcSSQoIZW5jb2RpbmcYASABKA4y", "Ny5nb29nbGUuY2xvdWQuc3BlZWNoLnYxLlJlY29nbml0aW9uQ29uZmlnLkF1", "ZGlvRW5jb2RpbmcSGQoRc2FtcGxlX3JhdGVfaGVydHoYAiABKAUSGwoTYXVk", "aW9fY2hhbm5lbF9jb3VudBgHIAEoBRIvCidlbmFibGVfc2VwYXJhdGVfcmVj", "b2duaXRpb25fcGVyX2NoYW5uZWwYDCABKAgSGgoNbGFuZ3VhZ2VfY29kZRgD", "IAEoCUID4EECEhgKEG1heF9hbHRlcm5hdGl2ZXMYBCABKAUSGAoQcHJvZmFu", "aXR5X2ZpbHRlchgFIAEoCBI+Cg9zcGVlY2hfY29udGV4dHMYBiADKAsyJS5n", "b29nbGUuY2xvdWQuc3BlZWNoLnYxLlNwZWVjaENvbnRleHQSIAoYZW5hYmxl", "X3dvcmRfdGltZV9vZmZzZXRzGAggASgIEiQKHGVuYWJsZV9hdXRvbWF0aWNf", "cHVuY3R1YXRpb24YCyABKAgSTAoSZGlhcml6YXRpb25fY29uZmlnGBMgASgL", "MjAuZ29vZ2xlLmNsb3VkLnNwZWVjaC52MS5TcGVha2VyRGlhcml6YXRpb25D", "b25maWcSPQoIbWV0YWRhdGEYCSABKAsyKy5nb29nbGUuY2xvdWQuc3BlZWNo", "LnYxLlJlY29nbml0aW9uTWV0YWRhdGESDQoFbW9kZWwYDSABKAkSFAoMdXNl", "X2VuaGFuY2VkGA4gASgIIosBCg1BdWRpb0VuY29kaW5nEhgKFEVOQ09ESU5H", "X1VOU1BFQ0lGSUVEEAASDAoITElORUFSMTYQARIICgRGTEFDEAISCQoFTVVM", "QVcQAxIHCgNBTVIQBBIKCgZBTVJfV0IQBRIMCghPR0dfT1BVUxAGEhoKFlNQ", "RUVYX1dJVEhfSEVBREVSX0JZVEUQByKQAQoYU3BlYWtlckRpYXJpemF0aW9u", "Q29uZmlnEiIKGmVuYWJsZV9zcGVha2VyX2RpYXJpemF0aW9uGAEgASgIEhkK", "EW1pbl9zcGVha2VyX2NvdW50GAIgASgFEhkKEW1heF9zcGVha2VyX2NvdW50", "GAMgASgFEhoKC3NwZWFrZXJfdGFnGAUgASgFQgUYAeBBAyKgCAoTUmVjb2du", "aXRpb25NZXRhZGF0YRJVChBpbnRlcmFjdGlvbl90eXBlGAEgASgOMjsuZ29v", "Z2xlLmNsb3VkLnNwZWVjaC52MS5SZWNvZ25pdGlvbk1ldGFkYXRhLkludGVy", "YWN0aW9uVHlwZRIkChxpbmR1c3RyeV9uYWljc19jb2RlX29mX2F1ZGlvGAMg", "ASgNElsKE21pY3JvcGhvbmVfZGlzdGFuY2UYBCABKA4yPi5nb29nbGUuY2xv", "dWQuc3BlZWNoLnYxLlJlY29nbml0aW9uTWV0YWRhdGEuTWljcm9waG9uZURp", "c3RhbmNlEloKE29yaWdpbmFsX21lZGlhX3R5cGUYBSABKA4yPS5nb29nbGUu", "Y2xvdWQuc3BlZWNoLnYxLlJlY29nbml0aW9uTWV0YWRhdGEuT3JpZ2luYWxN", "ZWRpYVR5cGUSXgoVcmVjb3JkaW5nX2RldmljZV90eXBlGAYgASgOMj8uZ29v", "Z2xlLmNsb3VkLnNwZWVjaC52MS5SZWNvZ25pdGlvbk1ldGFkYXRhLlJlY29y", "ZGluZ0RldmljZVR5cGUSHQoVcmVjb3JkaW5nX2RldmljZV9uYW1lGAcgASgJ", "EhoKEm9yaWdpbmFsX21pbWVfdHlwZRgIIAEoCRITCgthdWRpb190b3BpYxgK", "IAEoCSLFAQoPSW50ZXJhY3Rpb25UeXBlEiAKHElOVEVSQUNUSU9OX1RZUEVf", "VU5TUEVDSUZJRUQQABIOCgpESVNDVVNTSU9OEAESEAoMUFJFU0VOVEFUSU9O", "EAISDgoKUEhPTkVfQ0FMTBADEg0KCVZPSUNFTUFJTBAEEhsKF1BST0ZFU1NJ", "T05BTExZX1BST0RVQ0VEEAUSEAoMVk9JQ0VfU0VBUkNIEAYSEQoNVk9JQ0Vf", "Q09NTUFORBAHEg0KCURJQ1RBVElPThAIImQKEk1pY3JvcGhvbmVEaXN0YW5j", "ZRIjCh9NSUNST1BIT05FX0RJU1RBTkNFX1VOU1BFQ0lGSUVEEAASDQoJTkVB", "UkZJRUxEEAESDAoITUlERklFTEQQAhIMCghGQVJGSUVMRBADIk4KEU9yaWdp", "bmFsTWVkaWFUeXBlEiMKH09SSUdJTkFMX01FRElBX1RZUEVfVU5TUEVDSUZJ", "RUQQABIJCgVBVURJTxABEgkKBVZJREVPEAIipAEKE1JlY29yZGluZ0Rldmlj", "ZVR5cGUSJQohUkVDT1JESU5HX0RFVklDRV9UWVBFX1VOU1BFQ0lGSUVEEAAS", "DgoKU01BUlRQSE9ORRABEgYKAlBDEAISDgoKUEhPTkVfTElORRADEgsKB1ZF", "SElDTEUQBBIYChRPVEhFUl9PVVRET09SX0RFVklDRRAFEhcKE09USEVSX0lO", "RE9PUl9ERVZJQ0UQBiIgCg1TcGVlY2hDb250ZXh0Eg8KB3BocmFzZXMYASAD", "KAkiRAoQUmVjb2duaXRpb25BdWRpbxIRCgdjb250ZW50GAEgASgMSAASDQoD", "dXJpGAIgASgJSABCDgoMYXVkaW9fc291cmNlIosBChFSZWNvZ25pemVSZXNw", "b25zZRJACgdyZXN1bHRzGAIgAygLMi8uZ29vZ2xlLmNsb3VkLnNwZWVjaC52", "MS5TcGVlY2hSZWNvZ25pdGlvblJlc3VsdBI0ChF0b3RhbF9iaWxsZWRfdGlt", "ZRgDIAEoCzIZLmdvb2dsZS5wcm90b2J1Zi5EdXJhdGlvbiKWAQocTG9uZ1J1", "bm5pbmdSZWNvZ25pemVSZXNwb25zZRJACgdyZXN1bHRzGAIgAygLMi8uZ29v", "Z2xlLmNsb3VkLnNwZWVjaC52MS5TcGVlY2hSZWNvZ25pdGlvblJlc3VsdBI0", "ChF0b3RhbF9iaWxsZWRfdGltZRgDIAEoCzIZLmdvb2dsZS5wcm90b2J1Zi5E", "dXJhdGlvbiKwAQocTG9uZ1J1bm5pbmdSZWNvZ25pemVNZXRhZGF0YRIYChBw", "cm9ncmVzc19wZXJjZW50GAEgASgFEi4KCnN0YXJ0X3RpbWUYAiABKAsyGi5n", "b29nbGUucHJvdG9idWYuVGltZXN0YW1wEjQKEGxhc3RfdXBkYXRlX3RpbWUY", "AyABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEhAKA3VyaRgEIAEo", "CUID4EEDIucCChpTdHJlYW1pbmdSZWNvZ25pemVSZXNwb25zZRIhCgVlcnJv", "chgBIAEoCzISLmdvb2dsZS5ycGMuU3RhdHVzEkMKB3Jlc3VsdHMYAiADKAsy", "Mi5nb29nbGUuY2xvdWQuc3BlZWNoLnYxLlN0cmVhbWluZ1JlY29nbml0aW9u", "UmVzdWx0El0KEXNwZWVjaF9ldmVudF90eXBlGAQgASgOMkIuZ29vZ2xlLmNs", "b3VkLnNwZWVjaC52MS5TdHJlYW1pbmdSZWNvZ25pemVSZXNwb25zZS5TcGVl", "Y2hFdmVudFR5cGUSNAoRdG90YWxfYmlsbGVkX3RpbWUYBSABKAsyGS5nb29n", "bGUucHJvdG9idWYuRHVyYXRpb24iTAoPU3BlZWNoRXZlbnRUeXBlEhwKGFNQ", "RUVDSF9FVkVOVF9VTlNQRUNJRklFRBAAEhsKF0VORF9PRl9TSU5HTEVfVVRU", "RVJBTkNFEAEi8gEKGlN0cmVhbWluZ1JlY29nbml0aW9uUmVzdWx0EkoKDGFs", "dGVybmF0aXZlcxgBIAMoCzI0Lmdvb2dsZS5jbG91ZC5zcGVlY2gudjEuU3Bl", "ZWNoUmVjb2duaXRpb25BbHRlcm5hdGl2ZRIQCghpc19maW5hbBgCIAEoCBIR", "CglzdGFiaWxpdHkYAyABKAISMgoPcmVzdWx0X2VuZF90aW1lGAQgASgLMhku", "Z29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uEhMKC2NoYW5uZWxfdGFnGAUgASgF", "EhoKDWxhbmd1YWdlX2NvZGUYBiABKAlCA+BBAyJ6ChdTcGVlY2hSZWNvZ25p", "dGlvblJlc3VsdBJKCgxhbHRlcm5hdGl2ZXMYASADKAsyNC5nb29nbGUuY2xv", "dWQuc3BlZWNoLnYxLlNwZWVjaFJlY29nbml0aW9uQWx0ZXJuYXRpdmUSEwoL", "Y2hhbm5lbF90YWcYAiABKAUidwocU3BlZWNoUmVjb2duaXRpb25BbHRlcm5h", "dGl2ZRISCgp0cmFuc2NyaXB0GAEgASgJEhIKCmNvbmZpZGVuY2UYAiABKAIS", "LwoFd29yZHMYAyADKAsyIC5nb29nbGUuY2xvdWQuc3BlZWNoLnYxLldvcmRJ", "bmZvIo4BCghXb3JkSW5mbxItCgpzdGFydF90aW1lGAEgASgLMhkuZ29vZ2xl", "LnByb3RvYnVmLkR1cmF0aW9uEisKCGVuZF90aW1lGAIgASgLMhkuZ29vZ2xl", "LnByb3RvYnVmLkR1cmF0aW9uEgwKBHdvcmQYAyABKAkSGAoLc3BlYWtlcl90", "YWcYBSABKAVCA+BBAzLRBAoGU3BlZWNoEpABCglSZWNvZ25pemUSKC5nb29n", "bGUuY2xvdWQuc3BlZWNoLnYxLlJlY29nbml6ZVJlcXVlc3QaKS5nb29nbGUu", "Y2xvdWQuc3BlZWNoLnYxLlJlY29nbml6ZVJlc3BvbnNlIi6C0+STAhkiFC92", "MS9zcGVlY2g6cmVjb2duaXplOgEq2kEMY29uZmlnLGF1ZGlvEuQBChRMb25n", "UnVubmluZ1JlY29nbml6ZRIzLmdvb2dsZS5jbG91ZC5zcGVlY2gudjEuTG9u", "Z1J1bm5pbmdSZWNvZ25pemVSZXF1ZXN0Gh0uZ29vZ2xlLmxvbmdydW5uaW5n", "Lk9wZXJhdGlvbiJ4gtPkkwIkIh8vdjEvc3BlZWNoOmxvbmdydW5uaW5ncmVj", "b2duaXplOgEq2kEMY29uZmlnLGF1ZGlvykE8ChxMb25nUnVubmluZ1JlY29n", "bml6ZVJlc3BvbnNlEhxMb25nUnVubmluZ1JlY29nbml6ZU1ldGFkYXRhEoEB", "ChJTdHJlYW1pbmdSZWNvZ25pemUSMS5nb29nbGUuY2xvdWQuc3BlZWNoLnYx", "LlN0cmVhbWluZ1JlY29nbml6ZVJlcXVlc3QaMi5nb29nbGUuY2xvdWQuc3Bl", "ZWNoLnYxLlN0cmVhbWluZ1JlY29nbml6ZVJlc3BvbnNlIgAoATABGknKQRVz", "cGVlY2guZ29vZ2xlYXBpcy5jb23SQS5odHRwczovL3d3dy5nb29nbGVhcGlz", "LmNvbS9hdXRoL2Nsb3VkLXBsYXRmb3JtQnIKGmNvbS5nb29nbGUuY2xvdWQu", "c3BlZWNoLnYxQgtTcGVlY2hQcm90b1ABWjxnb29nbGUuZ29sYW5nLm9yZy9n", "ZW5wcm90by9nb29nbGVhcGlzL2Nsb3VkL3NwZWVjaC92MTtzcGVlY2j4AQGi", "AgNHQ1NiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Api.ClientReflection.Descriptor, global::Google.Api.FieldBehaviorReflection.Descriptor, global::Google.LongRunning.OperationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.AnyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor, global::Google.Rpc.StatusReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.RecognizeRequest), global::Google.Cloud.Speech.V1.RecognizeRequest.Parser, new[]{ "Config", "Audio" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.LongRunningRecognizeRequest), global::Google.Cloud.Speech.V1.LongRunningRecognizeRequest.Parser, new[]{ "Config", "Audio", "OutputConfig" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.TranscriptOutputConfig), global::Google.Cloud.Speech.V1.TranscriptOutputConfig.Parser, new[]{ "GcsUri" }, new[]{ "OutputType" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.StreamingRecognizeRequest), global::Google.Cloud.Speech.V1.StreamingRecognizeRequest.Parser, new[]{ "StreamingConfig", "AudioContent" }, new[]{ "StreamingRequest" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.StreamingRecognitionConfig), global::Google.Cloud.Speech.V1.StreamingRecognitionConfig.Parser, new[]{ "Config", "SingleUtterance", "InterimResults" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.RecognitionConfig), global::Google.Cloud.Speech.V1.RecognitionConfig.Parser, new[]{ "Encoding", "SampleRateHertz", "AudioChannelCount", "EnableSeparateRecognitionPerChannel", "LanguageCode", "MaxAlternatives", "ProfanityFilter", "SpeechContexts", "EnableWordTimeOffsets", "EnableAutomaticPunctuation", "DiarizationConfig", "Metadata", "Model", "UseEnhanced" }, null, new[]{ typeof(global::Google.Cloud.Speech.V1.RecognitionConfig.Types.AudioEncoding) }, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.SpeakerDiarizationConfig), global::Google.Cloud.Speech.V1.SpeakerDiarizationConfig.Parser, new[]{ "EnableSpeakerDiarization", "MinSpeakerCount", "MaxSpeakerCount", "SpeakerTag" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.RecognitionMetadata), global::Google.Cloud.Speech.V1.RecognitionMetadata.Parser, new[]{ "InteractionType", "IndustryNaicsCodeOfAudio", "MicrophoneDistance", "OriginalMediaType", "RecordingDeviceType", "RecordingDeviceName", "OriginalMimeType", "AudioTopic" }, null, new[]{ typeof(global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.InteractionType), typeof(global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.MicrophoneDistance), typeof(global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.OriginalMediaType), typeof(global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.RecordingDeviceType) }, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.SpeechContext), global::Google.Cloud.Speech.V1.SpeechContext.Parser, new[]{ "Phrases" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.RecognitionAudio), global::Google.Cloud.Speech.V1.RecognitionAudio.Parser, new[]{ "Content", "Uri" }, new[]{ "AudioSource" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.RecognizeResponse), global::Google.Cloud.Speech.V1.RecognizeResponse.Parser, new[]{ "Results", "TotalBilledTime" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.LongRunningRecognizeResponse), global::Google.Cloud.Speech.V1.LongRunningRecognizeResponse.Parser, new[]{ "Results", "TotalBilledTime" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.LongRunningRecognizeMetadata), global::Google.Cloud.Speech.V1.LongRunningRecognizeMetadata.Parser, new[]{ "ProgressPercent", "StartTime", "LastUpdateTime", "Uri" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.StreamingRecognizeResponse), global::Google.Cloud.Speech.V1.StreamingRecognizeResponse.Parser, new[]{ "Error", "Results", "SpeechEventType", "TotalBilledTime" }, null, new[]{ typeof(global::Google.Cloud.Speech.V1.StreamingRecognizeResponse.Types.SpeechEventType) }, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.StreamingRecognitionResult), global::Google.Cloud.Speech.V1.StreamingRecognitionResult.Parser, new[]{ "Alternatives", "IsFinal", "Stability", "ResultEndTime", "ChannelTag", "LanguageCode" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.SpeechRecognitionResult), global::Google.Cloud.Speech.V1.SpeechRecognitionResult.Parser, new[]{ "Alternatives", "ChannelTag" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.SpeechRecognitionAlternative), global::Google.Cloud.Speech.V1.SpeechRecognitionAlternative.Parser, new[]{ "Transcript", "Confidence", "Words" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Speech.V1.WordInfo), global::Google.Cloud.Speech.V1.WordInfo.Parser, new[]{ "StartTime", "EndTime", "Word", "SpeakerTag" }, null, null, null, null) })); } #endregion } #region Messages /// <summary> /// The top-level message sent by the client for the `Recognize` method. /// </summary> public sealed partial class RecognizeRequest : pb::IMessage<RecognizeRequest> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<RecognizeRequest> _parser = new pb::MessageParser<RecognizeRequest>(() => new RecognizeRequest()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<RecognizeRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RecognizeRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RecognizeRequest(RecognizeRequest other) : this() { config_ = other.config_ != null ? other.config_.Clone() : null; audio_ = other.audio_ != null ? other.audio_.Clone() : null; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RecognizeRequest Clone() { return new RecognizeRequest(this); } /// <summary>Field number for the "config" field.</summary> public const int ConfigFieldNumber = 1; private global::Google.Cloud.Speech.V1.RecognitionConfig config_; /// <summary> /// Required. Provides information to the recognizer that specifies how to /// process the request. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Speech.V1.RecognitionConfig Config { get { return config_; } set { config_ = value; } } /// <summary>Field number for the "audio" field.</summary> public const int AudioFieldNumber = 2; private global::Google.Cloud.Speech.V1.RecognitionAudio audio_; /// <summary> /// Required. The audio data to be recognized. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Speech.V1.RecognitionAudio Audio { get { return audio_; } set { audio_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as RecognizeRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(RecognizeRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Config, other.Config)) return false; if (!object.Equals(Audio, other.Audio)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (config_ != null) hash ^= Config.GetHashCode(); if (audio_ != null) hash ^= Audio.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (config_ != null) { output.WriteRawTag(10); output.WriteMessage(Config); } if (audio_ != null) { output.WriteRawTag(18); output.WriteMessage(Audio); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (config_ != null) { output.WriteRawTag(10); output.WriteMessage(Config); } if (audio_ != null) { output.WriteRawTag(18); output.WriteMessage(Audio); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (config_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Config); } if (audio_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Audio); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(RecognizeRequest other) { if (other == null) { return; } if (other.config_ != null) { if (config_ == null) { Config = new global::Google.Cloud.Speech.V1.RecognitionConfig(); } Config.MergeFrom(other.Config); } if (other.audio_ != null) { if (audio_ == null) { Audio = new global::Google.Cloud.Speech.V1.RecognitionAudio(); } Audio.MergeFrom(other.Audio); } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (config_ == null) { Config = new global::Google.Cloud.Speech.V1.RecognitionConfig(); } input.ReadMessage(Config); break; } case 18: { if (audio_ == null) { Audio = new global::Google.Cloud.Speech.V1.RecognitionAudio(); } input.ReadMessage(Audio); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { if (config_ == null) { Config = new global::Google.Cloud.Speech.V1.RecognitionConfig(); } input.ReadMessage(Config); break; } case 18: { if (audio_ == null) { Audio = new global::Google.Cloud.Speech.V1.RecognitionAudio(); } input.ReadMessage(Audio); break; } } } } #endif } /// <summary> /// The top-level message sent by the client for the `LongRunningRecognize` /// method. /// </summary> public sealed partial class LongRunningRecognizeRequest : pb::IMessage<LongRunningRecognizeRequest> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<LongRunningRecognizeRequest> _parser = new pb::MessageParser<LongRunningRecognizeRequest>(() => new LongRunningRecognizeRequest()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<LongRunningRecognizeRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public LongRunningRecognizeRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public LongRunningRecognizeRequest(LongRunningRecognizeRequest other) : this() { config_ = other.config_ != null ? other.config_.Clone() : null; audio_ = other.audio_ != null ? other.audio_.Clone() : null; outputConfig_ = other.outputConfig_ != null ? other.outputConfig_.Clone() : null; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public LongRunningRecognizeRequest Clone() { return new LongRunningRecognizeRequest(this); } /// <summary>Field number for the "config" field.</summary> public const int ConfigFieldNumber = 1; private global::Google.Cloud.Speech.V1.RecognitionConfig config_; /// <summary> /// Required. Provides information to the recognizer that specifies how to /// process the request. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Speech.V1.RecognitionConfig Config { get { return config_; } set { config_ = value; } } /// <summary>Field number for the "audio" field.</summary> public const int AudioFieldNumber = 2; private global::Google.Cloud.Speech.V1.RecognitionAudio audio_; /// <summary> /// Required. The audio data to be recognized. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Speech.V1.RecognitionAudio Audio { get { return audio_; } set { audio_ = value; } } /// <summary>Field number for the "output_config" field.</summary> public const int OutputConfigFieldNumber = 4; private global::Google.Cloud.Speech.V1.TranscriptOutputConfig outputConfig_; /// <summary> /// Optional. Specifies an optional destination for the recognition results. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Speech.V1.TranscriptOutputConfig OutputConfig { get { return outputConfig_; } set { outputConfig_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as LongRunningRecognizeRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(LongRunningRecognizeRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Config, other.Config)) return false; if (!object.Equals(Audio, other.Audio)) return false; if (!object.Equals(OutputConfig, other.OutputConfig)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (config_ != null) hash ^= Config.GetHashCode(); if (audio_ != null) hash ^= Audio.GetHashCode(); if (outputConfig_ != null) hash ^= OutputConfig.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (config_ != null) { output.WriteRawTag(10); output.WriteMessage(Config); } if (audio_ != null) { output.WriteRawTag(18); output.WriteMessage(Audio); } if (outputConfig_ != null) { output.WriteRawTag(34); output.WriteMessage(OutputConfig); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (config_ != null) { output.WriteRawTag(10); output.WriteMessage(Config); } if (audio_ != null) { output.WriteRawTag(18); output.WriteMessage(Audio); } if (outputConfig_ != null) { output.WriteRawTag(34); output.WriteMessage(OutputConfig); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (config_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Config); } if (audio_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Audio); } if (outputConfig_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(OutputConfig); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(LongRunningRecognizeRequest other) { if (other == null) { return; } if (other.config_ != null) { if (config_ == null) { Config = new global::Google.Cloud.Speech.V1.RecognitionConfig(); } Config.MergeFrom(other.Config); } if (other.audio_ != null) { if (audio_ == null) { Audio = new global::Google.Cloud.Speech.V1.RecognitionAudio(); } Audio.MergeFrom(other.Audio); } if (other.outputConfig_ != null) { if (outputConfig_ == null) { OutputConfig = new global::Google.Cloud.Speech.V1.TranscriptOutputConfig(); } OutputConfig.MergeFrom(other.OutputConfig); } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (config_ == null) { Config = new global::Google.Cloud.Speech.V1.RecognitionConfig(); } input.ReadMessage(Config); break; } case 18: { if (audio_ == null) { Audio = new global::Google.Cloud.Speech.V1.RecognitionAudio(); } input.ReadMessage(Audio); break; } case 34: { if (outputConfig_ == null) { OutputConfig = new global::Google.Cloud.Speech.V1.TranscriptOutputConfig(); } input.ReadMessage(OutputConfig); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { if (config_ == null) { Config = new global::Google.Cloud.Speech.V1.RecognitionConfig(); } input.ReadMessage(Config); break; } case 18: { if (audio_ == null) { Audio = new global::Google.Cloud.Speech.V1.RecognitionAudio(); } input.ReadMessage(Audio); break; } case 34: { if (outputConfig_ == null) { OutputConfig = new global::Google.Cloud.Speech.V1.TranscriptOutputConfig(); } input.ReadMessage(OutputConfig); break; } } } } #endif } /// <summary> /// Specifies an optional destination for the recognition results. /// </summary> public sealed partial class TranscriptOutputConfig : pb::IMessage<TranscriptOutputConfig> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<TranscriptOutputConfig> _parser = new pb::MessageParser<TranscriptOutputConfig>(() => new TranscriptOutputConfig()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<TranscriptOutputConfig> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public TranscriptOutputConfig() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public TranscriptOutputConfig(TranscriptOutputConfig other) : this() { switch (other.OutputTypeCase) { case OutputTypeOneofCase.GcsUri: GcsUri = other.GcsUri; break; } _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public TranscriptOutputConfig Clone() { return new TranscriptOutputConfig(this); } /// <summary>Field number for the "gcs_uri" field.</summary> public const int GcsUriFieldNumber = 1; /// <summary> /// Specifies a Cloud Storage URI for the recognition results. Must be /// specified in the format: `gs://bucket_name/object_name`, and the bucket /// must already exist. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string GcsUri { get { return outputTypeCase_ == OutputTypeOneofCase.GcsUri ? (string) outputType_ : ""; } set { outputType_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); outputTypeCase_ = OutputTypeOneofCase.GcsUri; } } private object outputType_; /// <summary>Enum of possible cases for the "output_type" oneof.</summary> public enum OutputTypeOneofCase { None = 0, GcsUri = 1, } private OutputTypeOneofCase outputTypeCase_ = OutputTypeOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public OutputTypeOneofCase OutputTypeCase { get { return outputTypeCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearOutputType() { outputTypeCase_ = OutputTypeOneofCase.None; outputType_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as TranscriptOutputConfig); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(TranscriptOutputConfig other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (GcsUri != other.GcsUri) return false; if (OutputTypeCase != other.OutputTypeCase) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (outputTypeCase_ == OutputTypeOneofCase.GcsUri) hash ^= GcsUri.GetHashCode(); hash ^= (int) outputTypeCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (outputTypeCase_ == OutputTypeOneofCase.GcsUri) { output.WriteRawTag(10); output.WriteString(GcsUri); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (outputTypeCase_ == OutputTypeOneofCase.GcsUri) { output.WriteRawTag(10); output.WriteString(GcsUri); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (outputTypeCase_ == OutputTypeOneofCase.GcsUri) { size += 1 + pb::CodedOutputStream.ComputeStringSize(GcsUri); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(TranscriptOutputConfig other) { if (other == null) { return; } switch (other.OutputTypeCase) { case OutputTypeOneofCase.GcsUri: GcsUri = other.GcsUri; break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { GcsUri = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { GcsUri = input.ReadString(); break; } } } } #endif } /// <summary> /// The top-level message sent by the client for the `StreamingRecognize` method. /// Multiple `StreamingRecognizeRequest` messages are sent. The first message /// must contain a `streaming_config` message and must not contain /// `audio_content`. All subsequent messages must contain `audio_content` and /// must not contain a `streaming_config` message. /// </summary> public sealed partial class StreamingRecognizeRequest : pb::IMessage<StreamingRecognizeRequest> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<StreamingRecognizeRequest> _parser = new pb::MessageParser<StreamingRecognizeRequest>(() => new StreamingRecognizeRequest()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<StreamingRecognizeRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public StreamingRecognizeRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public StreamingRecognizeRequest(StreamingRecognizeRequest other) : this() { switch (other.StreamingRequestCase) { case StreamingRequestOneofCase.StreamingConfig: StreamingConfig = other.StreamingConfig.Clone(); break; case StreamingRequestOneofCase.AudioContent: AudioContent = other.AudioContent; break; } _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public StreamingRecognizeRequest Clone() { return new StreamingRecognizeRequest(this); } /// <summary>Field number for the "streaming_config" field.</summary> public const int StreamingConfigFieldNumber = 1; /// <summary> /// Provides information to the recognizer that specifies how to process the /// request. The first `StreamingRecognizeRequest` message must contain a /// `streaming_config` message. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Speech.V1.StreamingRecognitionConfig StreamingConfig { get { return streamingRequestCase_ == StreamingRequestOneofCase.StreamingConfig ? (global::Google.Cloud.Speech.V1.StreamingRecognitionConfig) streamingRequest_ : null; } set { streamingRequest_ = value; streamingRequestCase_ = value == null ? StreamingRequestOneofCase.None : StreamingRequestOneofCase.StreamingConfig; } } /// <summary>Field number for the "audio_content" field.</summary> public const int AudioContentFieldNumber = 2; /// <summary> /// The audio data to be recognized. Sequential chunks of audio data are sent /// in sequential `StreamingRecognizeRequest` messages. The first /// `StreamingRecognizeRequest` message must not contain `audio_content` data /// and all subsequent `StreamingRecognizeRequest` messages must contain /// `audio_content` data. The audio bytes must be encoded as specified in /// `RecognitionConfig`. Note: as with all bytes fields, proto buffers use a /// pure binary representation (not base64). See /// [content limits](https://cloud.google.com/speech-to-text/quotas#content). /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pb::ByteString AudioContent { get { return streamingRequestCase_ == StreamingRequestOneofCase.AudioContent ? (pb::ByteString) streamingRequest_ : pb::ByteString.Empty; } set { streamingRequest_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); streamingRequestCase_ = StreamingRequestOneofCase.AudioContent; } } private object streamingRequest_; /// <summary>Enum of possible cases for the "streaming_request" oneof.</summary> public enum StreamingRequestOneofCase { None = 0, StreamingConfig = 1, AudioContent = 2, } private StreamingRequestOneofCase streamingRequestCase_ = StreamingRequestOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public StreamingRequestOneofCase StreamingRequestCase { get { return streamingRequestCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearStreamingRequest() { streamingRequestCase_ = StreamingRequestOneofCase.None; streamingRequest_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as StreamingRecognizeRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(StreamingRecognizeRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(StreamingConfig, other.StreamingConfig)) return false; if (AudioContent != other.AudioContent) return false; if (StreamingRequestCase != other.StreamingRequestCase) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (streamingRequestCase_ == StreamingRequestOneofCase.StreamingConfig) hash ^= StreamingConfig.GetHashCode(); if (streamingRequestCase_ == StreamingRequestOneofCase.AudioContent) hash ^= AudioContent.GetHashCode(); hash ^= (int) streamingRequestCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (streamingRequestCase_ == StreamingRequestOneofCase.StreamingConfig) { output.WriteRawTag(10); output.WriteMessage(StreamingConfig); } if (streamingRequestCase_ == StreamingRequestOneofCase.AudioContent) { output.WriteRawTag(18); output.WriteBytes(AudioContent); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (streamingRequestCase_ == StreamingRequestOneofCase.StreamingConfig) { output.WriteRawTag(10); output.WriteMessage(StreamingConfig); } if (streamingRequestCase_ == StreamingRequestOneofCase.AudioContent) { output.WriteRawTag(18); output.WriteBytes(AudioContent); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (streamingRequestCase_ == StreamingRequestOneofCase.StreamingConfig) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(StreamingConfig); } if (streamingRequestCase_ == StreamingRequestOneofCase.AudioContent) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(AudioContent); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(StreamingRecognizeRequest other) { if (other == null) { return; } switch (other.StreamingRequestCase) { case StreamingRequestOneofCase.StreamingConfig: if (StreamingConfig == null) { StreamingConfig = new global::Google.Cloud.Speech.V1.StreamingRecognitionConfig(); } StreamingConfig.MergeFrom(other.StreamingConfig); break; case StreamingRequestOneofCase.AudioContent: AudioContent = other.AudioContent; break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { global::Google.Cloud.Speech.V1.StreamingRecognitionConfig subBuilder = new global::Google.Cloud.Speech.V1.StreamingRecognitionConfig(); if (streamingRequestCase_ == StreamingRequestOneofCase.StreamingConfig) { subBuilder.MergeFrom(StreamingConfig); } input.ReadMessage(subBuilder); StreamingConfig = subBuilder; break; } case 18: { AudioContent = input.ReadBytes(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { global::Google.Cloud.Speech.V1.StreamingRecognitionConfig subBuilder = new global::Google.Cloud.Speech.V1.StreamingRecognitionConfig(); if (streamingRequestCase_ == StreamingRequestOneofCase.StreamingConfig) { subBuilder.MergeFrom(StreamingConfig); } input.ReadMessage(subBuilder); StreamingConfig = subBuilder; break; } case 18: { AudioContent = input.ReadBytes(); break; } } } } #endif } /// <summary> /// Provides information to the recognizer that specifies how to process the /// request. /// </summary> public sealed partial class StreamingRecognitionConfig : pb::IMessage<StreamingRecognitionConfig> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<StreamingRecognitionConfig> _parser = new pb::MessageParser<StreamingRecognitionConfig>(() => new StreamingRecognitionConfig()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<StreamingRecognitionConfig> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public StreamingRecognitionConfig() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public StreamingRecognitionConfig(StreamingRecognitionConfig other) : this() { config_ = other.config_ != null ? other.config_.Clone() : null; singleUtterance_ = other.singleUtterance_; interimResults_ = other.interimResults_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public StreamingRecognitionConfig Clone() { return new StreamingRecognitionConfig(this); } /// <summary>Field number for the "config" field.</summary> public const int ConfigFieldNumber = 1; private global::Google.Cloud.Speech.V1.RecognitionConfig config_; /// <summary> /// Required. Provides information to the recognizer that specifies how to /// process the request. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Speech.V1.RecognitionConfig Config { get { return config_; } set { config_ = value; } } /// <summary>Field number for the "single_utterance" field.</summary> public const int SingleUtteranceFieldNumber = 2; private bool singleUtterance_; /// <summary> /// If `false` or omitted, the recognizer will perform continuous /// recognition (continuing to wait for and process audio even if the user /// pauses speaking) until the client closes the input stream (gRPC API) or /// until the maximum time limit has been reached. May return multiple /// `StreamingRecognitionResult`s with the `is_final` flag set to `true`. /// /// If `true`, the recognizer will detect a single spoken utterance. When it /// detects that the user has paused or stopped speaking, it will return an /// `END_OF_SINGLE_UTTERANCE` event and cease recognition. It will return no /// more than one `StreamingRecognitionResult` with the `is_final` flag set to /// `true`. /// /// The `single_utterance` field can only be used with specified models, /// otherwise an error is thrown. The `model` field in [`RecognitionConfig`][] /// must be set to: /// /// * `command_and_search` /// * `phone_call` AND additional field `useEnhanced`=`true` /// * The `model` field is left undefined. In this case the API auto-selects /// a model based on any other parameters that you set in /// `RecognitionConfig`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool SingleUtterance { get { return singleUtterance_; } set { singleUtterance_ = value; } } /// <summary>Field number for the "interim_results" field.</summary> public const int InterimResultsFieldNumber = 3; private bool interimResults_; /// <summary> /// If `true`, interim results (tentative hypotheses) may be /// returned as they become available (these interim results are indicated with /// the `is_final=false` flag). /// If `false` or omitted, only `is_final=true` result(s) are returned. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool InterimResults { get { return interimResults_; } set { interimResults_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as StreamingRecognitionConfig); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(StreamingRecognitionConfig other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Config, other.Config)) return false; if (SingleUtterance != other.SingleUtterance) return false; if (InterimResults != other.InterimResults) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (config_ != null) hash ^= Config.GetHashCode(); if (SingleUtterance != false) hash ^= SingleUtterance.GetHashCode(); if (InterimResults != false) hash ^= InterimResults.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (config_ != null) { output.WriteRawTag(10); output.WriteMessage(Config); } if (SingleUtterance != false) { output.WriteRawTag(16); output.WriteBool(SingleUtterance); } if (InterimResults != false) { output.WriteRawTag(24); output.WriteBool(InterimResults); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (config_ != null) { output.WriteRawTag(10); output.WriteMessage(Config); } if (SingleUtterance != false) { output.WriteRawTag(16); output.WriteBool(SingleUtterance); } if (InterimResults != false) { output.WriteRawTag(24); output.WriteBool(InterimResults); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (config_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Config); } if (SingleUtterance != false) { size += 1 + 1; } if (InterimResults != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(StreamingRecognitionConfig other) { if (other == null) { return; } if (other.config_ != null) { if (config_ == null) { Config = new global::Google.Cloud.Speech.V1.RecognitionConfig(); } Config.MergeFrom(other.Config); } if (other.SingleUtterance != false) { SingleUtterance = other.SingleUtterance; } if (other.InterimResults != false) { InterimResults = other.InterimResults; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (config_ == null) { Config = new global::Google.Cloud.Speech.V1.RecognitionConfig(); } input.ReadMessage(Config); break; } case 16: { SingleUtterance = input.ReadBool(); break; } case 24: { InterimResults = input.ReadBool(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { if (config_ == null) { Config = new global::Google.Cloud.Speech.V1.RecognitionConfig(); } input.ReadMessage(Config); break; } case 16: { SingleUtterance = input.ReadBool(); break; } case 24: { InterimResults = input.ReadBool(); break; } } } } #endif } /// <summary> /// Provides information to the recognizer that specifies how to process the /// request. /// </summary> public sealed partial class RecognitionConfig : pb::IMessage<RecognitionConfig> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<RecognitionConfig> _parser = new pb::MessageParser<RecognitionConfig>(() => new RecognitionConfig()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<RecognitionConfig> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RecognitionConfig() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RecognitionConfig(RecognitionConfig other) : this() { encoding_ = other.encoding_; sampleRateHertz_ = other.sampleRateHertz_; audioChannelCount_ = other.audioChannelCount_; enableSeparateRecognitionPerChannel_ = other.enableSeparateRecognitionPerChannel_; languageCode_ = other.languageCode_; maxAlternatives_ = other.maxAlternatives_; profanityFilter_ = other.profanityFilter_; speechContexts_ = other.speechContexts_.Clone(); enableWordTimeOffsets_ = other.enableWordTimeOffsets_; enableAutomaticPunctuation_ = other.enableAutomaticPunctuation_; diarizationConfig_ = other.diarizationConfig_ != null ? other.diarizationConfig_.Clone() : null; metadata_ = other.metadata_ != null ? other.metadata_.Clone() : null; model_ = other.model_; useEnhanced_ = other.useEnhanced_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RecognitionConfig Clone() { return new RecognitionConfig(this); } /// <summary>Field number for the "encoding" field.</summary> public const int EncodingFieldNumber = 1; private global::Google.Cloud.Speech.V1.RecognitionConfig.Types.AudioEncoding encoding_ = global::Google.Cloud.Speech.V1.RecognitionConfig.Types.AudioEncoding.EncodingUnspecified; /// <summary> /// Encoding of audio data sent in all `RecognitionAudio` messages. /// This field is optional for `FLAC` and `WAV` audio files and required /// for all other audio formats. For details, see [AudioEncoding][google.cloud.speech.v1.RecognitionConfig.AudioEncoding]. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Speech.V1.RecognitionConfig.Types.AudioEncoding Encoding { get { return encoding_; } set { encoding_ = value; } } /// <summary>Field number for the "sample_rate_hertz" field.</summary> public const int SampleRateHertzFieldNumber = 2; private int sampleRateHertz_; /// <summary> /// Sample rate in Hertz of the audio data sent in all /// `RecognitionAudio` messages. Valid values are: 8000-48000. /// 16000 is optimal. For best results, set the sampling rate of the audio /// source to 16000 Hz. If that's not possible, use the native sample rate of /// the audio source (instead of re-sampling). /// This field is optional for FLAC and WAV audio files, but is /// required for all other audio formats. For details, see [AudioEncoding][google.cloud.speech.v1.RecognitionConfig.AudioEncoding]. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int SampleRateHertz { get { return sampleRateHertz_; } set { sampleRateHertz_ = value; } } /// <summary>Field number for the "audio_channel_count" field.</summary> public const int AudioChannelCountFieldNumber = 7; private int audioChannelCount_; /// <summary> /// The number of channels in the input audio data. /// ONLY set this for MULTI-CHANNEL recognition. /// Valid values for LINEAR16 and FLAC are `1`-`8`. /// Valid values for OGG_OPUS are '1'-'254'. /// Valid value for MULAW, AMR, AMR_WB and SPEEX_WITH_HEADER_BYTE is only `1`. /// If `0` or omitted, defaults to one channel (mono). /// Note: We only recognize the first channel by default. /// To perform independent recognition on each channel set /// `enable_separate_recognition_per_channel` to 'true'. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int AudioChannelCount { get { return audioChannelCount_; } set { audioChannelCount_ = value; } } /// <summary>Field number for the "enable_separate_recognition_per_channel" field.</summary> public const int EnableSeparateRecognitionPerChannelFieldNumber = 12; private bool enableSeparateRecognitionPerChannel_; /// <summary> /// This needs to be set to `true` explicitly and `audio_channel_count` > 1 /// to get each channel recognized separately. The recognition result will /// contain a `channel_tag` field to state which channel that result belongs /// to. If this is not true, we will only recognize the first channel. The /// request is billed cumulatively for all channels recognized: /// `audio_channel_count` multiplied by the length of the audio. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool EnableSeparateRecognitionPerChannel { get { return enableSeparateRecognitionPerChannel_; } set { enableSeparateRecognitionPerChannel_ = value; } } /// <summary>Field number for the "language_code" field.</summary> public const int LanguageCodeFieldNumber = 3; private string languageCode_ = ""; /// <summary> /// Required. The language of the supplied audio as a /// [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag. /// Example: "en-US". /// See [Language /// Support](https://cloud.google.com/speech-to-text/docs/languages) for a list /// of the currently supported language codes. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string LanguageCode { get { return languageCode_; } set { languageCode_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "max_alternatives" field.</summary> public const int MaxAlternativesFieldNumber = 4; private int maxAlternatives_; /// <summary> /// Maximum number of recognition hypotheses to be returned. /// Specifically, the maximum number of `SpeechRecognitionAlternative` messages /// within each `SpeechRecognitionResult`. /// The server may return fewer than `max_alternatives`. /// Valid values are `0`-`30`. A value of `0` or `1` will return a maximum of /// one. If omitted, will return a maximum of one. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int MaxAlternatives { get { return maxAlternatives_; } set { maxAlternatives_ = value; } } /// <summary>Field number for the "profanity_filter" field.</summary> public const int ProfanityFilterFieldNumber = 5; private bool profanityFilter_; /// <summary> /// If set to `true`, the server will attempt to filter out /// profanities, replacing all but the initial character in each filtered word /// with asterisks, e.g. "f***". If set to `false` or omitted, profanities /// won't be filtered out. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool ProfanityFilter { get { return profanityFilter_; } set { profanityFilter_ = value; } } /// <summary>Field number for the "speech_contexts" field.</summary> public const int SpeechContextsFieldNumber = 6; private static readonly pb::FieldCodec<global::Google.Cloud.Speech.V1.SpeechContext> _repeated_speechContexts_codec = pb::FieldCodec.ForMessage(50, global::Google.Cloud.Speech.V1.SpeechContext.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Speech.V1.SpeechContext> speechContexts_ = new pbc::RepeatedField<global::Google.Cloud.Speech.V1.SpeechContext>(); /// <summary> /// Array of [SpeechContext][google.cloud.speech.v1.SpeechContext]. /// A means to provide context to assist the speech recognition. For more /// information, see /// [speech /// adaptation](https://cloud.google.com/speech-to-text/docs/adaptation). /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<global::Google.Cloud.Speech.V1.SpeechContext> SpeechContexts { get { return speechContexts_; } } /// <summary>Field number for the "enable_word_time_offsets" field.</summary> public const int EnableWordTimeOffsetsFieldNumber = 8; private bool enableWordTimeOffsets_; /// <summary> /// If `true`, the top result includes a list of words and /// the start and end time offsets (timestamps) for those words. If /// `false`, no word-level time offset information is returned. The default is /// `false`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool EnableWordTimeOffsets { get { return enableWordTimeOffsets_; } set { enableWordTimeOffsets_ = value; } } /// <summary>Field number for the "enable_automatic_punctuation" field.</summary> public const int EnableAutomaticPunctuationFieldNumber = 11; private bool enableAutomaticPunctuation_; /// <summary> /// If 'true', adds punctuation to recognition result hypotheses. /// This feature is only available in select languages. Setting this for /// requests in other languages has no effect at all. /// The default 'false' value does not add punctuation to result hypotheses. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool EnableAutomaticPunctuation { get { return enableAutomaticPunctuation_; } set { enableAutomaticPunctuation_ = value; } } /// <summary>Field number for the "diarization_config" field.</summary> public const int DiarizationConfigFieldNumber = 19; private global::Google.Cloud.Speech.V1.SpeakerDiarizationConfig diarizationConfig_; /// <summary> /// Config to enable speaker diarization and set additional /// parameters to make diarization better suited for your application. /// Note: When this is enabled, we send all the words from the beginning of the /// audio for the top alternative in every consecutive STREAMING responses. /// This is done in order to improve our speaker tags as our models learn to /// identify the speakers in the conversation over time. /// For non-streaming requests, the diarization results will be provided only /// in the top alternative of the FINAL SpeechRecognitionResult. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Speech.V1.SpeakerDiarizationConfig DiarizationConfig { get { return diarizationConfig_; } set { diarizationConfig_ = value; } } /// <summary>Field number for the "metadata" field.</summary> public const int MetadataFieldNumber = 9; private global::Google.Cloud.Speech.V1.RecognitionMetadata metadata_; /// <summary> /// Metadata regarding this request. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Speech.V1.RecognitionMetadata Metadata { get { return metadata_; } set { metadata_ = value; } } /// <summary>Field number for the "model" field.</summary> public const int ModelFieldNumber = 13; private string model_ = ""; /// <summary> /// Which model to select for the given request. Select the model /// best suited to your domain to get best results. If a model is not /// explicitly specified, then we auto-select a model based on the parameters /// in the RecognitionConfig. /// &lt;table> /// &lt;tr> /// &lt;td>&lt;b>Model&lt;/b>&lt;/td> /// &lt;td>&lt;b>Description&lt;/b>&lt;/td> /// &lt;/tr> /// &lt;tr> /// &lt;td>&lt;code>command_and_search&lt;/code>&lt;/td> /// &lt;td>Best for short queries such as voice commands or voice search.&lt;/td> /// &lt;/tr> /// &lt;tr> /// &lt;td>&lt;code>phone_call&lt;/code>&lt;/td> /// &lt;td>Best for audio that originated from a phone call (typically /// recorded at an 8khz sampling rate).&lt;/td> /// &lt;/tr> /// &lt;tr> /// &lt;td>&lt;code>video&lt;/code>&lt;/td> /// &lt;td>Best for audio that originated from video or includes multiple /// speakers. Ideally the audio is recorded at a 16khz or greater /// sampling rate. This is a premium model that costs more than the /// standard rate.&lt;/td> /// &lt;/tr> /// &lt;tr> /// &lt;td>&lt;code>default&lt;/code>&lt;/td> /// &lt;td>Best for audio that is not one of the specific audio models. /// For example, long-form audio. Ideally the audio is high-fidelity, /// recorded at a 16khz or greater sampling rate.&lt;/td> /// &lt;/tr> /// &lt;/table> /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Model { get { return model_; } set { model_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "use_enhanced" field.</summary> public const int UseEnhancedFieldNumber = 14; private bool useEnhanced_; /// <summary> /// Set to true to use an enhanced model for speech recognition. /// If `use_enhanced` is set to true and the `model` field is not set, then /// an appropriate enhanced model is chosen if an enhanced model exists for /// the audio. /// /// If `use_enhanced` is true and an enhanced version of the specified model /// does not exist, then the speech is recognized using the standard version /// of the specified model. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool UseEnhanced { get { return useEnhanced_; } set { useEnhanced_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as RecognitionConfig); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(RecognitionConfig other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Encoding != other.Encoding) return false; if (SampleRateHertz != other.SampleRateHertz) return false; if (AudioChannelCount != other.AudioChannelCount) return false; if (EnableSeparateRecognitionPerChannel != other.EnableSeparateRecognitionPerChannel) return false; if (LanguageCode != other.LanguageCode) return false; if (MaxAlternatives != other.MaxAlternatives) return false; if (ProfanityFilter != other.ProfanityFilter) return false; if(!speechContexts_.Equals(other.speechContexts_)) return false; if (EnableWordTimeOffsets != other.EnableWordTimeOffsets) return false; if (EnableAutomaticPunctuation != other.EnableAutomaticPunctuation) return false; if (!object.Equals(DiarizationConfig, other.DiarizationConfig)) return false; if (!object.Equals(Metadata, other.Metadata)) return false; if (Model != other.Model) return false; if (UseEnhanced != other.UseEnhanced) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Encoding != global::Google.Cloud.Speech.V1.RecognitionConfig.Types.AudioEncoding.EncodingUnspecified) hash ^= Encoding.GetHashCode(); if (SampleRateHertz != 0) hash ^= SampleRateHertz.GetHashCode(); if (AudioChannelCount != 0) hash ^= AudioChannelCount.GetHashCode(); if (EnableSeparateRecognitionPerChannel != false) hash ^= EnableSeparateRecognitionPerChannel.GetHashCode(); if (LanguageCode.Length != 0) hash ^= LanguageCode.GetHashCode(); if (MaxAlternatives != 0) hash ^= MaxAlternatives.GetHashCode(); if (ProfanityFilter != false) hash ^= ProfanityFilter.GetHashCode(); hash ^= speechContexts_.GetHashCode(); if (EnableWordTimeOffsets != false) hash ^= EnableWordTimeOffsets.GetHashCode(); if (EnableAutomaticPunctuation != false) hash ^= EnableAutomaticPunctuation.GetHashCode(); if (diarizationConfig_ != null) hash ^= DiarizationConfig.GetHashCode(); if (metadata_ != null) hash ^= Metadata.GetHashCode(); if (Model.Length != 0) hash ^= Model.GetHashCode(); if (UseEnhanced != false) hash ^= UseEnhanced.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Encoding != global::Google.Cloud.Speech.V1.RecognitionConfig.Types.AudioEncoding.EncodingUnspecified) { output.WriteRawTag(8); output.WriteEnum((int) Encoding); } if (SampleRateHertz != 0) { output.WriteRawTag(16); output.WriteInt32(SampleRateHertz); } if (LanguageCode.Length != 0) { output.WriteRawTag(26); output.WriteString(LanguageCode); } if (MaxAlternatives != 0) { output.WriteRawTag(32); output.WriteInt32(MaxAlternatives); } if (ProfanityFilter != false) { output.WriteRawTag(40); output.WriteBool(ProfanityFilter); } speechContexts_.WriteTo(output, _repeated_speechContexts_codec); if (AudioChannelCount != 0) { output.WriteRawTag(56); output.WriteInt32(AudioChannelCount); } if (EnableWordTimeOffsets != false) { output.WriteRawTag(64); output.WriteBool(EnableWordTimeOffsets); } if (metadata_ != null) { output.WriteRawTag(74); output.WriteMessage(Metadata); } if (EnableAutomaticPunctuation != false) { output.WriteRawTag(88); output.WriteBool(EnableAutomaticPunctuation); } if (EnableSeparateRecognitionPerChannel != false) { output.WriteRawTag(96); output.WriteBool(EnableSeparateRecognitionPerChannel); } if (Model.Length != 0) { output.WriteRawTag(106); output.WriteString(Model); } if (UseEnhanced != false) { output.WriteRawTag(112); output.WriteBool(UseEnhanced); } if (diarizationConfig_ != null) { output.WriteRawTag(154, 1); output.WriteMessage(DiarizationConfig); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Encoding != global::Google.Cloud.Speech.V1.RecognitionConfig.Types.AudioEncoding.EncodingUnspecified) { output.WriteRawTag(8); output.WriteEnum((int) Encoding); } if (SampleRateHertz != 0) { output.WriteRawTag(16); output.WriteInt32(SampleRateHertz); } if (LanguageCode.Length != 0) { output.WriteRawTag(26); output.WriteString(LanguageCode); } if (MaxAlternatives != 0) { output.WriteRawTag(32); output.WriteInt32(MaxAlternatives); } if (ProfanityFilter != false) { output.WriteRawTag(40); output.WriteBool(ProfanityFilter); } speechContexts_.WriteTo(ref output, _repeated_speechContexts_codec); if (AudioChannelCount != 0) { output.WriteRawTag(56); output.WriteInt32(AudioChannelCount); } if (EnableWordTimeOffsets != false) { output.WriteRawTag(64); output.WriteBool(EnableWordTimeOffsets); } if (metadata_ != null) { output.WriteRawTag(74); output.WriteMessage(Metadata); } if (EnableAutomaticPunctuation != false) { output.WriteRawTag(88); output.WriteBool(EnableAutomaticPunctuation); } if (EnableSeparateRecognitionPerChannel != false) { output.WriteRawTag(96); output.WriteBool(EnableSeparateRecognitionPerChannel); } if (Model.Length != 0) { output.WriteRawTag(106); output.WriteString(Model); } if (UseEnhanced != false) { output.WriteRawTag(112); output.WriteBool(UseEnhanced); } if (diarizationConfig_ != null) { output.WriteRawTag(154, 1); output.WriteMessage(DiarizationConfig); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Encoding != global::Google.Cloud.Speech.V1.RecognitionConfig.Types.AudioEncoding.EncodingUnspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Encoding); } if (SampleRateHertz != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(SampleRateHertz); } if (AudioChannelCount != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(AudioChannelCount); } if (EnableSeparateRecognitionPerChannel != false) { size += 1 + 1; } if (LanguageCode.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(LanguageCode); } if (MaxAlternatives != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(MaxAlternatives); } if (ProfanityFilter != false) { size += 1 + 1; } size += speechContexts_.CalculateSize(_repeated_speechContexts_codec); if (EnableWordTimeOffsets != false) { size += 1 + 1; } if (EnableAutomaticPunctuation != false) { size += 1 + 1; } if (diarizationConfig_ != null) { size += 2 + pb::CodedOutputStream.ComputeMessageSize(DiarizationConfig); } if (metadata_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Metadata); } if (Model.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Model); } if (UseEnhanced != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(RecognitionConfig other) { if (other == null) { return; } if (other.Encoding != global::Google.Cloud.Speech.V1.RecognitionConfig.Types.AudioEncoding.EncodingUnspecified) { Encoding = other.Encoding; } if (other.SampleRateHertz != 0) { SampleRateHertz = other.SampleRateHertz; } if (other.AudioChannelCount != 0) { AudioChannelCount = other.AudioChannelCount; } if (other.EnableSeparateRecognitionPerChannel != false) { EnableSeparateRecognitionPerChannel = other.EnableSeparateRecognitionPerChannel; } if (other.LanguageCode.Length != 0) { LanguageCode = other.LanguageCode; } if (other.MaxAlternatives != 0) { MaxAlternatives = other.MaxAlternatives; } if (other.ProfanityFilter != false) { ProfanityFilter = other.ProfanityFilter; } speechContexts_.Add(other.speechContexts_); if (other.EnableWordTimeOffsets != false) { EnableWordTimeOffsets = other.EnableWordTimeOffsets; } if (other.EnableAutomaticPunctuation != false) { EnableAutomaticPunctuation = other.EnableAutomaticPunctuation; } if (other.diarizationConfig_ != null) { if (diarizationConfig_ == null) { DiarizationConfig = new global::Google.Cloud.Speech.V1.SpeakerDiarizationConfig(); } DiarizationConfig.MergeFrom(other.DiarizationConfig); } if (other.metadata_ != null) { if (metadata_ == null) { Metadata = new global::Google.Cloud.Speech.V1.RecognitionMetadata(); } Metadata.MergeFrom(other.Metadata); } if (other.Model.Length != 0) { Model = other.Model; } if (other.UseEnhanced != false) { UseEnhanced = other.UseEnhanced; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { Encoding = (global::Google.Cloud.Speech.V1.RecognitionConfig.Types.AudioEncoding) input.ReadEnum(); break; } case 16: { SampleRateHertz = input.ReadInt32(); break; } case 26: { LanguageCode = input.ReadString(); break; } case 32: { MaxAlternatives = input.ReadInt32(); break; } case 40: { ProfanityFilter = input.ReadBool(); break; } case 50: { speechContexts_.AddEntriesFrom(input, _repeated_speechContexts_codec); break; } case 56: { AudioChannelCount = input.ReadInt32(); break; } case 64: { EnableWordTimeOffsets = input.ReadBool(); break; } case 74: { if (metadata_ == null) { Metadata = new global::Google.Cloud.Speech.V1.RecognitionMetadata(); } input.ReadMessage(Metadata); break; } case 88: { EnableAutomaticPunctuation = input.ReadBool(); break; } case 96: { EnableSeparateRecognitionPerChannel = input.ReadBool(); break; } case 106: { Model = input.ReadString(); break; } case 112: { UseEnhanced = input.ReadBool(); break; } case 154: { if (diarizationConfig_ == null) { DiarizationConfig = new global::Google.Cloud.Speech.V1.SpeakerDiarizationConfig(); } input.ReadMessage(DiarizationConfig); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { Encoding = (global::Google.Cloud.Speech.V1.RecognitionConfig.Types.AudioEncoding) input.ReadEnum(); break; } case 16: { SampleRateHertz = input.ReadInt32(); break; } case 26: { LanguageCode = input.ReadString(); break; } case 32: { MaxAlternatives = input.ReadInt32(); break; } case 40: { ProfanityFilter = input.ReadBool(); break; } case 50: { speechContexts_.AddEntriesFrom(ref input, _repeated_speechContexts_codec); break; } case 56: { AudioChannelCount = input.ReadInt32(); break; } case 64: { EnableWordTimeOffsets = input.ReadBool(); break; } case 74: { if (metadata_ == null) { Metadata = new global::Google.Cloud.Speech.V1.RecognitionMetadata(); } input.ReadMessage(Metadata); break; } case 88: { EnableAutomaticPunctuation = input.ReadBool(); break; } case 96: { EnableSeparateRecognitionPerChannel = input.ReadBool(); break; } case 106: { Model = input.ReadString(); break; } case 112: { UseEnhanced = input.ReadBool(); break; } case 154: { if (diarizationConfig_ == null) { DiarizationConfig = new global::Google.Cloud.Speech.V1.SpeakerDiarizationConfig(); } input.ReadMessage(DiarizationConfig); break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the RecognitionConfig message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// The encoding of the audio data sent in the request. /// /// All encodings support only 1 channel (mono) audio, unless the /// `audio_channel_count` and `enable_separate_recognition_per_channel` fields /// are set. /// /// For best results, the audio source should be captured and transmitted using /// a lossless encoding (`FLAC` or `LINEAR16`). The accuracy of the speech /// recognition can be reduced if lossy codecs are used to capture or transmit /// audio, particularly if background noise is present. Lossy codecs include /// `MULAW`, `AMR`, `AMR_WB`, `OGG_OPUS`, `SPEEX_WITH_HEADER_BYTE`, `MP3`. /// /// The `FLAC` and `WAV` audio file formats include a header that describes the /// included audio content. You can request recognition for `WAV` files that /// contain either `LINEAR16` or `MULAW` encoded audio. /// If you send `FLAC` or `WAV` audio file format in /// your request, you do not need to specify an `AudioEncoding`; the audio /// encoding format is determined from the file header. If you specify /// an `AudioEncoding` when you send send `FLAC` or `WAV` audio, the /// encoding configuration must match the encoding described in the audio /// header; otherwise the request returns an /// [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT] error code. /// </summary> public enum AudioEncoding { /// <summary> /// Not specified. /// </summary> [pbr::OriginalName("ENCODING_UNSPECIFIED")] EncodingUnspecified = 0, /// <summary> /// Uncompressed 16-bit signed little-endian samples (Linear PCM). /// </summary> [pbr::OriginalName("LINEAR16")] Linear16 = 1, /// <summary> /// `FLAC` (Free Lossless Audio /// Codec) is the recommended encoding because it is /// lossless--therefore recognition is not compromised--and /// requires only about half the bandwidth of `LINEAR16`. `FLAC` stream /// encoding supports 16-bit and 24-bit samples, however, not all fields in /// `STREAMINFO` are supported. /// </summary> [pbr::OriginalName("FLAC")] Flac = 2, /// <summary> /// 8-bit samples that compand 14-bit audio samples using G.711 PCMU/mu-law. /// </summary> [pbr::OriginalName("MULAW")] Mulaw = 3, /// <summary> /// Adaptive Multi-Rate Narrowband codec. `sample_rate_hertz` must be 8000. /// </summary> [pbr::OriginalName("AMR")] Amr = 4, /// <summary> /// Adaptive Multi-Rate Wideband codec. `sample_rate_hertz` must be 16000. /// </summary> [pbr::OriginalName("AMR_WB")] AmrWb = 5, /// <summary> /// Opus encoded audio frames in Ogg container /// ([OggOpus](https://wiki.xiph.org/OggOpus)). /// `sample_rate_hertz` must be one of 8000, 12000, 16000, 24000, or 48000. /// </summary> [pbr::OriginalName("OGG_OPUS")] OggOpus = 6, /// <summary> /// Although the use of lossy encodings is not recommended, if a very low /// bitrate encoding is required, `OGG_OPUS` is highly preferred over /// Speex encoding. The [Speex](https://speex.org/) encoding supported by /// Cloud Speech API has a header byte in each block, as in MIME type /// `audio/x-speex-with-header-byte`. /// It is a variant of the RTP Speex encoding defined in /// [RFC 5574](https://tools.ietf.org/html/rfc5574). /// The stream is a sequence of blocks, one block per RTP packet. Each block /// starts with a byte containing the length of the block, in bytes, followed /// by one or more frames of Speex data, padded to an integral number of /// bytes (octets) as specified in RFC 5574. In other words, each RTP header /// is replaced with a single byte containing the block length. Only Speex /// wideband is supported. `sample_rate_hertz` must be 16000. /// </summary> [pbr::OriginalName("SPEEX_WITH_HEADER_BYTE")] SpeexWithHeaderByte = 7, } } #endregion } /// <summary> /// Config to enable speaker diarization. /// </summary> public sealed partial class SpeakerDiarizationConfig : pb::IMessage<SpeakerDiarizationConfig> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<SpeakerDiarizationConfig> _parser = new pb::MessageParser<SpeakerDiarizationConfig>(() => new SpeakerDiarizationConfig()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<SpeakerDiarizationConfig> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeakerDiarizationConfig() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeakerDiarizationConfig(SpeakerDiarizationConfig other) : this() { enableSpeakerDiarization_ = other.enableSpeakerDiarization_; minSpeakerCount_ = other.minSpeakerCount_; maxSpeakerCount_ = other.maxSpeakerCount_; speakerTag_ = other.speakerTag_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeakerDiarizationConfig Clone() { return new SpeakerDiarizationConfig(this); } /// <summary>Field number for the "enable_speaker_diarization" field.</summary> public const int EnableSpeakerDiarizationFieldNumber = 1; private bool enableSpeakerDiarization_; /// <summary> /// If 'true', enables speaker detection for each recognized word in /// the top alternative of the recognition result using a speaker_tag provided /// in the WordInfo. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool EnableSpeakerDiarization { get { return enableSpeakerDiarization_; } set { enableSpeakerDiarization_ = value; } } /// <summary>Field number for the "min_speaker_count" field.</summary> public const int MinSpeakerCountFieldNumber = 2; private int minSpeakerCount_; /// <summary> /// Minimum number of speakers in the conversation. This range gives you more /// flexibility by allowing the system to automatically determine the correct /// number of speakers. If not set, the default value is 2. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int MinSpeakerCount { get { return minSpeakerCount_; } set { minSpeakerCount_ = value; } } /// <summary>Field number for the "max_speaker_count" field.</summary> public const int MaxSpeakerCountFieldNumber = 3; private int maxSpeakerCount_; /// <summary> /// Maximum number of speakers in the conversation. This range gives you more /// flexibility by allowing the system to automatically determine the correct /// number of speakers. If not set, the default value is 6. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int MaxSpeakerCount { get { return maxSpeakerCount_; } set { maxSpeakerCount_ = value; } } /// <summary>Field number for the "speaker_tag" field.</summary> public const int SpeakerTagFieldNumber = 5; private int speakerTag_; /// <summary> /// Output only. Unused. /// </summary> [global::System.ObsoleteAttribute] [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int SpeakerTag { get { return speakerTag_; } set { speakerTag_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as SpeakerDiarizationConfig); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(SpeakerDiarizationConfig other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (EnableSpeakerDiarization != other.EnableSpeakerDiarization) return false; if (MinSpeakerCount != other.MinSpeakerCount) return false; if (MaxSpeakerCount != other.MaxSpeakerCount) return false; if (SpeakerTag != other.SpeakerTag) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (EnableSpeakerDiarization != false) hash ^= EnableSpeakerDiarization.GetHashCode(); if (MinSpeakerCount != 0) hash ^= MinSpeakerCount.GetHashCode(); if (MaxSpeakerCount != 0) hash ^= MaxSpeakerCount.GetHashCode(); if (SpeakerTag != 0) hash ^= SpeakerTag.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (EnableSpeakerDiarization != false) { output.WriteRawTag(8); output.WriteBool(EnableSpeakerDiarization); } if (MinSpeakerCount != 0) { output.WriteRawTag(16); output.WriteInt32(MinSpeakerCount); } if (MaxSpeakerCount != 0) { output.WriteRawTag(24); output.WriteInt32(MaxSpeakerCount); } if (SpeakerTag != 0) { output.WriteRawTag(40); output.WriteInt32(SpeakerTag); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (EnableSpeakerDiarization != false) { output.WriteRawTag(8); output.WriteBool(EnableSpeakerDiarization); } if (MinSpeakerCount != 0) { output.WriteRawTag(16); output.WriteInt32(MinSpeakerCount); } if (MaxSpeakerCount != 0) { output.WriteRawTag(24); output.WriteInt32(MaxSpeakerCount); } if (SpeakerTag != 0) { output.WriteRawTag(40); output.WriteInt32(SpeakerTag); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (EnableSpeakerDiarization != false) { size += 1 + 1; } if (MinSpeakerCount != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(MinSpeakerCount); } if (MaxSpeakerCount != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(MaxSpeakerCount); } if (SpeakerTag != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(SpeakerTag); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(SpeakerDiarizationConfig other) { if (other == null) { return; } if (other.EnableSpeakerDiarization != false) { EnableSpeakerDiarization = other.EnableSpeakerDiarization; } if (other.MinSpeakerCount != 0) { MinSpeakerCount = other.MinSpeakerCount; } if (other.MaxSpeakerCount != 0) { MaxSpeakerCount = other.MaxSpeakerCount; } if (other.SpeakerTag != 0) { SpeakerTag = other.SpeakerTag; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { EnableSpeakerDiarization = input.ReadBool(); break; } case 16: { MinSpeakerCount = input.ReadInt32(); break; } case 24: { MaxSpeakerCount = input.ReadInt32(); break; } case 40: { SpeakerTag = input.ReadInt32(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { EnableSpeakerDiarization = input.ReadBool(); break; } case 16: { MinSpeakerCount = input.ReadInt32(); break; } case 24: { MaxSpeakerCount = input.ReadInt32(); break; } case 40: { SpeakerTag = input.ReadInt32(); break; } } } } #endif } /// <summary> /// Description of audio data to be recognized. /// </summary> public sealed partial class RecognitionMetadata : pb::IMessage<RecognitionMetadata> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<RecognitionMetadata> _parser = new pb::MessageParser<RecognitionMetadata>(() => new RecognitionMetadata()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<RecognitionMetadata> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[7]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RecognitionMetadata() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RecognitionMetadata(RecognitionMetadata other) : this() { interactionType_ = other.interactionType_; industryNaicsCodeOfAudio_ = other.industryNaicsCodeOfAudio_; microphoneDistance_ = other.microphoneDistance_; originalMediaType_ = other.originalMediaType_; recordingDeviceType_ = other.recordingDeviceType_; recordingDeviceName_ = other.recordingDeviceName_; originalMimeType_ = other.originalMimeType_; audioTopic_ = other.audioTopic_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RecognitionMetadata Clone() { return new RecognitionMetadata(this); } /// <summary>Field number for the "interaction_type" field.</summary> public const int InteractionTypeFieldNumber = 1; private global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.InteractionType interactionType_ = global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.InteractionType.Unspecified; /// <summary> /// The use case most closely describing the audio content to be recognized. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.InteractionType InteractionType { get { return interactionType_; } set { interactionType_ = value; } } /// <summary>Field number for the "industry_naics_code_of_audio" field.</summary> public const int IndustryNaicsCodeOfAudioFieldNumber = 3; private uint industryNaicsCodeOfAudio_; /// <summary> /// The industry vertical to which this speech recognition request most /// closely applies. This is most indicative of the topics contained /// in the audio. Use the 6-digit NAICS code to identify the industry /// vertical - see https://www.naics.com/search/. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public uint IndustryNaicsCodeOfAudio { get { return industryNaicsCodeOfAudio_; } set { industryNaicsCodeOfAudio_ = value; } } /// <summary>Field number for the "microphone_distance" field.</summary> public const int MicrophoneDistanceFieldNumber = 4; private global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.MicrophoneDistance microphoneDistance_ = global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.MicrophoneDistance.Unspecified; /// <summary> /// The audio type that most closely describes the audio being recognized. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.MicrophoneDistance MicrophoneDistance { get { return microphoneDistance_; } set { microphoneDistance_ = value; } } /// <summary>Field number for the "original_media_type" field.</summary> public const int OriginalMediaTypeFieldNumber = 5; private global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.OriginalMediaType originalMediaType_ = global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.OriginalMediaType.Unspecified; /// <summary> /// The original media the speech was recorded on. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.OriginalMediaType OriginalMediaType { get { return originalMediaType_; } set { originalMediaType_ = value; } } /// <summary>Field number for the "recording_device_type" field.</summary> public const int RecordingDeviceTypeFieldNumber = 6; private global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.RecordingDeviceType recordingDeviceType_ = global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.RecordingDeviceType.Unspecified; /// <summary> /// The type of device the speech was recorded with. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.RecordingDeviceType RecordingDeviceType { get { return recordingDeviceType_; } set { recordingDeviceType_ = value; } } /// <summary>Field number for the "recording_device_name" field.</summary> public const int RecordingDeviceNameFieldNumber = 7; private string recordingDeviceName_ = ""; /// <summary> /// The device used to make the recording. Examples 'Nexus 5X' or /// 'Polycom SoundStation IP 6000' or 'POTS' or 'VoIP' or /// 'Cardioid Microphone'. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string RecordingDeviceName { get { return recordingDeviceName_; } set { recordingDeviceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "original_mime_type" field.</summary> public const int OriginalMimeTypeFieldNumber = 8; private string originalMimeType_ = ""; /// <summary> /// Mime type of the original audio file. For example `audio/m4a`, /// `audio/x-alaw-basic`, `audio/mp3`, `audio/3gpp`. /// A list of possible audio mime types is maintained at /// http://www.iana.org/assignments/media-types/media-types.xhtml#audio /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string OriginalMimeType { get { return originalMimeType_; } set { originalMimeType_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "audio_topic" field.</summary> public const int AudioTopicFieldNumber = 10; private string audioTopic_ = ""; /// <summary> /// Description of the content. Eg. "Recordings of federal supreme court /// hearings from 2012". /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string AudioTopic { get { return audioTopic_; } set { audioTopic_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as RecognitionMetadata); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(RecognitionMetadata other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (InteractionType != other.InteractionType) return false; if (IndustryNaicsCodeOfAudio != other.IndustryNaicsCodeOfAudio) return false; if (MicrophoneDistance != other.MicrophoneDistance) return false; if (OriginalMediaType != other.OriginalMediaType) return false; if (RecordingDeviceType != other.RecordingDeviceType) return false; if (RecordingDeviceName != other.RecordingDeviceName) return false; if (OriginalMimeType != other.OriginalMimeType) return false; if (AudioTopic != other.AudioTopic) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (InteractionType != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.InteractionType.Unspecified) hash ^= InteractionType.GetHashCode(); if (IndustryNaicsCodeOfAudio != 0) hash ^= IndustryNaicsCodeOfAudio.GetHashCode(); if (MicrophoneDistance != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.MicrophoneDistance.Unspecified) hash ^= MicrophoneDistance.GetHashCode(); if (OriginalMediaType != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.OriginalMediaType.Unspecified) hash ^= OriginalMediaType.GetHashCode(); if (RecordingDeviceType != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.RecordingDeviceType.Unspecified) hash ^= RecordingDeviceType.GetHashCode(); if (RecordingDeviceName.Length != 0) hash ^= RecordingDeviceName.GetHashCode(); if (OriginalMimeType.Length != 0) hash ^= OriginalMimeType.GetHashCode(); if (AudioTopic.Length != 0) hash ^= AudioTopic.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (InteractionType != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.InteractionType.Unspecified) { output.WriteRawTag(8); output.WriteEnum((int) InteractionType); } if (IndustryNaicsCodeOfAudio != 0) { output.WriteRawTag(24); output.WriteUInt32(IndustryNaicsCodeOfAudio); } if (MicrophoneDistance != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.MicrophoneDistance.Unspecified) { output.WriteRawTag(32); output.WriteEnum((int) MicrophoneDistance); } if (OriginalMediaType != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.OriginalMediaType.Unspecified) { output.WriteRawTag(40); output.WriteEnum((int) OriginalMediaType); } if (RecordingDeviceType != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.RecordingDeviceType.Unspecified) { output.WriteRawTag(48); output.WriteEnum((int) RecordingDeviceType); } if (RecordingDeviceName.Length != 0) { output.WriteRawTag(58); output.WriteString(RecordingDeviceName); } if (OriginalMimeType.Length != 0) { output.WriteRawTag(66); output.WriteString(OriginalMimeType); } if (AudioTopic.Length != 0) { output.WriteRawTag(82); output.WriteString(AudioTopic); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (InteractionType != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.InteractionType.Unspecified) { output.WriteRawTag(8); output.WriteEnum((int) InteractionType); } if (IndustryNaicsCodeOfAudio != 0) { output.WriteRawTag(24); output.WriteUInt32(IndustryNaicsCodeOfAudio); } if (MicrophoneDistance != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.MicrophoneDistance.Unspecified) { output.WriteRawTag(32); output.WriteEnum((int) MicrophoneDistance); } if (OriginalMediaType != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.OriginalMediaType.Unspecified) { output.WriteRawTag(40); output.WriteEnum((int) OriginalMediaType); } if (RecordingDeviceType != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.RecordingDeviceType.Unspecified) { output.WriteRawTag(48); output.WriteEnum((int) RecordingDeviceType); } if (RecordingDeviceName.Length != 0) { output.WriteRawTag(58); output.WriteString(RecordingDeviceName); } if (OriginalMimeType.Length != 0) { output.WriteRawTag(66); output.WriteString(OriginalMimeType); } if (AudioTopic.Length != 0) { output.WriteRawTag(82); output.WriteString(AudioTopic); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (InteractionType != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.InteractionType.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) InteractionType); } if (IndustryNaicsCodeOfAudio != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(IndustryNaicsCodeOfAudio); } if (MicrophoneDistance != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.MicrophoneDistance.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) MicrophoneDistance); } if (OriginalMediaType != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.OriginalMediaType.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) OriginalMediaType); } if (RecordingDeviceType != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.RecordingDeviceType.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) RecordingDeviceType); } if (RecordingDeviceName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(RecordingDeviceName); } if (OriginalMimeType.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(OriginalMimeType); } if (AudioTopic.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(AudioTopic); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(RecognitionMetadata other) { if (other == null) { return; } if (other.InteractionType != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.InteractionType.Unspecified) { InteractionType = other.InteractionType; } if (other.IndustryNaicsCodeOfAudio != 0) { IndustryNaicsCodeOfAudio = other.IndustryNaicsCodeOfAudio; } if (other.MicrophoneDistance != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.MicrophoneDistance.Unspecified) { MicrophoneDistance = other.MicrophoneDistance; } if (other.OriginalMediaType != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.OriginalMediaType.Unspecified) { OriginalMediaType = other.OriginalMediaType; } if (other.RecordingDeviceType != global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.RecordingDeviceType.Unspecified) { RecordingDeviceType = other.RecordingDeviceType; } if (other.RecordingDeviceName.Length != 0) { RecordingDeviceName = other.RecordingDeviceName; } if (other.OriginalMimeType.Length != 0) { OriginalMimeType = other.OriginalMimeType; } if (other.AudioTopic.Length != 0) { AudioTopic = other.AudioTopic; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { InteractionType = (global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.InteractionType) input.ReadEnum(); break; } case 24: { IndustryNaicsCodeOfAudio = input.ReadUInt32(); break; } case 32: { MicrophoneDistance = (global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.MicrophoneDistance) input.ReadEnum(); break; } case 40: { OriginalMediaType = (global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.OriginalMediaType) input.ReadEnum(); break; } case 48: { RecordingDeviceType = (global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.RecordingDeviceType) input.ReadEnum(); break; } case 58: { RecordingDeviceName = input.ReadString(); break; } case 66: { OriginalMimeType = input.ReadString(); break; } case 82: { AudioTopic = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { InteractionType = (global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.InteractionType) input.ReadEnum(); break; } case 24: { IndustryNaicsCodeOfAudio = input.ReadUInt32(); break; } case 32: { MicrophoneDistance = (global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.MicrophoneDistance) input.ReadEnum(); break; } case 40: { OriginalMediaType = (global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.OriginalMediaType) input.ReadEnum(); break; } case 48: { RecordingDeviceType = (global::Google.Cloud.Speech.V1.RecognitionMetadata.Types.RecordingDeviceType) input.ReadEnum(); break; } case 58: { RecordingDeviceName = input.ReadString(); break; } case 66: { OriginalMimeType = input.ReadString(); break; } case 82: { AudioTopic = input.ReadString(); break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the RecognitionMetadata message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// Use case categories that the audio recognition request can be described /// by. /// </summary> public enum InteractionType { /// <summary> /// Use case is either unknown or is something other than one of the other /// values below. /// </summary> [pbr::OriginalName("INTERACTION_TYPE_UNSPECIFIED")] Unspecified = 0, /// <summary> /// Multiple people in a conversation or discussion. For example in a /// meeting with two or more people actively participating. Typically /// all the primary people speaking would be in the same room (if not, /// see PHONE_CALL) /// </summary> [pbr::OriginalName("DISCUSSION")] Discussion = 1, /// <summary> /// One or more persons lecturing or presenting to others, mostly /// uninterrupted. /// </summary> [pbr::OriginalName("PRESENTATION")] Presentation = 2, /// <summary> /// A phone-call or video-conference in which two or more people, who are /// not in the same room, are actively participating. /// </summary> [pbr::OriginalName("PHONE_CALL")] PhoneCall = 3, /// <summary> /// A recorded message intended for another person to listen to. /// </summary> [pbr::OriginalName("VOICEMAIL")] Voicemail = 4, /// <summary> /// Professionally produced audio (eg. TV Show, Podcast). /// </summary> [pbr::OriginalName("PROFESSIONALLY_PRODUCED")] ProfessionallyProduced = 5, /// <summary> /// Transcribe spoken questions and queries into text. /// </summary> [pbr::OriginalName("VOICE_SEARCH")] VoiceSearch = 6, /// <summary> /// Transcribe voice commands, such as for controlling a device. /// </summary> [pbr::OriginalName("VOICE_COMMAND")] VoiceCommand = 7, /// <summary> /// Transcribe speech to text to create a written document, such as a /// text-message, email or report. /// </summary> [pbr::OriginalName("DICTATION")] Dictation = 8, } /// <summary> /// Enumerates the types of capture settings describing an audio file. /// </summary> public enum MicrophoneDistance { /// <summary> /// Audio type is not known. /// </summary> [pbr::OriginalName("MICROPHONE_DISTANCE_UNSPECIFIED")] Unspecified = 0, /// <summary> /// The audio was captured from a closely placed microphone. Eg. phone, /// dictaphone, or handheld microphone. Generally if there speaker is within /// 1 meter of the microphone. /// </summary> [pbr::OriginalName("NEARFIELD")] Nearfield = 1, /// <summary> /// The speaker if within 3 meters of the microphone. /// </summary> [pbr::OriginalName("MIDFIELD")] Midfield = 2, /// <summary> /// The speaker is more than 3 meters away from the microphone. /// </summary> [pbr::OriginalName("FARFIELD")] Farfield = 3, } /// <summary> /// The original media the speech was recorded on. /// </summary> public enum OriginalMediaType { /// <summary> /// Unknown original media type. /// </summary> [pbr::OriginalName("ORIGINAL_MEDIA_TYPE_UNSPECIFIED")] Unspecified = 0, /// <summary> /// The speech data is an audio recording. /// </summary> [pbr::OriginalName("AUDIO")] Audio = 1, /// <summary> /// The speech data originally recorded on a video. /// </summary> [pbr::OriginalName("VIDEO")] Video = 2, } /// <summary> /// The type of device the speech was recorded with. /// </summary> public enum RecordingDeviceType { /// <summary> /// The recording device is unknown. /// </summary> [pbr::OriginalName("RECORDING_DEVICE_TYPE_UNSPECIFIED")] Unspecified = 0, /// <summary> /// Speech was recorded on a smartphone. /// </summary> [pbr::OriginalName("SMARTPHONE")] Smartphone = 1, /// <summary> /// Speech was recorded using a personal computer or tablet. /// </summary> [pbr::OriginalName("PC")] Pc = 2, /// <summary> /// Speech was recorded over a phone line. /// </summary> [pbr::OriginalName("PHONE_LINE")] PhoneLine = 3, /// <summary> /// Speech was recorded in a vehicle. /// </summary> [pbr::OriginalName("VEHICLE")] Vehicle = 4, /// <summary> /// Speech was recorded outdoors. /// </summary> [pbr::OriginalName("OTHER_OUTDOOR_DEVICE")] OtherOutdoorDevice = 5, /// <summary> /// Speech was recorded indoors. /// </summary> [pbr::OriginalName("OTHER_INDOOR_DEVICE")] OtherIndoorDevice = 6, } } #endregion } /// <summary> /// Provides "hints" to the speech recognizer to favor specific words and phrases /// in the results. /// </summary> public sealed partial class SpeechContext : pb::IMessage<SpeechContext> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<SpeechContext> _parser = new pb::MessageParser<SpeechContext>(() => new SpeechContext()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<SpeechContext> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[8]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechContext() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechContext(SpeechContext other) : this() { phrases_ = other.phrases_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechContext Clone() { return new SpeechContext(this); } /// <summary>Field number for the "phrases" field.</summary> public const int PhrasesFieldNumber = 1; private static readonly pb::FieldCodec<string> _repeated_phrases_codec = pb::FieldCodec.ForString(10); private readonly pbc::RepeatedField<string> phrases_ = new pbc::RepeatedField<string>(); /// <summary> /// A list of strings containing words and phrases "hints" so that /// the speech recognition is more likely to recognize them. This can be used /// to improve the accuracy for specific words and phrases, for example, if /// specific commands are typically spoken by the user. This can also be used /// to add additional words to the vocabulary of the recognizer. See /// [usage limits](https://cloud.google.com/speech-to-text/quotas#content). /// /// List items can also be set to classes for groups of words that represent /// common concepts that occur in natural language. For example, rather than /// providing phrase hints for every month of the year, using the $MONTH class /// improves the likelihood of correctly transcribing audio that includes /// months. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<string> Phrases { get { return phrases_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as SpeechContext); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(SpeechContext other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!phrases_.Equals(other.phrases_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; hash ^= phrases_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else phrases_.WriteTo(output, _repeated_phrases_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { phrases_.WriteTo(ref output, _repeated_phrases_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; size += phrases_.CalculateSize(_repeated_phrases_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(SpeechContext other) { if (other == null) { return; } phrases_.Add(other.phrases_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { phrases_.AddEntriesFrom(input, _repeated_phrases_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { phrases_.AddEntriesFrom(ref input, _repeated_phrases_codec); break; } } } } #endif } /// <summary> /// Contains audio data in the encoding specified in the `RecognitionConfig`. /// Either `content` or `uri` must be supplied. Supplying both or neither /// returns [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. See /// [content limits](https://cloud.google.com/speech-to-text/quotas#content). /// </summary> public sealed partial class RecognitionAudio : pb::IMessage<RecognitionAudio> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<RecognitionAudio> _parser = new pb::MessageParser<RecognitionAudio>(() => new RecognitionAudio()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<RecognitionAudio> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[9]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RecognitionAudio() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RecognitionAudio(RecognitionAudio other) : this() { switch (other.AudioSourceCase) { case AudioSourceOneofCase.Content: Content = other.Content; break; case AudioSourceOneofCase.Uri: Uri = other.Uri; break; } _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RecognitionAudio Clone() { return new RecognitionAudio(this); } /// <summary>Field number for the "content" field.</summary> public const int ContentFieldNumber = 1; /// <summary> /// The audio data bytes encoded as specified in /// `RecognitionConfig`. Note: as with all bytes fields, proto buffers use a /// pure binary representation, whereas JSON representations use base64. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pb::ByteString Content { get { return audioSourceCase_ == AudioSourceOneofCase.Content ? (pb::ByteString) audioSource_ : pb::ByteString.Empty; } set { audioSource_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); audioSourceCase_ = AudioSourceOneofCase.Content; } } /// <summary>Field number for the "uri" field.</summary> public const int UriFieldNumber = 2; /// <summary> /// URI that points to a file that contains audio data bytes as specified in /// `RecognitionConfig`. The file must not be compressed (for example, gzip). /// Currently, only Google Cloud Storage URIs are /// supported, which must be specified in the following format: /// `gs://bucket_name/object_name` (other URI formats return /// [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see /// [Request URIs](https://cloud.google.com/storage/docs/reference-uris). /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Uri { get { return audioSourceCase_ == AudioSourceOneofCase.Uri ? (string) audioSource_ : ""; } set { audioSource_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); audioSourceCase_ = AudioSourceOneofCase.Uri; } } private object audioSource_; /// <summary>Enum of possible cases for the "audio_source" oneof.</summary> public enum AudioSourceOneofCase { None = 0, Content = 1, Uri = 2, } private AudioSourceOneofCase audioSourceCase_ = AudioSourceOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AudioSourceOneofCase AudioSourceCase { get { return audioSourceCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void ClearAudioSource() { audioSourceCase_ = AudioSourceOneofCase.None; audioSource_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as RecognitionAudio); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(RecognitionAudio other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Content != other.Content) return false; if (Uri != other.Uri) return false; if (AudioSourceCase != other.AudioSourceCase) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (audioSourceCase_ == AudioSourceOneofCase.Content) hash ^= Content.GetHashCode(); if (audioSourceCase_ == AudioSourceOneofCase.Uri) hash ^= Uri.GetHashCode(); hash ^= (int) audioSourceCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (audioSourceCase_ == AudioSourceOneofCase.Content) { output.WriteRawTag(10); output.WriteBytes(Content); } if (audioSourceCase_ == AudioSourceOneofCase.Uri) { output.WriteRawTag(18); output.WriteString(Uri); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (audioSourceCase_ == AudioSourceOneofCase.Content) { output.WriteRawTag(10); output.WriteBytes(Content); } if (audioSourceCase_ == AudioSourceOneofCase.Uri) { output.WriteRawTag(18); output.WriteString(Uri); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (audioSourceCase_ == AudioSourceOneofCase.Content) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(Content); } if (audioSourceCase_ == AudioSourceOneofCase.Uri) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Uri); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(RecognitionAudio other) { if (other == null) { return; } switch (other.AudioSourceCase) { case AudioSourceOneofCase.Content: Content = other.Content; break; case AudioSourceOneofCase.Uri: Uri = other.Uri; break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Content = input.ReadBytes(); break; } case 18: { Uri = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Content = input.ReadBytes(); break; } case 18: { Uri = input.ReadString(); break; } } } } #endif } /// <summary> /// The only message returned to the client by the `Recognize` method. It /// contains the result as zero or more sequential `SpeechRecognitionResult` /// messages. /// </summary> public sealed partial class RecognizeResponse : pb::IMessage<RecognizeResponse> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<RecognizeResponse> _parser = new pb::MessageParser<RecognizeResponse>(() => new RecognizeResponse()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<RecognizeResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[10]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RecognizeResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RecognizeResponse(RecognizeResponse other) : this() { results_ = other.results_.Clone(); totalBilledTime_ = other.totalBilledTime_ != null ? other.totalBilledTime_.Clone() : null; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RecognizeResponse Clone() { return new RecognizeResponse(this); } /// <summary>Field number for the "results" field.</summary> public const int ResultsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Cloud.Speech.V1.SpeechRecognitionResult> _repeated_results_codec = pb::FieldCodec.ForMessage(18, global::Google.Cloud.Speech.V1.SpeechRecognitionResult.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Speech.V1.SpeechRecognitionResult> results_ = new pbc::RepeatedField<global::Google.Cloud.Speech.V1.SpeechRecognitionResult>(); /// <summary> /// Sequential list of transcription results corresponding to /// sequential portions of audio. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<global::Google.Cloud.Speech.V1.SpeechRecognitionResult> Results { get { return results_; } } /// <summary>Field number for the "total_billed_time" field.</summary> public const int TotalBilledTimeFieldNumber = 3; private global::Google.Protobuf.WellKnownTypes.Duration totalBilledTime_; /// <summary> /// When available, billed audio seconds for the corresponding request. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Protobuf.WellKnownTypes.Duration TotalBilledTime { get { return totalBilledTime_; } set { totalBilledTime_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as RecognizeResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(RecognizeResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!results_.Equals(other.results_)) return false; if (!object.Equals(TotalBilledTime, other.TotalBilledTime)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; hash ^= results_.GetHashCode(); if (totalBilledTime_ != null) hash ^= TotalBilledTime.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else results_.WriteTo(output, _repeated_results_codec); if (totalBilledTime_ != null) { output.WriteRawTag(26); output.WriteMessage(TotalBilledTime); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { results_.WriteTo(ref output, _repeated_results_codec); if (totalBilledTime_ != null) { output.WriteRawTag(26); output.WriteMessage(TotalBilledTime); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; size += results_.CalculateSize(_repeated_results_codec); if (totalBilledTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(TotalBilledTime); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(RecognizeResponse other) { if (other == null) { return; } results_.Add(other.results_); if (other.totalBilledTime_ != null) { if (totalBilledTime_ == null) { TotalBilledTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } TotalBilledTime.MergeFrom(other.TotalBilledTime); } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 18: { results_.AddEntriesFrom(input, _repeated_results_codec); break; } case 26: { if (totalBilledTime_ == null) { TotalBilledTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(TotalBilledTime); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 18: { results_.AddEntriesFrom(ref input, _repeated_results_codec); break; } case 26: { if (totalBilledTime_ == null) { TotalBilledTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(TotalBilledTime); break; } } } } #endif } /// <summary> /// The only message returned to the client by the `LongRunningRecognize` method. /// It contains the result as zero or more sequential `SpeechRecognitionResult` /// messages. It is included in the `result.response` field of the `Operation` /// returned by the `GetOperation` call of the `google::longrunning::Operations` /// service. /// </summary> public sealed partial class LongRunningRecognizeResponse : pb::IMessage<LongRunningRecognizeResponse> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<LongRunningRecognizeResponse> _parser = new pb::MessageParser<LongRunningRecognizeResponse>(() => new LongRunningRecognizeResponse()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<LongRunningRecognizeResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[11]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public LongRunningRecognizeResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public LongRunningRecognizeResponse(LongRunningRecognizeResponse other) : this() { results_ = other.results_.Clone(); totalBilledTime_ = other.totalBilledTime_ != null ? other.totalBilledTime_.Clone() : null; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public LongRunningRecognizeResponse Clone() { return new LongRunningRecognizeResponse(this); } /// <summary>Field number for the "results" field.</summary> public const int ResultsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Cloud.Speech.V1.SpeechRecognitionResult> _repeated_results_codec = pb::FieldCodec.ForMessage(18, global::Google.Cloud.Speech.V1.SpeechRecognitionResult.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Speech.V1.SpeechRecognitionResult> results_ = new pbc::RepeatedField<global::Google.Cloud.Speech.V1.SpeechRecognitionResult>(); /// <summary> /// Sequential list of transcription results corresponding to /// sequential portions of audio. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<global::Google.Cloud.Speech.V1.SpeechRecognitionResult> Results { get { return results_; } } /// <summary>Field number for the "total_billed_time" field.</summary> public const int TotalBilledTimeFieldNumber = 3; private global::Google.Protobuf.WellKnownTypes.Duration totalBilledTime_; /// <summary> /// When available, billed audio seconds for the corresponding request. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Protobuf.WellKnownTypes.Duration TotalBilledTime { get { return totalBilledTime_; } set { totalBilledTime_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as LongRunningRecognizeResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(LongRunningRecognizeResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!results_.Equals(other.results_)) return false; if (!object.Equals(TotalBilledTime, other.TotalBilledTime)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; hash ^= results_.GetHashCode(); if (totalBilledTime_ != null) hash ^= TotalBilledTime.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else results_.WriteTo(output, _repeated_results_codec); if (totalBilledTime_ != null) { output.WriteRawTag(26); output.WriteMessage(TotalBilledTime); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { results_.WriteTo(ref output, _repeated_results_codec); if (totalBilledTime_ != null) { output.WriteRawTag(26); output.WriteMessage(TotalBilledTime); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; size += results_.CalculateSize(_repeated_results_codec); if (totalBilledTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(TotalBilledTime); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(LongRunningRecognizeResponse other) { if (other == null) { return; } results_.Add(other.results_); if (other.totalBilledTime_ != null) { if (totalBilledTime_ == null) { TotalBilledTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } TotalBilledTime.MergeFrom(other.TotalBilledTime); } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 18: { results_.AddEntriesFrom(input, _repeated_results_codec); break; } case 26: { if (totalBilledTime_ == null) { TotalBilledTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(TotalBilledTime); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 18: { results_.AddEntriesFrom(ref input, _repeated_results_codec); break; } case 26: { if (totalBilledTime_ == null) { TotalBilledTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(TotalBilledTime); break; } } } } #endif } /// <summary> /// Describes the progress of a long-running `LongRunningRecognize` call. It is /// included in the `metadata` field of the `Operation` returned by the /// `GetOperation` call of the `google::longrunning::Operations` service. /// </summary> public sealed partial class LongRunningRecognizeMetadata : pb::IMessage<LongRunningRecognizeMetadata> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<LongRunningRecognizeMetadata> _parser = new pb::MessageParser<LongRunningRecognizeMetadata>(() => new LongRunningRecognizeMetadata()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<LongRunningRecognizeMetadata> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[12]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public LongRunningRecognizeMetadata() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public LongRunningRecognizeMetadata(LongRunningRecognizeMetadata other) : this() { progressPercent_ = other.progressPercent_; startTime_ = other.startTime_ != null ? other.startTime_.Clone() : null; lastUpdateTime_ = other.lastUpdateTime_ != null ? other.lastUpdateTime_.Clone() : null; uri_ = other.uri_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public LongRunningRecognizeMetadata Clone() { return new LongRunningRecognizeMetadata(this); } /// <summary>Field number for the "progress_percent" field.</summary> public const int ProgressPercentFieldNumber = 1; private int progressPercent_; /// <summary> /// Approximate percentage of audio processed thus far. Guaranteed to be 100 /// when the audio is fully processed and the results are available. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int ProgressPercent { get { return progressPercent_; } set { progressPercent_ = value; } } /// <summary>Field number for the "start_time" field.</summary> public const int StartTimeFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Timestamp startTime_; /// <summary> /// Time when the request was received. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Protobuf.WellKnownTypes.Timestamp StartTime { get { return startTime_; } set { startTime_ = value; } } /// <summary>Field number for the "last_update_time" field.</summary> public const int LastUpdateTimeFieldNumber = 3; private global::Google.Protobuf.WellKnownTypes.Timestamp lastUpdateTime_; /// <summary> /// Time of the most recent processing update. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Protobuf.WellKnownTypes.Timestamp LastUpdateTime { get { return lastUpdateTime_; } set { lastUpdateTime_ = value; } } /// <summary>Field number for the "uri" field.</summary> public const int UriFieldNumber = 4; private string uri_ = ""; /// <summary> /// Output only. The URI of the audio file being transcribed. Empty if the audio was sent /// as byte content. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Uri { get { return uri_; } set { uri_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as LongRunningRecognizeMetadata); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(LongRunningRecognizeMetadata other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ProgressPercent != other.ProgressPercent) return false; if (!object.Equals(StartTime, other.StartTime)) return false; if (!object.Equals(LastUpdateTime, other.LastUpdateTime)) return false; if (Uri != other.Uri) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (ProgressPercent != 0) hash ^= ProgressPercent.GetHashCode(); if (startTime_ != null) hash ^= StartTime.GetHashCode(); if (lastUpdateTime_ != null) hash ^= LastUpdateTime.GetHashCode(); if (Uri.Length != 0) hash ^= Uri.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (ProgressPercent != 0) { output.WriteRawTag(8); output.WriteInt32(ProgressPercent); } if (startTime_ != null) { output.WriteRawTag(18); output.WriteMessage(StartTime); } if (lastUpdateTime_ != null) { output.WriteRawTag(26); output.WriteMessage(LastUpdateTime); } if (Uri.Length != 0) { output.WriteRawTag(34); output.WriteString(Uri); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (ProgressPercent != 0) { output.WriteRawTag(8); output.WriteInt32(ProgressPercent); } if (startTime_ != null) { output.WriteRawTag(18); output.WriteMessage(StartTime); } if (lastUpdateTime_ != null) { output.WriteRawTag(26); output.WriteMessage(LastUpdateTime); } if (Uri.Length != 0) { output.WriteRawTag(34); output.WriteString(Uri); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (ProgressPercent != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(ProgressPercent); } if (startTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(StartTime); } if (lastUpdateTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(LastUpdateTime); } if (Uri.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Uri); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(LongRunningRecognizeMetadata other) { if (other == null) { return; } if (other.ProgressPercent != 0) { ProgressPercent = other.ProgressPercent; } if (other.startTime_ != null) { if (startTime_ == null) { StartTime = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } StartTime.MergeFrom(other.StartTime); } if (other.lastUpdateTime_ != null) { if (lastUpdateTime_ == null) { LastUpdateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } LastUpdateTime.MergeFrom(other.LastUpdateTime); } if (other.Uri.Length != 0) { Uri = other.Uri; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { ProgressPercent = input.ReadInt32(); break; } case 18: { if (startTime_ == null) { StartTime = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(StartTime); break; } case 26: { if (lastUpdateTime_ == null) { LastUpdateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(LastUpdateTime); break; } case 34: { Uri = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { ProgressPercent = input.ReadInt32(); break; } case 18: { if (startTime_ == null) { StartTime = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(StartTime); break; } case 26: { if (lastUpdateTime_ == null) { LastUpdateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(LastUpdateTime); break; } case 34: { Uri = input.ReadString(); break; } } } } #endif } /// <summary> /// `StreamingRecognizeResponse` is the only message returned to the client by /// `StreamingRecognize`. A series of zero or more `StreamingRecognizeResponse` /// messages are streamed back to the client. If there is no recognizable /// audio, and `single_utterance` is set to false, then no messages are streamed /// back to the client. /// /// Here's an example of a series of `StreamingRecognizeResponse`s that might be /// returned while processing audio: /// /// 1. results { alternatives { transcript: "tube" } stability: 0.01 } /// /// 2. results { alternatives { transcript: "to be a" } stability: 0.01 } /// /// 3. results { alternatives { transcript: "to be" } stability: 0.9 } /// results { alternatives { transcript: " or not to be" } stability: 0.01 } /// /// 4. results { alternatives { transcript: "to be or not to be" /// confidence: 0.92 } /// alternatives { transcript: "to bee or not to bee" } /// is_final: true } /// /// 5. results { alternatives { transcript: " that's" } stability: 0.01 } /// /// 6. results { alternatives { transcript: " that is" } stability: 0.9 } /// results { alternatives { transcript: " the question" } stability: 0.01 } /// /// 7. results { alternatives { transcript: " that is the question" /// confidence: 0.98 } /// alternatives { transcript: " that was the question" } /// is_final: true } /// /// Notes: /// /// - Only two of the above responses #4 and #7 contain final results; they are /// indicated by `is_final: true`. Concatenating these together generates the /// full transcript: "to be or not to be that is the question". /// /// - The others contain interim `results`. #3 and #6 contain two interim /// `results`: the first portion has a high stability and is less likely to /// change; the second portion has a low stability and is very likely to /// change. A UI designer might choose to show only high stability `results`. /// /// - The specific `stability` and `confidence` values shown above are only for /// illustrative purposes. Actual values may vary. /// /// - In each response, only one of these fields will be set: /// `error`, /// `speech_event_type`, or /// one or more (repeated) `results`. /// </summary> public sealed partial class StreamingRecognizeResponse : pb::IMessage<StreamingRecognizeResponse> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<StreamingRecognizeResponse> _parser = new pb::MessageParser<StreamingRecognizeResponse>(() => new StreamingRecognizeResponse()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<StreamingRecognizeResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[13]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public StreamingRecognizeResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public StreamingRecognizeResponse(StreamingRecognizeResponse other) : this() { error_ = other.error_ != null ? other.error_.Clone() : null; results_ = other.results_.Clone(); speechEventType_ = other.speechEventType_; totalBilledTime_ = other.totalBilledTime_ != null ? other.totalBilledTime_.Clone() : null; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public StreamingRecognizeResponse Clone() { return new StreamingRecognizeResponse(this); } /// <summary>Field number for the "error" field.</summary> public const int ErrorFieldNumber = 1; private global::Google.Rpc.Status error_; /// <summary> /// If set, returns a [google.rpc.Status][google.rpc.Status] message that /// specifies the error for the operation. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Rpc.Status Error { get { return error_; } set { error_ = value; } } /// <summary>Field number for the "results" field.</summary> public const int ResultsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Cloud.Speech.V1.StreamingRecognitionResult> _repeated_results_codec = pb::FieldCodec.ForMessage(18, global::Google.Cloud.Speech.V1.StreamingRecognitionResult.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Speech.V1.StreamingRecognitionResult> results_ = new pbc::RepeatedField<global::Google.Cloud.Speech.V1.StreamingRecognitionResult>(); /// <summary> /// This repeated list contains zero or more results that /// correspond to consecutive portions of the audio currently being processed. /// It contains zero or one `is_final=true` result (the newly settled portion), /// followed by zero or more `is_final=false` results (the interim results). /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<global::Google.Cloud.Speech.V1.StreamingRecognitionResult> Results { get { return results_; } } /// <summary>Field number for the "speech_event_type" field.</summary> public const int SpeechEventTypeFieldNumber = 4; private global::Google.Cloud.Speech.V1.StreamingRecognizeResponse.Types.SpeechEventType speechEventType_ = global::Google.Cloud.Speech.V1.StreamingRecognizeResponse.Types.SpeechEventType.SpeechEventUnspecified; /// <summary> /// Indicates the type of speech event. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Cloud.Speech.V1.StreamingRecognizeResponse.Types.SpeechEventType SpeechEventType { get { return speechEventType_; } set { speechEventType_ = value; } } /// <summary>Field number for the "total_billed_time" field.</summary> public const int TotalBilledTimeFieldNumber = 5; private global::Google.Protobuf.WellKnownTypes.Duration totalBilledTime_; /// <summary> /// When available, billed audio seconds for the stream. /// Set only if this is the last response in the stream. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Protobuf.WellKnownTypes.Duration TotalBilledTime { get { return totalBilledTime_; } set { totalBilledTime_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as StreamingRecognizeResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(StreamingRecognizeResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Error, other.Error)) return false; if(!results_.Equals(other.results_)) return false; if (SpeechEventType != other.SpeechEventType) return false; if (!object.Equals(TotalBilledTime, other.TotalBilledTime)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (error_ != null) hash ^= Error.GetHashCode(); hash ^= results_.GetHashCode(); if (SpeechEventType != global::Google.Cloud.Speech.V1.StreamingRecognizeResponse.Types.SpeechEventType.SpeechEventUnspecified) hash ^= SpeechEventType.GetHashCode(); if (totalBilledTime_ != null) hash ^= TotalBilledTime.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (error_ != null) { output.WriteRawTag(10); output.WriteMessage(Error); } results_.WriteTo(output, _repeated_results_codec); if (SpeechEventType != global::Google.Cloud.Speech.V1.StreamingRecognizeResponse.Types.SpeechEventType.SpeechEventUnspecified) { output.WriteRawTag(32); output.WriteEnum((int) SpeechEventType); } if (totalBilledTime_ != null) { output.WriteRawTag(42); output.WriteMessage(TotalBilledTime); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (error_ != null) { output.WriteRawTag(10); output.WriteMessage(Error); } results_.WriteTo(ref output, _repeated_results_codec); if (SpeechEventType != global::Google.Cloud.Speech.V1.StreamingRecognizeResponse.Types.SpeechEventType.SpeechEventUnspecified) { output.WriteRawTag(32); output.WriteEnum((int) SpeechEventType); } if (totalBilledTime_ != null) { output.WriteRawTag(42); output.WriteMessage(TotalBilledTime); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (error_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Error); } size += results_.CalculateSize(_repeated_results_codec); if (SpeechEventType != global::Google.Cloud.Speech.V1.StreamingRecognizeResponse.Types.SpeechEventType.SpeechEventUnspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) SpeechEventType); } if (totalBilledTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(TotalBilledTime); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(StreamingRecognizeResponse other) { if (other == null) { return; } if (other.error_ != null) { if (error_ == null) { Error = new global::Google.Rpc.Status(); } Error.MergeFrom(other.Error); } results_.Add(other.results_); if (other.SpeechEventType != global::Google.Cloud.Speech.V1.StreamingRecognizeResponse.Types.SpeechEventType.SpeechEventUnspecified) { SpeechEventType = other.SpeechEventType; } if (other.totalBilledTime_ != null) { if (totalBilledTime_ == null) { TotalBilledTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } TotalBilledTime.MergeFrom(other.TotalBilledTime); } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (error_ == null) { Error = new global::Google.Rpc.Status(); } input.ReadMessage(Error); break; } case 18: { results_.AddEntriesFrom(input, _repeated_results_codec); break; } case 32: { SpeechEventType = (global::Google.Cloud.Speech.V1.StreamingRecognizeResponse.Types.SpeechEventType) input.ReadEnum(); break; } case 42: { if (totalBilledTime_ == null) { TotalBilledTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(TotalBilledTime); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { if (error_ == null) { Error = new global::Google.Rpc.Status(); } input.ReadMessage(Error); break; } case 18: { results_.AddEntriesFrom(ref input, _repeated_results_codec); break; } case 32: { SpeechEventType = (global::Google.Cloud.Speech.V1.StreamingRecognizeResponse.Types.SpeechEventType) input.ReadEnum(); break; } case 42: { if (totalBilledTime_ == null) { TotalBilledTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(TotalBilledTime); break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the StreamingRecognizeResponse message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// Indicates the type of speech event. /// </summary> public enum SpeechEventType { /// <summary> /// No speech event specified. /// </summary> [pbr::OriginalName("SPEECH_EVENT_UNSPECIFIED")] SpeechEventUnspecified = 0, /// <summary> /// This event indicates that the server has detected the end of the user's /// speech utterance and expects no additional speech. Therefore, the server /// will not process additional audio (although it may subsequently return /// additional results). The client should stop sending additional audio /// data, half-close the gRPC connection, and wait for any additional results /// until the server closes the gRPC connection. This event is only sent if /// `single_utterance` was set to `true`, and is not used otherwise. /// </summary> [pbr::OriginalName("END_OF_SINGLE_UTTERANCE")] EndOfSingleUtterance = 1, } } #endregion } /// <summary> /// A streaming speech recognition result corresponding to a portion of the audio /// that is currently being processed. /// </summary> public sealed partial class StreamingRecognitionResult : pb::IMessage<StreamingRecognitionResult> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<StreamingRecognitionResult> _parser = new pb::MessageParser<StreamingRecognitionResult>(() => new StreamingRecognitionResult()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<StreamingRecognitionResult> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[14]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public StreamingRecognitionResult() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public StreamingRecognitionResult(StreamingRecognitionResult other) : this() { alternatives_ = other.alternatives_.Clone(); isFinal_ = other.isFinal_; stability_ = other.stability_; resultEndTime_ = other.resultEndTime_ != null ? other.resultEndTime_.Clone() : null; channelTag_ = other.channelTag_; languageCode_ = other.languageCode_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public StreamingRecognitionResult Clone() { return new StreamingRecognitionResult(this); } /// <summary>Field number for the "alternatives" field.</summary> public const int AlternativesFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Cloud.Speech.V1.SpeechRecognitionAlternative> _repeated_alternatives_codec = pb::FieldCodec.ForMessage(10, global::Google.Cloud.Speech.V1.SpeechRecognitionAlternative.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Speech.V1.SpeechRecognitionAlternative> alternatives_ = new pbc::RepeatedField<global::Google.Cloud.Speech.V1.SpeechRecognitionAlternative>(); /// <summary> /// May contain one or more recognition hypotheses (up to the /// maximum specified in `max_alternatives`). /// These alternatives are ordered in terms of accuracy, with the top (first) /// alternative being the most probable, as ranked by the recognizer. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<global::Google.Cloud.Speech.V1.SpeechRecognitionAlternative> Alternatives { get { return alternatives_; } } /// <summary>Field number for the "is_final" field.</summary> public const int IsFinalFieldNumber = 2; private bool isFinal_; /// <summary> /// If `false`, this `StreamingRecognitionResult` represents an /// interim result that may change. If `true`, this is the final time the /// speech service will return this particular `StreamingRecognitionResult`, /// the recognizer will not return any further hypotheses for this portion of /// the transcript and corresponding audio. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool IsFinal { get { return isFinal_; } set { isFinal_ = value; } } /// <summary>Field number for the "stability" field.</summary> public const int StabilityFieldNumber = 3; private float stability_; /// <summary> /// An estimate of the likelihood that the recognizer will not /// change its guess about this interim result. Values range from 0.0 /// (completely unstable) to 1.0 (completely stable). /// This field is only provided for interim results (`is_final=false`). /// The default of 0.0 is a sentinel value indicating `stability` was not set. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public float Stability { get { return stability_; } set { stability_ = value; } } /// <summary>Field number for the "result_end_time" field.</summary> public const int ResultEndTimeFieldNumber = 4; private global::Google.Protobuf.WellKnownTypes.Duration resultEndTime_; /// <summary> /// Time offset of the end of this result relative to the /// beginning of the audio. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Protobuf.WellKnownTypes.Duration ResultEndTime { get { return resultEndTime_; } set { resultEndTime_ = value; } } /// <summary>Field number for the "channel_tag" field.</summary> public const int ChannelTagFieldNumber = 5; private int channelTag_; /// <summary> /// For multi-channel audio, this is the channel number corresponding to the /// recognized result for the audio from that channel. /// For audio_channel_count = N, its output values can range from '1' to 'N'. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int ChannelTag { get { return channelTag_; } set { channelTag_ = value; } } /// <summary>Field number for the "language_code" field.</summary> public const int LanguageCodeFieldNumber = 6; private string languageCode_ = ""; /// <summary> /// The [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag of /// the language in this result. This language code was detected to have the /// most likelihood of being spoken in the audio. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string LanguageCode { get { return languageCode_; } set { languageCode_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as StreamingRecognitionResult); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(StreamingRecognitionResult other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!alternatives_.Equals(other.alternatives_)) return false; if (IsFinal != other.IsFinal) return false; if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(Stability, other.Stability)) return false; if (!object.Equals(ResultEndTime, other.ResultEndTime)) return false; if (ChannelTag != other.ChannelTag) return false; if (LanguageCode != other.LanguageCode) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; hash ^= alternatives_.GetHashCode(); if (IsFinal != false) hash ^= IsFinal.GetHashCode(); if (Stability != 0F) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(Stability); if (resultEndTime_ != null) hash ^= ResultEndTime.GetHashCode(); if (ChannelTag != 0) hash ^= ChannelTag.GetHashCode(); if (LanguageCode.Length != 0) hash ^= LanguageCode.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else alternatives_.WriteTo(output, _repeated_alternatives_codec); if (IsFinal != false) { output.WriteRawTag(16); output.WriteBool(IsFinal); } if (Stability != 0F) { output.WriteRawTag(29); output.WriteFloat(Stability); } if (resultEndTime_ != null) { output.WriteRawTag(34); output.WriteMessage(ResultEndTime); } if (ChannelTag != 0) { output.WriteRawTag(40); output.WriteInt32(ChannelTag); } if (LanguageCode.Length != 0) { output.WriteRawTag(50); output.WriteString(LanguageCode); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { alternatives_.WriteTo(ref output, _repeated_alternatives_codec); if (IsFinal != false) { output.WriteRawTag(16); output.WriteBool(IsFinal); } if (Stability != 0F) { output.WriteRawTag(29); output.WriteFloat(Stability); } if (resultEndTime_ != null) { output.WriteRawTag(34); output.WriteMessage(ResultEndTime); } if (ChannelTag != 0) { output.WriteRawTag(40); output.WriteInt32(ChannelTag); } if (LanguageCode.Length != 0) { output.WriteRawTag(50); output.WriteString(LanguageCode); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; size += alternatives_.CalculateSize(_repeated_alternatives_codec); if (IsFinal != false) { size += 1 + 1; } if (Stability != 0F) { size += 1 + 4; } if (resultEndTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(ResultEndTime); } if (ChannelTag != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(ChannelTag); } if (LanguageCode.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(LanguageCode); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(StreamingRecognitionResult other) { if (other == null) { return; } alternatives_.Add(other.alternatives_); if (other.IsFinal != false) { IsFinal = other.IsFinal; } if (other.Stability != 0F) { Stability = other.Stability; } if (other.resultEndTime_ != null) { if (resultEndTime_ == null) { ResultEndTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } ResultEndTime.MergeFrom(other.ResultEndTime); } if (other.ChannelTag != 0) { ChannelTag = other.ChannelTag; } if (other.LanguageCode.Length != 0) { LanguageCode = other.LanguageCode; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { alternatives_.AddEntriesFrom(input, _repeated_alternatives_codec); break; } case 16: { IsFinal = input.ReadBool(); break; } case 29: { Stability = input.ReadFloat(); break; } case 34: { if (resultEndTime_ == null) { ResultEndTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(ResultEndTime); break; } case 40: { ChannelTag = input.ReadInt32(); break; } case 50: { LanguageCode = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { alternatives_.AddEntriesFrom(ref input, _repeated_alternatives_codec); break; } case 16: { IsFinal = input.ReadBool(); break; } case 29: { Stability = input.ReadFloat(); break; } case 34: { if (resultEndTime_ == null) { ResultEndTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(ResultEndTime); break; } case 40: { ChannelTag = input.ReadInt32(); break; } case 50: { LanguageCode = input.ReadString(); break; } } } } #endif } /// <summary> /// A speech recognition result corresponding to a portion of the audio. /// </summary> public sealed partial class SpeechRecognitionResult : pb::IMessage<SpeechRecognitionResult> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<SpeechRecognitionResult> _parser = new pb::MessageParser<SpeechRecognitionResult>(() => new SpeechRecognitionResult()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<SpeechRecognitionResult> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[15]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechRecognitionResult() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechRecognitionResult(SpeechRecognitionResult other) : this() { alternatives_ = other.alternatives_.Clone(); channelTag_ = other.channelTag_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechRecognitionResult Clone() { return new SpeechRecognitionResult(this); } /// <summary>Field number for the "alternatives" field.</summary> public const int AlternativesFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Cloud.Speech.V1.SpeechRecognitionAlternative> _repeated_alternatives_codec = pb::FieldCodec.ForMessage(10, global::Google.Cloud.Speech.V1.SpeechRecognitionAlternative.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Speech.V1.SpeechRecognitionAlternative> alternatives_ = new pbc::RepeatedField<global::Google.Cloud.Speech.V1.SpeechRecognitionAlternative>(); /// <summary> /// May contain one or more recognition hypotheses (up to the /// maximum specified in `max_alternatives`). /// These alternatives are ordered in terms of accuracy, with the top (first) /// alternative being the most probable, as ranked by the recognizer. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<global::Google.Cloud.Speech.V1.SpeechRecognitionAlternative> Alternatives { get { return alternatives_; } } /// <summary>Field number for the "channel_tag" field.</summary> public const int ChannelTagFieldNumber = 2; private int channelTag_; /// <summary> /// For multi-channel audio, this is the channel number corresponding to the /// recognized result for the audio from that channel. /// For audio_channel_count = N, its output values can range from '1' to 'N'. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int ChannelTag { get { return channelTag_; } set { channelTag_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as SpeechRecognitionResult); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(SpeechRecognitionResult other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!alternatives_.Equals(other.alternatives_)) return false; if (ChannelTag != other.ChannelTag) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; hash ^= alternatives_.GetHashCode(); if (ChannelTag != 0) hash ^= ChannelTag.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else alternatives_.WriteTo(output, _repeated_alternatives_codec); if (ChannelTag != 0) { output.WriteRawTag(16); output.WriteInt32(ChannelTag); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { alternatives_.WriteTo(ref output, _repeated_alternatives_codec); if (ChannelTag != 0) { output.WriteRawTag(16); output.WriteInt32(ChannelTag); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; size += alternatives_.CalculateSize(_repeated_alternatives_codec); if (ChannelTag != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(ChannelTag); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(SpeechRecognitionResult other) { if (other == null) { return; } alternatives_.Add(other.alternatives_); if (other.ChannelTag != 0) { ChannelTag = other.ChannelTag; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { alternatives_.AddEntriesFrom(input, _repeated_alternatives_codec); break; } case 16: { ChannelTag = input.ReadInt32(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { alternatives_.AddEntriesFrom(ref input, _repeated_alternatives_codec); break; } case 16: { ChannelTag = input.ReadInt32(); break; } } } } #endif } /// <summary> /// Alternative hypotheses (a.k.a. n-best list). /// </summary> public sealed partial class SpeechRecognitionAlternative : pb::IMessage<SpeechRecognitionAlternative> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<SpeechRecognitionAlternative> _parser = new pb::MessageParser<SpeechRecognitionAlternative>(() => new SpeechRecognitionAlternative()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<SpeechRecognitionAlternative> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[16]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechRecognitionAlternative() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechRecognitionAlternative(SpeechRecognitionAlternative other) : this() { transcript_ = other.transcript_; confidence_ = other.confidence_; words_ = other.words_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public SpeechRecognitionAlternative Clone() { return new SpeechRecognitionAlternative(this); } /// <summary>Field number for the "transcript" field.</summary> public const int TranscriptFieldNumber = 1; private string transcript_ = ""; /// <summary> /// Transcript text representing the words that the user spoke. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Transcript { get { return transcript_; } set { transcript_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "confidence" field.</summary> public const int ConfidenceFieldNumber = 2; private float confidence_; /// <summary> /// The confidence estimate between 0.0 and 1.0. A higher number /// indicates an estimated greater likelihood that the recognized words are /// correct. This field is set only for the top alternative of a non-streaming /// result or, of a streaming result where `is_final=true`. /// This field is not guaranteed to be accurate and users should not rely on it /// to be always provided. /// The default of 0.0 is a sentinel value indicating `confidence` was not set. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public float Confidence { get { return confidence_; } set { confidence_ = value; } } /// <summary>Field number for the "words" field.</summary> public const int WordsFieldNumber = 3; private static readonly pb::FieldCodec<global::Google.Cloud.Speech.V1.WordInfo> _repeated_words_codec = pb::FieldCodec.ForMessage(26, global::Google.Cloud.Speech.V1.WordInfo.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Speech.V1.WordInfo> words_ = new pbc::RepeatedField<global::Google.Cloud.Speech.V1.WordInfo>(); /// <summary> /// A list of word-specific information for each recognized word. /// Note: When `enable_speaker_diarization` is true, you will see all the words /// from the beginning of the audio. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<global::Google.Cloud.Speech.V1.WordInfo> Words { get { return words_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as SpeechRecognitionAlternative); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(SpeechRecognitionAlternative other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Transcript != other.Transcript) return false; if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(Confidence, other.Confidence)) return false; if(!words_.Equals(other.words_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Transcript.Length != 0) hash ^= Transcript.GetHashCode(); if (Confidence != 0F) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(Confidence); hash ^= words_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Transcript.Length != 0) { output.WriteRawTag(10); output.WriteString(Transcript); } if (Confidence != 0F) { output.WriteRawTag(21); output.WriteFloat(Confidence); } words_.WriteTo(output, _repeated_words_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Transcript.Length != 0) { output.WriteRawTag(10); output.WriteString(Transcript); } if (Confidence != 0F) { output.WriteRawTag(21); output.WriteFloat(Confidence); } words_.WriteTo(ref output, _repeated_words_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Transcript.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Transcript); } if (Confidence != 0F) { size += 1 + 4; } size += words_.CalculateSize(_repeated_words_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(SpeechRecognitionAlternative other) { if (other == null) { return; } if (other.Transcript.Length != 0) { Transcript = other.Transcript; } if (other.Confidence != 0F) { Confidence = other.Confidence; } words_.Add(other.words_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Transcript = input.ReadString(); break; } case 21: { Confidence = input.ReadFloat(); break; } case 26: { words_.AddEntriesFrom(input, _repeated_words_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Transcript = input.ReadString(); break; } case 21: { Confidence = input.ReadFloat(); break; } case 26: { words_.AddEntriesFrom(ref input, _repeated_words_codec); break; } } } } #endif } /// <summary> /// Word-specific information for recognized words. /// </summary> public sealed partial class WordInfo : pb::IMessage<WordInfo> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<WordInfo> _parser = new pb::MessageParser<WordInfo>(() => new WordInfo()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<WordInfo> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.MessageTypes[17]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public WordInfo() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public WordInfo(WordInfo other) : this() { startTime_ = other.startTime_ != null ? other.startTime_.Clone() : null; endTime_ = other.endTime_ != null ? other.endTime_.Clone() : null; word_ = other.word_; speakerTag_ = other.speakerTag_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public WordInfo Clone() { return new WordInfo(this); } /// <summary>Field number for the "start_time" field.</summary> public const int StartTimeFieldNumber = 1; private global::Google.Protobuf.WellKnownTypes.Duration startTime_; /// <summary> /// Time offset relative to the beginning of the audio, /// and corresponding to the start of the spoken word. /// This field is only set if `enable_word_time_offsets=true` and only /// in the top hypothesis. /// This is an experimental feature and the accuracy of the time offset can /// vary. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Protobuf.WellKnownTypes.Duration StartTime { get { return startTime_; } set { startTime_ = value; } } /// <summary>Field number for the "end_time" field.</summary> public const int EndTimeFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Duration endTime_; /// <summary> /// Time offset relative to the beginning of the audio, /// and corresponding to the end of the spoken word. /// This field is only set if `enable_word_time_offsets=true` and only /// in the top hypothesis. /// This is an experimental feature and the accuracy of the time offset can /// vary. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Protobuf.WellKnownTypes.Duration EndTime { get { return endTime_; } set { endTime_ = value; } } /// <summary>Field number for the "word" field.</summary> public const int WordFieldNumber = 3; private string word_ = ""; /// <summary> /// The word corresponding to this set of information. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Word { get { return word_; } set { word_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "speaker_tag" field.</summary> public const int SpeakerTagFieldNumber = 5; private int speakerTag_; /// <summary> /// Output only. A distinct integer value is assigned for every speaker within /// the audio. This field specifies which one of those speakers was detected to /// have spoken this word. Value ranges from '1' to diarization_speaker_count. /// speaker_tag is set if enable_speaker_diarization = 'true' and only in the /// top alternative. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int SpeakerTag { get { return speakerTag_; } set { speakerTag_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as WordInfo); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(WordInfo other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(StartTime, other.StartTime)) return false; if (!object.Equals(EndTime, other.EndTime)) return false; if (Word != other.Word) return false; if (SpeakerTag != other.SpeakerTag) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (startTime_ != null) hash ^= StartTime.GetHashCode(); if (endTime_ != null) hash ^= EndTime.GetHashCode(); if (Word.Length != 0) hash ^= Word.GetHashCode(); if (SpeakerTag != 0) hash ^= SpeakerTag.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (startTime_ != null) { output.WriteRawTag(10); output.WriteMessage(StartTime); } if (endTime_ != null) { output.WriteRawTag(18); output.WriteMessage(EndTime); } if (Word.Length != 0) { output.WriteRawTag(26); output.WriteString(Word); } if (SpeakerTag != 0) { output.WriteRawTag(40); output.WriteInt32(SpeakerTag); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (startTime_ != null) { output.WriteRawTag(10); output.WriteMessage(StartTime); } if (endTime_ != null) { output.WriteRawTag(18); output.WriteMessage(EndTime); } if (Word.Length != 0) { output.WriteRawTag(26); output.WriteString(Word); } if (SpeakerTag != 0) { output.WriteRawTag(40); output.WriteInt32(SpeakerTag); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (startTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(StartTime); } if (endTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(EndTime); } if (Word.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Word); } if (SpeakerTag != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(SpeakerTag); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(WordInfo other) { if (other == null) { return; } if (other.startTime_ != null) { if (startTime_ == null) { StartTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } StartTime.MergeFrom(other.StartTime); } if (other.endTime_ != null) { if (endTime_ == null) { EndTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } EndTime.MergeFrom(other.EndTime); } if (other.Word.Length != 0) { Word = other.Word; } if (other.SpeakerTag != 0) { SpeakerTag = other.SpeakerTag; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (startTime_ == null) { StartTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(StartTime); break; } case 18: { if (endTime_ == null) { EndTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(EndTime); break; } case 26: { Word = input.ReadString(); break; } case 40: { SpeakerTag = input.ReadInt32(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { if (startTime_ == null) { StartTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(StartTime); break; } case 18: { if (endTime_ == null) { EndTime = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(EndTime); break; } case 26: { Word = input.ReadString(); break; } case 40: { SpeakerTag = input.ReadInt32(); break; } } } } #endif } #endregion } #endregion Designer generated code
apache-2.0
wanghaoran1988/origin
pkg/authorization/controller/authorizationsync/origin_to_rbac_clusterrole_controller_test.go
7914
package authorizationsync import ( "fmt" "strings" "testing" apiequality "k8s.io/apimachinery/pkg/api/equality" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/sets" clienttesting "k8s.io/client-go/testing" "k8s.io/client-go/tools/cache" "k8s.io/kubernetes/pkg/apis/rbac" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" rbaclister "k8s.io/kubernetes/pkg/client/listers/rbac/internalversion" authorizationapi "github.com/openshift/origin/pkg/authorization/apis/authorization" originlister "github.com/openshift/origin/pkg/authorization/generated/listers/authorization/internalversion" ) func TestSyncClusterRole(t *testing.T) { tests := []struct { name string key string startingRBAC []*rbac.ClusterRole startingOrigin []*authorizationapi.ClusterRole reactions map[reactionMatch]clienttesting.ReactionFunc actionCheck func([]clienttesting.Action) error expectedError string }{ { name: "no action on missing both", key: "resource-01", actionCheck: func(actions []clienttesting.Action) error { if len(actions) != 0 { return fmt.Errorf("expected %v, got %v", 0, actions) } return nil }, }, { name: "simple create", key: "resource-01", startingOrigin: []*authorizationapi.ClusterRole{ {ObjectMeta: metav1.ObjectMeta{Name: "resource-01"}}, }, actionCheck: func(actions []clienttesting.Action) error { action, err := ensureSingleCreateAction(actions) if err != nil { return err } if e, a := "resource-01", action.GetObject().(*rbac.ClusterRole).Name; e != a { return fmt.Errorf("expected %v, got %v", e, a) } return nil }, }, { name: "simple create with normalization", key: "resource-01", startingOrigin: []*authorizationapi.ClusterRole{ { ObjectMeta: metav1.ObjectMeta{Name: "resource-01"}, Rules: []authorizationapi.PolicyRule{ { Verbs: sets.NewString("CREATE"), Resources: sets.NewString("NAMESPACE"), APIGroups: []string{"V2"}, }, }, }, }, actionCheck: func(actions []clienttesting.Action) error { action, err := ensureSingleCreateAction(actions) if err != nil { return err } rbacRole := action.GetObject().(*rbac.ClusterRole) if e, a := "resource-01", rbacRole.Name; e != a { return fmt.Errorf("expected %v, got %v", e, a) } expectedRBACRules := []rbac.PolicyRule{ { Verbs: []string{"create"}, Resources: []string{"namespace"}, APIGroups: []string{"v2"}, }, } if !apiequality.Semantic.DeepEqual(expectedRBACRules, rbacRole.Rules) { return fmt.Errorf("expected %v, got %v", expectedRBACRules, rbacRole.Rules) } return nil }, }, { name: "delete on missing origin", key: "resource-01", startingRBAC: []*rbac.ClusterRole{ {ObjectMeta: metav1.ObjectMeta{Name: "resource-01"}}, }, actionCheck: func(actions []clienttesting.Action) error { action, err := ensureSingleDeleteAction(actions) if err != nil { return err } if e, a := "resource-01", action.GetName(); e != a { return fmt.Errorf("expected %v, got %v", e, a) } return nil }, }, { name: "simple update", key: "resource-01", startingRBAC: []*rbac.ClusterRole{ {ObjectMeta: metav1.ObjectMeta{Name: "resource-01"}}, }, startingOrigin: []*authorizationapi.ClusterRole{ {ObjectMeta: metav1.ObjectMeta{Name: "resource-01", Annotations: map[string]string{"foo": "different"}}}, }, actionCheck: func(actions []clienttesting.Action) error { action, err := ensureSingleUpdateAction(actions) if err != nil { return err } if e, a := "resource-01", action.GetObject().(*rbac.ClusterRole).Name; e != a { return fmt.Errorf("expected %v, got %v", e, a) } return nil }, }, { name: "update with annotation transform", key: "resource-01", startingRBAC: []*rbac.ClusterRole{ {ObjectMeta: metav1.ObjectMeta{Name: "resource-01"}}, }, startingOrigin: []*authorizationapi.ClusterRole{ {ObjectMeta: metav1.ObjectMeta{Name: "resource-01", Annotations: map[string]string{"openshift.io/reconcile-protect": "true"}}}, }, actionCheck: func(actions []clienttesting.Action) error { action, err := ensureSingleUpdateAction(actions) if err != nil { return err } if e, a := "resource-01", action.GetObject().(*rbac.ClusterRole).Name; e != a { return fmt.Errorf("expected %v, got %v", e, a) } if e, a := "false", action.GetObject().(*rbac.ClusterRole).Annotations["rbac.authorization.kubernetes.io/autoupdate"]; e != a { return fmt.Errorf("expected %v, got %v", e, a) } return nil }, }, { name: "no action on zero diff", key: "resource-01", startingRBAC: []*rbac.ClusterRole{ {ObjectMeta: metav1.ObjectMeta{Name: "resource-01"}}, }, startingOrigin: []*authorizationapi.ClusterRole{ {ObjectMeta: metav1.ObjectMeta{Name: "resource-01"}}, }, actionCheck: func(actions []clienttesting.Action) error { if len(actions) != 0 { return fmt.Errorf("expected %v, got %v", 0, actions) } return nil }, }, { name: "invalid update", key: "resource-01", startingRBAC: []*rbac.ClusterRole{ {ObjectMeta: metav1.ObjectMeta{Name: "resource-01"}}, }, startingOrigin: []*authorizationapi.ClusterRole{ {ObjectMeta: metav1.ObjectMeta{Name: "resource-01", Annotations: map[string]string{"foo": "different"}}}, }, actionCheck: func(actions []clienttesting.Action) error { if len(actions) != 2 { return fmt.Errorf("expected update then delete, got %v", actions) } if _, ok := actions[0].(clienttesting.UpdateAction); !ok { return fmt.Errorf("expected update, got %v", actions) } if _, ok := actions[1].(clienttesting.DeleteAction); !ok { return fmt.Errorf("expected delete, got %v", actions) } return nil }, reactions: map[reactionMatch]clienttesting.ReactionFunc{ reactionMatch{verb: "update", resource: "clusterroles"}: func(action clienttesting.Action) (handled bool, ret runtime.Object, err error) { return true, nil, apierrors.NewInvalid(rbac.Kind("ClusterRole"), "dummy", nil) }, }, expectedError: "is invalid", }, } for _, tc := range tests { objs := []runtime.Object{} rbacIndexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}) originIndexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}) for _, obj := range tc.startingRBAC { rbacIndexer.Add(obj) objs = append(objs, obj) } for _, obj := range tc.startingOrigin { originIndexer.Add(obj) } fakeClient := fake.NewSimpleClientset(objs...) for reactionMatch, action := range tc.reactions { fakeClient.PrependReactor(reactionMatch.verb, reactionMatch.resource, action) } c := &OriginClusterRoleToRBACClusterRoleController{ rbacClient: fakeClient.Rbac(), rbacLister: rbaclister.NewClusterRoleLister(rbacIndexer), originLister: originlister.NewClusterRoleLister(originIndexer), } err := c.syncClusterRole(tc.key) switch { case len(tc.expectedError) == 0 && err == nil: case len(tc.expectedError) == 0 && err != nil: t.Errorf("%s: %v", tc.name, err) case len(tc.expectedError) != 0 && err == nil: t.Errorf("%s: missing %v", tc.name, tc.expectedError) case len(tc.expectedError) != 0 && err != nil && !strings.Contains(err.Error(), tc.expectedError): t.Errorf("%s: expected %v, got %v", tc.name, tc.expectedError, err) } if err := tc.actionCheck(fakeClient.Actions()); err != nil { t.Errorf("%s: %v", tc.name, err) } } }
apache-2.0
sshcherbakov/incubator-geode
gemfire-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/command/Put65.java
23056
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * */ package com.gemstone.gemfire.internal.cache.tier.sockets.command; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import com.gemstone.gemfire.InvalidDeltaException; import com.gemstone.gemfire.cache.DynamicRegionFactory; import com.gemstone.gemfire.cache.Operation; import com.gemstone.gemfire.cache.RegionDestroyedException; import com.gemstone.gemfire.cache.ResourceException; import com.gemstone.gemfire.cache.operations.PutOperationContext; import com.gemstone.gemfire.distributed.internal.DistributionStats; import com.gemstone.gemfire.internal.HeapDataOutputStream; import com.gemstone.gemfire.internal.InternalDataSerializer; import com.gemstone.gemfire.internal.Version; import com.gemstone.gemfire.internal.cache.CachedDeserializable; import com.gemstone.gemfire.internal.cache.EntryEventImpl; import com.gemstone.gemfire.internal.cache.EventID; import com.gemstone.gemfire.internal.cache.LocalRegion; import com.gemstone.gemfire.internal.cache.PartitionedRegion; import com.gemstone.gemfire.internal.cache.TXManagerImpl; import com.gemstone.gemfire.internal.cache.Token; import com.gemstone.gemfire.internal.cache.tier.CachedRegionHelper; import com.gemstone.gemfire.internal.cache.tier.Command; import com.gemstone.gemfire.internal.cache.tier.MessageType; import com.gemstone.gemfire.internal.cache.tier.sockets.BaseCommand; import com.gemstone.gemfire.internal.cache.tier.sockets.CacheServerStats; import com.gemstone.gemfire.internal.cache.tier.sockets.Message; import com.gemstone.gemfire.internal.cache.tier.sockets.Part; import com.gemstone.gemfire.internal.cache.tier.sockets.ServerConnection; import com.gemstone.gemfire.internal.cache.versions.VersionTag; import com.gemstone.gemfire.internal.i18n.LocalizedStrings; import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage; import com.gemstone.gemfire.internal.security.AuthorizeRequest; import com.gemstone.gemfire.internal.util.Breadcrumbs; import com.gemstone.gemfire.security.GemFireSecurityException; /** * @since 6.5 */ public class Put65 extends BaseCommand { private final static Put65 singleton = new Put65(); public static Command getCommand() { return singleton; } protected Put65() { } @Override public void cmdExecute(Message msg, ServerConnection servConn, long p_start) throws IOException, InterruptedException { long start = p_start; Part regionNamePart = null, keyPart = null, valuePart = null, callbackArgPart = null; String regionName = null; Object callbackArg = null, key = null; Part eventPart = null; StringBuffer errMessage = new StringBuffer(); boolean isDelta = false; CachedRegionHelper crHelper = servConn.getCachedRegionHelper(); CacheServerStats stats = servConn.getCacheServerStats(); if (crHelper.emulateSlowServer() > 0) { boolean interrupted = Thread.interrupted(); try { Thread.sleep(crHelper.emulateSlowServer()); } catch (InterruptedException ugh) { interrupted = true; } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } // requiresResponse = true; servConn.setAsTrue(REQUIRES_RESPONSE); { long oldStart = start; start = DistributionStats.getStatTime(); stats.incReadPutRequestTime(start - oldStart); } // Retrieve the data from the message parts int idx = 0; regionNamePart = msg.getPart(idx++); Operation operation; try { operation = (Operation)msg.getPart(idx++).getObject(); if (operation == null) { // native clients send a null since the op is java-serialized operation = Operation.UPDATE; } } catch (ClassNotFoundException e) { writeException(msg, e, false, servConn); servConn.setAsTrue(RESPONDED); return; } int flags = msg.getPart(idx++).getInt(); boolean requireOldValue = ((flags & 0x01) == 0x01); boolean haveExpectedOldValue = ((flags & 0x02) == 0x02); Object expectedOldValue = null; if (haveExpectedOldValue) { try { expectedOldValue = msg.getPart(idx++).getObject(); } catch (ClassNotFoundException e) { writeException(msg, e, false, servConn); servConn.setAsTrue(RESPONDED); return; } } keyPart = msg.getPart(idx++); try { isDelta = ((Boolean)msg.getPart(idx).getObject()).booleanValue(); idx += 1; } catch (Exception e) { writeException(msg, MessageType.PUT_DELTA_ERROR, e, false, servConn); servConn.setAsTrue(RESPONDED); // CachePerfStats not available here. return; } valuePart = msg.getPart(idx++); eventPart = msg.getPart(idx++); if (msg.getNumberOfParts() > idx) { callbackArgPart = msg.getPart(idx++); try { callbackArg = callbackArgPart.getObject(); } catch (Exception e) { writeException(msg, e, false, servConn); servConn.setAsTrue(RESPONDED); return; } } regionName = regionNamePart.getString(); try { key = keyPart.getStringOrObject(); } catch (Exception e) { writeException(msg, e, false, servConn); servConn.setAsTrue(RESPONDED); return; } final boolean isDebugEnabled = logger.isDebugEnabled(); if (isDebugEnabled) { logger.debug("{}: Received {}put request ({} bytes) from {} for region {} key {} txId {} posdup: {}", servConn.getName(), (isDelta ? " delta " : " "), msg.getPayloadLength(), servConn.getSocketString(), regionName, key, msg.getTransactionId(), msg.isRetry()); } // Process the put request if (key == null || regionName == null) { if (key == null) { String putMsg = " The input key for the put request is null"; if (isDebugEnabled) { logger.debug("{}:{}", servConn.getName(), putMsg); } errMessage.append(putMsg); } if (regionName == null) { String putMsg = " The input region name for the put request is null"; if (isDebugEnabled) { logger.debug("{}:{}", servConn.getName(), putMsg); } errMessage.append(putMsg); } writeErrorResponse(msg, MessageType.PUT_DATA_ERROR, errMessage.toString(), servConn); servConn.setAsTrue(RESPONDED); } else { LocalRegion region = (LocalRegion)crHelper.getRegion(regionName); if (region == null) { String reason = " was not found during put request"; writeRegionDestroyedEx(msg, regionName, reason, servConn); servConn.setAsTrue(RESPONDED); } else if (valuePart.isNull() && operation != Operation.PUT_IF_ABSENT && region.containsKey(key)) { // Invalid to 'put' a null value in an existing key String putMsg = " Attempted to put a null value for existing key " + key; if (isDebugEnabled) { logger.debug("{}:{}", servConn.getName(), putMsg); } errMessage.append(putMsg); writeErrorResponse(msg, MessageType.PUT_DATA_ERROR, errMessage .toString(), servConn); servConn.setAsTrue(RESPONDED); } else { // try { // this.eventId = (EventID)eventPart.getObject(); ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(eventPart .getSerializedForm()); long threadId = EventID .readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer); long sequenceId = EventID .readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer); EntryEventImpl clientEvent = new EntryEventImpl( new EventID(servConn.getEventMemberIDByteArray(), threadId, sequenceId)); Breadcrumbs.setEventId(clientEvent.getEventId()); // msg.isRetry might be set by v7.0 and later clients if (msg.isRetry()) { // if (logger.isDebugEnabled()) { // logger.debug("DEBUG: encountered isRetry in Put65"); // } clientEvent.setPossibleDuplicate(true); if (region.getAttributes().getConcurrencyChecksEnabled()) { // recover the version tag from other servers clientEvent.setRegion(region); if (!recoverVersionTagForRetriedOperation(clientEvent)) { clientEvent.setPossibleDuplicate(false); // no-one has seen this event } } } boolean result = false; boolean sendOldValue = false; boolean oldValueIsObject = true; Object oldValue = null; try { Object value = null; if (!isDelta) { value = valuePart.getSerializedForm(); } boolean isObject = valuePart.isObject(); boolean isMetaRegion = region.isUsedForMetaRegion(); msg.setMetaRegion(isMetaRegion); AuthorizeRequest authzRequest = null; if (!isMetaRegion) { authzRequest = servConn.getAuthzRequest(); } if (authzRequest != null) { // TODO SW: This is to handle DynamicRegionFactory create // calls. Rework this when the semantics of DynamicRegionFactory are // cleaned up. if (DynamicRegionFactory.regionIsDynamicRegionList(regionName)) { authzRequest.createRegionAuthorize((String)key); } // Allow PUT operations on meta regions (bug #38961) else { PutOperationContext putContext = authzRequest.putAuthorize( regionName, key, value, isObject, callbackArg); value = putContext.getValue(); isObject = putContext.isObject(); callbackArg = putContext.getCallbackArg(); } } if (isDebugEnabled) { logger.debug("processing put65 with operation={}", operation); } // If the value is 1 byte and the byte represents null, // attempt to create the entry. This test needs to be // moved to DataSerializer or DataSerializer.NULL needs // to be publicly accessible. if (operation == Operation.PUT_IF_ABSENT) { // try { if (msg.isRetry() && clientEvent.getVersionTag() != null) { // bug #46590 the operation was successful the last time since it // was applied to the cache, so return success and the recovered // version tag if (isDebugEnabled) { logger.debug("putIfAbsent operation was successful last time with version {}", clientEvent.getVersionTag()); } // invoke basicBridgePutIfAbsent anyway to ensure that the event is distributed to all // servers - bug #51664 region.basicBridgePutIfAbsent(key, value, isObject, callbackArg, servConn.getProxyID(), true, clientEvent); oldValue = null; } else { oldValue = region.basicBridgePutIfAbsent(key, value, isObject, callbackArg, servConn.getProxyID(), true, clientEvent); } sendOldValue = true; oldValueIsObject = true; Version clientVersion = servConn.getClientVersion(); if (oldValue instanceof CachedDeserializable) { oldValue = ((CachedDeserializable)oldValue).getSerializedValue(); } else if (oldValue instanceof byte[]) { oldValueIsObject = false; } else if ((oldValue instanceof Token) && clientVersion.compareTo(Version.GFE_651) <= 0) { // older clients don't know that Token is now a DSFID class, so we // put the token in a serialized form they can consume HeapDataOutputStream str = new HeapDataOutputStream(Version.CURRENT); DataOutput dstr = new DataOutputStream(str); InternalDataSerializer.writeSerializableObject(oldValue, dstr); oldValue = str.toByteArray(); } result = true; // } catch (Exception e) { // writeException(msg, e, false, servConn); // servConn.setAsTrue(RESPONDED); // return; // } } else if (operation == Operation.REPLACE) { // try { if (requireOldValue) { // <V> replace(<K>, <V>) if (msg.isRetry() && clientEvent.isConcurrencyConflict() && clientEvent.getVersionTag() != null) { if (isDebugEnabled) { logger.debug("replace(k,v) operation was successful last time with version {}", clientEvent.getVersionTag()); } } oldValue = region.basicBridgeReplace(key, value, isObject, callbackArg, servConn.getProxyID(), true, clientEvent); sendOldValue = !clientEvent.isConcurrencyConflict(); oldValueIsObject = true; Version clientVersion = servConn.getClientVersion(); if (oldValue instanceof CachedDeserializable) { oldValue = ((CachedDeserializable)oldValue).getSerializedValue(); } else if (oldValue instanceof byte[]) { oldValueIsObject = false; } else if ((oldValue instanceof Token) && clientVersion.compareTo(Version.GFE_651) <= 0) { // older clients don't know that Token is now a DSFID class, so we // put the token in a serialized form they can consume HeapDataOutputStream str = new HeapDataOutputStream(Version.CURRENT); DataOutput dstr = new DataOutputStream(str); InternalDataSerializer.writeSerializableObject(oldValue, dstr); oldValue = str.toByteArray(); } if (isDebugEnabled) { logger.debug("returning {} from replace(K,V)", oldValue); } result = true; } else { // boolean replace(<K>, <V>, <V>) { boolean didPut; didPut = region.basicBridgeReplace(key, expectedOldValue, value, isObject, callbackArg, servConn.getProxyID(), true, clientEvent); if (msg.isRetry() && clientEvent.getVersionTag() != null) { if (isDebugEnabled) { logger.debug("replace(k,v,v) operation was successful last time with version {}", clientEvent.getVersionTag()); } didPut = true; } sendOldValue = true; oldValueIsObject = true; oldValue = didPut? Boolean.TRUE : Boolean.FALSE; if (isDebugEnabled) { logger.debug("returning {} from replace(K,V,V)", oldValue); } result = true; } // } catch (Exception e) { // writeException(msg, e, false, servConn); // servConn.setAsTrue(RESPONDED); // return; // } } else if (value == null && !isDelta) { // Create the null entry. Since the value is null, the value of the // isObject // the true after null doesn't matter and is not used. result = region.basicBridgeCreate(key, null, true, callbackArg, servConn.getProxyID(), true, clientEvent, false); if (msg.isRetry() && clientEvent.isConcurrencyConflict() && clientEvent.getVersionTag() != null) { result = true; if (isDebugEnabled) { logger.debug("create(k,null) operation was successful last time with version {}", clientEvent.getVersionTag()); } } } else { // Put the entry byte[] delta = null; if (isDelta) { delta = valuePart.getSerializedForm(); } TXManagerImpl txMgr = (TXManagerImpl)servConn.getCache().getCacheTransactionManager(); // bug 43068 - use create() if in a transaction and op is CREATE if (txMgr.getTXState() != null && operation.isCreate()) { result = region.basicBridgeCreate(key, (byte[])value, isObject, callbackArg, servConn.getProxyID(), true, clientEvent, true); } else { result = region.basicBridgePut(key, value, delta, isObject, callbackArg, servConn.getProxyID(), true, clientEvent, servConn .isSqlFabricSystem()); } if (msg.isRetry() && clientEvent.isConcurrencyConflict() && clientEvent.getVersionTag() != null) { if (isDebugEnabled) { logger.debug("put(k,v) operation was successful last time with version {}", clientEvent.getVersionTag()); } result = true; } } if (result) { servConn.setModificationInfo(true, regionName, key); } else { String message = servConn.getName() + ": Failed to put entry for region " + regionName + " key " + key + " value " + valuePart; if (isDebugEnabled) { logger.debug(message); } throw new Exception(message); } } catch (RegionDestroyedException rde) { writeException(msg, rde, false, servConn); servConn.setAsTrue(RESPONDED); return; } catch (ResourceException re) { writeException(msg, re, false, servConn); servConn.setAsTrue(RESPONDED); return; } catch (InvalidDeltaException ide) { logger.info(LocalizedMessage.create(LocalizedStrings.UpdateOperation_ERROR_APPLYING_DELTA_FOR_KEY_0_OF_REGION_1,new Object[] { key, regionName })); writeException(msg, MessageType.PUT_DELTA_ERROR, ide, false, servConn); servConn.setAsTrue(RESPONDED); region.getCachePerfStats().incDeltaFullValuesRequested(); return; } catch (Exception ce) { // If an interrupted exception is thrown , rethrow it checkForInterrupt(servConn, ce); // If an exception occurs during the put, preserve the connection writeException(msg, ce, false, servConn); servConn.setAsTrue(RESPONDED); if (ce instanceof GemFireSecurityException) { // Fine logging for security exceptions since these are already // logged by the security logger if (isDebugEnabled) { logger.debug("{}: Unexpected Security exception", servConn.getName(), ce); } } else if (isDebugEnabled) { logger.debug("{}: Unexpected Exception", servConn.getName(), ce); } return; } finally { long oldStart = start; start = DistributionStats.getStatTime(); stats.incProcessPutTime(start - oldStart); } // Increment statistics and write the reply if (region instanceof PartitionedRegion) { PartitionedRegion pr = (PartitionedRegion)region; if (pr.isNetworkHop().byteValue() != (byte)0) { writeReplyWithRefreshMetadata(msg, servConn, pr, sendOldValue, oldValueIsObject, oldValue, pr.isNetworkHop().byteValue(), clientEvent.getVersionTag()); pr.setIsNetworkHop((byte)0); pr.setMetadataVersion(Byte.valueOf((byte)0)); } else { writeReply(msg, servConn, sendOldValue, oldValueIsObject, oldValue, clientEvent.getVersionTag()); } } else { writeReply(msg, servConn, sendOldValue, oldValueIsObject, oldValue, clientEvent.getVersionTag()); } servConn.setAsTrue(RESPONDED); if (isDebugEnabled) { logger.debug("{}: Sent put response back to {} for region {} key {} value {}", servConn.getName(), servConn.getSocketString(), regionName, key, valuePart); } stats.incWritePutResponseTime(DistributionStats.getStatTime() - start); } } } protected void writeReply(Message origMsg, ServerConnection servConn, boolean sendOldValue, boolean oldValueIsObject, Object oldValue, VersionTag tag) throws IOException { Message replyMsg = servConn.getReplyMessage(); servConn.getCache().getCancelCriterion().checkCancelInProgress(null); replyMsg.setMessageType(MessageType.REPLY); replyMsg.setNumberOfParts(sendOldValue? 3 : 1); replyMsg.setTransactionId(origMsg.getTransactionId()); replyMsg.addBytesPart(OK_BYTES); if (sendOldValue) { replyMsg.addIntPart(oldValueIsObject?1:0); replyMsg.addObjPart(oldValue); } replyMsg.send(servConn); if (logger.isTraceEnabled()) { logger.trace("{}: rpl tx: {} parts={}", servConn.getName(), origMsg.getTransactionId(), replyMsg.getNumberOfParts()); } } protected void writeReplyWithRefreshMetadata(Message origMsg, ServerConnection servConn, PartitionedRegion pr, boolean sendOldValue, boolean oldValueIsObject, Object oldValue, byte nwHopType, VersionTag tag) throws IOException { Message replyMsg = servConn.getReplyMessage(); servConn.getCache().getCancelCriterion().checkCancelInProgress(null); replyMsg.setMessageType(MessageType.REPLY); replyMsg.setNumberOfParts(sendOldValue? 3 : 1); replyMsg.setTransactionId(origMsg.getTransactionId()); replyMsg.addBytesPart(new byte[]{pr.getMetadataVersion().byteValue(), nwHopType}); if (sendOldValue) { replyMsg.addIntPart(oldValueIsObject?1:0); replyMsg.addObjPart(oldValue); } replyMsg.send(servConn); pr.getPrStats().incPRMetaDataSentCount(); if (logger.isTraceEnabled()) { logger.trace("{}: rpl with REFRESH_METADAT tx: {} parts={}", servConn.getName(), origMsg.getTransactionId(), replyMsg.getNumberOfParts()); } } }
apache-2.0
apache/sis
core/sis-feature/src/main/java/org/apache/sis/internal/filter/Node.java
11838
/* * 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.sis.internal.filter; import java.util.Map; import java.util.IdentityHashMap; import java.util.Collection; import java.io.Serializable; import java.util.Collections; import java.util.function.Predicate; import java.util.logging.Logger; import org.opengis.util.CodeList; import org.opengis.util.LocalName; import org.opengis.util.ScopedName; import org.apache.sis.feature.DefaultAttributeType; import org.apache.sis.internal.feature.Resources; import org.apache.sis.internal.feature.Geometries; import org.apache.sis.internal.feature.GeometryWrapper; import org.apache.sis.util.iso.Names; import org.apache.sis.util.collection.DefaultTreeTable; import org.apache.sis.util.collection.TableColumn; import org.apache.sis.util.collection.TreeTable; import org.apache.sis.util.resources.Vocabulary; import org.apache.sis.util.logging.Logging; import org.apache.sis.internal.system.Loggers; // Branch-dependent imports import org.apache.sis.filter.Filter; import org.apache.sis.filter.Expression; /** * Base class of Apache SIS implementation of OGC expressions, comparators or filters. * {@code Node} instances are associated together in a tree, which can be formatted * by {@link #toString()}. * * @author Johann Sorel (Geomatys) * @author Martin Desruisseaux (Geomatys) * @version 1.1 * @since 1.1 * @module */ public abstract class Node implements Serializable { /** * For cross-version compatibility. */ private static final long serialVersionUID = -749201100175374658L; /** * Scope of all names defined by SIS convention. * * @see #createName(String) */ private static final LocalName SCOPE = Names.createLocalName("Apache", null, "sis"); /** * Creates a new expression, operator or filter. */ protected Node() { } /** * Creates an attribute type for values of the given type and name. * The attribute is mandatory, unbounded and has no default value. * * @param <T> compile-time value of {@code type}. * @param type type of values in the attribute. * @param name name of the attribute to create. * @return an attribute of the given type and name. * * @see Expression#getFunctionName() */ protected static <T> DefaultAttributeType<T> createType(final Class<T> type, final Object name) { return new DefaultAttributeType<>(Collections.singletonMap(DefaultAttributeType.NAME_KEY, name), type, 1, 1, null, (DefaultAttributeType<?>[]) null); } /** * Returns the mathematical symbol for this binary function. * For comparison operators, the symbol should be one of {@literal < > ≤ ≥ = ≠}. * For arithmetic operators, the symbol should be one of {@literal + − × ÷}. * * @return the mathematical symbol, or 0 if none. */ protected char symbol() { return (char) 0; } /** * Returns the name of the function or filter to be called. * For example, this might be {@code "sis:cos"} or {@code "sis:atan2"}. * The type depend on the implemented interface: * * <ul> * <li>{@link ScopedName} if this node implements {@link Expression}.</li> * <li>{@link CodeList} if this node implements {@link Filter}.</li> * </ul> * * <div class="note"><b>Note for implementers:</b> * implementations typically return a hard-coded value. If the returned value may vary for the same class, * then implementers should override also the {@link #equals(Object)} and {@link #hashCode()} methods.</div> * * @return the name of this function. */ private Object getDisplayName() { if (this instanceof Expression<?,?>) { return ((Expression<?,?>) this).getFunctionName(); } else if (this instanceof Filter<?>) { return ((Filter<?>) this).getOperatorType(); } else { return getClass().getSimpleName(); } } /** * Creates a name in the "SIS" scope. * This is a helper method for {@link #getFunctionName()} implementations. * * @param tip the expression name in SIS namespace. * @return an expression name in the SIS namespace. */ protected static ScopedName createName(final String tip) { return Names.createScopedName(SCOPE, null, tip); } /** * Returns an expression whose results is a geometry wrapper. * * @param <R> the type of resources (e.g. {@code Feature}) used as inputs. * @param <G> the geometry implementation type. * @param library the geometry library to use. * @param expression the expression providing source values. * @return an expression whose results is a geometry wrapper. * @throws IllegalArgumentException if the given expression is already a wrapper * but for another geometry implementation. */ @SuppressWarnings("unchecked") protected static <R,G> Expression<R, GeometryWrapper<G>> toGeometryWrapper( final Geometries<G> library, final Expression<R,?> expression) { if (expression instanceof GeometryConverter<?,?>) { if (library.equals(((GeometryConverter<?,?>) expression).library)) { return (GeometryConverter<R,G>) expression; } else { throw new IllegalArgumentException(); // TODO: provide a message. } } return new GeometryConverter<>(library, expression); } /** * If the given exception was wrapped by {@link #toGeometryWrapper(Geometries, Expression)}, * returns the original expression. Otherwise returns the given expression. * * @param <R> the type of resources (e.g. {@code Feature}) used as inputs. * @param <G> the geometry implementation type. * @param expression the expression to unwrap. * @return the unwrapped expression. */ protected static <R,G> Expression<? super R, ?> unwrap(final Expression<R, GeometryWrapper<G>> expression) { if (expression instanceof GeometryConverter<?,?>) { return ((GeometryConverter<R,?>) expression).expression; } else { return expression; } } /** * Returns a handler for the library of geometric objects used by the given expression. * The given expression should be the first parameter (as requested by SQLMM specification), * otherwise the error message will not be accurate. * * @param <G> the type of geometry created by the expression. * @param expression the expression for which to get the geometry library. * @return the geometry library (never {@code null}). */ protected static <G> Geometries<G> getGeometryLibrary(final Expression<?, GeometryWrapper<G>> expression) { if (expression instanceof GeometryConverter<?,?>) { return ((GeometryConverter<?,G>) expression).library; } throw new IllegalArgumentException(Resources.format(Resources.Keys.NotAGeometryAtFirstExpression)); } /** * Returns the children of this node, or an empty collection if none. This is used * for information purpose, for example in order to build a string representation. * * @return the children of this node, or an empty collection if none. */ protected abstract Collection<?> getChildren(); /** * Builds a tree representation of this node, including all children. This method expects an * initially empty node, which will be set to the {@linkplain #getFunctionName() name} of this node. * Then all children will be appended recursively, with a check against cyclic graph. * * @param root where to create a tree representation of this node. * @param visited nodes already visited. This method will write in this map. */ private void toTree(final TreeTable.Node root, final Map<Object,Boolean> visited) { root.setValue(TableColumn.VALUE, getDisplayName()); for (final Object child : getChildren()) { final TreeTable.Node node = root.newChild(); final String value; if (child instanceof Node) { if (visited.putIfAbsent(child, Boolean.TRUE) == null) { ((Node) child).toTree(node, visited); continue; } else { value = Vocabulary.format(Vocabulary.Keys.CycleOmitted); } } else { value = String.valueOf(child); } node.setValue(TableColumn.VALUE, value); } } /** * Returns a string representation of this node. This representation can be printed * to the {@linkplain System#out standard output stream} (for example) if it uses a * monospaced font and supports Unicode. * * @return a string representation of this filter. */ @Override public final String toString() { final DefaultTreeTable table = new DefaultTreeTable(TableColumn.VALUE); toTree(table.getRoot(), new IdentityHashMap<>()); return table.toString(); } /** * Returns a hash code value computed from the class and the children. */ @Override public int hashCode() { return getClass().hashCode() + 37 * getChildren().hashCode(); } /** * Returns {@code true} if the given object is an instance of the same class with the equal children. * * @param other the other object to compare with this node. * @return whether the two object are equal. */ @Override public boolean equals(final Object other) { if (other != null && other.getClass() == getClass()) { return getChildren().equals(((Node) other).getChildren()); } return false; } /** * Reports that an operation failed because of the given exception. * This method assumes that the warning occurred in a {@code test(…)} or {@code apply(…)} method. * * @param e the exception that occurred. * @param recoverable {@code true} if the caller has been able to fallback on a default value, * or {@code false} if the caller has to return {@code null}. * * @todo Consider defining a {@code Context} class providing, among other information, listeners where to report warnings. * * @see <a href="https://issues.apache.org/jira/browse/SIS-460">SIS-460</a> */ protected final void warning(final Exception e, final boolean recoverable) { final Logger logger = Logging.getLogger(Loggers.FILTER); final String method = (this instanceof Predicate) ? "test" : "apply"; if (recoverable) { Logging.recoverableException(logger, getClass(), method, e); } else { Logging.unexpectedException(logger, getClass(), method, e); } } }
apache-2.0
flofreud/aws-sdk-java
aws-java-sdk-kms/src/main/java/com/amazonaws/services/kms/model/transform/CreateAliasRequestMarshaller.java
3298
/* * Copyright 2010-2016 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.kms.model.transform; import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.Map; import java.util.List; import java.util.regex.Pattern; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.kms.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.StringUtils; import com.amazonaws.util.IdempotentUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.protocol.json.*; /** * CreateAliasRequest Marshaller */ public class CreateAliasRequestMarshaller implements Marshaller<Request<CreateAliasRequest>, CreateAliasRequest> { private final SdkJsonProtocolFactory protocolFactory; public CreateAliasRequestMarshaller(SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<CreateAliasRequest> marshall( CreateAliasRequest createAliasRequest) { if (createAliasRequest == null) { throw new AmazonClientException( "Invalid argument passed to marshall(...)"); } Request<CreateAliasRequest> request = new DefaultRequest<CreateAliasRequest>( createAliasRequest, "AWSKMS"); request.addHeader("X-Amz-Target", "TrentService.CreateAlias"); request.setHttpMethod(HttpMethodName.POST); request.setResourcePath(""); try { final StructuredJsonGenerator jsonGenerator = protocolFactory .createGenerator(); jsonGenerator.writeStartObject(); if (createAliasRequest.getAliasName() != null) { jsonGenerator.writeFieldName("AliasName").writeValue( createAliasRequest.getAliasName()); } if (createAliasRequest.getTargetKeyId() != null) { jsonGenerator.writeFieldName("TargetKeyId").writeValue( createAliasRequest.getTargetKeyId()); } jsonGenerator.writeEndObject(); byte[] content = jsonGenerator.getBytes(); request.setContent(new ByteArrayInputStream(content)); request.addHeader("Content-Length", Integer.toString(content.length)); request.addHeader("Content-Type", jsonGenerator.getContentType()); } catch (Throwable t) { throw new AmazonClientException( "Unable to marshall request to JSON: " + t.getMessage(), t); } return request; } }
apache-2.0
adessaigne/camel
core/camel-support/src/main/java/org/apache/camel/support/ObjectHelper.java
29423
/* * 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.camel.support; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.Callable; import java.util.regex.Pattern; import java.util.stream.Stream; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Ordered; import org.apache.camel.RuntimeCamelException; import org.apache.camel.TypeConverter; import org.apache.camel.util.Scanner; import org.apache.camel.util.StringHelper; /** * A number of useful helper methods for working with Objects */ public final class ObjectHelper { static { DEFAULT_PATTERN = Pattern.compile(",(?!(?:[^\\(,]|[^\\)],[^\\)])+\\))"); } private static final Pattern DEFAULT_PATTERN; private static final String DEFAULT_DELIMITER = ","; /** * Utility classes should not have a public constructor. */ private ObjectHelper() { } /** * A helper method for comparing objects for equality in which it uses type coercion to coerce types between the * left and right values. This allows you test for equality for example with a String and Integer type as Camel will * be able to coerce the types. */ public static boolean typeCoerceEquals(TypeConverter converter, Object leftValue, Object rightValue) { return typeCoerceEquals(converter, leftValue, rightValue, false); } /** * A helper method for comparing objects for equality in which it uses type coercion to coerce types between the * left and right values. This allows you test for equality for example with a String and Integer type as Camel will * be able to coerce the types. */ public static boolean typeCoerceEquals(TypeConverter converter, Object leftValue, Object rightValue, boolean ignoreCase) { // sanity check if (leftValue == null && rightValue == null) { // they are equal return true; } else if (leftValue == null || rightValue == null) { // only one of them is null so they are not equal return false; } // try without type coerce boolean answer = org.apache.camel.util.ObjectHelper.equal(leftValue, rightValue, ignoreCase); if (answer) { return true; } // are they same type, if so return false as the equals returned false if (leftValue.getClass().isInstance(rightValue)) { return false; } // convert left to right Object value = converter.tryConvertTo(rightValue.getClass(), leftValue); answer = org.apache.camel.util.ObjectHelper.equal(value, rightValue, ignoreCase); if (answer) { return true; } // convert right to left value = converter.tryConvertTo(leftValue.getClass(), rightValue); answer = org.apache.camel.util.ObjectHelper.equal(leftValue, value, ignoreCase); return answer; } /** * A helper method for comparing objects for inequality in which it uses type coercion to coerce types between the * left and right values. This allows you test for inequality for example with a String and Integer type as Camel * will be able to coerce the types. */ public static boolean typeCoerceNotEquals(TypeConverter converter, Object leftValue, Object rightValue) { return !typeCoerceEquals(converter, leftValue, rightValue); } /** * A helper method for comparing objects ordering in which it uses type coercion to coerce types between the left * and right values. This allows you test for ordering for example with a String and Integer type as Camel will be * able to coerce the types. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static int typeCoerceCompare(TypeConverter converter, Object leftValue, Object rightValue) { // if both values is numeric then compare using numeric Long leftNum = converter.tryConvertTo(Long.class, leftValue); Long rightNum = converter.tryConvertTo(Long.class, rightValue); if (leftNum != null && rightNum != null) { return leftNum.compareTo(rightNum); } // also try with floating point numbers Double leftDouble = converter.tryConvertTo(Double.class, leftValue); Double rightDouble = converter.tryConvertTo(Double.class, rightValue); if (leftDouble != null && rightDouble != null) { return leftDouble.compareTo(rightDouble); } // prefer to NOT coerce to String so use the type which is not String // for example if we are comparing String vs Integer then prefer to coerce to Integer // as all types can be converted to String which does not work well for comparison // as eg "10" < 6 would return true, where as 10 < 6 will return false. // if they are both String then it doesn't matter if (rightValue instanceof String && (!(leftValue instanceof String))) { // if right is String and left is not then flip order (remember to * -1 the result then) return typeCoerceCompare(converter, rightValue, leftValue) * -1; } // prefer to coerce to the right hand side at first if (rightValue instanceof Comparable) { Object value = converter.tryConvertTo(rightValue.getClass(), leftValue); if (value != null) { return ((Comparable) rightValue).compareTo(value) * -1; } } // then fallback to the left hand side if (leftValue instanceof Comparable) { Object value = converter.tryConvertTo(leftValue.getClass(), rightValue); if (value != null) { return ((Comparable) leftValue).compareTo(value); } } // use regular compare return compare(leftValue, rightValue); } /** * A helper method to invoke a method via reflection and wrap any exceptions as {@link RuntimeCamelException} * instances * * @param method the method to invoke * @param instance the object instance (or null for static methods) * @param parameters the parameters to the method * @return the result of the method invocation */ public static Object invokeMethod(Method method, Object instance, Object... parameters) { try { if (parameters != null) { return method.invoke(instance, parameters); } else { return method.invoke(instance); } } catch (IllegalAccessException e) { throw new RuntimeCamelException(e); } catch (InvocationTargetException e) { throw RuntimeCamelException.wrapRuntimeCamelException(e.getCause()); } } /** * A helper method to invoke a method via reflection in a safe way by allowing to invoke methods that are not * accessible by default and wrap any exceptions as {@link RuntimeCamelException} instances * * @param method the method to invoke * @param instance the object instance (or null for static methods) * @param parameters the parameters to the method * @return the result of the method invocation */ public static Object invokeMethodSafe(Method method, Object instance, Object... parameters) throws InvocationTargetException, IllegalAccessException { Object answer; if (!method.isAccessible()) { method.setAccessible(true); } if (parameters != null) { answer = method.invoke(instance, parameters); } else { answer = method.invoke(instance); } return answer; } /** * A helper method to create a new instance of a type using the default constructor arguments. */ public static <T> T newInstance(Class<T> type) { try { return type.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new RuntimeCamelException(e); } } /** * A helper method to create a new instance of a type using the default constructor arguments. */ public static <T> T newInstance(Class<?> actualType, Class<T> expectedType) { try { Object value = actualType.getDeclaredConstructor().newInstance(); return org.apache.camel.util.ObjectHelper.cast(expectedType, value); } catch (Exception e) { throw new RuntimeCamelException(e); } } /** * A helper method for performing an ordered comparison on the objects handling nulls and objects which do not * handle sorting gracefully */ public static int compare(Object a, Object b) { return compare(a, b, false); } /** * A helper method for performing an ordered comparison on the objects handling nulls and objects which do not * handle sorting gracefully * * @param a the first object * @param b the second object * @param ignoreCase ignore case for string comparison */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static int compare(Object a, Object b, boolean ignoreCase) { if (a == b) { return 0; } if (a == null) { return -1; } if (b == null) { return 1; } if (a instanceof Ordered && b instanceof Ordered) { return ((Ordered) a).getOrder() - ((Ordered) b).getOrder(); } if (ignoreCase && a instanceof String && b instanceof String) { return ((String) a).compareToIgnoreCase((String) b); } if (a instanceof Comparable) { Comparable comparable = (Comparable) a; return comparable.compareTo(b); } int answer = a.getClass().getName().compareTo(b.getClass().getName()); if (answer == 0) { answer = a.hashCode() - b.hashCode(); } return answer; } /** * Calling the Callable with the setting of TCCL with the camel context application classloader. * * @param call the Callable instance * @param exchange the exchange * @return the result of Callable return */ public static Object callWithTCCL(Callable<?> call, Exchange exchange) throws Exception { ClassLoader apcl = null; if (exchange != null && exchange.getContext() != null) { apcl = exchange.getContext().getApplicationContextClassLoader(); } return callWithTCCL(call, apcl); } /** * Calling the Callable with the setting of TCCL with a given classloader. * * @param call the Callable instance * @param classloader the class loader * @return the result of Callable return */ public static Object callWithTCCL(Callable<?> call, ClassLoader classloader) throws Exception { final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { if (classloader != null) { Thread.currentThread().setContextClassLoader(classloader); } return call.call(); } finally { Thread.currentThread().setContextClassLoader(tccl); } } /** * Creates an iterable over the value if the value is a collection, an Object[], a String with values separated by * comma, or a primitive type array; otherwise to simplify the caller's code, we just create a singleton collection * iterator over a single value * <p/> * Will default use comma for String separating String values. This method does <b>not</b> allow empty values * * @param value the value * @return the iterable */ public static Iterable<?> createIterable(Object value) { return createIterable(value, DEFAULT_DELIMITER); } /** * Creates an iterable over the value if the value is a collection, an Object[], a String with values separated by * the given delimiter, or a primitive type array; otherwise to simplify the caller's code, we just create a * singleton collection iterator over a single value * <p/> * This method does <b>not</b> allow empty values * * @param value the value * @param delimiter delimiter for separating String values * @return the iterable */ public static Iterable<?> createIterable(Object value, String delimiter) { return createIterable(value, delimiter, false); } public static Iterable<String> createIterable(String value) { return createIterable(value, DEFAULT_DELIMITER); } public static Iterable<String> createIterable(String value, String delimiter) { return createIterable(value, delimiter, false); } public static Iterable<String> createIterable(String value, String delimiter, boolean allowEmptyValues) { return createIterable(value, delimiter, allowEmptyValues, false); } public static Iterable<String> createIterable(String value, String delimiter, boolean allowEmptyValues, boolean pattern) { if (value == null) { return Collections.emptyList(); } else if (delimiter != null && (pattern || value.contains(delimiter))) { if (DEFAULT_DELIMITER.equals(delimiter)) { // we use the default delimiter which is a comma, then cater for bean expressions with OGNL // which may have balanced parentheses pairs as well. // if the value contains parentheses we need to balance those, to avoid iterating // in the middle of parentheses pair, so use this regular expression (a bit hard to read) // the regexp will split by comma, but honor parentheses pair that may include commas // as well, eg if value = "bean=foo?method=killer(a,b),bean=bar?method=great(a,b)" // then the regexp will split that into two: // -> bean=foo?method=killer(a,b) // -> bean=bar?method=great(a,b) // http://stackoverflow.com/questions/1516090/splitting-a-title-into-separate-parts return () -> new Scanner(value, DEFAULT_PATTERN); } return () -> new Scanner(value, delimiter); } else if (allowEmptyValues || org.apache.camel.util.ObjectHelper.isNotEmpty(value)) { return Collections.singletonList(value); } else { return Collections.emptyList(); } } /** * Creates an iterator over the value if the value is a {@link Stream}, collection, an Object[], a String with * values separated by comma, or a primitive type array; otherwise to simplify the caller's code, we just create a * singleton collection iterator over a single value * <p/> * Will default use comma for String separating String values. This method does <b>not</b> allow empty values * * @param value the value * @return the iterator */ public static Iterator<?> createIterator(Object value) { return createIterator(value, DEFAULT_DELIMITER); } /** * Creates an iterator over the value if the value is a {@link Stream}, collection, an Object[], a String with * values separated by the given delimiter, or a primitive type array; otherwise to simplify the caller's code, we * just create a singleton collection iterator over a single value * <p/> * This method does <b>not</b> allow empty values * * @param value the value * @param delimiter delimiter for separating String values * @return the iterator */ public static Iterator<?> createIterator(Object value, String delimiter) { return createIterator(value, delimiter, false); } /** * Creates an iterator over the value if the value is a {@link Stream}, collection, an Object[], a String with * values separated by the given delimiter, or a primitive type array; otherwise to simplify the caller's code, we * just create a singleton collection iterator over a single value * * </p> * In case of primitive type arrays the returned {@code Iterator} iterates over the corresponding Java primitive * wrapper objects of the given elements inside the {@code value} array. That's we get an autoboxing of the * primitive types here for free as it's also the case in Java language itself. * * @param value the value * @param delimiter delimiter for separating String values * @param allowEmptyValues whether to allow empty values * @return the iterator */ public static Iterator<?> createIterator(Object value, String delimiter, boolean allowEmptyValues) { if (value instanceof Stream) { return ((Stream) value).iterator(); } return createIterable(value, delimiter, allowEmptyValues, false).iterator(); } /** * Creates an iterator over the value if the value is a {@link Stream}, collection, an Object[], a String with * values separated by the given delimiter, or a primitive type array; otherwise to simplify the caller's code, we * just create a singleton collection iterator over a single value * * </p> * In case of primitive type arrays the returned {@code Iterator} iterates over the corresponding Java primitive * wrapper objects of the given elements inside the {@code value} array. That's we get an autoboxing of the * primitive types here for free as it's also the case in Java language itself. * * @param value the value * @param delimiter delimiter for separating String values * @param allowEmptyValues whether to allow empty values * @param pattern whether the delimiter is a pattern * @return the iterator */ public static Iterator<?> createIterator( Object value, String delimiter, boolean allowEmptyValues, boolean pattern) { if (value instanceof Stream) { return ((Stream) value).iterator(); } return createIterable(value, delimiter, allowEmptyValues, pattern).iterator(); } /** * Creates an iterable over the value if the value is a collection, an Object[], a String with values separated by * the given delimiter, or a primitive type array; otherwise to simplify the caller's code, we just create a * singleton collection iterator over a single value * * </p> * In case of primitive type arrays the returned {@code Iterable} iterates over the corresponding Java primitive * wrapper objects of the given elements inside the {@code value} array. That's we get an autoboxing of the * primitive types here for free as it's also the case in Java language itself. * * @param value the value * @param delimiter delimiter for separating String values * @param allowEmptyValues whether to allow empty values * @return the iterable * @see Iterable */ public static Iterable<?> createIterable( Object value, String delimiter, final boolean allowEmptyValues) { return createIterable(value, delimiter, allowEmptyValues, false); } /** * Creates an iterable over the value if the value is a collection, an Object[], a String with values separated by * the given delimiter, or a primitive type array; otherwise to simplify the caller's code, we just create a * singleton collection iterator over a single value * * </p> * In case of primitive type arrays the returned {@code Iterable} iterates over the corresponding Java primitive * wrapper objects of the given elements inside the {@code value} array. That's we get an autoboxing of the * primitive types here for free as it's also the case in Java language itself. * * @param value the value * @param delimiter delimiter for separating String values * @param allowEmptyValues whether to allow empty values * @param pattern whether the delimiter is a pattern * @return the iterable * @see Iterable */ @SuppressWarnings("unchecked") public static Iterable<?> createIterable( Object value, String delimiter, final boolean allowEmptyValues, final boolean pattern) { // if its a message than we want to iterate its body if (value instanceof Message) { value = ((Message) value).getBody(); } if (value == null) { return Collections.emptyList(); } else if (value instanceof Iterator) { final Iterator<Object> iterator = (Iterator<Object>) value; return new Iterable<Object>() { @Override public Iterator<Object> iterator() { return iterator; } }; } else if (value instanceof Iterable) { return (Iterable<Object>) value; } else if (value.getClass().isArray()) { if (org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(value.getClass())) { final Object array = value; return (Iterable<Object>) () -> new Iterator<Object>() { private int idx; public boolean hasNext() { return idx < Array.getLength(array); } public Object next() { if (!hasNext()) { throw new NoSuchElementException( "no more element available for '" + array + "' at the index " + idx); } return Array.get(array, idx++); } public void remove() { throw new UnsupportedOperationException(); } }; } else { return Arrays.asList((Object[]) value); } } else if (value instanceof NodeList) { // lets iterate through DOM results after performing XPaths final NodeList nodeList = (NodeList) value; return (Iterable<Node>) () -> new Iterator<Node>() { private int idx; public boolean hasNext() { return idx < nodeList.getLength(); } public Node next() { if (!hasNext()) { throw new NoSuchElementException( "no more element available for '" + nodeList + "' at the index " + idx); } return nodeList.item(idx++); } public void remove() { throw new UnsupportedOperationException(); } }; } else if (value instanceof String) { final String s = (String) value; // this code is optimized to only use a Scanner if needed, eg there is a delimiter if (delimiter != null && (pattern || s.contains(delimiter))) { if (DEFAULT_DELIMITER.equals(delimiter)) { // we use the default delimiter which is a comma, then cater for bean expressions with OGNL // which may have balanced parentheses pairs as well. // if the value contains parentheses we need to balance those, to avoid iterating // in the middle of parentheses pair, so use this regular expression (a bit hard to read) // the regexp will split by comma, but honor parentheses pair that may include commas // as well, eg if value = "bean=foo?method=killer(a,b),bean=bar?method=great(a,b)" // then the regexp will split that into two: // -> bean=foo?method=killer(a,b) // -> bean=bar?method=great(a,b) // http://stackoverflow.com/questions/1516090/splitting-a-title-into-separate-parts return (Iterable<String>) () -> new Scanner(s, DEFAULT_PATTERN); } return (Iterable<String>) () -> new Scanner(s, delimiter); } else { return (Iterable<Object>) () -> { // use a plain iterator that returns the value as is as there are only a single value return new Iterator<Object>() { private int idx; public boolean hasNext() { return idx == 0 && (allowEmptyValues || org.apache.camel.util.ObjectHelper.isNotEmpty(s)); } public Object next() { if (!hasNext()) { throw new NoSuchElementException( "no more element available for '" + s + "' at the index " + idx); } idx++; return s; } public void remove() { throw new UnsupportedOperationException(); } }; }; } } else { return Collections.singletonList(value); } } /** * Returns true if the collection contains the specified value */ public static boolean contains(Object collectionOrArray, Object value) { // favor String types if (collectionOrArray != null && (collectionOrArray instanceof StringBuffer || collectionOrArray instanceof StringBuilder)) { collectionOrArray = collectionOrArray.toString(); } if (value != null && (value instanceof StringBuffer || value instanceof StringBuilder)) { value = value.toString(); } if (collectionOrArray instanceof Collection) { Collection<?> collection = (Collection<?>) collectionOrArray; return collection.contains(value); } else if (collectionOrArray instanceof String && value instanceof String) { String str = (String) collectionOrArray; String subStr = (String) value; return str.contains(subStr); } else { Iterator<?> iter = createIterator(collectionOrArray); while (iter.hasNext()) { if (org.apache.camel.util.ObjectHelper.equal(value, iter.next())) { return true; } } } return false; } /** * Returns true if the collection contains the specified value by considering case insensitivity */ public static boolean containsIgnoreCase(Object collectionOrArray, Object value) { // favor String types if (collectionOrArray != null && (collectionOrArray instanceof StringBuffer || collectionOrArray instanceof StringBuilder)) { collectionOrArray = collectionOrArray.toString(); } if (value != null && (value instanceof StringBuffer || value instanceof StringBuilder)) { value = value.toString(); } if (collectionOrArray instanceof Collection) { Collection<?> collection = (Collection<?>) collectionOrArray; return collection.contains(value); } else if (collectionOrArray instanceof String && value instanceof String) { String str = (String) collectionOrArray; String subStr = (String) value; return StringHelper.containsIgnoreCase(str, subStr); } else { Iterator<?> iter = createIterator(collectionOrArray); while (iter.hasNext()) { if (org.apache.camel.util.ObjectHelper.equalIgnoreCase(value, iter.next())) { return true; } } } return false; } }
apache-2.0
hangzhang925/WhereHows
wherehows-dao/src/main/java/wherehows/dao/view/OwnerViewDao.java
2013
/** * Copyright 2015 LinkedIn Corp. 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. */ package wherehows.dao.view; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityManagerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import wherehows.models.view.DatasetOwner; public class OwnerViewDao extends BaseViewDao { private static final Logger log = LoggerFactory.getLogger(OwnerViewDao.class); public OwnerViewDao(EntityManagerFactory factory) { super(factory); } private final static String GET_DATASET_OWNERS_BY_ID = "SELECT o.owner_id, u.display_name, o.sort_id, o.owner_type, o.namespace, o.owner_id_type, o.owner_source, " + "o.owner_sub_type, o.confirmed_by, u.email, u.is_active, is_group, o.modified_time " + "FROM dataset_owner o " + "LEFT JOIN dir_external_user_info u on (o.owner_id = u.user_id and u.app_id = 300) " + "WHERE o.dataset_urn = :datasetUrn and (o.is_deleted is null OR o.is_deleted != 'Y') ORDER BY o.sort_id"; /** * Get dataset owner list by WH dataset URN * @param datasetUrn String * @return List of DatasetOwner */ public List<DatasetOwner> getDatasetOwnersByUrn(String datasetUrn) { Map<String, Object> params = new HashMap<>(); params.put("datasetUrn", datasetUrn); List<DatasetOwner> owners = getEntityListBy(GET_DATASET_OWNERS_BY_ID, DatasetOwner.class, params); for (DatasetOwner owner : owners) { owner.setModifiedTime(owner.getModifiedTime() * 1000); } return owners; } }
apache-2.0
lrytz/scala
test/async/jvm/live.scala
5267
// scalac: -Xasync object Test extends scala.tools.partest.JUnitTest(classOf[scala.async.run.live.LiveVariablesSpec]) package scala.async.run.live { import org.junit.Test import org.junit.Assert._ import scala.concurrent._ import duration.Duration import scala.tools.testkit.async.Async.{async, await} import scala.collection.immutable object TestUtil { import language.implicitConversions implicit def lift[T](t: T): Future[T] = Future.successful(t) def block[T](f: Future[T]): T = Await.result(f, Duration.Inf) } import TestUtil._ case class Cell[T](v: T) class Meter(val len: Long) extends AnyVal case class MCell[T](var v: T) class LiveVariablesSpec { implicit object testingEc extends ExecutionContext { var lastStateMachine: Any = _ var lastFailure: Throwable = _ def live[T: reflect.ClassTag]: List[T] = { val instance = lastStateMachine val flds = instance.getClass.getDeclaredFields val filterClass = reflect.classTag[T].runtimeClass flds.toList.flatMap { fld => fld.setAccessible(true) val value = fld.get(instance) if (filterClass.isInstance(value)) { value.asInstanceOf[T] :: Nil } else Nil } } override def execute(runnable: Runnable): Unit = try { lastStateMachine = reflectivelyExtractStateMachine(runnable) runnable.run() } catch { case t: Throwable => throw new RuntimeException(t) } override def reportFailure(cause: Throwable): Unit = { lastFailure = cause } private def reflectivelyExtractStateMachine(runnable: Runnable) = { assert(runnable.getClass == Class.forName("scala.concurrent.impl.Promise$Transformation"), runnable.getClass) val fld = runnable.getClass.getDeclaredField("_fun") fld.setAccessible(true) val stateMachine = fld.get(runnable) assert(stateMachine.getClass.getName.contains("stateMachine"), stateMachine.getClass) stateMachine } } @Test def `zero out fields of reference type`(): Unit = { def live: Set[Any] = { testingEc.live[Cell[_]].map(_.v).toSet } def m3() = async { val _0: Any = await(Cell(0)) val _1: Cell[Int] = await(Cell(1)) identity(_1) val _2 = await(Cell(2)) identity(_1) assertEquals(Set(0, 1), live) val res = await(_2.toString) assertEquals(Set(0), live) identity(_0) res } assert(block(m3()) == "Cell(2)") } @Test def `zero out fields after use in loop`(): Unit = { val f = Cell(1) def live: Set[Any] = { testingEc.live[Cell[_]].map(_.v).toSet } def m3() = async { val _0: Any = await(Cell(0)) val _1: Cell[Int] = await(Cell(1)) var i = 0 while (i < 5) { identity(await(_1)) assertEquals("in loop", Set(0, 1), live) i += 1 } assertEquals("after loop", Set(0), live) identity(_0) await(()) assertEquals("end of block", Set(), live) () } block(m3()) } @Test def `don't zero captured fields captured lambda`(): Unit = { def live: Set[Any] = { testingEc.live[Cell[_]].map(_.v).toSet } def m3() = async { val _1 = Cell(1) val _2 = Cell(2) val _3 = Cell(3) val _4 = Cell(4) val _5 = Cell(5) val _6 = Cell(6) await(0) _1.toString.reverse val fun = () => assert(_2 != null) class LocalClass { assert(_3 != null) } object localObject { assert(_4 != null) } def localDef = { assert(_5 != null) } lazy val localLazy = { assert(_6 != null) } await(0) assertEquals("after capture", Set(2, 3, 4, 5, 6), live) fun() new LocalClass() localObject } block(m3()) } @Test def `capture bug`(): Unit = { sealed trait Base case class B1() extends Base case class B2() extends Base val outer = List[(Base, Int)]((B1(), 8)) def getMore(b: Base) = 4 def baz = async { outer.head match { case (a @ B1(), r) => { val ents = await(getMore(a)) { () => // println(a) assert(a ne null) } } case (b @ B2(), x) => () => ??? } } block(baz).apply() } // https://github.com/scala/async/issues/104 @Test def dontNullOutVarsOfTypeNothing_t104(): Unit = { def errorGenerator(randomNum: Double) = { Future { if (randomNum < 0) { throw new IllegalStateException("Random number was too low!") } else { throw new IllegalStateException("Random number was too high!") } } } def randomTimesTwo = async { val num = _root_.scala.math.random() if (num < 0 || num > 1) { await(errorGenerator(num)) } num * 2 } block(randomTimesTwo) // was: NotImplementedError } } }
apache-2.0
LookThisCode/DeveloperBus
Season 2013/Brazil/Projects/PowerUp-master/appengine/src/main/java/br/com/powerup/infrastructure/DefaultPowerUp.java
4180
package br.com.powerup.infrastructure; import static br.com.powerup.infrastructure.persistence.OfyService.ofy; import java.util.List; import javax.inject.Inject; import br.com.powerup.domain.model.Badge; import br.com.powerup.domain.model.LogWorkRequest; import br.com.powerup.domain.model.LogWorkResponse; import br.com.powerup.domain.model.NewWorkoutRequest; import br.com.powerup.domain.model.PowerUp; import br.com.powerup.domain.model.Score; import br.com.powerup.domain.model.SignupRequest; import br.com.powerup.domain.model.Training; import br.com.powerup.domain.model.TrainingRepository; import br.com.powerup.domain.model.UserProfile; import br.com.powerup.domain.model.Worklog; import br.com.powerup.domain.model.Workout; import br.com.powerup.domain.model.WorkoutSession; import br.com.powerup.infrastructure.persistence.Transact; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.users.User; import com.googlecode.objectify.Key; import com.googlecode.objectify.NotFoundException; import com.googlecode.objectify.TxnType; public class DefaultPowerUp implements PowerUp { private static final int POINTS_PER_WORKLOG = 10; private TrainingRepository trainingRepository; @Inject public DefaultPowerUp(TrainingRepository trainingRepository) { super(); this.trainingRepository = trainingRepository; } private Training training(String userId) { return trainingRepository.get(userId); } @Override @Transact(TxnType.REQUIRED) public LogWorkResponse logWork(LogWorkRequest logWorkRequest) { int pointsEarned = POINTS_PER_WORKLOG; Worklog worklog = new Worklog(logWorkRequest.getExerciseId(), logWorkRequest.getTrainingId()); ofy().save().entity(worklog); List<Worklog> logs = logs(logWorkRequest); Training training = training(logWorkRequest.getUserId()); if (logs.size() == training.totalExercises()) { pointsEarned += 50; } Score score = score(logWorkRequest.getUserId()); score.increment(pointsEarned); ofy().save().entity(score); UserProfile userProfile = userProfile(logWorkRequest.getUserId()); LogWorkResponse logWorkResponse = new LogWorkResponse(pointsEarned, score.getTotalPoints()); if (isFirstWorkoutForTraining(training)) { userProfile.addBadge(Badge.Estreia); logWorkResponse.addBadge(Badge.Estreia); } if ( userProfile.adjustLevel(score) ) { ofy().save().entity(userProfile); logWorkResponse.levelUp(); } return logWorkResponse; } private boolean isFirstWorkoutForTraining(Training training) { Integer count = ofy().load().type(Workout.class) .ancestor(KeyFactory.createKey(Training.class.getSimpleName(), training.getId())) .count(); return count == 1; } private List<Worklog> logs(LogWorkRequest logWorkRequest) { return ofy() .load() .type(Worklog.class) .ancestor( KeyFactory.createKey(Workout.class.getSimpleName(), logWorkRequest.getTrainingId())).list(); } private Score score(String userId) { try { Score score = ofy().load().type(Score.class) .ancestor(userParentKey(userId)).first().safe(); return score; } catch (NotFoundException e) { return new Score(userId); } } private com.google.appengine.api.datastore.Key userParentKey(String userId) { return KeyFactory.createKey(User.class.getSimpleName(), userId); } @Override public UserProfile signUp(SignupRequest signupRequest) { UserProfile userProfile = new UserProfile(signupRequest); ofy().save().entity(userProfile).now(); return userProfile; } @Override public WorkoutSession startNewWorkout(NewWorkoutRequest newWorkoutRequest) { Training training = training(newWorkoutRequest.getUserId()); UserProfile userProfile = userProfile(newWorkoutRequest); Key<Workout> k = ofy().save().entity(new Workout(training.getId())) .now(); return new WorkoutSession(k.getId(), userProfile, training); } private UserProfile userProfile(NewWorkoutRequest newWorkoutRequest) { return userProfile(newWorkoutRequest.getUserId()); } private UserProfile userProfile(String userId) { return ofy().load().type(UserProfile.class) .ancestor(userParentKey(userId)).first().safe(); } }
apache-2.0
antoinesd/weld-core
tests-arquillian/src/test/java/org/jboss/weld/tests/event/ordering/NoPriority.java
238
package org.jboss.weld.tests.event.ordering; import javax.enterprise.event.Observes; public class NoPriority { public void observeEvent(@Observes EventPayload payload) { payload.record(NoPriority.class.getName()); } }
apache-2.0
bowlofstew/Macaroni
Main/App/Source/test/lua/Macaroni/Parser/Pippy/Tests/PippyParserTests_Constructor.lua
2882
-------------------------------------------------------------------------------- -- Copyright 2011 Tim Simpson -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use self file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -------------------------------------------------------------------------------- -- require "Macaroni.Model.Context"; -- require "Macaroni.Environment.Messages"; -- require "Macaroni.Parser.Pippy.PippyParser"; -- require "Macaroni.Parser.Parser"; -- require "Macaroni.Parser.ParserException"; -- require "Macaroni.Model.Source"; -- require "Macaroni.Model.Type"; -- require "Macaroni.Model.TypeArgument"; -- require "Macaroni.Model.TypeArgumentList"; -- require "Macaroni.Model.TypeList"; local Context = require "Macaroni.Model.Context"; local Messages = require "Macaroni.Environment.Messages"; local PippyParser = require "Macaroni.Parser.Pippy.PippyParser"; local FileName = require "Macaroni.Model.FileName"; local Source = require "Macaroni.Model.Source"; local Type = require "Macaroni.Model.Type"; local TypeArgumentList = require "Macaroni.Model.TypeArgumentList"; local TypeList = require "Macaroni.Model.TypeList"; require "Macaroni/Parser/Pippy/Tests/TryParse" Test.register( { name = "PippyParser Tests :: Constructor", tests = { { name = "Creating an empty method.", init = function(self) ParserTest.init(self) self.parser:Read(self.target, self.src, [[ class Blah { public Blah(int a, int b) {} } ]]); end, tests = { ["Blah class exists."] = function(self) Test.assertEquals(2, #self.root.Children); Test.assertEquals("Blah", self.root.Children[2].FullName); local Blah = self.root.Children[2]; Test.assertEquals(1, #Blah.Children); Test.assertEquals("Blah::$ctor", Blah.Children[1].FullName); local ctorNode = Blah.Children[1]; Test.assertEquals("Constructor", ctorNode.Element.TypeName); Test.assertEquals(1, #(ctorNode.Children)); local ol = ctorNode.Children[1] Test.assertEquals("ConstructorOverload", ol.Element.TypeName); Test.assertEquals("ConstructorOverload", ol.Element.TypeName); Test.assertEquals(2, #ol.Element.Arguments); end, } }, } -- end of tests table }); -- End of register call
apache-2.0
GoogleCloudPlatform/prometheus-engine
third_party/prometheus_ui/base/web/ui/react-app/node_modules/axe-core/lib/core/base/cache.js
500
let _cache = {}; const cache = { /** * Set an item in the cache. * @param {String} key - Name of the key. * @param {*} value - Value to store. */ set(key, value) { _cache[key] = value; }, /** * Retrieve an item from the cache. * @param {String} key - Name of the key the value was stored as. * @returns {*} The item stored */ get(key) { return _cache[key]; }, /** * Clear the cache. */ clear() { _cache = {}; } }; export default cache;
apache-2.0
rancherio/validation-tests
tests/v2_validation/cattlevalidationtest/core/test_container.py
10963
from common_fixtures import * # NOQA import requests import websocket as ws import base64 def test_sibling_pinging(client, one_per_host): instances = one_per_host hosts = {} hostnames = set() for i in instances: port = i.ports_link()[0] host = port.publicIpAddress().address port = port.publicPort base_url = 'http://{}:{}'.format(host, port) pong = requests.get(base_url + '/ping').text hostname = requests.get(base_url + '/hostname').text assert pong == 'pong' assert hostname not in hostnames hostnames.add(hostname) hosts[hostname] = base_url count = 0 for hostname, base_url in hosts.items(): url = base_url + '/get' for other_hostname, other_url in hosts.items(): if other_hostname == hostname: continue test_hostname = requests.get(url, params={ 'url': other_url + '/hostname' }).text count += 1 assert other_hostname == test_hostname assert count == len(instances) * (len(instances) - 1) delete_all(client, instances) def test_dynamic_port(client, test_name): c = client.create_container(name=test_name, networkMode=MANAGED_NETWORK, imageUuid=TEST_IMAGE_UUID) c = client.wait_success(c) ports = c.ports_link() assert len(ports) == 1 port = ports[0] assert port.publicPort is None port = client.wait_success(client.update(port, publicPort=3001)) assert port.publicPort == 3001 ping_port(port) port = client.wait_success(client.update(port, publicPort=3002)) assert port.publicPort == 3002 ping_port(port) delete_all(client, [c]) def test_linking(client, admin_client, test_name): hosts = client.list_host(kind='docker', removed_null=True) assert len(hosts) > 2 random_val = random_str() random_val2 = random_str() link_server = client.create_container(name=test_name + '-server', imageUuid=TEST_IMAGE_UUID, networkMode=MANAGED_NETWORK, hostname=test_name + '-server', environment={ 'VALUE': random_val }, requestedHostId=hosts[2].id) link_server2 = client.create_container(name=test_name + '-server2', imageUuid=TEST_IMAGE_UUID, networkMode=MANAGED_NETWORK, hostname=test_name + '-server2', environment={ 'VALUE': random_val2 }, requestedHostId=hosts[1].id) link_client = client.create_container(name=test_name + '-client', imageUuid=TEST_IMAGE_UUID, networkMode=MANAGED_NETWORK, ports=['3000:3000'], hostname=test_name + '-client1', instanceLinks={ 'client': link_server.id }, requestedHostId=hosts[0].id) link_client = client.wait_success(link_client) link_client = admin_client.reload(link_client) link_server = client.wait_success(link_server) link_server = admin_client.reload(link_server) ping_link(link_client, 'client', var='VALUE', value=random_val) link_server2 = client.wait_success(link_server2) link = link_client.instanceLinks()[0] link = client.update(link, targetInstanceId=link_server2.id) client.wait_success(link) ping_link(link_client, 'client', var='VALUE', value=random_val2) delete_all(client, [link_client, link_server, link_server2]) def test_ip_inject(client, test_name): cleanup_items = [] try: cmd = ['/bin/bash', '-c', 'sleep 5; ip addr show eth0'] container = client.create_container(name=test_name, imageUuid=TEST_IMAGE_UUID, networkMode=MANAGED_NETWORK, command=cmd) cleanup_items.append(container) container = client.wait_success(container) assert_ip_inject(container) finally: delete_all(client, cleanup_items) def assert_ip_inject(container): ip = container.primaryIpAddress logs = container.logs() conn = ws.create_connection(logs.url + '?token=' + logs.token, timeout=10) count = 0 found_ip = False while count <= 100: count += 1 try: result = conn.recv() if ip in result: found_ip = True break except ws.WebSocketConnectionClosedException: break assert found_ip def test_container_execute(client, test_name): cleanup_items = [] try: container = client.create_container(name=test_name, imageUuid=TEST_IMAGE_UUID, networkMode=MANAGED_NETWORK, attachStdin=True, attachStdout=True, tty=True, command='/bin/bash') cleanup_items.append(container) container = client.wait_success(container) test_msg = 'EXEC_WORKS' assert_execute(container, test_msg) finally: delete_all(client, cleanup_items) def assert_execute(container, test_msg): execute = container.execute(attachStdin=True, attachStdout=True, command=['/bin/bash', '-c', 'echo ' + test_msg], tty=True) conn = ws.create_connection(execute.url + '?token=' + execute.token, timeout=10) # Python is weird about closures closure_wrapper = { 'result': '' } def exec_check(): msg = conn.recv() closure_wrapper['result'] += base64.b64decode(msg) return test_msg == closure_wrapper['result'].rstrip() wait_for(exec_check, 'Timeout waiting for exec msg %s' % test_msg) def test_container_stats(client, test_name): cleanup_items = [] try: container = client.create_container(name=test_name, imageUuid=TEST_IMAGE_UUID, networkMode=MANAGED_NETWORK, attachStdin=True, attachStdout=True, tty=True, command='/bin/bash') cleanup_items.append(container) container = client.wait_success(container) assert_stats(container) finally: delete_all(client, cleanup_items) @if_container_refactoring def test_create_container_with_stack(client): stack = create_env(client) con = create_sa_container(client, stack) assert con.stackId == stack.id delete_all(client, [stack]) @if_container_refactoring def test_create_container_without_stack(client): con = create_sa_container(client) default_env = client.list_stack(name="Default") assert len(default_env) == 1 assert con.stackId == default_env[0].id delete_all(client, [con]) @if_container_refactoring def test_create_container_with_healthcheck_on(client): con = create_sa_container(client, healthcheck=True) default_env = client.list_stack(name="Default") assert len(default_env) == 1 assert con.stackId == default_env[0].id delete_all(client, [con]) @if_container_refactoring def test_container_with_healthcheck_becoming_unhealthy(client): con_port = "9001" con = create_sa_container(client, healthcheck=True, port=con_port) # Delete requestUrl from one of the containers to trigger health check # failure and service reconcile mark_container_unhealthy(client, con, int(con_port)) wait_for_condition( client, con, lambda x: x.healthState == 'unhealthy', lambda x: 'State is: ' + x.healthState) con = client.reload(con) assert con.healthState == "unhealthy" wait_for_condition( client, con, lambda x: x.state in ('removed', 'purged'), lambda x: 'State is: ' + x.healthState) new_containers = client.list_container(name=con.name, state="running", healthState="healthy") assert len(new_containers) == 1 delete_all(client, [con]) @if_container_refactoring def test_create_container_with_sidekick(client): # Deploy container as as sidekick to an existing container and make sure # they land on the same host con = create_sa_container(client, healthcheck=True) sidekick_con = create_sa_container(client, sidekick_to=con) con_host = get_container_host(client, con) sidekick_con_host = get_container_host(client, sidekick_con) assert con_host.id == sidekick_con_host.id delete_all(client, [con, sidekick_con]) @if_container_refactoring def test_create_container_with_sidekick_with_ports(client): # Consume host ports in 2 of the 3 hosts in the setup con_port = "9000" con_sidekick_port = "9001" test_con1 = create_sa_container(client, healthcheck=True, port=con_port) test_con2 = create_sa_container(client, healthcheck=True, port=con_port) # Deploy container as as sidekick to an existing container and make sure # they land on the same host con = create_sa_container(client, healthcheck=True, port=con_port) sidekick_con = create_sa_container(client, sidekick_to=con, port=con_sidekick_port) con_host = get_container_host(client, con) sidekick_con_host = get_container_host(client, sidekick_con) assert con_host.id == sidekick_con_host.id delete_all(client, [test_con1, test_con2, con, sidekick_con]) def test_set_up(): print "Start cleanup" def assert_stats(container): stats = container.stats() conn = ws.create_connection(stats.url + '?token=' + stats.token, timeout=10) result = conn.recv() assert 'per_cpu_usage' in result
apache-2.0
GenericStudent/home-assistant
tests/components/smart_meter_texas/test_config_flow.py
4020
"""Test the Smart Meter Texas config flow.""" import asyncio from aiohttp import ClientError import pytest from smart_meter_texas.exceptions import ( SmartMeterTexasAPIError, SmartMeterTexasAuthError, ) from homeassistant import config_entries, setup from homeassistant.components.smart_meter_texas.const import DOMAIN from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from tests.async_mock import patch from tests.common import MockConfigEntry TEST_LOGIN = {CONF_USERNAME: "test-username", CONF_PASSWORD: "test-password"} async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("smart_meter_texas.Client.authenticate", return_value=True), patch( "homeassistant.components.smart_meter_texas.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.smart_meter_texas.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], TEST_LOGIN ) assert result2["type"] == "create_entry" assert result2["title"] == TEST_LOGIN[CONF_USERNAME] assert result2["data"] == TEST_LOGIN await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_form_invalid_auth(hass): """Test we handle invalid auth.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch( "smart_meter_texas.Client.authenticate", side_effect=SmartMeterTexasAuthError, ): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], TEST_LOGIN, ) assert result2["type"] == "form" assert result2["errors"] == {"base": "invalid_auth"} @pytest.mark.parametrize( "side_effect", [asyncio.TimeoutError, ClientError, SmartMeterTexasAPIError] ) async def test_form_cannot_connect(hass, side_effect): """Test we handle cannot connect error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch( "smart_meter_texas.Client.authenticate", side_effect=side_effect, ): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], TEST_LOGIN ) assert result2["type"] == "form" assert result2["errors"] == {"base": "cannot_connect"} async def test_form_unknown_exception(hass): """Test base exception is handled.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch( "smart_meter_texas.Client.authenticate", side_effect=Exception, ): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], TEST_LOGIN, ) assert result2["type"] == "form" assert result2["errors"] == {"base": "unknown"} async def test_form_duplicate_account(hass): """Test that a duplicate account cannot be configured.""" MockConfigEntry( domain=DOMAIN, unique_id="user123", data={"username": "user123", "password": "password123"}, ).add_to_hass(hass) with patch( "smart_meter_texas.Client.authenticate", return_value=True, ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER}, data={"username": "user123", "password": "password123"}, ) assert result["type"] == "abort" assert result["reason"] == "already_configured"
apache-2.0
awayjs/stage
lib/factories/DefaultGraphicsFactory.ts
441
import {BitmapImage2D} from "../image/BitmapImage2D"; import {Image2D} from "../image/Image2D"; import {IGraphicsFactory} from "./IGraphicsFactory"; export class DefaultGraphicsFactory implements IGraphicsFactory { public createImage2D(width:number, height:number, transparent:boolean = true, fillColor:number = null, powerOfTwo:boolean = true):Image2D { return new BitmapImage2D(width, height, transparent, fillColor, powerOfTwo) } }
apache-2.0
fluentassertions/fluentassertions
Src/FluentAssertions/Execution/IAssertionStrategy.cs
953
using System.Collections.Generic; namespace FluentAssertions.Execution { /// <summary> /// Defines a strategy for handling failures in a <see cref="AssertionScope"/>. /// </summary> public interface IAssertionStrategy { /// <summary> /// Returns the messages for the assertion failures that happened until now. /// </summary> IEnumerable<string> FailureMessages { get; } /// <summary> /// Instructs the strategy to handle a assertion failure. /// </summary> void HandleFailure(string message); /// <summary> /// Discards and returns the failure messages that happened up to now. /// </summary> IEnumerable<string> DiscardFailures(); /// <summary> /// Will throw a combined exception for any failures have been collected. /// </summary> void ThrowIfAny(IDictionary<string, object> context); } }
apache-2.0
hornn/interviews
depends/libyarn/src/rpc/SaslClient.cpp
3853
/******************************************************************** * Copyright (c) 2014, Pivotal Inc. * All rights reserved. * * Author: Zhanwei Wang ********************************************************************/ #include <algorithm> #include <cctype> #include "Exception.h" #include "ExceptionInternal.h" #include "SaslClient.h" #define SASL_SUCCESS 0 namespace Yarn { namespace Internal { SaslClient::SaslClient(const hadoop::common::RpcSaslProto_SaslAuth & auth, const Token & token, const std::string & principal) : complete(false) { int rc; ctx = NULL; RpcAuth method = RpcAuth(RpcAuth::ParseMethod(auth.method())); rc = gsasl_init(&ctx); if (rc != GSASL_OK) { THROW(YarnIOException, "cannot initialize libgsasl"); } switch (method.getMethod()) { case AuthMethod::KERBEROS: initKerberos(auth, principal); break; case AuthMethod::TOKEN: initDigestMd5(auth, token); break; default: THROW(YarnIOException, "unknown auth method."); break; } } SaslClient::~SaslClient() { if (session != NULL) { gsasl_finish(session); } if (ctx != NULL) { gsasl_done(ctx); } } void SaslClient::initKerberos(const hadoop::common::RpcSaslProto_SaslAuth & auth, const std::string & principal) { int rc; /* Create new authentication session. */ if ((rc = gsasl_client_start(ctx, auth.mechanism().c_str(), &session)) != GSASL_OK) { THROW(YarnIOException, "Cannot initialize client (%d): %s", rc, gsasl_strerror(rc)); } gsasl_property_set(session, GSASL_SERVICE, auth.protocol().c_str()); gsasl_property_set(session, GSASL_AUTHID, principal.c_str()); gsasl_property_set(session, GSASL_HOSTNAME, auth.serverid().c_str()); } std::string Base64Encode(const std::string & in) { char * temp; size_t len; std::string retval; int rc = gsasl_base64_to(in.c_str(), in.size(), &temp, &len); if (rc != GSASL_OK) { throw std::bad_alloc(); } if (temp) { retval = temp; free(temp); } if (!temp || retval.length() != len) { THROW(YarnIOException, "SaslClient: Failed to encode string to base64"); } return retval; } void SaslClient::initDigestMd5(const hadoop::common::RpcSaslProto_SaslAuth & auth, const Token & token) { int rc; if ((rc = gsasl_client_start(ctx, auth.mechanism().c_str(), &session)) != GSASL_OK) { THROW(YarnIOException, "Cannot initialize client (%d): %s", rc, gsasl_strerror(rc)); } std::string password = Base64Encode(token.getPassword()); std::string identifier = Base64Encode(token.getIdentifier()); gsasl_property_set(session, GSASL_PASSWORD, password.c_str()); gsasl_property_set(session, GSASL_AUTHID, identifier.c_str()); gsasl_property_set(session, GSASL_HOSTNAME, auth.serverid().c_str()); gsasl_property_set(session, GSASL_SERVICE, auth.protocol().c_str()); } std::string SaslClient::evaluateChallenge(const std::string & challenge) { int rc; char * output = NULL; size_t outputSize; std::string retval; rc = gsasl_step(session, &challenge[0], challenge.size(), &output, &outputSize); if (rc == GSASL_NEEDS_MORE || rc == GSASL_OK) { retval.resize(outputSize); memcpy(&retval[0], output, outputSize); if (output) { free(output); } } else { if (output) { free(output); } THROW(AccessControlException, "Failed to evaluate challenge: %s", gsasl_strerror(rc)); } if (rc == GSASL_OK) { complete = true; } return retval; } bool SaslClient::isComplete() { return complete; } } }
apache-2.0
apache/geronimo-yoko
yoko-spec-corba/src/main/java/org/omg/DynamicAny/DynValue.java
997
/* * 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.omg.DynamicAny; // // IDL:omg.org/DynamicAny/DynValue:1.0 // /***/ public interface DynValue extends DynValueOperations, DynValueCommon { }
apache-2.0
mattxia/spring-2.5-analysis
test/org/springframework/beans/factory/config/PropertiesFactoryBeanTests.java
5278
/* * Copyright 2002-2006 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.springframework.beans.factory.config; import java.util.Properties; import junit.framework.TestCase; import org.springframework.core.JdkVersion; import org.springframework.core.io.ClassPathResource; /** * @author Juergen Hoeller * @since 01.11.2003 */ public class PropertiesFactoryBeanTests extends TestCase { public void testWithPropertiesFile() throws Exception { PropertiesFactoryBean pfb = new PropertiesFactoryBean(); pfb.setLocation(new ClassPathResource("/org/springframework/beans/factory/config/test.properties")); pfb.afterPropertiesSet(); Properties props = (Properties) pfb.getObject(); assertEquals("99", props.getProperty("tb.array[0].age")); } public void testWithPropertiesXmlFile() throws Exception { // ignore for JDK < 1.5 if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) { return; } PropertiesFactoryBean pfb = new PropertiesFactoryBean(); pfb.setLocation(new ClassPathResource("/org/springframework/beans/factory/config/test-properties.xml")); pfb.afterPropertiesSet(); Properties props = (Properties) pfb.getObject(); assertEquals("99", props.getProperty("tb.array[0].age")); } public void testWithLocalProperties() throws Exception { PropertiesFactoryBean pfb = new PropertiesFactoryBean(); Properties localProps = new Properties(); localProps.setProperty("key2", "value2"); pfb.setProperties(localProps); pfb.afterPropertiesSet(); Properties props = (Properties) pfb.getObject(); assertEquals("value2", props.getProperty("key2")); } public void testWithPropertiesFileAndLocalProperties() throws Exception { PropertiesFactoryBean pfb = new PropertiesFactoryBean(); pfb.setLocation(new ClassPathResource("/org/springframework/beans/factory/config/test.properties")); Properties localProps = new Properties(); localProps.setProperty("key2", "value2"); localProps.setProperty("tb.array[0].age", "0"); pfb.setProperties(localProps); pfb.afterPropertiesSet(); Properties props = (Properties) pfb.getObject(); assertEquals("99", props.getProperty("tb.array[0].age")); assertEquals("value2", props.getProperty("key2")); } public void testWithPropertiesFileAndMultipleLocalProperties() throws Exception { PropertiesFactoryBean pfb = new PropertiesFactoryBean(); pfb.setLocation(new ClassPathResource("/org/springframework/beans/factory/config/test.properties")); Properties props1 = new Properties(); props1.setProperty("key2", "value2"); props1.setProperty("tb.array[0].age", "0"); Properties props2 = new Properties(); props2.setProperty("spring", "framework"); props2.setProperty("Don", "Mattingly"); Properties props3 = new Properties(); props3.setProperty("spider", "man"); props3.setProperty("bat", "man"); pfb.setPropertiesArray(new Properties[] {props1, props2, props3}); pfb.afterPropertiesSet(); Properties props = (Properties) pfb.getObject(); assertEquals("99", props.getProperty("tb.array[0].age")); assertEquals("value2", props.getProperty("key2")); assertEquals("framework", props.getProperty("spring")); assertEquals("Mattingly", props.getProperty("Don")); assertEquals("man", props.getProperty("spider")); assertEquals("man", props.getProperty("bat")); } public void testWithPropertiesFileAndLocalPropertiesAndLocalOverride() throws Exception { PropertiesFactoryBean pfb = new PropertiesFactoryBean(); pfb.setLocation(new ClassPathResource("/org/springframework/beans/factory/config/test.properties")); Properties localProps = new Properties(); localProps.setProperty("key2", "value2"); localProps.setProperty("tb.array[0].age", "0"); pfb.setProperties(localProps); pfb.setLocalOverride(true); pfb.afterPropertiesSet(); Properties props = (Properties) pfb.getObject(); assertEquals("0", props.getProperty("tb.array[0].age")); assertEquals("value2", props.getProperty("key2")); } public void testWithPrototype() throws Exception { PropertiesFactoryBean pfb = new PropertiesFactoryBean(); pfb.setSingleton(false); pfb.setLocation(new ClassPathResource("/org/springframework/beans/factory/config/test.properties")); Properties localProps = new Properties(); localProps.setProperty("key2", "value2"); pfb.setProperties(localProps); pfb.afterPropertiesSet(); Properties props = (Properties) pfb.getObject(); assertEquals("99", props.getProperty("tb.array[0].age")); assertEquals("value2", props.getProperty("key2")); Properties newProps = (Properties) pfb.getObject(); assertTrue(props != newProps); assertEquals("99", newProps.getProperty("tb.array[0].age")); assertEquals("value2", newProps.getProperty("key2")); } }
apache-2.0
tijoparacka/nifi
nifi-nar-bundles/nifi-kafka-bundle/nifi-kafka-0-9-processors/src/main/java/org/apache/nifi/processors/kafka/pubsub/PublishKafka.java
20601
/* * 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.nifi.processors.kafka.pubsub; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.xml.bind.DatatypeConverter; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.ByteArraySerializer; import org.apache.nifi.annotation.behavior.DynamicProperty; import org.apache.nifi.annotation.behavior.InputRequirement; import org.apache.nifi.annotation.behavior.WritesAttribute; import org.apache.nifi.annotation.documentation.CapabilityDescription; import org.apache.nifi.annotation.documentation.Tags; import org.apache.nifi.annotation.lifecycle.OnStopped; import org.apache.nifi.components.AllowableValue; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.components.ValidationContext; import org.apache.nifi.components.ValidationResult; import org.apache.nifi.flowfile.FlowFile; import org.apache.nifi.processor.AbstractProcessor; import org.apache.nifi.processor.DataUnit; import org.apache.nifi.processor.ProcessContext; import org.apache.nifi.processor.ProcessSession; import org.apache.nifi.processor.Relationship; import org.apache.nifi.processor.exception.ProcessException; import org.apache.nifi.processor.io.InputStreamCallback; import org.apache.nifi.processor.util.FlowFileFilters; import org.apache.nifi.processor.util.StandardValidators; @Tags({"Apache", "Kafka", "Put", "Send", "Message", "PubSub", "0.9.x"}) @CapabilityDescription("Sends the contents of a FlowFile as a message to Apache Kafka using the Kafka 0.9.x Producer. " + "The messages to send may be individual FlowFiles or may be delimited, using a " + "user-specified delimiter, such as a new-line. " + " Please note there are cases where the publisher can get into an indefinite stuck state. We are closely monitoring" + " how this evolves in the Kafka community and will take advantage of those fixes as soon as we can. In the mean time" + " it is possible to enter states where the only resolution will be to restart the JVM NiFi runs on. The complementary NiFi processor for fetching messages is ConsumeKafka.") @InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED) @DynamicProperty(name = "The name of a Kafka configuration property.", value = "The value of a given Kafka configuration property.", description = "These properties will be added on the Kafka configuration after loading any provided configuration properties." + " In the event a dynamic property represents a property that was already set, its value will be ignored and WARN message logged." + " For the list of available Kafka properties please refer to: http://kafka.apache.org/documentation.html#configuration. ") @WritesAttribute(attribute = "msg.count", description = "The number of messages that were sent to Kafka for this FlowFile. This attribute is added only to " + "FlowFiles that are routed to success. If the <Message Demarcator> Property is not set, this will always be 1, but if the Property is set, it may " + "be greater than 1.") public class PublishKafka extends AbstractProcessor { protected static final String MSG_COUNT = "msg.count"; static final AllowableValue DELIVERY_REPLICATED = new AllowableValue("all", "Guarantee Replicated Delivery", "FlowFile will be routed to failure unless the message is replicated to the appropriate " + "number of Kafka Nodes according to the Topic configuration"); static final AllowableValue DELIVERY_ONE_NODE = new AllowableValue("1", "Guarantee Single Node Delivery", "FlowFile will be routed to success if the message is received by a single Kafka node, " + "whether or not it is replicated. This is faster than <Guarantee Replicated Delivery> " + "but can result in data loss if a Kafka node crashes"); static final AllowableValue DELIVERY_BEST_EFFORT = new AllowableValue("0", "Best Effort", "FlowFile will be routed to success after successfully writing the content to a Kafka node, " + "without waiting for a response. This provides the best performance but may result in data loss."); static final AllowableValue ROUND_ROBIN_PARTITIONING = new AllowableValue(Partitioners.RoundRobinPartitioner.class.getName(), Partitioners.RoundRobinPartitioner.class.getSimpleName(), "Messages will be assigned partitions in a round-robin fashion, sending the first message to Partition 1, " + "the next Partition to Partition 2, and so on, wrapping as necessary."); static final AllowableValue RANDOM_PARTITIONING = new AllowableValue("org.apache.kafka.clients.producer.internals.DefaultPartitioner", "DefaultPartitioner", "Messages will be assigned to random partitions."); static final AllowableValue UTF8_ENCODING = new AllowableValue("utf-8", "UTF-8 Encoded", "The key is interpreted as a UTF-8 Encoded string."); static final AllowableValue HEX_ENCODING = new AllowableValue("hex", "Hex Encoded", "The key is interpreted as arbitrary binary data that is encoded using hexadecimal characters with uppercase letters."); static final PropertyDescriptor TOPIC = new PropertyDescriptor.Builder() .name("topic") .displayName("Topic Name") .description("The name of the Kafka Topic to publish to.") .required(true) .addValidator(StandardValidators.NON_BLANK_VALIDATOR) .expressionLanguageSupported(true) .build(); static final PropertyDescriptor DELIVERY_GUARANTEE = new PropertyDescriptor.Builder() .name(ProducerConfig.ACKS_CONFIG) .displayName("Delivery Guarantee") .description("Specifies the requirement for guaranteeing that a message is sent to Kafka. Corresponds to Kafka's 'acks' property.") .required(true) .expressionLanguageSupported(false) .allowableValues(DELIVERY_BEST_EFFORT, DELIVERY_ONE_NODE, DELIVERY_REPLICATED) .defaultValue(DELIVERY_BEST_EFFORT.getValue()) .build(); static final PropertyDescriptor METADATA_WAIT_TIME = new PropertyDescriptor.Builder() .name(ProducerConfig.MAX_BLOCK_MS_CONFIG) .displayName("Max Metadata Wait Time") .description("The amount of time publisher will wait to obtain metadata or wait for the buffer to flush during the 'send' call before failing the " + "entire 'send' call. Corresponds to Kafka's 'max.block.ms' property") .required(true) .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR) .expressionLanguageSupported(true) .defaultValue("5 sec") .build(); static final PropertyDescriptor ACK_WAIT_TIME = new PropertyDescriptor.Builder() .name("ack.wait.time") .displayName("Acknowledgment Wait Time") .description("After sending a message to Kafka, this indicates the amount of time that we are willing to wait for a response from Kafka. " + "If Kafka does not acknowledge the message within this time period, the FlowFile will be routed to 'failure'.") .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR) .expressionLanguageSupported(false) .required(true) .defaultValue("5 secs") .build(); static final PropertyDescriptor MAX_REQUEST_SIZE = new PropertyDescriptor.Builder() .name("max.request.size") .displayName("Max Request Size") .description("The maximum size of a request in bytes. Corresponds to Kafka's 'max.request.size' property and defaults to 1 MB (1048576).") .required(true) .addValidator(StandardValidators.DATA_SIZE_VALIDATOR) .defaultValue("1 MB") .build(); static final PropertyDescriptor KEY = new PropertyDescriptor.Builder() .name("kafka-key") .displayName("Kafka Key") .description("The Key to use for the Message. " + "If not specified, the flow file attribute 'kafka.key' is used as the message key, if it is present." + "Beware that setting Kafka key and demarcating at the same time may potentially lead to many Kafka messages with the same key." + "Normally this is not a problem as Kafka does not enforce or assume message and key uniqueness. Still, setting the demarcator and Kafka key at the same time poses a risk of " + "data loss on Kafka. During a topic compaction on Kafka, messages will be deduplicated based on this key.") .required(false) .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) .expressionLanguageSupported(true) .build(); static final PropertyDescriptor KEY_ATTRIBUTE_ENCODING = new PropertyDescriptor.Builder() .name("key-attribute-encoding") .displayName("Key Attribute Encoding") .description("FlowFiles that are emitted have an attribute named '" + KafkaProcessorUtils.KAFKA_KEY + "'. This property dictates how the value of the attribute should be encoded.") .required(true) .defaultValue(UTF8_ENCODING.getValue()) .allowableValues(UTF8_ENCODING, HEX_ENCODING) .build(); static final PropertyDescriptor MESSAGE_DEMARCATOR = new PropertyDescriptor.Builder() .name("message-demarcator") .displayName("Message Demarcator") .required(false) .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) .expressionLanguageSupported(true) .description("Specifies the string (interpreted as UTF-8) to use for demarcating multiple messages within " + "a single FlowFile. If not specified, the entire content of the FlowFile will be used as a single message. If specified, the " + "contents of the FlowFile will be split on this delimiter and each section sent as a separate Kafka message. " + "To enter special character such as 'new line' use CTRL+Enter or Shift+Enter, depending on your OS.") .build(); static final PropertyDescriptor PARTITION_CLASS = new PropertyDescriptor.Builder() .name(ProducerConfig.PARTITIONER_CLASS_CONFIG) .displayName("Partitioner class") .description("Specifies which class to use to compute a partition id for a message. Corresponds to Kafka's 'partitioner.class' property.") .allowableValues(ROUND_ROBIN_PARTITIONING, RANDOM_PARTITIONING) .defaultValue(RANDOM_PARTITIONING.getValue()) .required(false) .build(); static final PropertyDescriptor COMPRESSION_CODEC = new PropertyDescriptor.Builder() .name(ProducerConfig.COMPRESSION_TYPE_CONFIG) .displayName("Compression Type") .description("This parameter allows you to specify the compression codec for all data generated by this producer.") .required(true) .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) .allowableValues("none", "gzip", "snappy", "lz4") .defaultValue("none") .build(); static final Relationship REL_SUCCESS = new Relationship.Builder() .name("success") .description("FlowFiles for which all content was sent to Kafka.") .build(); static final Relationship REL_FAILURE = new Relationship.Builder() .name("failure") .description("Any FlowFile that cannot be sent to Kafka will be routed to this Relationship") .build(); private static final List<PropertyDescriptor> PROPERTIES; private static final Set<Relationship> RELATIONSHIPS; private volatile PublisherPool publisherPool = null; static { final List<PropertyDescriptor> properties = new ArrayList<>(); properties.addAll(KafkaProcessorUtils.getCommonPropertyDescriptors()); properties.add(TOPIC); properties.add(DELIVERY_GUARANTEE); properties.add(KEY); properties.add(KEY_ATTRIBUTE_ENCODING); properties.add(MESSAGE_DEMARCATOR); properties.add(MAX_REQUEST_SIZE); properties.add(ACK_WAIT_TIME); properties.add(METADATA_WAIT_TIME); properties.add(PARTITION_CLASS); properties.add(COMPRESSION_CODEC); PROPERTIES = Collections.unmodifiableList(properties); final Set<Relationship> relationships = new HashSet<>(); relationships.add(REL_SUCCESS); relationships.add(REL_FAILURE); RELATIONSHIPS = Collections.unmodifiableSet(relationships); } @Override public Set<Relationship> getRelationships() { return RELATIONSHIPS; } @Override protected List<PropertyDescriptor> getSupportedPropertyDescriptors() { return PROPERTIES; } @Override protected PropertyDescriptor getSupportedDynamicPropertyDescriptor(final String propertyDescriptorName) { return new PropertyDescriptor.Builder() .description("Specifies the value for '" + propertyDescriptorName + "' Kafka Configuration.") .name(propertyDescriptorName) .addValidator(new KafkaProcessorUtils.KafkaConfigValidator(ProducerConfig.class)) .dynamic(true) .build(); } @Override protected Collection<ValidationResult> customValidate(final ValidationContext validationContext) { return KafkaProcessorUtils.validateCommonProperties(validationContext); } private synchronized PublisherPool getPublisherPool(final ProcessContext context) { PublisherPool pool = publisherPool; if (pool != null) { return pool; } return publisherPool = createPublisherPool(context); } protected PublisherPool createPublisherPool(final ProcessContext context) { final int maxMessageSize = context.getProperty(MAX_REQUEST_SIZE).asDataSize(DataUnit.B).intValue(); final long maxAckWaitMillis = context.getProperty(ACK_WAIT_TIME).asTimePeriod(TimeUnit.MILLISECONDS).longValue(); final Map<String, Object> kafkaProperties = new HashMap<>(); KafkaProcessorUtils.buildCommonKafkaProperties(context, ProducerConfig.class, kafkaProperties); kafkaProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getName()); kafkaProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getName()); kafkaProperties.put("max.request.size", String.valueOf(maxMessageSize)); return new PublisherPool(kafkaProperties, getLogger(), maxMessageSize, maxAckWaitMillis); } @OnStopped public void closePool() { if (publisherPool != null) { publisherPool.close(); } publisherPool = null; } @Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { final boolean useDemarcator = context.getProperty(MESSAGE_DEMARCATOR).isSet(); final List<FlowFile> flowFiles = session.get(FlowFileFilters.newSizeBasedFilter(250, DataUnit.KB, 500)); if (flowFiles.isEmpty()) { return; } final PublisherPool pool = getPublisherPool(context); if (pool == null) { context.yield(); return; } final String securityProtocol = context.getProperty(KafkaProcessorUtils.SECURITY_PROTOCOL).getValue(); final String bootstrapServers = context.getProperty(KafkaProcessorUtils.BOOTSTRAP_SERVERS).evaluateAttributeExpressions().getValue(); final long startTime = System.nanoTime(); try (final PublisherLease lease = pool.obtainPublisher()) { // Send each FlowFile to Kafka asynchronously. for (final FlowFile flowFile : flowFiles) { if (!isScheduled()) { // If stopped, re-queue FlowFile instead of sending it session.transfer(flowFile); continue; } final byte[] messageKey = getMessageKey(flowFile, context); final String topic = context.getProperty(TOPIC).evaluateAttributeExpressions(flowFile).getValue(); final byte[] demarcatorBytes; if (useDemarcator) { demarcatorBytes = context.getProperty(MESSAGE_DEMARCATOR).evaluateAttributeExpressions(flowFile).getValue().getBytes(StandardCharsets.UTF_8); } else { demarcatorBytes = null; } session.read(flowFile, new InputStreamCallback() { @Override public void process(final InputStream rawIn) throws IOException { try (final InputStream in = new BufferedInputStream(rawIn)) { lease.publish(flowFile, in, messageKey, demarcatorBytes, topic); } } }); } // Complete the send final PublishResult publishResult = lease.complete(); // Transfer any successful FlowFiles. final long transmissionMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); for (FlowFile success : publishResult.getSuccessfulFlowFiles()) { final String topic = context.getProperty(TOPIC).evaluateAttributeExpressions(success).getValue(); final int msgCount = publishResult.getSuccessfulMessageCount(success); success = session.putAttribute(success, MSG_COUNT, String.valueOf(msgCount)); session.adjustCounter("Messages Sent", msgCount, true); final String transitUri = KafkaProcessorUtils.buildTransitURI(securityProtocol, bootstrapServers, topic); session.getProvenanceReporter().send(success, transitUri, "Sent " + msgCount + " messages", transmissionMillis); session.transfer(success, REL_SUCCESS); } // Transfer any failures. for (final FlowFile failure : publishResult.getFailedFlowFiles()) { final int successCount = publishResult.getSuccessfulMessageCount(failure); if (successCount > 0) { getLogger().error("Failed to send some messages for {} to Kafka, but {} messages were acknowledged by Kafka. Routing to failure due to {}", new Object[] {failure, successCount, publishResult.getReasonForFailure(failure)}); } else { getLogger().error("Failed to send all message for {} to Kafka; routing to failure due to {}", new Object[] {failure, publishResult.getReasonForFailure(failure)}); } session.transfer(failure, REL_FAILURE); } } } private byte[] getMessageKey(final FlowFile flowFile, final ProcessContext context) { final String uninterpretedKey; if (context.getProperty(KEY).isSet()) { uninterpretedKey = context.getProperty(KEY).evaluateAttributeExpressions(flowFile).getValue(); } else { uninterpretedKey = flowFile.getAttribute(KafkaProcessorUtils.KAFKA_KEY); } if (uninterpretedKey == null) { return null; } final String keyEncoding = context.getProperty(KEY_ATTRIBUTE_ENCODING).getValue(); if (UTF8_ENCODING.getValue().equals(keyEncoding)) { return uninterpretedKey.getBytes(StandardCharsets.UTF_8); } return DatatypeConverter.parseHexBinary(uninterpretedKey); } }
apache-2.0
jyemin/mongo-java-driver
driver-core/src/main/com/mongodb/internal/connection/ProtocolExecutor.java
1414
/* * Copyright 2008-present MongoDB, 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.mongodb.internal.connection; import com.mongodb.internal.async.SingleResultCallback; import com.mongodb.internal.session.SessionContext; public interface ProtocolExecutor { default <T> T execute(LegacyProtocol<T> protocol, InternalConnection connection) { throw new UnsupportedOperationException(); } default <T> void executeAsync(LegacyProtocol<T> protocol, InternalConnection connection, SingleResultCallback<T> callback) { throw new UnsupportedOperationException(); } <T> T execute(CommandProtocol<T> protocol, InternalConnection connection, SessionContext sessionContext); <T> void executeAsync(CommandProtocol<T> protocol, InternalConnection connection, SessionContext sessionContext, SingleResultCallback<T> callback); }
apache-2.0
lichengshuang/createvhost
python/others/oldboy/day3/test.py
881
<<<<<<< HEAD import MySQLdb try: conn=MySQLdb.connect(host='localhost',user='root',passwd='asher',port=3306) cur=conn.cursor() cur.execute('create database if not exists python') conn.select_db('python') cur.execute('create table test(id int,info varchar(20))') value=[1,'hi rollen'] cur.execute('insert into test values(%s,%s)',value) values=[] for i in range(20): values.append((i,'hi rollen'+str(i))) cur.executemany('insert into test values(%s,%s)',values) cur.execute('update test set info="I am rollen" where id=3') conn.commit() cur.close() conn.close() except MySQLdb.Error,e: print "Mysql Error %d: %s" % (e.args[0], e.args[1]) ======= #!/usr/bin/env python #coding:gbk s = raw_input("please input :").strip() print s >>>>>>> ac945f36b85f5ee13b978a621dca2215a925dfbc
apache-2.0
Seagate/swift
test/unit/common/test_db_replicator.py
60462
# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from contextlib import contextmanager import os import logging import errno import math import time from mock import patch, call from shutil import rmtree, copy from tempfile import mkdtemp, NamedTemporaryFile import mock import simplejson from swift.container.backend import DATADIR from swift.common import db_replicator from swift.common.utils import (normalize_timestamp, hash_path, storage_directory) from swift.common.exceptions import DriveNotMounted from swift.common.swob import HTTPException from test import unit from test.unit.common.test_db import ExampleBroker TEST_ACCOUNT_NAME = 'a c t' TEST_CONTAINER_NAME = 'c o n' def teardown_module(): "clean up my monkey patching" reload(db_replicator) @contextmanager def lock_parent_directory(filename): yield True class FakeRing(object): class Ring(object): devs = [] def __init__(self, path, reload_time=15, ring_name=None): pass def get_part(self, account, container=None, obj=None): return 0 def get_part_nodes(self, part): return [] def get_more_nodes(self, *args): return [] class FakeRingWithSingleNode(object): class Ring(object): devs = [dict( id=1, weight=10.0, zone=1, ip='1.1.1.1', port=6000, device='sdb', meta='', replication_ip='1.1.1.1', replication_port=6000 )] def __init__(self, path, reload_time=15, ring_name=None): pass def get_part(self, account, container=None, obj=None): return 0 def get_part_nodes(self, part): return self.devs def get_more_nodes(self, *args): return (d for d in self.devs) class FakeRingWithNodes(object): class Ring(object): devs = [dict( id=1, weight=10.0, zone=1, ip='1.1.1.1', port=6000, device='sdb', meta='', replication_ip='1.1.1.1', replication_port=6000, region=1 ), dict( id=2, weight=10.0, zone=2, ip='1.1.1.2', port=6000, device='sdb', meta='', replication_ip='1.1.1.2', replication_port=6000, region=2 ), dict( id=3, weight=10.0, zone=3, ip='1.1.1.3', port=6000, device='sdb', meta='', replication_ip='1.1.1.3', replication_port=6000, region=1 ), dict( id=4, weight=10.0, zone=4, ip='1.1.1.4', port=6000, device='sdb', meta='', replication_ip='1.1.1.4', replication_port=6000, region=2 ), dict( id=5, weight=10.0, zone=5, ip='1.1.1.5', port=6000, device='sdb', meta='', replication_ip='1.1.1.5', replication_port=6000, region=1 ), dict( id=6, weight=10.0, zone=6, ip='1.1.1.6', port=6000, device='sdb', meta='', replication_ip='1.1.1.6', replication_port=6000, region=2 )] def __init__(self, path, reload_time=15, ring_name=None): pass def get_part(self, account, container=None, obj=None): return 0 def get_part_nodes(self, part): return self.devs[:3] def get_more_nodes(self, *args): return (d for d in self.devs[3:]) class FakeProcess(object): def __init__(self, *codes): self.codes = iter(codes) self.args = None self.kwargs = None def __call__(self, *args, **kwargs): self.args = args self.kwargs = kwargs class Failure(object): def communicate(innerself): next = self.codes.next() if isinstance(next, int): innerself.returncode = next return next raise next return Failure() @contextmanager def _mock_process(*args): orig_process = db_replicator.subprocess.Popen db_replicator.subprocess.Popen = FakeProcess(*args) yield db_replicator.subprocess.Popen db_replicator.subprocess.Popen = orig_process class ReplHttp(object): def __init__(self, response=None, set_status=200): self.response = response self.set_status = set_status replicated = False host = 'localhost' def replicate(self, *args): self.replicated = True class Response(object): status = self.set_status data = self.response def read(innerself): return self.response return Response() class ChangingMtimesOs(object): def __init__(self): self.mtime = 0 def __call__(self, *args, **kwargs): self.mtime += 1 return self.mtime class FakeBroker(object): db_file = __file__ get_repl_missing_table = False stub_replication_info = None db_type = 'container' db_contains_type = 'object' info = {'account': TEST_ACCOUNT_NAME, 'container': TEST_CONTAINER_NAME} def __init__(self, *args, **kwargs): self.locked = False return None @contextmanager def lock(self): self.locked = True yield True self.locked = False def get_sync(self, *args, **kwargs): return 5 def get_syncs(self): return [] def get_items_since(self, point, *args): if point == 0: return [{'ROWID': 1}] if point == -1: return [{'ROWID': 1}, {'ROWID': 2}] return [] def merge_syncs(self, *args, **kwargs): self.args = args def merge_items(self, *args): self.args = args def get_replication_info(self): if self.get_repl_missing_table: raise Exception('no such table') info = dict(self.info) info.update({ 'hash': 12345, 'delete_timestamp': 0, 'put_timestamp': 1, 'created_at': 1, 'count': 0, }) if self.stub_replication_info: info.update(self.stub_replication_info) return info def reclaim(self, item_timestamp, sync_timestamp): pass def newid(self, remote_d): pass def update_metadata(self, metadata): self.metadata = metadata def merge_timestamps(self, created_at, put_timestamp, delete_timestamp): self.created_at = created_at self.put_timestamp = put_timestamp self.delete_timestamp = delete_timestamp class FakeAccountBroker(FakeBroker): db_type = 'account' db_contains_type = 'container' info = {'account': TEST_ACCOUNT_NAME} class TestReplicator(db_replicator.Replicator): server_type = 'container' ring_file = 'container.ring.gz' brokerclass = FakeBroker datadir = DATADIR default_port = 1000 class TestDBReplicator(unittest.TestCase): def setUp(self): db_replicator.ring = FakeRing() self.delete_db_calls = [] self._patchers = [] def tearDown(self): for patcher in self._patchers: patcher.stop() def _patch(self, patching_fn, *args, **kwargs): patcher = patching_fn(*args, **kwargs) patched_thing = patcher.start() self._patchers.append(patcher) return patched_thing def stub_delete_db(self, broker): self.delete_db_calls.append('/path/to/file') def test_repl_connection(self): node = {'replication_ip': '127.0.0.1', 'replication_port': 80, 'device': 'sdb1'} conn = db_replicator.ReplConnection(node, '1234567890', 'abcdefg', logging.getLogger()) def req(method, path, body, headers): self.assertEquals(method, 'REPLICATE') self.assertEquals(headers['Content-Type'], 'application/json') class Resp(object): def read(self): return 'data' resp = Resp() conn.request = req conn.getresponse = lambda *args: resp self.assertEquals(conn.replicate(1, 2, 3), resp) def other_req(method, path, body, headers): raise Exception('blah') conn.request = other_req self.assertEquals(conn.replicate(1, 2, 3), None) def test_rsync_file(self): replicator = TestReplicator({}) with _mock_process(-1): self.assertEquals( False, replicator._rsync_file('/some/file', 'remote:/some/file')) with _mock_process(0): self.assertEquals( True, replicator._rsync_file('/some/file', 'remote:/some/file')) def test_rsync_file_popen_args(self): replicator = TestReplicator({}) with _mock_process(0) as process: replicator._rsync_file('/some/file', 'remote:/some_file') exp_args = ([ 'rsync', '--quiet', '--no-motd', '--timeout=%s' % int(math.ceil(replicator.node_timeout)), '--contimeout=%s' % int(math.ceil(replicator.conn_timeout)), '--whole-file', '/some/file', 'remote:/some_file'],) self.assertEqual(exp_args, process.args) def test_rsync_file_popen_args_whole_file_false(self): replicator = TestReplicator({}) with _mock_process(0) as process: replicator._rsync_file('/some/file', 'remote:/some_file', False) exp_args = ([ 'rsync', '--quiet', '--no-motd', '--timeout=%s' % int(math.ceil(replicator.node_timeout)), '--contimeout=%s' % int(math.ceil(replicator.conn_timeout)), '/some/file', 'remote:/some_file'],) self.assertEqual(exp_args, process.args) def test_rsync_file_popen_args_different_region_and_rsync_compress(self): replicator = TestReplicator({}) for rsync_compress in (False, True): replicator.rsync_compress = rsync_compress for different_region in (False, True): with _mock_process(0) as process: replicator._rsync_file('/some/file', 'remote:/some_file', False, different_region) if rsync_compress and different_region: # --compress arg should be passed to rsync binary # only when rsync_compress option is enabled # AND destination node is in a different # region self.assertTrue('--compress' in process.args[0]) else: self.assertFalse('--compress' in process.args[0]) def test_rsync_db(self): replicator = TestReplicator({}) replicator._rsync_file = lambda *args, **kwargs: True fake_device = {'replication_ip': '127.0.0.1', 'device': 'sda1'} replicator._rsync_db(FakeBroker(), fake_device, ReplHttp(), 'abcd') def test_rsync_db_rsync_file_call(self): fake_device = {'ip': '127.0.0.1', 'port': '0', 'replication_ip': '127.0.0.1', 'replication_port': '0', 'device': 'sda1'} def mock_rsync_ip(ip): self.assertEquals(fake_device['ip'], ip) return 'rsync_ip(%s)' % ip class MyTestReplicator(TestReplicator): def __init__(self, db_file, remote_file): super(MyTestReplicator, self).__init__({}) self.db_file = db_file self.remote_file = remote_file def _rsync_file(self_, db_file, remote_file, whole_file=True, different_region=False): self.assertEqual(self_.db_file, db_file) self.assertEqual(self_.remote_file, remote_file) self_._rsync_file_called = True return False with patch('swift.common.db_replicator.rsync_ip', mock_rsync_ip): broker = FakeBroker() remote_file = 'rsync_ip(127.0.0.1)::container/sda1/tmp/abcd' replicator = MyTestReplicator(broker.db_file, remote_file) replicator._rsync_db(broker, fake_device, ReplHttp(), 'abcd') self.assert_(replicator._rsync_file_called) with patch('swift.common.db_replicator.rsync_ip', mock_rsync_ip): broker = FakeBroker() remote_file = 'rsync_ip(127.0.0.1)::container0/sda1/tmp/abcd' replicator = MyTestReplicator(broker.db_file, remote_file) replicator.vm_test_mode = True replicator._rsync_db(broker, fake_device, ReplHttp(), 'abcd') self.assert_(replicator._rsync_file_called) def test_rsync_db_rsync_file_failure(self): class MyTestReplicator(TestReplicator): def __init__(self): super(MyTestReplicator, self).__init__({}) self._rsync_file_called = False def _rsync_file(self_, *args, **kwargs): self.assertEqual( False, self_._rsync_file_called, '_sync_file() should only be called once') self_._rsync_file_called = True return False with patch('os.path.exists', lambda *args: True): replicator = MyTestReplicator() fake_device = {'ip': '127.0.0.1', 'replication_ip': '127.0.0.1', 'device': 'sda1'} replicator._rsync_db(FakeBroker(), fake_device, ReplHttp(), 'abcd') self.assertEqual(True, replicator._rsync_file_called) def test_rsync_db_change_after_sync(self): class MyTestReplicator(TestReplicator): def __init__(self, broker): super(MyTestReplicator, self).__init__({}) self.broker = broker self._rsync_file_call_count = 0 def _rsync_file(self_, db_file, remote_file, whole_file=True, different_region=False): self_._rsync_file_call_count += 1 if self_._rsync_file_call_count == 1: self.assertEquals(True, whole_file) self.assertEquals(False, self_.broker.locked) elif self_._rsync_file_call_count == 2: self.assertEquals(False, whole_file) self.assertEquals(True, self_.broker.locked) else: raise RuntimeError('_rsync_file() called too many times') return True # with journal file with patch('os.path.exists', lambda *args: True): broker = FakeBroker() replicator = MyTestReplicator(broker) fake_device = {'ip': '127.0.0.1', 'replication_ip': '127.0.0.1', 'device': 'sda1'} replicator._rsync_db(broker, fake_device, ReplHttp(), 'abcd') self.assertEquals(2, replicator._rsync_file_call_count) # with new mtime with patch('os.path.exists', lambda *args: False): with patch('os.path.getmtime', ChangingMtimesOs()): broker = FakeBroker() replicator = MyTestReplicator(broker) fake_device = {'ip': '127.0.0.1', 'replication_ip': '127.0.0.1', 'device': 'sda1'} replicator._rsync_db(broker, fake_device, ReplHttp(), 'abcd') self.assertEquals(2, replicator._rsync_file_call_count) def test_in_sync(self): replicator = TestReplicator({}) self.assertEquals(replicator._in_sync( {'id': 'a', 'point': 0, 'max_row': 0, 'hash': 'b'}, {'id': 'a', 'point': -1, 'max_row': 0, 'hash': 'b'}, FakeBroker(), -1), True) self.assertEquals(replicator._in_sync( {'id': 'a', 'point': -1, 'max_row': 0, 'hash': 'b'}, {'id': 'a', 'point': -1, 'max_row': 10, 'hash': 'b'}, FakeBroker(), -1), True) self.assertEquals(bool(replicator._in_sync( {'id': 'a', 'point': -1, 'max_row': 0, 'hash': 'c'}, {'id': 'a', 'point': -1, 'max_row': 10, 'hash': 'd'}, FakeBroker(), -1)), False) def test_run_once(self): replicator = TestReplicator({}) replicator.run_once() def test_run_once_no_ips(self): replicator = TestReplicator({}, logger=unit.FakeLogger()) self._patch(patch.object, db_replicator, 'whataremyips', lambda *args: []) replicator.run_once() self.assertEqual( replicator.logger.log_dict['error'], [(('ERROR Failed to get my own IPs?',), {})]) def test_run_once_node_is_not_mounted(self): db_replicator.ring = FakeRingWithSingleNode() conf = {'mount_check': 'true', 'bind_port': 6000} replicator = TestReplicator(conf, logger=unit.FakeLogger()) self.assertEqual(replicator.mount_check, True) self.assertEqual(replicator.port, 6000) def mock_ismount(path): self.assertEquals(path, os.path.join(replicator.root, replicator.ring.devs[0]['device'])) return False self._patch(patch.object, db_replicator, 'whataremyips', lambda *args: ['1.1.1.1']) self._patch(patch.object, db_replicator, 'ismount', mock_ismount) replicator.run_once() self.assertEqual( replicator.logger.log_dict['warning'], [(('Skipping %(device)s as it is not mounted' % replicator.ring.devs[0],), {})]) def test_run_once_node_is_mounted(self): db_replicator.ring = FakeRingWithSingleNode() conf = {'mount_check': 'true', 'bind_port': 6000} replicator = TestReplicator(conf, logger=unit.FakeLogger()) self.assertEqual(replicator.mount_check, True) self.assertEqual(replicator.port, 6000) def mock_unlink_older_than(path, mtime): self.assertEquals(path, os.path.join(replicator.root, replicator.ring.devs[0]['device'], 'tmp')) self.assertTrue(time.time() - replicator.reclaim_age >= mtime) def mock_spawn_n(fn, part, object_file, node_id): self.assertEquals('123', part) self.assertEquals('/srv/node/sda/c.db', object_file) self.assertEquals(1, node_id) self._patch(patch.object, db_replicator, 'whataremyips', lambda *args: ['1.1.1.1']) self._patch(patch.object, db_replicator, 'ismount', lambda *args: True) self._patch(patch.object, db_replicator, 'unlink_older_than', mock_unlink_older_than) self._patch(patch.object, db_replicator, 'roundrobin_datadirs', lambda *args: [('123', '/srv/node/sda/c.db', 1)]) self._patch(patch.object, replicator.cpool, 'spawn_n', mock_spawn_n) with patch('swift.common.db_replicator.os', new=mock.MagicMock(wraps=os)) as mock_os: mock_os.path.isdir.return_value = True replicator.run_once() mock_os.path.isdir.assert_called_with( os.path.join(replicator.root, replicator.ring.devs[0]['device'], replicator.datadir)) def test_usync(self): fake_http = ReplHttp() replicator = TestReplicator({}) replicator._usync_db(0, FakeBroker(), fake_http, '12345', '67890') def test_usync_http_error_above_300(self): fake_http = ReplHttp(set_status=301) replicator = TestReplicator({}) self.assertFalse( replicator._usync_db(0, FakeBroker(), fake_http, '12345', '67890')) def test_usync_http_error_below_200(self): fake_http = ReplHttp(set_status=101) replicator = TestReplicator({}) self.assertFalse( replicator._usync_db(0, FakeBroker(), fake_http, '12345', '67890')) def test_stats(self): # I'm not sure how to test that this logs the right thing, # but we can at least make sure it gets covered. replicator = TestReplicator({}) replicator._zero_stats() replicator._report_stats() def test_replicate_object(self): db_replicator.ring = FakeRingWithNodes() replicator = TestReplicator({}) replicator.delete_db = self.stub_delete_db replicator._replicate_object('0', '/path/to/file', 'node_id') self.assertEquals([], self.delete_db_calls) def test_replicate_object_quarantine(self): replicator = TestReplicator({}) self._patch(patch.object, replicator.brokerclass, 'db_file', '/a/b/c/d/e/hey') self._patch(patch.object, replicator.brokerclass, 'get_repl_missing_table', True) def mock_renamer(was, new, fsync=False, cause_colision=False): if cause_colision and '-' not in new: raise OSError(errno.EEXIST, "File already exists") self.assertEquals('/a/b/c/d/e', was) if '-' in new: self.assert_( new.startswith('/a/quarantined/containers/e-')) else: self.assertEquals('/a/quarantined/containers/e', new) def mock_renamer_error(was, new, fsync): return mock_renamer(was, new, fsync, cause_colision=True) with patch.object(db_replicator, 'renamer', mock_renamer): replicator._replicate_object('0', 'file', 'node_id') # try the double quarantine with patch.object(db_replicator, 'renamer', mock_renamer_error): replicator._replicate_object('0', 'file', 'node_id') def test_replicate_object_delete_because_deleted(self): replicator = TestReplicator({}) try: replicator.delete_db = self.stub_delete_db replicator.brokerclass.stub_replication_info = { 'delete_timestamp': 2, 'put_timestamp': 1} replicator._replicate_object('0', '/path/to/file', 'node_id') finally: replicator.brokerclass.stub_replication_info = None self.assertEquals(['/path/to/file'], self.delete_db_calls) def test_replicate_object_delete_because_not_shouldbehere(self): replicator = TestReplicator({}) replicator.delete_db = self.stub_delete_db replicator._replicate_object('0', '/path/to/file', 'node_id') self.assertEquals(['/path/to/file'], self.delete_db_calls) def test_replicate_account_out_of_place(self): replicator = TestReplicator({}, logger=unit.FakeLogger()) replicator.ring = FakeRingWithNodes().Ring('path') replicator.brokerclass = FakeAccountBroker replicator._repl_to_node = lambda *args: True replicator.delete_db = self.stub_delete_db # Correct node_id, wrong part part = replicator.ring.get_part(TEST_ACCOUNT_NAME) + 1 node_id = replicator.ring.get_part_nodes(part)[0]['id'] replicator._replicate_object(str(part), '/path/to/file', node_id) self.assertEqual(['/path/to/file'], self.delete_db_calls) error_msgs = replicator.logger.get_lines_for_level('error') expected = 'Found /path/to/file for /a%20c%20t when it should be ' \ 'on partition 0; will replicate out and remove.' self.assertEqual(error_msgs, [expected]) def test_replicate_container_out_of_place(self): replicator = TestReplicator({}, logger=unit.FakeLogger()) replicator.ring = FakeRingWithNodes().Ring('path') replicator._repl_to_node = lambda *args: True replicator.delete_db = self.stub_delete_db # Correct node_id, wrong part part = replicator.ring.get_part( TEST_ACCOUNT_NAME, TEST_CONTAINER_NAME) + 1 node_id = replicator.ring.get_part_nodes(part)[0]['id'] replicator._replicate_object(str(part), '/path/to/file', node_id) self.assertEqual(['/path/to/file'], self.delete_db_calls) self.assertEqual( replicator.logger.log_dict['error'], [(('Found /path/to/file for /a%20c%20t/c%20o%20n when it should ' 'be on partition 0; will replicate out and remove.',), {})]) def test_replicate_object_different_region(self): db_replicator.ring = FakeRingWithNodes() replicator = TestReplicator({}) replicator._repl_to_node = mock.Mock() # For node_id = 1, one replica in same region(1) and other is in a # different region(2). Refer: FakeRingWithNodes replicator._replicate_object('0', '/path/to/file', 1) # different_region was set True and passed to _repl_to_node() self.assertEqual(replicator._repl_to_node.call_args_list[0][0][-1], True) # different_region was set False and passed to _repl_to_node() self.assertEqual(replicator._repl_to_node.call_args_list[1][0][-1], False) def test_delete_db(self): db_replicator.lock_parent_directory = lock_parent_directory replicator = TestReplicator({}, logger=unit.FakeLogger()) replicator._zero_stats() replicator.extract_device = lambda _: 'some_device' temp_dir = mkdtemp() try: temp_suf_dir = os.path.join(temp_dir, '16e') os.mkdir(temp_suf_dir) temp_hash_dir = os.path.join(temp_suf_dir, '166e33924a08ede4204871468c11e16e') os.mkdir(temp_hash_dir) temp_file = NamedTemporaryFile(dir=temp_hash_dir, delete=False) temp_hash_dir2 = os.path.join(temp_suf_dir, '266e33924a08ede4204871468c11e16e') os.mkdir(temp_hash_dir2) temp_file2 = NamedTemporaryFile(dir=temp_hash_dir2, delete=False) # sanity-checks self.assertTrue(os.path.exists(temp_dir)) self.assertTrue(os.path.exists(temp_suf_dir)) self.assertTrue(os.path.exists(temp_hash_dir)) self.assertTrue(os.path.exists(temp_file.name)) self.assertTrue(os.path.exists(temp_hash_dir2)) self.assertTrue(os.path.exists(temp_file2.name)) self.assertEqual(0, replicator.stats['remove']) temp_file.db_file = temp_file.name replicator.delete_db(temp_file) self.assertTrue(os.path.exists(temp_dir)) self.assertTrue(os.path.exists(temp_suf_dir)) self.assertFalse(os.path.exists(temp_hash_dir)) self.assertFalse(os.path.exists(temp_file.name)) self.assertTrue(os.path.exists(temp_hash_dir2)) self.assertTrue(os.path.exists(temp_file2.name)) self.assertEqual([(('removes.some_device',), {})], replicator.logger.log_dict['increment']) self.assertEqual(1, replicator.stats['remove']) temp_file2.db_file = temp_file2.name replicator.delete_db(temp_file2) self.assertTrue(os.path.exists(temp_dir)) self.assertFalse(os.path.exists(temp_suf_dir)) self.assertFalse(os.path.exists(temp_hash_dir)) self.assertFalse(os.path.exists(temp_file.name)) self.assertFalse(os.path.exists(temp_hash_dir2)) self.assertFalse(os.path.exists(temp_file2.name)) self.assertEqual([(('removes.some_device',), {})] * 2, replicator.logger.log_dict['increment']) self.assertEqual(2, replicator.stats['remove']) finally: rmtree(temp_dir) def test_extract_device(self): replicator = TestReplicator({'devices': '/some/root'}) self.assertEqual('some_device', replicator.extract_device( '/some/root/some_device/deeper/and/deeper')) self.assertEqual('UNKNOWN', replicator.extract_device( '/some/foo/some_device/deeper/and/deeper')) def test_dispatch_no_arg_pop(self): rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) response = rpc.dispatch(('a',), 'arg') self.assertEquals('Invalid object type', response.body) self.assertEquals(400, response.status_int) def test_dispatch_drive_not_mounted(self): rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, True) def mock_ismount(path): self.assertEquals('/drive', path) return False self._patch(patch.object, db_replicator, 'ismount', mock_ismount) response = rpc.dispatch(('drive', 'part', 'hash'), ['method']) self.assertEquals('507 drive is not mounted', response.status) self.assertEquals(507, response.status_int) def test_dispatch_unexpected_operation_db_does_not_exist(self): rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) def mock_mkdirs(path): self.assertEquals('/drive/tmp', path) self._patch(patch.object, db_replicator, 'mkdirs', mock_mkdirs) with patch('swift.common.db_replicator.os', new=mock.MagicMock(wraps=os)) as mock_os: mock_os.path.exists.return_value = False response = rpc.dispatch(('drive', 'part', 'hash'), ['unexpected']) self.assertEquals('404 Not Found', response.status) self.assertEquals(404, response.status_int) def test_dispatch_operation_unexpected(self): rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) self._patch(patch.object, db_replicator, 'mkdirs', lambda *args: True) def unexpected_method(broker, args): self.assertEquals(FakeBroker, broker.__class__) self.assertEqual(['arg1', 'arg2'], args) return 'unexpected-called' rpc.unexpected = unexpected_method with patch('swift.common.db_replicator.os', new=mock.MagicMock(wraps=os)) as mock_os: mock_os.path.exists.return_value = True response = rpc.dispatch(('drive', 'part', 'hash'), ['unexpected', 'arg1', 'arg2']) mock_os.path.exists.assert_called_with('/part/ash/hash/hash.db') self.assertEquals('unexpected-called', response) def test_dispatch_operation_rsync_then_merge(self): rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) self._patch(patch.object, db_replicator, 'renamer', lambda *args: True) with patch('swift.common.db_replicator.os', new=mock.MagicMock(wraps=os)) as mock_os: mock_os.path.exists.return_value = True response = rpc.dispatch(('drive', 'part', 'hash'), ['rsync_then_merge', 'arg1', 'arg2']) expected_calls = [call('/part/ash/hash/hash.db'), call('/drive/tmp/arg1')] self.assertEquals(mock_os.path.exists.call_args_list, expected_calls) self.assertEquals('204 No Content', response.status) self.assertEquals(204, response.status_int) def test_dispatch_operation_complete_rsync(self): rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) self._patch(patch.object, db_replicator, 'renamer', lambda *args: True) with patch('swift.common.db_replicator.os', new=mock.MagicMock( wraps=os)) as mock_os: mock_os.path.exists.side_effect = [False, True] response = rpc.dispatch(('drive', 'part', 'hash'), ['complete_rsync', 'arg1', 'arg2']) expected_calls = [call('/part/ash/hash/hash.db'), call('/drive/tmp/arg1')] self.assertEquals(mock_os.path.exists.call_args_list, expected_calls) self.assertEquals('204 No Content', response.status) self.assertEquals(204, response.status_int) def test_rsync_then_merge_db_does_not_exist(self): rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) with patch('swift.common.db_replicator.os', new=mock.MagicMock(wraps=os)) as mock_os: mock_os.path.exists.return_value = False response = rpc.rsync_then_merge('drive', '/data/db.db', ('arg1', 'arg2')) mock_os.path.exists.assert_called_with('/data/db.db') self.assertEquals('404 Not Found', response.status) self.assertEquals(404, response.status_int) def test_rsync_then_merge_old_does_not_exist(self): rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) with patch('swift.common.db_replicator.os', new=mock.MagicMock(wraps=os)) as mock_os: mock_os.path.exists.side_effect = [True, False] response = rpc.rsync_then_merge('drive', '/data/db.db', ('arg1', 'arg2')) expected_calls = [call('/data/db.db'), call('/drive/tmp/arg1')] self.assertEquals(mock_os.path.exists.call_args_list, expected_calls) self.assertEquals('404 Not Found', response.status) self.assertEquals(404, response.status_int) def test_rsync_then_merge_with_objects(self): rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) def mock_renamer(old, new): self.assertEquals('/drive/tmp/arg1', old) self.assertEquals('/data/db.db', new) self._patch(patch.object, db_replicator, 'renamer', mock_renamer) with patch('swift.common.db_replicator.os', new=mock.MagicMock(wraps=os)) as mock_os: mock_os.path.exists.return_value = True response = rpc.rsync_then_merge('drive', '/data/db.db', ['arg1', 'arg2']) self.assertEquals('204 No Content', response.status) self.assertEquals(204, response.status_int) def test_complete_rsync_db_does_not_exist(self): rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) with patch('swift.common.db_replicator.os', new=mock.MagicMock(wraps=os)) as mock_os: mock_os.path.exists.return_value = True response = rpc.complete_rsync('drive', '/data/db.db', ['arg1', 'arg2']) mock_os.path.exists.assert_called_with('/data/db.db') self.assertEquals('404 Not Found', response.status) self.assertEquals(404, response.status_int) def test_complete_rsync_old_file_does_not_exist(self): rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) with patch('swift.common.db_replicator.os', new=mock.MagicMock(wraps=os)) as mock_os: mock_os.path.exists.return_value = False response = rpc.complete_rsync('drive', '/data/db.db', ['arg1', 'arg2']) expected_calls = [call('/data/db.db'), call('/drive/tmp/arg1')] self.assertEquals(expected_calls, mock_os.path.exists.call_args_list) self.assertEquals('404 Not Found', response.status) self.assertEquals(404, response.status_int) def test_complete_rsync_rename(self): rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) def mock_exists(path): if path == '/data/db.db': return False self.assertEquals('/drive/tmp/arg1', path) return True def mock_renamer(old, new): self.assertEquals('/drive/tmp/arg1', old) self.assertEquals('/data/db.db', new) self._patch(patch.object, db_replicator, 'renamer', mock_renamer) with patch('swift.common.db_replicator.os', new=mock.MagicMock(wraps=os)) as mock_os: mock_os.path.exists.side_effect = [False, True] response = rpc.complete_rsync('drive', '/data/db.db', ['arg1', 'arg2']) self.assertEquals('204 No Content', response.status) self.assertEquals(204, response.status_int) def test_replicator_sync_with_broker_replication_missing_table(self): rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) rpc.logger = unit.debug_logger() broker = FakeBroker() broker.get_repl_missing_table = True called = [] def mock_quarantine_db(object_file, server_type): called.append(True) self.assertEquals(broker.db_file, object_file) self.assertEquals(broker.db_type, server_type) self._patch(patch.object, db_replicator, 'quarantine_db', mock_quarantine_db) response = rpc.sync(broker, ('remote_sync', 'hash_', 'id_', 'created_at', 'put_timestamp', 'delete_timestamp', 'metadata')) self.assertEquals('404 Not Found', response.status) self.assertEquals(404, response.status_int) self.assertEqual(called, [True]) errors = rpc.logger.get_lines_for_level('error') self.assertEqual(errors, ["Unable to decode remote metadata 'metadata'", "Quarantining DB %s" % broker]) def test_replicator_sync(self): rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) broker = FakeBroker() response = rpc.sync(broker, (broker.get_sync() + 1, 12345, 'id_', 'created_at', 'put_timestamp', 'delete_timestamp', '{"meta1": "data1", "meta2": "data2"}')) self.assertEquals({'meta1': 'data1', 'meta2': 'data2'}, broker.metadata) self.assertEquals('created_at', broker.created_at) self.assertEquals('put_timestamp', broker.put_timestamp) self.assertEquals('delete_timestamp', broker.delete_timestamp) self.assertEquals('200 OK', response.status) self.assertEquals(200, response.status_int) def test_rsync_then_merge(self): rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) rpc.rsync_then_merge('sda1', '/srv/swift/blah', ('a', 'b')) def test_merge_items(self): rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) fake_broker = FakeBroker() args = ('a', 'b') rpc.merge_items(fake_broker, args) self.assertEquals(fake_broker.args, args) def test_merge_syncs(self): rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) fake_broker = FakeBroker() args = ('a', 'b') rpc.merge_syncs(fake_broker, args) self.assertEquals(fake_broker.args, (args[0],)) def test_complete_rsync_with_bad_input(self): drive = '/some/root' db_file = __file__ args = ['old_file'] rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) resp = rpc.complete_rsync(drive, db_file, args) self.assertTrue(isinstance(resp, HTTPException)) self.assertEquals(404, resp.status_int) resp = rpc.complete_rsync(drive, 'new_db_file', args) self.assertTrue(isinstance(resp, HTTPException)) self.assertEquals(404, resp.status_int) def test_complete_rsync(self): drive = mkdtemp() args = ['old_file'] rpc = db_replicator.ReplicatorRpc('/', '/', FakeBroker, False) os.mkdir('%s/tmp' % drive) old_file = '%s/tmp/old_file' % drive new_file = '%s/new_db_file' % drive try: fp = open(old_file, 'w') fp.write('void') fp.close resp = rpc.complete_rsync(drive, new_file, args) self.assertEquals(204, resp.status_int) finally: rmtree(drive) def test_roundrobin_datadirs(self): listdir_calls = [] isdir_calls = [] exists_calls = [] shuffle_calls = [] rmdir_calls = [] def _listdir(path): listdir_calls.append(path) if not path.startswith('/srv/node/sda/containers') and \ not path.startswith('/srv/node/sdb/containers'): return [] path = path[len('/srv/node/sdx/containers'):] if path == '': return ['123', '456', '789', '9999'] # 456 will pretend to be a file # 9999 will be an empty partition with no contents elif path == '/123': return ['abc', 'def.db'] # def.db will pretend to be a file elif path == '/123/abc': # 11111111111111111111111111111abc will pretend to be a file return ['00000000000000000000000000000abc', '11111111111111111111111111111abc'] elif path == '/123/abc/00000000000000000000000000000abc': return ['00000000000000000000000000000abc.db', # This other.db isn't in the right place, so should be # ignored later. '000000000000000000000000000other.db', 'weird1'] # weird1 will pretend to be a dir, if asked elif path == '/789': return ['ghi', 'jkl'] # jkl will pretend to be a file elif path == '/789/ghi': # 33333333333333333333333333333ghi will pretend to be a file return ['22222222222222222222222222222ghi', '33333333333333333333333333333ghi'] elif path == '/789/ghi/22222222222222222222222222222ghi': return ['22222222222222222222222222222ghi.db', 'weird2'] # weird2 will pretend to be a dir, if asked elif path == '9999': return [] return [] def _isdir(path): isdir_calls.append(path) if not path.startswith('/srv/node/sda/containers') and \ not path.startswith('/srv/node/sdb/containers'): return False path = path[len('/srv/node/sdx/containers'):] if path in ('/123', '/123/abc', '/123/abc/00000000000000000000000000000abc', '/123/abc/00000000000000000000000000000abc/weird1', '/789', '/789/ghi', '/789/ghi/22222222222222222222222222222ghi', '/789/ghi/22222222222222222222222222222ghi/weird2', '/9999'): return True return False def _exists(arg): exists_calls.append(arg) return True def _shuffle(arg): shuffle_calls.append(arg) def _rmdir(arg): rmdir_calls.append(arg) orig_listdir = db_replicator.os.listdir orig_isdir = db_replicator.os.path.isdir orig_exists = db_replicator.os.path.exists orig_shuffle = db_replicator.random.shuffle orig_rmdir = db_replicator.os.rmdir try: db_replicator.os.listdir = _listdir db_replicator.os.path.isdir = _isdir db_replicator.os.path.exists = _exists db_replicator.random.shuffle = _shuffle db_replicator.os.rmdir = _rmdir datadirs = [('/srv/node/sda/containers', 1), ('/srv/node/sdb/containers', 2)] results = list(db_replicator.roundrobin_datadirs(datadirs)) # The results show that the .db files are returned, the devices # interleaved. self.assertEquals(results, [ ('123', '/srv/node/sda/containers/123/abc/' '00000000000000000000000000000abc/' '00000000000000000000000000000abc.db', 1), ('123', '/srv/node/sdb/containers/123/abc/' '00000000000000000000000000000abc/' '00000000000000000000000000000abc.db', 2), ('789', '/srv/node/sda/containers/789/ghi/' '22222222222222222222222222222ghi/' '22222222222222222222222222222ghi.db', 1), ('789', '/srv/node/sdb/containers/789/ghi/' '22222222222222222222222222222ghi/' '22222222222222222222222222222ghi.db', 2)]) # The listdir calls show that we only listdir the dirs self.assertEquals(listdir_calls, [ '/srv/node/sda/containers', '/srv/node/sda/containers/123', '/srv/node/sda/containers/123/abc', '/srv/node/sdb/containers', '/srv/node/sdb/containers/123', '/srv/node/sdb/containers/123/abc', '/srv/node/sda/containers/789', '/srv/node/sda/containers/789/ghi', '/srv/node/sdb/containers/789', '/srv/node/sdb/containers/789/ghi', '/srv/node/sda/containers/9999', '/srv/node/sdb/containers/9999']) # The isdir calls show that we did ask about the things pretending # to be files at various levels. self.assertEquals(isdir_calls, [ '/srv/node/sda/containers/123', '/srv/node/sda/containers/123/abc', ('/srv/node/sda/containers/123/abc/' '00000000000000000000000000000abc'), '/srv/node/sdb/containers/123', '/srv/node/sdb/containers/123/abc', ('/srv/node/sdb/containers/123/abc/' '00000000000000000000000000000abc'), ('/srv/node/sda/containers/123/abc/' '11111111111111111111111111111abc'), '/srv/node/sda/containers/123/def.db', '/srv/node/sda/containers/456', '/srv/node/sda/containers/789', '/srv/node/sda/containers/789/ghi', ('/srv/node/sda/containers/789/ghi/' '22222222222222222222222222222ghi'), ('/srv/node/sdb/containers/123/abc/' '11111111111111111111111111111abc'), '/srv/node/sdb/containers/123/def.db', '/srv/node/sdb/containers/456', '/srv/node/sdb/containers/789', '/srv/node/sdb/containers/789/ghi', ('/srv/node/sdb/containers/789/ghi/' '22222222222222222222222222222ghi'), ('/srv/node/sda/containers/789/ghi/' '33333333333333333333333333333ghi'), '/srv/node/sda/containers/789/jkl', '/srv/node/sda/containers/9999', ('/srv/node/sdb/containers/789/ghi/' '33333333333333333333333333333ghi'), '/srv/node/sdb/containers/789/jkl', '/srv/node/sdb/containers/9999']) # The exists calls are the .db files we looked for as we walked the # structure. self.assertEquals(exists_calls, [ ('/srv/node/sda/containers/123/abc/' '00000000000000000000000000000abc/' '00000000000000000000000000000abc.db'), ('/srv/node/sdb/containers/123/abc/' '00000000000000000000000000000abc/' '00000000000000000000000000000abc.db'), ('/srv/node/sda/containers/789/ghi/' '22222222222222222222222222222ghi/' '22222222222222222222222222222ghi.db'), ('/srv/node/sdb/containers/789/ghi/' '22222222222222222222222222222ghi/' '22222222222222222222222222222ghi.db')]) # Shows that we called shuffle twice, once for each device. self.assertEquals( shuffle_calls, [['123', '456', '789', '9999'], ['123', '456', '789', '9999']]) # Shows that we called removed the two empty partition directories. self.assertEquals( rmdir_calls, ['/srv/node/sda/containers/9999', '/srv/node/sdb/containers/9999']) finally: db_replicator.os.listdir = orig_listdir db_replicator.os.path.isdir = orig_isdir db_replicator.os.path.exists = orig_exists db_replicator.random.shuffle = orig_shuffle db_replicator.os.rmdir = orig_rmdir @mock.patch("swift.common.db_replicator.ReplConnection", mock.Mock()) def test_http_connect(self): node = "node" partition = "partition" db_file = __file__ replicator = TestReplicator({}) replicator._http_connect(node, partition, db_file) db_replicator.ReplConnection.assert_has_calls( mock.call(node, partition, os.path.basename(db_file).split('.', 1)[0], replicator.logger)) class TestReplToNode(unittest.TestCase): def setUp(self): db_replicator.ring = FakeRing() self.delete_db_calls = [] self.broker = FakeBroker() self.replicator = TestReplicator({}) self.fake_node = {'ip': '127.0.0.1', 'device': 'sda1', 'port': 1000} self.fake_info = {'id': 'a', 'point': -1, 'max_row': 10, 'hash': 'b', 'created_at': 100, 'put_timestamp': 0, 'delete_timestamp': 0, 'count': 0, 'metadata': { 'Test': ('Value', normalize_timestamp(1))}} self.replicator.logger = mock.Mock() self.replicator._rsync_db = mock.Mock(return_value=True) self.replicator._usync_db = mock.Mock(return_value=True) self.http = ReplHttp('{"id": 3, "point": -1}') self.replicator._http_connect = lambda *args: self.http def test_repl_to_node_usync_success(self): rinfo = {"id": 3, "point": -1, "max_row": 5, "hash": "c"} self.http = ReplHttp(simplejson.dumps(rinfo)) local_sync = self.broker.get_sync() self.assertEquals(self.replicator._repl_to_node( self.fake_node, self.broker, '0', self.fake_info), True) self.replicator._usync_db.assert_has_calls([ mock.call(max(rinfo['point'], local_sync), self.broker, self.http, rinfo['id'], self.fake_info['id']) ]) def test_repl_to_node_rsync_success(self): rinfo = {"id": 3, "point": -1, "max_row": 4, "hash": "c"} self.http = ReplHttp(simplejson.dumps(rinfo)) self.broker.get_sync() self.assertEquals(self.replicator._repl_to_node( self.fake_node, self.broker, '0', self.fake_info), True) self.replicator.logger.increment.assert_has_calls([ mock.call.increment('remote_merges') ]) self.replicator._rsync_db.assert_has_calls([ mock.call(self.broker, self.fake_node, self.http, self.fake_info['id'], replicate_method='rsync_then_merge', replicate_timeout=(self.fake_info['count'] / 2000), different_region=False) ]) def test_repl_to_node_already_in_sync(self): rinfo = {"id": 3, "point": -1, "max_row": 10, "hash": "b"} self.http = ReplHttp(simplejson.dumps(rinfo)) self.broker.get_sync() self.assertEquals(self.replicator._repl_to_node( self.fake_node, self.broker, '0', self.fake_info), True) self.assertEquals(self.replicator._rsync_db.call_count, 0) self.assertEquals(self.replicator._usync_db.call_count, 0) def test_repl_to_node_not_found(self): self.http = ReplHttp('{"id": 3, "point": -1}', set_status=404) self.assertEquals(self.replicator._repl_to_node( self.fake_node, self.broker, '0', self.fake_info, False), True) self.replicator.logger.increment.assert_has_calls([ mock.call.increment('rsyncs') ]) self.replicator._rsync_db.assert_has_calls([ mock.call(self.broker, self.fake_node, self.http, self.fake_info['id'], different_region=False) ]) def test_repl_to_node_drive_not_mounted(self): self.http = ReplHttp('{"id": 3, "point": -1}', set_status=507) self.assertRaises(DriveNotMounted, self.replicator._repl_to_node, self.fake_node, FakeBroker(), '0', self.fake_info) def test_repl_to_node_300_status(self): self.http = ReplHttp('{"id": 3, "point": -1}', set_status=300) self.assertEquals(self.replicator._repl_to_node( self.fake_node, FakeBroker(), '0', self.fake_info), None) def test_repl_to_node_not_response(self): self.http = mock.Mock(replicate=mock.Mock(return_value=None)) self.assertEquals(self.replicator._repl_to_node( self.fake_node, FakeBroker(), '0', self.fake_info), False) class FakeHTTPResponse(object): def __init__(self, resp): self.resp = resp @property def status(self): return self.resp.status_int @property def data(self): return self.resp.body def attach_fake_replication_rpc(rpc, replicate_hook=None): class FakeReplConnection(object): def __init__(self, node, partition, hash_, logger): self.logger = logger self.node = node self.partition = partition self.path = '/%s/%s/%s' % (node['device'], partition, hash_) self.host = node['replication_ip'] def replicate(self, op, *sync_args): print 'REPLICATE: %s, %s, %r' % (self.path, op, sync_args) replicate_args = self.path.lstrip('/').split('/') args = [op] + list(sync_args) swob_response = rpc.dispatch(replicate_args, args) resp = FakeHTTPResponse(swob_response) if replicate_hook: replicate_hook(op, *sync_args) return resp return FakeReplConnection class ExampleReplicator(db_replicator.Replicator): server_type = 'fake' brokerclass = ExampleBroker datadir = 'fake' default_port = 1000 class TestReplicatorSync(unittest.TestCase): # override in subclass backend = ExampleReplicator.brokerclass datadir = ExampleReplicator.datadir replicator_daemon = ExampleReplicator replicator_rpc = db_replicator.ReplicatorRpc def setUp(self): self.root = mkdtemp() self.rpc = self.replicator_rpc( self.root, self.datadir, self.backend, False, logger=unit.debug_logger()) FakeReplConnection = attach_fake_replication_rpc(self.rpc) self._orig_ReplConnection = db_replicator.ReplConnection db_replicator.ReplConnection = FakeReplConnection self._orig_Ring = db_replicator.ring.Ring self._ring = unit.FakeRing() db_replicator.ring.Ring = lambda *args, **kwargs: self._get_ring() self.logger = unit.debug_logger() def tearDown(self): db_replicator.ReplConnection = self._orig_ReplConnection db_replicator.ring.Ring = self._orig_Ring rmtree(self.root) def _get_ring(self): return self._ring def _get_broker(self, account, container=None, node_index=0): hash_ = hash_path(account, container) part, nodes = self._ring.get_nodes(account, container) drive = nodes[node_index]['device'] db_path = os.path.join(self.root, drive, storage_directory(self.datadir, part, hash_), hash_ + '.db') return self.backend(db_path, account=account, container=container) def _get_broker_part_node(self, broker): part, nodes = self._ring.get_nodes(broker.account, broker.container) storage_dir = broker.db_file[len(self.root):].lstrip(os.path.sep) broker_device = storage_dir.split(os.path.sep, 1)[0] for node in nodes: if node['device'] == broker_device: return part, node def _get_daemon(self, node, conf_updates): conf = { 'devices': self.root, 'recon_cache_path': self.root, 'mount_check': 'false', 'bind_port': node['replication_port'], } if conf_updates: conf.update(conf_updates) return self.replicator_daemon(conf, logger=self.logger) def _run_once(self, node, conf_updates=None, daemon=None): daemon = daemon or self._get_daemon(node, conf_updates) def _rsync_file(db_file, remote_file, **kwargs): remote_server, remote_path = remote_file.split('/', 1) dest_path = os.path.join(self.root, remote_path) copy(db_file, dest_path) return True daemon._rsync_file = _rsync_file with mock.patch('swift.common.db_replicator.whataremyips', new=lambda: [node['replication_ip']]): daemon.run_once() return daemon def test_local_ids(self): for drive in ('sda', 'sdb', 'sdd'): os.makedirs(os.path.join(self.root, drive, self.datadir)) for node in self._ring.devs: daemon = self._run_once(node) if node['device'] == 'sdc': self.assertEqual(daemon._local_device_ids, set()) else: self.assertEqual(daemon._local_device_ids, set([node['id']])) def test_clean_up_after_deleted_brokers(self): broker = self._get_broker('a', 'c', node_index=0) part, node = self._get_broker_part_node(broker) part = str(part) daemon = self._run_once(node) # create a super old broker and delete it! forever_ago = time.time() - daemon.reclaim_age put_timestamp = normalize_timestamp(forever_ago - 2) delete_timestamp = normalize_timestamp(forever_ago - 1) broker.initialize(put_timestamp) broker.delete_db(delete_timestamp) # if we have a container broker make sure it's reported if hasattr(broker, 'reported'): info = broker.get_info() broker.reported(info['put_timestamp'], info['delete_timestamp'], info['object_count'], info['bytes_used']) info = broker.get_replication_info() self.assertTrue(daemon.report_up_to_date(info)) # we have a part dir part_root = os.path.join(self.root, node['device'], self.datadir) parts = os.listdir(part_root) self.assertEqual([part], parts) # with a single suffix suff = os.listdir(os.path.join(part_root, part)) self.assertEqual(1, len(suff)) # running replicator will remove the deleted db daemon = self._run_once(node, daemon=daemon) self.assertEqual(1, daemon.stats['remove']) # we still have a part dir (but it's empty) suff = os.listdir(os.path.join(part_root, part)) self.assertEqual(0, len(suff)) # run it again and there's nothing to do... daemon = self._run_once(node, daemon=daemon) self.assertEqual(0, daemon.stats['attempted']) # but empty part dir is cleaned up! parts = os.listdir(part_root) self.assertEqual(0, len(parts)) if __name__ == '__main__': unittest.main()
apache-2.0
P1start/rust
src/librustc/middle/typeck/collect.rs
92687
// Copyright 2012-2014 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. /* # Collect phase The collect phase of type check has the job of visiting all items, determining their type, and writing that type into the `tcx.tcache` table. Despite its name, this table does not really operate as a *cache*, at least not for the types of items defined within the current crate: we assume that after the collect phase, the types of all local items will be present in the table. Unlike most of the types that are present in Rust, the types computed for each item are in fact polytypes. In "layman's terms", this means that they are generic types that may have type parameters (more mathematically phrased, they are universally quantified over a set of type parameters). Polytypes are represented by an instance of `ty::Polytype`. This combines the core type along with a list of the bounds for each parameter. Type parameters themselves are represented as `ty_param()` instances. */ use metadata::csearch; use middle::def; use middle::lang_items::SizedTraitLangItem; use middle::resolve_lifetime; use middle::subst; use middle::subst::{Substs}; use middle::ty::{ImplContainer, ImplOrTraitItemContainer, TraitContainer}; use middle::ty::{Polytype}; use middle::ty; use middle::ty_fold::TypeFolder; use middle::typeck::astconv::{AstConv, ty_of_arg}; use middle::typeck::astconv::{ast_ty_to_ty, ast_region_to_region}; use middle::typeck::astconv; use middle::typeck::infer; use middle::typeck::rscope::*; use middle::typeck::{CrateCtxt, lookup_def_tcx, no_params, write_ty_to_tcx}; use middle::typeck; use util::ppaux; use util::ppaux::{Repr,UserString}; use std::collections::{HashMap, HashSet}; use std::rc::Rc; use syntax::abi; use syntax::ast; use syntax::ast_map; use syntax::ast_util::{local_def, PostExpansionMethod}; use syntax::codemap::Span; use syntax::parse::token::{special_idents}; use syntax::parse::token; use syntax::print::pprust::{path_to_string}; use syntax::ptr::P; use syntax::visit; /////////////////////////////////////////////////////////////////////////// // Main entry point pub fn collect_item_types(ccx: &CrateCtxt) { fn collect_intrinsic_type(ccx: &CrateCtxt, lang_item: ast::DefId) { let ty::Polytype { ty: ty, .. } = ccx.get_item_ty(lang_item); ccx.tcx.intrinsic_defs.borrow_mut().insert(lang_item, ty); } match ccx.tcx.lang_items.ty_desc() { Some(id) => { collect_intrinsic_type(ccx, id); } None => {} } match ccx.tcx.lang_items.opaque() { Some(id) => { collect_intrinsic_type(ccx, id); } None => {} } let mut visitor = CollectTraitDefVisitor{ ccx: ccx }; visit::walk_crate(&mut visitor, ccx.tcx.map.krate()); let mut visitor = CollectItemTypesVisitor{ ccx: ccx }; visit::walk_crate(&mut visitor, ccx.tcx.map.krate()); } /////////////////////////////////////////////////////////////////////////// // First phase: just collect *trait definitions* -- basically, the set // of type parameters and supertraits. This is information we need to // know later when parsing field defs. struct CollectTraitDefVisitor<'a, 'tcx: 'a> { ccx: &'a CrateCtxt<'a, 'tcx> } impl<'a, 'tcx, 'v> visit::Visitor<'v> for CollectTraitDefVisitor<'a, 'tcx> { fn visit_item(&mut self, i: &ast::Item) { match i.node { ast::ItemTrait(..) => { // computing the trait def also fills in the table let _ = trait_def_of_item(self.ccx, i); } _ => { } } visit::walk_item(self, i); } } /////////////////////////////////////////////////////////////////////////// // Second phase: collection proper. struct CollectItemTypesVisitor<'a, 'tcx: 'a> { ccx: &'a CrateCtxt<'a, 'tcx> } impl<'a, 'tcx, 'v> visit::Visitor<'v> for CollectItemTypesVisitor<'a, 'tcx> { fn visit_item(&mut self, i: &ast::Item) { convert(self.ccx, i); visit::walk_item(self, i); } fn visit_foreign_item(&mut self, i: &ast::ForeignItem) { convert_foreign(self.ccx, i); visit::walk_foreign_item(self, i); } } /////////////////////////////////////////////////////////////////////////// // Utility types and common code for the above passes. pub trait ToTy { fn to_ty<RS:RegionScope>(&self, rs: &RS, ast_ty: &ast::Ty) -> ty::t; } impl<'a,'tcx> ToTy for ImplCtxt<'a,'tcx> { fn to_ty<RS:RegionScope>(&self, rs: &RS, ast_ty: &ast::Ty) -> ty::t { ast_ty_to_ty(self, rs, ast_ty) } } impl<'a,'tcx> ToTy for CrateCtxt<'a,'tcx> { fn to_ty<RS:RegionScope>(&self, rs: &RS, ast_ty: &ast::Ty) -> ty::t { ast_ty_to_ty(self, rs, ast_ty) } } impl<'a, 'tcx> AstConv<'tcx> for CrateCtxt<'a, 'tcx> { fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { self.tcx } fn get_item_ty(&self, id: ast::DefId) -> ty::Polytype { if id.krate != ast::LOCAL_CRATE { return csearch::get_type(self.tcx, id) } match self.tcx.map.find(id.node) { Some(ast_map::NodeItem(item)) => ty_of_item(self, &*item), Some(ast_map::NodeForeignItem(foreign_item)) => { let abi = self.tcx.map.get_foreign_abi(id.node); ty_of_foreign_item(self, &*foreign_item, abi) } Some(ast_map::NodeTraitItem(trait_item)) => { ty_of_trait_item(self, &*trait_item) } x => { self.tcx.sess.bug(format!("unexpected sort of node \ in get_item_ty(): {:?}", x).as_slice()); } } } fn get_trait_def(&self, id: ast::DefId) -> Rc<ty::TraitDef> { get_trait_def(self, id) } fn ty_infer(&self, span: Span) -> ty::t { span_err!(self.tcx.sess, span, E0121, "the type placeholder `_` is not allowed within types on item signatures."); ty::mk_err() } fn associated_types_of_trait_are_valid(&self, _: ty::t, _: ast::DefId) -> bool { false } fn associated_type_binding(&self, span: Span, _: Option<ty::t>, _: ast::DefId, _: ast::DefId) -> ty::t { self.tcx().sess.span_err(span, "associated types may not be \ referenced here"); ty::mk_err() } } pub fn get_enum_variant_types(ccx: &CrateCtxt, enum_ty: ty::t, variants: &[P<ast::Variant>], generics: &ast::Generics) { let tcx = ccx.tcx; // Create a set of parameter types shared among all the variants. for variant in variants.iter() { // Nullary enum constructors get turned into constants; n-ary enum // constructors get turned into functions. let scope = variant.node.id; let result_ty = match variant.node.kind { ast::TupleVariantKind(ref args) if args.len() > 0 => { let rs = ExplicitRscope; let input_tys: Vec<_> = args.iter().map(|va| ccx.to_ty(&rs, &*va.ty)).collect(); ty::mk_ctor_fn(tcx, scope, input_tys.as_slice(), enum_ty) } ast::TupleVariantKind(_) => { enum_ty } ast::StructVariantKind(ref struct_def) => { let pty = Polytype { generics: ty_generics_for_type( ccx, generics, DontCreateTypeParametersForAssociatedTypes), ty: enum_ty }; convert_struct(ccx, &**struct_def, pty, variant.node.id); let input_tys: Vec<_> = struct_def.fields.iter().map( |f| ty::node_id_to_type(ccx.tcx, f.node.id)).collect(); ty::mk_ctor_fn(tcx, scope, input_tys.as_slice(), enum_ty) } }; let pty = Polytype { generics: ty_generics_for_type( ccx, generics, DontCreateTypeParametersForAssociatedTypes), ty: result_ty }; tcx.tcache.borrow_mut().insert(local_def(variant.node.id), pty); write_ty_to_tcx(tcx, variant.node.id, result_ty); } } fn collect_trait_methods(ccx: &CrateCtxt, trait_id: ast::NodeId, trait_def: &ty::TraitDef) { let tcx = ccx.tcx; match tcx.map.get(trait_id) { ast_map::NodeItem(item) => { match item.node { ast::ItemTrait(_, _, _, ref trait_items) => { // For each method, construct a suitable ty::Method and // store it into the `tcx.impl_or_trait_items` table: for trait_item in trait_items.iter() { match *trait_item { ast::RequiredMethod(_) | ast::ProvidedMethod(_) => { let ty_method = Rc::new(match *trait_item { ast::RequiredMethod(ref m) => { ty_method_of_trait_method( ccx, trait_id, &trait_def.generics, trait_items.as_slice(), &m.id, &m.ident, &m.explicit_self, m.abi, &m.generics, &m.fn_style, &*m.decl) } ast::ProvidedMethod(ref m) => { ty_method_of_trait_method( ccx, trait_id, &trait_def.generics, trait_items.as_slice(), &m.id, &m.pe_ident(), m.pe_explicit_self(), m.pe_abi(), m.pe_generics(), &m.pe_fn_style(), &*m.pe_fn_decl()) } ast::TypeTraitItem(ref at) => { tcx.sess.span_bug(at.span, "there shouldn't \ be a type trait \ item here") } }); if ty_method.explicit_self == ty::StaticExplicitSelfCategory { make_static_method_ty(ccx, &*ty_method); } tcx.impl_or_trait_items .borrow_mut() .insert(ty_method.def_id, ty::MethodTraitItem(ty_method)); } ast::TypeTraitItem(ref ast_associated_type) => { let trait_did = local_def(trait_id); let associated_type = ty::AssociatedType { ident: ast_associated_type.ident, vis: ast::Public, def_id: local_def(ast_associated_type.id), container: TraitContainer(trait_did), }; let trait_item = ty::TypeTraitItem(Rc::new( associated_type)); tcx.impl_or_trait_items .borrow_mut() .insert(associated_type.def_id, trait_item); } } } // Add an entry mapping let trait_item_def_ids = Rc::new(trait_items.iter() .map(|ti| { match *ti { ast::RequiredMethod(ref ty_method) => { ty::MethodTraitItemId(local_def( ty_method.id)) } ast::ProvidedMethod(ref method) => { ty::MethodTraitItemId(local_def( method.id)) } ast::TypeTraitItem(ref typedef) => { ty::TypeTraitItemId(local_def(typedef.id)) } } }).collect()); let trait_def_id = local_def(trait_id); tcx.trait_item_def_ids.borrow_mut() .insert(trait_def_id, trait_item_def_ids); } _ => {} // Ignore things that aren't traits. } } _ => { /* Ignore things that aren't traits */ } } fn make_static_method_ty(ccx: &CrateCtxt, m: &ty::Method) { ccx.tcx.tcache.borrow_mut().insert( m.def_id, Polytype { generics: m.generics.clone(), ty: ty::mk_bare_fn(ccx.tcx, m.fty.clone()) }); } fn ty_method_of_trait_method(ccx: &CrateCtxt, trait_id: ast::NodeId, trait_generics: &ty::Generics, trait_items: &[ast::TraitItem], m_id: &ast::NodeId, m_ident: &ast::Ident, m_explicit_self: &ast::ExplicitSelf, m_abi: abi::Abi, m_generics: &ast::Generics, m_fn_style: &ast::FnStyle, m_decl: &ast::FnDecl) -> ty::Method { let ty_generics = ty_generics_for_fn_or_method( ccx, m_generics, (*trait_generics).clone(), DontCreateTypeParametersForAssociatedTypes); let (fty, explicit_self_category) = { let tmcx = TraitMethodCtxt { ccx: ccx, trait_id: local_def(trait_id), trait_items: trait_items.as_slice(), method_generics: &ty_generics, }; let trait_self_ty = ty::mk_self_type(tmcx.tcx(), local_def(trait_id)); astconv::ty_of_method(&tmcx, *m_id, *m_fn_style, trait_self_ty, m_explicit_self, m_decl, m_abi) }; ty::Method::new( *m_ident, ty_generics, fty, explicit_self_category, // assume public, because this is only invoked on trait methods ast::Public, local_def(*m_id), TraitContainer(local_def(trait_id)), None ) } } pub fn convert_field(ccx: &CrateCtxt, struct_generics: &ty::Generics, v: &ast::StructField, origin: ast::DefId) -> ty::field_ty { let tt = ccx.to_ty(&ExplicitRscope, &*v.node.ty); write_ty_to_tcx(ccx.tcx, v.node.id, tt); /* add the field to the tcache */ ccx.tcx.tcache.borrow_mut().insert(local_def(v.node.id), ty::Polytype { generics: struct_generics.clone(), ty: tt }); match v.node.kind { ast::NamedField(ident, visibility) => { ty::field_ty { name: ident.name, id: local_def(v.node.id), vis: visibility, origin: origin, } } ast::UnnamedField(visibility) => { ty::field_ty { name: special_idents::unnamed_field.name, id: local_def(v.node.id), vis: visibility, origin: origin, } } } } fn convert_associated_type(ccx: &CrateCtxt, trait_def: &ty::TraitDef, associated_type: &ast::AssociatedType) -> ty::Polytype { // Find the type parameter ID corresponding to this // associated type. let type_parameter_def = trait_def.generics .types .get_slice(subst::TypeSpace) .iter() .find(|def| { def.def_id == local_def(associated_type.id) }); let type_parameter_def = match type_parameter_def { Some(type_parameter_def) => type_parameter_def, None => { ccx.tcx().sess.span_bug(associated_type.span, "`convert_associated_type()` didn't find \ a type parameter ID corresponding to \ this type") } }; let param_type = ty::mk_param(ccx.tcx, subst::TypeSpace, type_parameter_def.index, local_def(associated_type.id)); ccx.tcx.tcache.borrow_mut().insert(local_def(associated_type.id), Polytype { generics: ty::Generics::empty(), ty: param_type, }); write_ty_to_tcx(ccx.tcx, associated_type.id, param_type); let associated_type = Rc::new(ty::AssociatedType { ident: associated_type.ident, vis: ast::Public, def_id: local_def(associated_type.id), container: TraitContainer(trait_def.trait_ref.def_id), }); ccx.tcx .impl_or_trait_items .borrow_mut() .insert(associated_type.def_id, ty::TypeTraitItem(associated_type)); Polytype { generics: ty::Generics::empty(), ty: param_type, } } enum ConvertMethodContext<'a> { /// Used when converting implementation methods. ImplConvertMethodContext, /// Used when converting method signatures. The def ID is the def ID of /// the trait we're translating. TraitConvertMethodContext(ast::DefId, &'a [ast::TraitItem]), } fn convert_methods<'a,I>(ccx: &CrateCtxt, convert_method_context: ConvertMethodContext, container: ImplOrTraitItemContainer, mut ms: I, untransformed_rcvr_ty: ty::t, rcvr_ty_generics: &ty::Generics, rcvr_visibility: ast::Visibility) where I: Iterator<&'a ast::Method> { debug!("convert_methods(untransformed_rcvr_ty={}, \ rcvr_ty_generics={})", untransformed_rcvr_ty.repr(ccx.tcx), rcvr_ty_generics.repr(ccx.tcx)); let tcx = ccx.tcx; let mut seen_methods = HashSet::new(); for m in ms { if !seen_methods.insert(m.pe_ident().repr(tcx)) { tcx.sess.span_err(m.span, "duplicate method in trait impl"); } let mty = Rc::new(ty_of_method(ccx, convert_method_context, container, m, untransformed_rcvr_ty, rcvr_ty_generics, rcvr_visibility)); let fty = ty::mk_bare_fn(tcx, mty.fty.clone()); debug!("method {} (id {}) has type {}", m.pe_ident().repr(tcx), m.id, fty.repr(tcx)); tcx.tcache.borrow_mut().insert( local_def(m.id), Polytype { generics: mty.generics.clone(), ty: fty }); write_ty_to_tcx(tcx, m.id, fty); debug!("writing method type: def_id={} mty={}", mty.def_id, mty.repr(ccx.tcx)); tcx.impl_or_trait_items .borrow_mut() .insert(mty.def_id, ty::MethodTraitItem(mty)); } fn ty_of_method(ccx: &CrateCtxt, convert_method_context: ConvertMethodContext, container: ImplOrTraitItemContainer, m: &ast::Method, untransformed_rcvr_ty: ty::t, rcvr_ty_generics: &ty::Generics, rcvr_visibility: ast::Visibility) -> ty::Method { // FIXME(pcwalton): Hack until we have syntax in stage0 for snapshots. let real_abi = match container { ty::TraitContainer(trait_id) => { if ccx.tcx.lang_items.fn_trait() == Some(trait_id) || ccx.tcx.lang_items.fn_mut_trait() == Some(trait_id) || ccx.tcx.lang_items.fn_once_trait() == Some(trait_id) { abi::RustCall } else { m.pe_abi() } } _ => m.pe_abi(), }; let m_ty_generics = ty_generics_for_fn_or_method( ccx, m.pe_generics(), (*rcvr_ty_generics).clone(), CreateTypeParametersForAssociatedTypes); let (fty, explicit_self_category) = match convert_method_context { ImplConvertMethodContext => { let imcx = ImplMethodCtxt { ccx: ccx, method_generics: &m_ty_generics, }; astconv::ty_of_method(&imcx, m.id, m.pe_fn_style(), untransformed_rcvr_ty, m.pe_explicit_self(), &*m.pe_fn_decl(), real_abi) } TraitConvertMethodContext(trait_id, trait_items) => { let tmcx = TraitMethodCtxt { ccx: ccx, trait_id: trait_id, trait_items: trait_items, method_generics: &m_ty_generics, }; astconv::ty_of_method(&tmcx, m.id, m.pe_fn_style(), untransformed_rcvr_ty, m.pe_explicit_self(), &*m.pe_fn_decl(), real_abi) } }; // if the method specifies a visibility, use that, otherwise // inherit the visibility from the impl (so `foo` in `pub impl // { fn foo(); }` is public, but private in `priv impl { fn // foo(); }`). let method_vis = m.pe_vis().inherit_from(rcvr_visibility); ty::Method::new(m.pe_ident(), m_ty_generics, fty, explicit_self_category, method_vis, local_def(m.id), container, None) } } pub fn ensure_no_ty_param_bounds(ccx: &CrateCtxt, span: Span, generics: &ast::Generics, thing: &'static str) { for ty_param in generics.ty_params.iter() { let bounds = ty_param.bounds.iter(); let mut bounds = bounds.chain(ty_param.unbound.iter()); for bound in bounds { match *bound { ast::TraitTyParamBound(..) | ast::UnboxedFnTyParamBound(..) => { // According to accepted RFC #XXX, we should // eventually accept these, but it will not be // part of this PR. Still, convert to warning to // make bootstrapping easier. span_warn!(ccx.tcx.sess, span, E0122, "trait bounds are not (yet) enforced \ in {} definitions", thing); } ast::RegionTyParamBound(..) => { } } } } } fn is_associated_type_valid_for_param(ty: ty::t, trait_id: ast::DefId, generics: &ty::Generics) -> bool { match ty::get(ty).sty { ty::ty_param(param_ty) => { let type_parameter = generics.types.get(param_ty.space, param_ty.idx); for trait_bound in type_parameter.bounds.trait_bounds.iter() { if trait_bound.def_id == trait_id { return true } } } _ => {} } false } fn find_associated_type_in_generics(tcx: &ty::ctxt, span: Span, ty: Option<ty::t>, associated_type_id: ast::DefId, generics: &ty::Generics) -> ty::t { let ty = match ty { None => { tcx.sess.span_bug(span, "find_associated_type_in_generics(): no self \ type") } Some(ty) => ty, }; match ty::get(ty).sty { ty::ty_param(ref param_ty) => { /*let type_parameter = generics.types.get(param_ty.space, param_ty.idx); let param_id = type_parameter.def_id;*/ let param_id = param_ty.def_id; for type_parameter in generics.types.iter() { if type_parameter.def_id == associated_type_id && type_parameter.associated_with == Some(param_id) { return ty::mk_param_from_def(tcx, type_parameter) } } tcx.sess.span_bug(span, "find_associated_type_in_generics(): didn't \ find associated type anywhere in the generics \ list") } _ => { tcx.sess.span_bug(span, "find_associated_type_in_generics(): self type \ is not a parameter") } } } fn type_is_self(ty: ty::t) -> bool { match ty::get(ty).sty { ty::ty_param(ref param_ty) if param_ty.is_self() => true, _ => false, } } struct ImplCtxt<'a,'tcx:'a> { ccx: &'a CrateCtxt<'a,'tcx>, opt_trait_ref_id: Option<ast::DefId>, impl_items: &'a [ast::ImplItem], impl_generics: &'a ty::Generics, } impl<'a,'tcx> AstConv<'tcx> for ImplCtxt<'a,'tcx> { fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { self.ccx.tcx } fn get_item_ty(&self, id: ast::DefId) -> ty::Polytype { self.ccx.get_item_ty(id) } fn get_trait_def(&self, id: ast::DefId) -> Rc<ty::TraitDef> { self.ccx.get_trait_def(id) } fn ty_infer(&self, span: Span) -> ty::t { self.ccx.ty_infer(span) } fn associated_types_of_trait_are_valid(&self, ty: ty::t, trait_id: ast::DefId) -> bool { // OK if the trait with the associated type is the trait we're // implementing. match self.opt_trait_ref_id { Some(trait_ref_id) if trait_ref_id == trait_id => { if type_is_self(ty) { return true } } Some(_) | None => {} } // OK if the trait with the associated type is one of the traits in // our bounds. is_associated_type_valid_for_param(ty, trait_id, self.impl_generics) } fn associated_type_binding(&self, span: Span, ty: Option<ty::t>, trait_id: ast::DefId, associated_type_id: ast::DefId) -> ty::t { ensure_associated_types(self, trait_id); let associated_type_ids = ty::associated_types_for_trait(self.ccx.tcx, trait_id); match self.opt_trait_ref_id { Some(trait_ref_id) if trait_ref_id == trait_id => { // It's an associated type on the trait that we're // implementing. let associated_type_id = associated_type_ids.iter() .find(|id| { id.def_id == associated_type_id }) .expect("associated_type_binding(): \ expected associated type ID \ in trait"); let associated_type = ty::impl_or_trait_item(self.ccx.tcx, associated_type_id.def_id); for impl_item in self.impl_items.iter() { match *impl_item { ast::MethodImplItem(_) => {} ast::TypeImplItem(ref typedef) => { if associated_type.ident().name == typedef.ident .name { return self.ccx.to_ty(&ExplicitRscope, &*typedef.typ) } } } } self.ccx .tcx .sess .span_bug(span, "ImplCtxt::associated_type_binding(): didn't \ find associated type") } Some(_) | None => {} } // OK then, it should be an associated type on one of the traits in // our bounds. find_associated_type_in_generics(self.ccx.tcx, span, ty, associated_type_id, self.impl_generics) } } struct FnCtxt<'a,'tcx:'a> { ccx: &'a CrateCtxt<'a,'tcx>, generics: &'a ty::Generics, } impl<'a,'tcx> AstConv<'tcx> for FnCtxt<'a,'tcx> { fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { self.ccx.tcx } fn get_item_ty(&self, id: ast::DefId) -> ty::Polytype { self.ccx.get_item_ty(id) } fn get_trait_def(&self, id: ast::DefId) -> Rc<ty::TraitDef> { self.ccx.get_trait_def(id) } fn ty_infer(&self, span: Span) -> ty::t { self.ccx.ty_infer(span) } fn associated_types_of_trait_are_valid(&self, ty: ty::t, trait_id: ast::DefId) -> bool { // OK if the trait with the associated type is one of the traits in // our bounds. is_associated_type_valid_for_param(ty, trait_id, self.generics) } fn associated_type_binding(&self, span: Span, ty: Option<ty::t>, _: ast::DefId, associated_type_id: ast::DefId) -> ty::t { debug!("collect::FnCtxt::associated_type_binding()"); // The ID should map to an associated type on one of the traits in // our bounds. find_associated_type_in_generics(self.ccx.tcx, span, ty, associated_type_id, self.generics) } } struct ImplMethodCtxt<'a,'tcx:'a> { ccx: &'a CrateCtxt<'a,'tcx>, method_generics: &'a ty::Generics, } impl<'a,'tcx> AstConv<'tcx> for ImplMethodCtxt<'a,'tcx> { fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { self.ccx.tcx } fn get_item_ty(&self, id: ast::DefId) -> ty::Polytype { self.ccx.get_item_ty(id) } fn get_trait_def(&self, id: ast::DefId) -> Rc<ty::TraitDef> { self.ccx.get_trait_def(id) } fn ty_infer(&self, span: Span) -> ty::t { self.ccx.ty_infer(span) } fn associated_types_of_trait_are_valid(&self, ty: ty::t, trait_id: ast::DefId) -> bool { is_associated_type_valid_for_param(ty, trait_id, self.method_generics) } fn associated_type_binding(&self, span: Span, ty: Option<ty::t>, _: ast::DefId, associated_type_id: ast::DefId) -> ty::t { debug!("collect::ImplMethodCtxt::associated_type_binding()"); // The ID should map to an associated type on one of the traits in // our bounds. find_associated_type_in_generics(self.ccx.tcx, span, ty, associated_type_id, self.method_generics) } } struct TraitMethodCtxt<'a,'tcx:'a> { ccx: &'a CrateCtxt<'a,'tcx>, trait_id: ast::DefId, trait_items: &'a [ast::TraitItem], method_generics: &'a ty::Generics, } impl<'a,'tcx> AstConv<'tcx> for TraitMethodCtxt<'a,'tcx> { fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { self.ccx.tcx } fn get_item_ty(&self, id: ast::DefId) -> ty::Polytype { self.ccx.get_item_ty(id) } fn get_trait_def(&self, id: ast::DefId) -> Rc<ty::TraitDef> { self.ccx.get_trait_def(id) } fn ty_infer(&self, span: Span) -> ty::t { self.ccx.ty_infer(span) } fn associated_types_of_trait_are_valid(&self, ty: ty::t, trait_id: ast::DefId) -> bool { // OK if the trait with the associated type is this trait. if self.trait_id == trait_id && type_is_self(ty) { return true } // OK if the trait with the associated type is one of the traits in // our bounds. is_associated_type_valid_for_param(ty, trait_id, self.method_generics) } fn associated_type_binding(&self, span: Span, ty: Option<ty::t>, trait_id: ast::DefId, associated_type_id: ast::DefId) -> ty::t { debug!("collect::TraitMethodCtxt::associated_type_binding()"); // If this is one of our own associated types, return it. if trait_id == self.trait_id { let mut index = 0; for item in self.trait_items.iter() { match *item { ast::RequiredMethod(_) | ast::ProvidedMethod(_) => {} ast::TypeTraitItem(ref item) => { if local_def(item.id) == associated_type_id { return ty::mk_param(self.tcx(), subst::TypeSpace, index, associated_type_id) } index += 1; } } } self.ccx .tcx .sess .span_bug(span, "TraitMethodCtxt::associated_type_binding(): \ didn't find associated type anywhere in the item \ list") } // The ID should map to an associated type on one of the traits in // our bounds. find_associated_type_in_generics(self.ccx.tcx, span, ty, associated_type_id, self.method_generics) } } struct GenericsCtxt<'a,AC:'a> { chain: &'a AC, associated_types_generics: &'a ty::Generics, } impl<'a,'tcx,AC:AstConv<'tcx>> AstConv<'tcx> for GenericsCtxt<'a,AC> { fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { self.chain.tcx() } fn get_item_ty(&self, id: ast::DefId) -> ty::Polytype { self.chain.get_item_ty(id) } fn get_trait_def(&self, id: ast::DefId) -> Rc<ty::TraitDef> { self.chain.get_trait_def(id) } fn ty_infer(&self, span: Span) -> ty::t { self.chain.ty_infer(span) } fn associated_types_of_trait_are_valid(&self, ty: ty::t, trait_id: ast::DefId) -> bool { // OK if the trait with the associated type is one of the traits in // our bounds. is_associated_type_valid_for_param(ty, trait_id, self.associated_types_generics) } fn associated_type_binding(&self, span: Span, ty: Option<ty::t>, _: ast::DefId, associated_type_id: ast::DefId) -> ty::t { debug!("collect::GenericsCtxt::associated_type_binding()"); // The ID should map to an associated type on one of the traits in // our bounds. find_associated_type_in_generics(self.chain.tcx(), span, ty, associated_type_id, self.associated_types_generics) } } pub fn convert(ccx: &CrateCtxt, it: &ast::Item) { let tcx = ccx.tcx; debug!("convert: item {} with id {}", token::get_ident(it.ident), it.id); match it.node { // These don't define types. ast::ItemForeignMod(_) | ast::ItemMod(_) | ast::ItemMac(_) => {} ast::ItemEnum(ref enum_definition, ref generics) => { let pty = ty_of_item(ccx, it); write_ty_to_tcx(tcx, it.id, pty.ty); get_enum_variant_types(ccx, pty.ty, enum_definition.variants.as_slice(), generics); }, ast::ItemImpl(ref generics, ref opt_trait_ref, ref selfty, ref impl_items) => { // Create generics from the generics specified in the impl head. let ty_generics = ty_generics_for_type( ccx, generics, CreateTypeParametersForAssociatedTypes); let selfty = ccx.to_ty(&ExplicitRscope, &**selfty); write_ty_to_tcx(tcx, it.id, selfty); tcx.tcache .borrow_mut() .insert(local_def(it.id), Polytype { generics: ty_generics.clone(), ty: selfty, }); // If there is a trait reference, treat the methods as always public. // This is to work around some incorrect behavior in privacy checking: // when the method belongs to a trait, it should acquire the privacy // from the trait, not the impl. Forcing the visibility to be public // makes things sorta work. let parent_visibility = if opt_trait_ref.is_some() { ast::Public } else { it.vis }; let icx = ImplCtxt { ccx: ccx, opt_trait_ref_id: match *opt_trait_ref { None => None, Some(ref ast_trait_ref) => { Some(lookup_def_tcx(tcx, ast_trait_ref.path.span, ast_trait_ref.ref_id).def_id()) } }, impl_items: impl_items.as_slice(), impl_generics: &ty_generics, }; let mut methods = Vec::new(); for impl_item in impl_items.iter() { match *impl_item { ast::MethodImplItem(ref method) => { check_method_self_type(ccx, &BindingRscope::new(method.id), selfty, method.pe_explicit_self()); methods.push(&**method); } ast::TypeImplItem(ref typedef) => { let typ = icx.to_ty(&ExplicitRscope, &*typedef.typ); tcx.tcache .borrow_mut() .insert(local_def(typedef.id), Polytype { generics: ty::Generics::empty(), ty: typ, }); write_ty_to_tcx(ccx.tcx, typedef.id, typ); let associated_type = Rc::new(ty::AssociatedType { ident: typedef.ident, vis: typedef.vis, def_id: local_def(typedef.id), container: ty::ImplContainer(local_def(it.id)), }); tcx.impl_or_trait_items .borrow_mut() .insert(local_def(typedef.id), ty::TypeTraitItem(associated_type)); } } } convert_methods(ccx, ImplConvertMethodContext, ImplContainer(local_def(it.id)), methods.into_iter(), selfty, &ty_generics, parent_visibility); for trait_ref in opt_trait_ref.iter() { instantiate_trait_ref(&icx, trait_ref, selfty, None); } }, ast::ItemTrait(_, _, _, ref trait_methods) => { let trait_def = trait_def_of_item(ccx, it); debug!("trait_def: ident={} trait_def={}", it.ident.repr(ccx.tcx), trait_def.repr(ccx.tcx())); for trait_method in trait_methods.iter() { let self_type = ty::mk_param(ccx.tcx, subst::SelfSpace, 0, local_def(it.id)); match *trait_method { ast::RequiredMethod(ref type_method) => { let rscope = BindingRscope::new(type_method.id); check_method_self_type(ccx, &rscope, self_type, &type_method.explicit_self) } ast::ProvidedMethod(ref method) => { check_method_self_type(ccx, &BindingRscope::new(method.id), self_type, method.pe_explicit_self()) } ast::TypeTraitItem(ref associated_type) => { convert_associated_type(ccx, &*trait_def, &**associated_type); } } } // Run convert_methods on the provided methods. let untransformed_rcvr_ty = ty::mk_self_type(tcx, local_def(it.id)); let convert_method_context = TraitConvertMethodContext(local_def(it.id), trait_methods.as_slice()); convert_methods(ccx, convert_method_context, TraitContainer(local_def(it.id)), trait_methods.iter().filter_map(|m| match *m { ast::RequiredMethod(_) => None, ast::ProvidedMethod(ref m) => Some(&**m), ast::TypeTraitItem(_) => None, }), untransformed_rcvr_ty, &trait_def.generics, it.vis); // We need to do this *after* converting methods, since // convert_methods produces a tcache entry that is wrong for // static trait methods. This is somewhat unfortunate. collect_trait_methods(ccx, it.id, &*trait_def); }, ast::ItemStruct(ref struct_def, _) => { // Write the class type. let pty = ty_of_item(ccx, it); write_ty_to_tcx(tcx, it.id, pty.ty); tcx.tcache.borrow_mut().insert(local_def(it.id), pty.clone()); // Write the super-struct type, if it exists. match struct_def.super_struct { Some(ref ty) => { let supserty = ccx.to_ty(&ExplicitRscope, &**ty); write_ty_to_tcx(tcx, it.id, supserty); }, _ => {}, } convert_struct(ccx, &**struct_def, pty, it.id); }, ast::ItemTy(_, ref generics) => { ensure_no_ty_param_bounds(ccx, it.span, generics, "type"); let tpt = ty_of_item(ccx, it); write_ty_to_tcx(tcx, it.id, tpt.ty); }, _ => { // This call populates the type cache with the converted type // of the item in passing. All we have to do here is to write // it into the node type table. let pty = ty_of_item(ccx, it); write_ty_to_tcx(tcx, it.id, pty.ty); }, } } pub fn convert_struct(ccx: &CrateCtxt, struct_def: &ast::StructDef, pty: ty::Polytype, id: ast::NodeId) { let tcx = ccx.tcx; // Write the type of each of the members and check for duplicate fields. let mut seen_fields: HashMap<ast::Name, Span> = HashMap::new(); let field_tys = struct_def.fields.iter().map(|f| { let result = convert_field(ccx, &pty.generics, f, local_def(id)); if result.name != special_idents::unnamed_field.name { let dup = match seen_fields.find(&result.name) { Some(prev_span) => { span_err!(tcx.sess, f.span, E0124, "field `{}` is already declared", token::get_name(result.name)); span_note!(tcx.sess, *prev_span, "previously declared here"); true }, None => false, }; // FIXME(#6393) this whole dup thing is just to satisfy // the borrow checker :-( if !dup { seen_fields.insert(result.name, f.span); } } result }).collect(); tcx.struct_fields.borrow_mut().insert(local_def(id), Rc::new(field_tys)); let super_struct = match struct_def.super_struct { Some(ref t) => match t.node { ast::TyPath(_, _, path_id) => { let def_map = tcx.def_map.borrow(); match def_map.find(&path_id) { Some(&def::DefStruct(def_id)) => { // FIXME(#12511) Check for cycles in the inheritance hierarchy. // Check super-struct is virtual. match tcx.map.find(def_id.node) { Some(ast_map::NodeItem(i)) => match i.node { ast::ItemStruct(ref struct_def, _) => { if !struct_def.is_virtual { span_err!(tcx.sess, t.span, E0126, "struct inheritance is only \ allowed from virtual structs"); } }, _ => {}, }, _ => {}, } Some(def_id) }, _ => None, } } _ => None, }, None => None, }; tcx.superstructs.borrow_mut().insert(local_def(id), super_struct); let substs = mk_item_substs(ccx, &pty.generics); let selfty = ty::mk_struct(tcx, local_def(id), substs); // If this struct is enum-like or tuple-like, create the type of its // constructor. match struct_def.ctor_id { None => {} Some(ctor_id) => { if struct_def.fields.len() == 0 { // Enum-like. write_ty_to_tcx(tcx, ctor_id, selfty); tcx.tcache.borrow_mut().insert(local_def(ctor_id), pty); } else if struct_def.fields.get(0).node.kind.is_unnamed() { // Tuple-like. let inputs: Vec<_> = struct_def.fields.iter().map( |field| tcx.tcache.borrow().get( &local_def(field.node.id)).ty).collect(); let ctor_fn_ty = ty::mk_ctor_fn(tcx, ctor_id, inputs.as_slice(), selfty); write_ty_to_tcx(tcx, ctor_id, ctor_fn_ty); tcx.tcache.borrow_mut().insert(local_def(ctor_id), Polytype { generics: pty.generics, ty: ctor_fn_ty }); } } } } pub fn convert_foreign(ccx: &CrateCtxt, i: &ast::ForeignItem) { // As above, this call populates the type table with the converted // type of the foreign item. We simply write it into the node type // table. // For reasons I cannot fully articulate, I do so hate the AST // map, and I regard each time that I use it as a personal and // moral failing, but at the moment it seems like the only // convenient way to extract the ABI. - ndm let abi = ccx.tcx.map.get_foreign_abi(i.id); let pty = ty_of_foreign_item(ccx, i, abi); write_ty_to_tcx(ccx.tcx, i.id, pty.ty); ccx.tcx.tcache.borrow_mut().insert(local_def(i.id), pty); } pub fn instantiate_trait_ref<'tcx,AC>(this: &AC, ast_trait_ref: &ast::TraitRef, self_ty: ty::t, associated_type: Option<ty::t>) -> Rc<ty::TraitRef> where AC: AstConv<'tcx> { /*! * Instantiates the path for the given trait reference, assuming that * it's bound to a valid trait type. Returns the def_id for the defining * trait. Fails if the type is a type other than a trait type. */ // FIXME(#5121) -- distinguish early vs late lifetime params let rscope = ExplicitRscope; match lookup_def_tcx(this.tcx(), ast_trait_ref.path.span, ast_trait_ref.ref_id) { def::DefTrait(trait_did) => { let trait_ref = astconv::ast_path_to_trait_ref(this, &rscope, trait_did, Some(self_ty), associated_type, &ast_trait_ref.path); this.tcx().trait_refs.borrow_mut().insert(ast_trait_ref.ref_id, trait_ref.clone()); trait_ref } _ => { this.tcx().sess.span_fatal( ast_trait_ref.path.span, format!("`{}` is not a trait", path_to_string(&ast_trait_ref.path)).as_slice()); } } } pub fn instantiate_unboxed_fn_ty<'tcx,AC>(this: &AC, unboxed_function: &ast::UnboxedFnTy, param_ty: ty::ParamTy) -> Rc<ty::TraitRef> where AC: AstConv<'tcx> { let rscope = ExplicitRscope; let param_ty = param_ty.to_ty(this.tcx()); Rc::new(astconv::trait_ref_for_unboxed_function(this, &rscope, unboxed_function.kind, &*unboxed_function.decl, Some(param_ty))) } fn get_trait_def(ccx: &CrateCtxt, trait_id: ast::DefId) -> Rc<ty::TraitDef> { if trait_id.krate != ast::LOCAL_CRATE { return ty::lookup_trait_def(ccx.tcx, trait_id) } match ccx.tcx.map.get(trait_id.node) { ast_map::NodeItem(item) => trait_def_of_item(ccx, &*item), _ => { ccx.tcx.sess.bug(format!("get_trait_def({}): not an item", trait_id.node).as_slice()) } } } pub fn trait_def_of_item(ccx: &CrateCtxt, it: &ast::Item) -> Rc<ty::TraitDef> { let def_id = local_def(it.id); let tcx = ccx.tcx; match tcx.trait_defs.borrow().find(&def_id) { Some(def) => return def.clone(), _ => {} } let (generics, unbound, bounds, items) = match it.node { ast::ItemTrait(ref generics, ref unbound, ref supertraits, ref items) => { (generics, unbound, supertraits, items.as_slice()) } ref s => { tcx.sess.span_bug( it.span, format!("trait_def_of_item invoked on {:?}", s).as_slice()); } }; let substs = mk_trait_substs(ccx, it.id, generics, items); let ty_generics = ty_generics_for_trait(ccx, it.id, &substs, generics, items); let self_param_ty = ty::ParamTy::for_self(def_id); let bounds = compute_bounds(ccx, token::SELF_KEYWORD_NAME, self_param_ty, bounds.as_slice(), unbound, it.span, &generics.where_clause); let substs = mk_item_substs(ccx, &ty_generics); let trait_def = Rc::new(ty::TraitDef { generics: ty_generics, bounds: bounds, trait_ref: Rc::new(ty::TraitRef { def_id: def_id, substs: substs }) }); tcx.trait_defs.borrow_mut().insert(def_id, trait_def.clone()); return trait_def; fn mk_trait_substs(ccx: &CrateCtxt, trait_id: ast::NodeId, generics: &ast::Generics, items: &[ast::TraitItem]) -> subst::Substs { // Creates a no-op substitution for the trait's type parameters. let regions = generics.lifetimes .iter() .enumerate() .map(|(i, def)| ty::ReEarlyBound(def.lifetime.id, subst::TypeSpace, i, def.lifetime.name)) .collect(); // Start with the generics in the type parameters... let mut types: Vec<_> = generics.ty_params .iter() .enumerate() .map(|(i, def)| ty::mk_param(ccx.tcx, subst::TypeSpace, i, local_def(def.id))) .collect(); // ...and add generics synthesized from the associated types. for item in items.iter() { match *item { ast::TypeTraitItem(ref trait_item) => { let index = types.len(); types.push(ty::mk_param(ccx.tcx, subst::TypeSpace, index, local_def(trait_item.id))) } ast::RequiredMethod(_) | ast::ProvidedMethod(_) => {} } } let self_ty = ty::mk_param(ccx.tcx, subst::SelfSpace, 0, local_def(trait_id)); subst::Substs::new_trait(types, regions, self_ty) } } pub fn ty_of_item(ccx: &CrateCtxt, it: &ast::Item) -> ty::Polytype { let def_id = local_def(it.id); let tcx = ccx.tcx; match tcx.tcache.borrow().find(&def_id) { Some(pty) => return pty.clone(), _ => {} } match it.node { ast::ItemStatic(ref t, _, _) => { let typ = ccx.to_ty(&ExplicitRscope, &**t); let pty = no_params(typ); tcx.tcache.borrow_mut().insert(local_def(it.id), pty.clone()); return pty; } ast::ItemFn(ref decl, fn_style, abi, ref generics, _) => { let ty_generics = ty_generics_for_fn_or_method( ccx, generics, ty::Generics::empty(), CreateTypeParametersForAssociatedTypes); let tofd = { let fcx = FnCtxt { ccx: ccx, generics: &ty_generics, }; astconv::ty_of_bare_fn(&fcx, it.id, fn_style, abi, &**decl) }; let pty = Polytype { generics: ty_generics, ty: ty::mk_bare_fn(ccx.tcx, tofd) }; debug!("type of {} (id {}) is {}", token::get_ident(it.ident), it.id, pty.repr(tcx)); ccx.tcx.tcache.borrow_mut().insert(local_def(it.id), pty.clone()); return pty; } ast::ItemTy(ref t, ref generics) => { match tcx.tcache.borrow_mut().find(&local_def(it.id)) { Some(pty) => return pty.clone(), None => { } } let pty = { let ty = ccx.to_ty(&ExplicitRscope, &**t); Polytype { generics: ty_generics_for_type( ccx, generics, DontCreateTypeParametersForAssociatedTypes), ty: ty } }; tcx.tcache.borrow_mut().insert(local_def(it.id), pty.clone()); return pty; } ast::ItemEnum(_, ref generics) => { // Create a new generic polytype. let ty_generics = ty_generics_for_type( ccx, generics, DontCreateTypeParametersForAssociatedTypes); let substs = mk_item_substs(ccx, &ty_generics); let t = ty::mk_enum(tcx, local_def(it.id), substs); let pty = Polytype { generics: ty_generics, ty: t }; tcx.tcache.borrow_mut().insert(local_def(it.id), pty.clone()); return pty; } ast::ItemTrait(..) => { tcx.sess.span_bug(it.span, "invoked ty_of_item on trait"); } ast::ItemStruct(_, ref generics) => { let ty_generics = ty_generics_for_type( ccx, generics, DontCreateTypeParametersForAssociatedTypes); let substs = mk_item_substs(ccx, &ty_generics); let t = ty::mk_struct(tcx, local_def(it.id), substs); let pty = Polytype { generics: ty_generics, ty: t }; tcx.tcache.borrow_mut().insert(local_def(it.id), pty.clone()); return pty; } ast::ItemImpl(..) | ast::ItemMod(_) | ast::ItemForeignMod(_) | ast::ItemMac(_) => fail!(), } } pub fn ty_of_foreign_item(ccx: &CrateCtxt, it: &ast::ForeignItem, abi: abi::Abi) -> ty::Polytype { match it.node { ast::ForeignItemFn(ref fn_decl, ref generics) => { ty_of_foreign_fn_decl(ccx, &**fn_decl, local_def(it.id), generics, abi) } ast::ForeignItemStatic(ref t, _) => { ty::Polytype { generics: ty::Generics::empty(), ty: ast_ty_to_ty(ccx, &ExplicitRscope, &**t) } } } } fn ty_of_trait_item(ccx: &CrateCtxt, trait_item: &ast::TraitItem) -> ty::Polytype { match *trait_item { ast::RequiredMethod(ref m) => { ccx.tcx.sess.span_bug(m.span, "ty_of_trait_item() on required method") } ast::ProvidedMethod(ref m) => { ccx.tcx.sess.span_bug(m.span, "ty_of_trait_item() on provided method") } ast::TypeTraitItem(ref associated_type) => { let parent = ccx.tcx.map.get_parent(associated_type.id); let trait_def = match ccx.tcx.map.get(parent) { ast_map::NodeItem(item) => trait_def_of_item(ccx, &*item), _ => { ccx.tcx.sess.span_bug(associated_type.span, "associated type's parent wasn't \ an item?!") } }; convert_associated_type(ccx, &*trait_def, &**associated_type) } } } fn ty_generics_for_type(ccx: &CrateCtxt, generics: &ast::Generics, create_type_parameters_for_associated_types: CreateTypeParametersForAssociatedTypesFlag) -> ty::Generics { ty_generics(ccx, subst::TypeSpace, generics.lifetimes.as_slice(), generics.ty_params.as_slice(), ty::Generics::empty(), &generics.where_clause, create_type_parameters_for_associated_types) } fn ty_generics_for_trait(ccx: &CrateCtxt, trait_id: ast::NodeId, substs: &subst::Substs, generics: &ast::Generics, items: &[ast::TraitItem]) -> ty::Generics { let mut generics = ty_generics(ccx, subst::TypeSpace, generics.lifetimes.as_slice(), generics.ty_params.as_slice(), ty::Generics::empty(), &generics.where_clause, DontCreateTypeParametersForAssociatedTypes); // Add in type parameters for any associated types. for item in items.iter() { match *item { ast::TypeTraitItem(ref associated_type) => { let def = ty::TypeParameterDef { space: subst::TypeSpace, index: generics.types.len(subst::TypeSpace), ident: associated_type.ident, def_id: local_def(associated_type.id), bounds: ty::ParamBounds { builtin_bounds: ty::empty_builtin_bounds(), trait_bounds: Vec::new(), region_bounds: Vec::new(), }, associated_with: Some(local_def(trait_id)), default: None, }; ccx.tcx.ty_param_defs.borrow_mut().insert(associated_type.id, def.clone()); generics.types.push(subst::TypeSpace, def); } ast::ProvidedMethod(_) | ast::RequiredMethod(_) => {} } } // Add in the self type parameter. // // Something of a hack: use the node id for the trait, also as // the node id for the Self type parameter. let param_id = trait_id; let self_trait_ref = Rc::new(ty::TraitRef { def_id: local_def(trait_id), substs: (*substs).clone() }); let def = ty::TypeParameterDef { space: subst::SelfSpace, index: 0, ident: special_idents::type_self, def_id: local_def(param_id), bounds: ty::ParamBounds { region_bounds: vec!(), builtin_bounds: ty::empty_builtin_bounds(), trait_bounds: vec!(self_trait_ref), }, associated_with: None, default: None }; ccx.tcx.ty_param_defs.borrow_mut().insert(param_id, def.clone()); generics.types.push(subst::SelfSpace, def); generics } fn ty_generics_for_fn_or_method<'tcx,AC>( this: &AC, generics: &ast::Generics, base_generics: ty::Generics, create_type_parameters_for_associated_types: CreateTypeParametersForAssociatedTypesFlag) -> ty::Generics where AC: AstConv<'tcx> { let early_lifetimes = resolve_lifetime::early_bound_lifetimes(generics); ty_generics(this, subst::FnSpace, early_lifetimes.as_slice(), generics.ty_params.as_slice(), base_generics, &generics.where_clause, create_type_parameters_for_associated_types) } // Add the Sized bound, unless the type parameter is marked as `Sized?`. fn add_unsized_bound<'tcx,AC>(this: &AC, unbound: &Option<ast::TyParamBound>, bounds: &mut ty::BuiltinBounds, desc: &str, span: Span) where AC: AstConv<'tcx> { let kind_id = this.tcx().lang_items.require(SizedTraitLangItem); match unbound { &Some(ast::TraitTyParamBound(ref tpb)) => { // FIXME(#8559) currently requires the unbound to be built-in. let trait_def_id = ty::trait_ref_to_def_id(this.tcx(), tpb); match kind_id { Ok(kind_id) if trait_def_id != kind_id => { this.tcx().sess.span_warn(span, format!("default bound relaxed \ for a {}, but this \ does nothing because \ the given bound is not \ a default. \ Only `Sized?` is \ supported.", desc).as_slice()); ty::try_add_builtin_trait(this.tcx(), kind_id, bounds); } _ => {} } } _ if kind_id.is_ok() => { ty::try_add_builtin_trait(this.tcx(), kind_id.unwrap(), bounds); } // No lang item for Sized, so we can't add it as a bound. _ => {} } } #[deriving(Clone, PartialEq, Eq)] enum CreateTypeParametersForAssociatedTypesFlag { DontCreateTypeParametersForAssociatedTypes, CreateTypeParametersForAssociatedTypes, } fn ensure_associated_types<'tcx,AC>(this: &AC, trait_id: ast::DefId) where AC: AstConv<'tcx> { if this.tcx().trait_associated_types.borrow().contains_key(&trait_id) { return } if trait_id.krate == ast::LOCAL_CRATE { match this.tcx().map.find(trait_id.node) { Some(ast_map::NodeItem(item)) => { match item.node { ast::ItemTrait(_, _, _, ref trait_items) => { let mut result = Vec::new(); let mut index = 0; for trait_item in trait_items.iter() { match *trait_item { ast::RequiredMethod(_) | ast::ProvidedMethod(_) => {} ast::TypeTraitItem(ref associated_type) => { let info = ty::AssociatedTypeInfo { def_id: local_def(associated_type.id), index: index, ident: associated_type.ident, }; result.push(info); index += 1; } } } this.tcx() .trait_associated_types .borrow_mut() .insert(trait_id, Rc::new(result)); return } _ => { this.tcx().sess.bug("ensure_associated_types() \ called on non-trait") } } } _ => { this.tcx().sess.bug("ensure_associated_types() called on \ non-trait") } } } // Cross-crate case. let mut result = Vec::new(); let mut index = 0; let trait_items = ty::trait_items(this.tcx(), trait_id); for trait_item in trait_items.iter() { match *trait_item { ty::MethodTraitItem(_) => {} ty::TypeTraitItem(ref associated_type) => { let info = ty::AssociatedTypeInfo { def_id: associated_type.def_id, index: index, ident: associated_type.ident }; result.push(info); index += 1; } } } this.tcx().trait_associated_types.borrow_mut().insert(trait_id, Rc::new(result)); } fn ty_generics<'tcx,AC>(this: &AC, space: subst::ParamSpace, lifetime_defs: &[ast::LifetimeDef], types: &[ast::TyParam], base_generics: ty::Generics, where_clause: &ast::WhereClause, create_type_parameters_for_associated_types: CreateTypeParametersForAssociatedTypesFlag) -> ty::Generics where AC: AstConv<'tcx> { let mut result = base_generics; for (i, l) in lifetime_defs.iter().enumerate() { let bounds = l.bounds.iter() .map(|l| ast_region_to_region(this.tcx(), l)) .collect(); let def = ty::RegionParameterDef { name: l.lifetime.name, space: space, index: i, def_id: local_def(l.lifetime.id), bounds: bounds }; debug!("ty_generics: def for region param: {}", def); result.regions.push(space, def); } assert!(result.types.is_empty_in(space)); // First, create the virtual type parameters for associated types if // necessary. let mut associated_types_generics = ty::Generics::empty(); match create_type_parameters_for_associated_types { DontCreateTypeParametersForAssociatedTypes => {} CreateTypeParametersForAssociatedTypes => { let mut index = 0; for param in types.iter() { for bound in param.bounds.iter() { match *bound { ast::TraitTyParamBound(ref trait_bound) => { match lookup_def_tcx(this.tcx(), trait_bound.path.span, trait_bound.ref_id) { def::DefTrait(trait_did) => { ensure_associated_types(this, trait_did); let associated_types = ty::associated_types_for_trait( this.tcx(), trait_did); for associated_type_info in associated_types.iter() { let associated_type_trait_item = ty::impl_or_trait_item( this.tcx(), associated_type_info.def_id); let def = ty::TypeParameterDef { ident: associated_type_trait_item .ident(), def_id: associated_type_info.def_id, space: space, index: types.len() + index, bounds: ty::ParamBounds { builtin_bounds: ty::empty_builtin_bounds(), trait_bounds: Vec::new(), region_bounds: Vec::new(), }, associated_with: { Some(local_def(param.id)) }, default: None, }; associated_types_generics.types .push(space, def); index += 1; } } _ => { this.tcx().sess.span_bug(trait_bound.path .span, "not a trait?!") } } } _ => {} } } } } } // Now create the real type parameters. let gcx = GenericsCtxt { chain: this, associated_types_generics: &associated_types_generics, }; for (i, param) in types.iter().enumerate() { let def = get_or_create_type_parameter_def(&gcx, space, param, i, where_clause); debug!("ty_generics: def for type param: {}, {}", def.repr(this.tcx()), space); result.types.push(space, def); } // Append the associated types to the result. for associated_type_param in associated_types_generics.types .get_slice(space) .iter() { assert!(result.types.get_slice(space).len() == associated_type_param.index); debug!("ty_generics: def for associated type: {}, {}", associated_type_param.repr(this.tcx()), space); result.types.push(space, (*associated_type_param).clone()); } return result; fn get_or_create_type_parameter_def<'tcx,AC>( this: &AC, space: subst::ParamSpace, param: &ast::TyParam, index: uint, where_clause: &ast::WhereClause) -> ty::TypeParameterDef where AC: AstConv<'tcx> { match this.tcx().ty_param_defs.borrow().find(&param.id) { Some(d) => { return (*d).clone(); } None => { } } let param_ty = ty::ParamTy::new(space, index, local_def(param.id)); let bounds = compute_bounds(this, param.ident.name, param_ty, param.bounds.as_slice(), &param.unbound, param.span, where_clause); let default = match param.default { None => None, Some(ref path) => { let ty = ast_ty_to_ty(this, &ExplicitRscope, &**path); let cur_idx = index; ty::walk_ty(ty, |t| { match ty::get(t).sty { ty::ty_param(p) => if p.idx > cur_idx { span_err!(this.tcx().sess, path.span, E0128, "type parameters with a default cannot use \ forward declared identifiers"); }, _ => {} } }); Some(ty) } }; let def = ty::TypeParameterDef { space: space, index: index, ident: param.ident, def_id: local_def(param.id), associated_with: None, bounds: bounds, default: default }; this.tcx().ty_param_defs.borrow_mut().insert(param.id, def.clone()); def } } fn compute_bounds<'tcx,AC>(this: &AC, name_of_bounded_thing: ast::Name, param_ty: ty::ParamTy, ast_bounds: &[ast::TyParamBound], unbound: &Option<ast::TyParamBound>, span: Span, where_clause: &ast::WhereClause) -> ty::ParamBounds where AC: AstConv<'tcx> { /*! * Translate the AST's notion of ty param bounds (which are an * enum consisting of a newtyped Ty or a region) to ty's * notion of ty param bounds, which can either be user-defined * traits, or the built-in trait (formerly known as kind): Send. */ let mut param_bounds = conv_param_bounds(this, span, param_ty, ast_bounds, where_clause); add_unsized_bound(this, unbound, &mut param_bounds.builtin_bounds, "type parameter", span); check_bounds_compatible(this.tcx(), name_of_bounded_thing, &param_bounds, span); param_bounds.trait_bounds.sort_by(|a,b| a.def_id.cmp(&b.def_id)); param_bounds } fn check_bounds_compatible(tcx: &ty::ctxt, name_of_bounded_thing: ast::Name, param_bounds: &ty::ParamBounds, span: Span) { // Currently the only bound which is incompatible with other bounds is // Sized/Unsized. if !param_bounds.builtin_bounds.contains_elem(ty::BoundSized) { ty::each_bound_trait_and_supertraits( tcx, param_bounds.trait_bounds.as_slice(), |trait_ref| { let trait_def = ty::lookup_trait_def(tcx, trait_ref.def_id); if trait_def.bounds.builtin_bounds.contains_elem(ty::BoundSized) { span_err!(tcx.sess, span, E0129, "incompatible bounds on type parameter `{}`, \ bound `{}` does not allow unsized type", name_of_bounded_thing.user_string(tcx), ppaux::trait_ref_to_string(tcx, &*trait_ref)); } true }); } } fn conv_param_bounds<'tcx,AC>(this: &AC, span: Span, param_ty: ty::ParamTy, ast_bounds: &[ast::TyParamBound], where_clause: &ast::WhereClause) -> ty::ParamBounds where AC: AstConv<'tcx> { let all_bounds = merge_param_bounds(this.tcx(), param_ty, ast_bounds, where_clause); let astconv::PartitionedBounds { builtin_bounds, trait_bounds, region_bounds, unboxed_fn_ty_bounds } = astconv::partition_bounds(this.tcx(), span, all_bounds.as_slice()); let unboxed_fn_ty_bounds = unboxed_fn_ty_bounds.move_iter().map(|b| { let trait_id = this.tcx().def_map.borrow().get(&b.ref_id).def_id(); let mut kind = None; for &(lang_item, this_kind) in [ (this.tcx().lang_items.fn_trait(), ast::FnUnboxedClosureKind), (this.tcx().lang_items.fn_mut_trait(), ast::FnMutUnboxedClosureKind), (this.tcx().lang_items.fn_once_trait(), ast::FnOnceUnboxedClosureKind) ].iter() { if Some(trait_id) == lang_item { kind = Some(this_kind); break } } let kind = match kind { Some(kind) => kind, None => { this.tcx().sess.span_err(b.path.span, "unboxed function trait must be one \ of `Fn`, `FnMut`, or `FnOnce`"); ast::FnMutUnboxedClosureKind } }; let rscope = ExplicitRscope; let param_ty = param_ty.to_ty(this.tcx()); Rc::new(astconv::trait_ref_for_unboxed_function(this, &rscope, kind, &*b.decl, Some(param_ty))) }); let trait_bounds: Vec<Rc<ty::TraitRef>> = trait_bounds.into_iter() .map(|b| { instantiate_trait_ref(this, b, param_ty.to_ty(this.tcx()), Some(param_ty.to_ty(this.tcx()))) }) .chain(unboxed_fn_ty_bounds) .collect(); let region_bounds: Vec<ty::Region> = region_bounds.move_iter() .map(|r| ast_region_to_region(this.tcx(), r)) .collect(); ty::ParamBounds { region_bounds: region_bounds, builtin_bounds: builtin_bounds, trait_bounds: trait_bounds, } } fn merge_param_bounds<'a>(tcx: &ty::ctxt, param_ty: ty::ParamTy, ast_bounds: &'a [ast::TyParamBound], where_clause: &'a ast::WhereClause) -> Vec<&'a ast::TyParamBound> { /*! * Merges the bounds declared on a type parameter with those * found from where clauses into a single list. */ let mut result = Vec::new(); for ast_bound in ast_bounds.iter() { result.push(ast_bound); } for predicate in where_clause.predicates.iter() { let predicate_param_id = tcx.def_map .borrow() .find(&predicate.id) .expect("compute_bounds(): resolve didn't resolve the type \ parameter identifier in a `where` clause") .def_id(); if param_ty.def_id != predicate_param_id { continue } for bound in predicate.bounds.iter() { result.push(bound); } } result } pub fn ty_of_foreign_fn_decl(ccx: &CrateCtxt, decl: &ast::FnDecl, def_id: ast::DefId, ast_generics: &ast::Generics, abi: abi::Abi) -> ty::Polytype { for i in decl.inputs.iter() { match (*i).pat.node { ast::PatIdent(_, _, _) => (), ast::PatWild(ast::PatWildSingle) => (), _ => { span_err!(ccx.tcx.sess, (*i).pat.span, E0130, "patterns aren't allowed in foreign function declarations"); } } } let ty_generics_for_fn_or_method = ty_generics_for_fn_or_method( ccx, ast_generics, ty::Generics::empty(), DontCreateTypeParametersForAssociatedTypes); let rb = BindingRscope::new(def_id.node); let input_tys = decl.inputs .iter() .map(|a| ty_of_arg(ccx, &rb, a, None)) .collect(); let output_ty = ast_ty_to_ty(ccx, &rb, &*decl.output); let t_fn = ty::mk_bare_fn( ccx.tcx, ty::BareFnTy { abi: abi, fn_style: ast::UnsafeFn, sig: ty::FnSig {binder_id: def_id.node, inputs: input_tys, output: output_ty, variadic: decl.variadic} }); let pty = Polytype { generics: ty_generics_for_fn_or_method, ty: t_fn }; ccx.tcx.tcache.borrow_mut().insert(def_id, pty.clone()); return pty; } pub fn mk_item_substs(ccx: &CrateCtxt, ty_generics: &ty::Generics) -> subst::Substs { let types = ty_generics.types.map( |def| ty::mk_param_from_def(ccx.tcx, def)); let regions = ty_generics.regions.map( |def| ty::ReEarlyBound(def.def_id.node, def.space, def.index, def.name)); subst::Substs::new(types, regions) } /// Verifies that the explicit self type of a method matches the impl or /// trait. fn check_method_self_type<RS:RegionScope>( crate_context: &CrateCtxt, rs: &RS, required_type: ty::t, explicit_self: &ast::ExplicitSelf) { match explicit_self.node { ast::SelfExplicit(ref ast_type, _) => { let typ = crate_context.to_ty(rs, &**ast_type); let base_type = match ty::get(typ).sty { ty::ty_ptr(tm) | ty::ty_rptr(_, tm) => tm.ty, ty::ty_uniq(typ) => typ, _ => typ, }; let infcx = infer::new_infer_ctxt(crate_context.tcx); drop(typeck::require_same_types(crate_context.tcx, Some(&infcx), false, explicit_self.span, base_type, required_type, || { format!("mismatched self type: expected `{}`", ppaux::ty_to_string(crate_context.tcx, required_type)) })); infcx.resolve_regions_and_report_errors(); } _ => {} } }
apache-2.0
HewlettPackard/grommet
src/js/components/NameValueList/stories/CustomThemed/Themed.tsx
1201
import React from 'react'; import { Box, Grommet, grommet, NameValueList, NameValuePair } from 'grommet'; import { deepMerge } from 'grommet/utils'; import { ThemeType } from 'grommet/themes'; import { data } from '../data'; // Type annotations can only be used in TypeScript files. // Remove ': ThemeType' if you are not using Typescript. const customTheme: ThemeType = deepMerge(grommet, { nameValueList: { pair: { column: { gap: { column: 'large', row: 'small', }, }, }, }, nameValuePair: { name: { color: 'text', size: 'xsmall', weight: 'bold', }, value: { color: 'text', }, }, }); export const Themed = () => ( <Grommet theme={customTheme}> <Box pad="small"> <NameValueList pairProps={{ direction: 'column' }}> {Object.entries(data).map( ([name, value]: [string, string | React.ReactElement]) => ( <NameValuePair key={name} name={name}> {value} </NameValuePair> ), )} </NameValueList> </Box> </Grommet> ); export default { title: 'Visualizations/NameValueList/Custom Themed/TS-Custom', };
apache-2.0
jwausle/cmvn
de.tototec.cmvn/src/main/scala/de/tototec/cmvn/configfile/ConfigFileReader.scala
160
package de.tototec.cmvn.configfile import java.io.File import java.util.List trait ConfigFileReader { def readKeyValues(configFile: File): List[KeyValue] }
apache-2.0
apache/uima-uimaj
uimaj-cpe/src/test/java/org/apache/uima/collection/impl/TestCasInitializer.java
1359
/* * 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.uima.collection.impl; import java.io.IOException; import org.apache.uima.cas.CAS; import org.apache.uima.collection.CasInitializer_ImplBase; import org.apache.uima.collection.CollectionException; public class TestCasInitializer extends CasInitializer_ImplBase { /* * (non-Javadoc) * * @see org.apache.uima.collection.CasInitializer#initializeCas(java.lang.Object, * org.apache.uima.cas.CAS) */ @Override public void initializeCas(Object aObj, CAS aCAS) throws CollectionException, IOException { } }
apache-2.0
davidkarlsen/camel
components/camel-http4/src/test/java/org/apache/camel/component/http4/AdviceAndInterceptHttp4IssueTest.java
3324
/* * 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.camel.component.http4; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.AdviceWithRouteBuilder; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.reifier.RouteReifier; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; /** * */ public class AdviceAndInterceptHttp4IssueTest extends CamelTestSupport { private String simpleProvider = "http4:fakeHTTPADDRESS.com:80?throwExceptionOnFailure=false"; private String providerWithParameter = "http4:fakeHTTPADDRESS.com:80?throwExceptionOnFailure=false&httpClient.cookieSpec=ignoreCookies"; private volatile boolean messageIntercepted; @Test public void testHttp4WithoutHttpClientParameter() throws Exception { doTestHttp4Parameter(simpleProvider); } @Test public void testHttp4WithHttpClientParameter() throws Exception { doTestHttp4Parameter(providerWithParameter); } @Override public boolean isUseAdviceWith() { return true; } @Override public boolean isUseRouteBuilder() { return true; } private void doTestHttp4Parameter(final String provider) throws Exception { messageIntercepted = false; context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") .to(provider) .to("mock:result"); } }); RouteReifier.adviceWith(context.getRouteDefinitions().get(0), context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { interceptSendToEndpoint("http4:fakeHTTPADDRESS.com:80*") .skipSendToOriginalEndpoint() .process(new Processor() { @Override public void process(Exchange exchange) throws Exception { messageIntercepted = true; } }) .to("mock:advised"); } }); context.start(); getMockEndpoint("mock:advised").expectedMessageCount(1); getMockEndpoint("mock:result").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); assertTrue(messageIntercepted); } }
apache-2.0
mschlenstedt/Loxberry
webfrontend/html/system/scripts/form-validator/html5.dev.js
5779
/** * jQuery Form Validator Module: html5 * ------------------------------------------ * Created by Victor Jonsson <http://www.victorjonsson.se> * * The following module will make this jQuery plugin serve as a * html5 fallback. It makes older browsers support the following * - validation when type="email" * - validation when type="url" * - validation when type="time" * - validation when type="date" * - validation when type="number" and max="" min="" * - validation when pattern="REGEXP" * - validation when using maxlength * - Using datalist element for creating suggestions * - placeholders * * @website http://formvalidator.net/ * @license MIT * @version 2.2.141 */ (function($, window) { 'use strict'; var SUPPORTS_PLACEHOLDER = 'placeholder' in document.createElement('INPUT'), SUPPORTS_DATALIST = 'options' in document.createElement('DATALIST'), hasLoadedDateModule = false, setupValidationUsingHTML5Attr = function($form) { $form.each(function() { var $f = $(this), $formInputs = $f.find('input,textarea,select'), foundHtml5Rule = false; $formInputs.each(function() { var validation = [], $input = $(this), isRequired = $input.attr('required'), attrs = {}; switch ( ($input.attr('type') || '').toLowerCase() ) { case 'time': validation.push('time'); if( !$.formUtils.validators.validate_date && !hasLoadedDateModule ) { hasLoadedDateModule = true; $.formUtils.loadModules('date'); } break; case 'url': validation.push('url'); break; case 'email': validation.push('email'); break; case 'date': validation.push('date'); break; case 'number': validation.push('number'); var max = $input.attr('max'), min = $input.attr('min'); if( min || max ) { if ( !min ) { min = '0'; } if ( !max ) { max = '9007199254740992'; // js max int } attrs['data-validation-allowing'] = 'range['+min+';'+max+']'; if( min.indexOf('-') === 0 || max.indexOf('-') === 0 ) { attrs['data-validation-allowing'] += ',negative'; } if( min.indexOf('.') > -1 || max.indexOf('.') > -1 ) { attrs['data-validation-allowing'] += ',float'; } } break; } if( $input.attr('pattern') ) { validation.push('custom'); attrs['data-validation-regexp'] = $input.attr('pattern'); } if( $input.attr('maxlength') ) { validation.push('length'); attrs['data-validation-length'] = 'max'+$input.attr('maxlength'); } if( !SUPPORTS_DATALIST && $input.attr('list') ) { var suggestions = [], $list = $('#'+$input.attr('list')); $list.find('option').each(function() { suggestions.push($(this).text()); }); if( suggestions.length === 0 ) { // IE fix var opts = $.trim($('#'+$input.attr('list')).text()).split('\n'); $.each(opts, function(i, option) { suggestions.push($.trim(option)); }); } $list.remove(); $.formUtils.suggest( $input, suggestions ); } if ( isRequired && validation.length === 0 ) { validation.push('required'); } if( validation.length ) { if( !isRequired ) { attrs['data-validation-optional'] = 'true'; } foundHtml5Rule = true; $input.attr('data-validation', validation.join(' ')); $.each(attrs, function(attrName, attrVal) { $input.attr(attrName, attrVal); }); } }); if( foundHtml5Rule ) { $f.trigger('html5ValidationAttrsFound'); } if( !SUPPORTS_PLACEHOLDER ) { $formInputs.filter('input[placeholder]').each(function() { this.defaultValue = this.getAttribute('placeholder'); $(this) .bind('focus', function() { if(this.value === this.defaultValue) { this.value = ''; $(this).removeClass('showing-placeholder'); } }) .bind('blur', function() { if($.trim(this.value) === '') { this.value = this.defaultValue; $(this).addClass('showing-placeholder'); } }); }); } }); }; $(window).bind('validatorsLoaded formValidationSetup', function(evt, $form) { if( !$form ) { $form = $('form'); } setupValidationUsingHTML5Attr($form); }); // Make this method available outside the module $.formUtils.setupValidationUsingHTML5Attr = setupValidationUsingHTML5Attr; })(jQuery, window);
apache-2.0
astroilov/google-storage-plugin
src/main/java/com/google/jenkins/plugins/storage/UploadModule.java
2707
/* * Copyright 2013 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.jenkins.plugins.storage; import java.io.Serializable; import java.security.GeneralSecurityException; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.jackson.JacksonFactory; import com.google.api.services.storage.Storage; import com.google.jenkins.plugins.credentials.domains.DomainRequirementProvider; import com.google.jenkins.plugins.credentials.domains.RequiresDomain; import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials; import com.google.jenkins.plugins.util.Executor; /** * This module abstracts how the Upload implementations instantiate * their connection to the Storage service. */ @RequiresDomain(value = StorageScopeRequirement.class) public class UploadModule implements Serializable { /** * Interface for requesting the {@link Executor} for executing requests. * * @return a new {@link Executor} instance for issuing requests * @throws CloudManagementException if a service connection cannot * be established. */ public Executor newExecutor() { return new Executor.Default(); } public StorageScopeRequirement getRequirement() { return DomainRequirementProvider.of(getClass(), StorageScopeRequirement.class); } public Storage getStorageService(GoogleRobotCredentials credentials) throws UploadException { try { return new Storage.Builder(new NetHttpTransport(), new JacksonFactory(), credentials.getGoogleCredential(getRequirement())) .setApplicationName(Messages.UploadModule_AppName()) .build(); } catch (GeneralSecurityException e) { throw new UploadException( Messages.UploadModule_ExceptionStorageService(), e); } } /** * Controls the number of object insertion retries. */ public int getInsertRetryCount() { return 5; } /** * Prefix the given log message with our module. */ public String prefix(String x) { return Messages.UploadModule_PrefixFormat( Messages.GoogleCloudStorageUploader_DisplayName(), x); } }
apache-2.0
atomiqio/atomiq
vendor/docker.io/go-docker/swarm_leave.go
368
package docker // import "docker.io/go-docker" import ( "net/url" "golang.org/x/net/context" ) // SwarmLeave leaves the swarm. func (cli *Client) SwarmLeave(ctx context.Context, force bool) error { query := url.Values{} if force { query.Set("force", "1") } resp, err := cli.post(ctx, "/swarm/leave", query, nil, nil) ensureReaderClosed(resp) return err }
apache-2.0
forcedotcom/aura
aura-impl/src/main/java/org/auraframework/component/auradev/TestDataProvider2Controller.java
1393
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.auraframework.component.auradev; import org.auraframework.annotations.Annotations.ServiceComponent; import org.auraframework.ds.servicecomponent.Controller; import org.auraframework.system.Annotations.AuraEnabled; import org.auraframework.system.Annotations.Key; import java.util.ArrayList; import java.util.Calendar; import java.util.List; @ServiceComponent public class TestDataProvider2Controller implements Controller { @AuraEnabled public List<TestDataItem> getItems(@Key("keyword") String keyword) throws Exception { List<TestDataItem> l = new ArrayList<>(10); for (int i = 0; i < 10; i++) { l.add(new TestDataItem(i + Calendar.getInstance().get(Calendar.SECOND) + "MRU", "value" + i)); } return l; } }
apache-2.0
streamsets/datacollector
kinesis-lib/src/main/java/com/streamsets/pipeline/stage/origin/kinesis/KinesisDSource.java
1755
/* * Copyright 2017 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.stage.origin.kinesis; import com.streamsets.pipeline.api.ConfigDefBean; import com.streamsets.pipeline.api.ConfigGroups; import com.streamsets.pipeline.api.ExecutionMode; import com.streamsets.pipeline.api.GenerateResourceBundle; import com.streamsets.pipeline.api.PushSource; import com.streamsets.pipeline.api.StageDef; import com.streamsets.pipeline.api.base.configurablestage.DPushSource; @StageDef( version = 10, label = "Kinesis Consumer", description = "Reads data from Kinesis", icon = "kinesis_multithreaded.png", execution = ExecutionMode.STANDALONE, recordsByRef = true, resetOffset = true, upgrader = KinesisSourceUpgrader.class, upgraderDef = "upgrader/KinesisDSource.yaml", onlineHelpRefUrl ="index.html?contextID=task_p4b_vv4_yr" ) @ConfigGroups(value = Groups.class) @GenerateResourceBundle public class KinesisDSource extends DPushSource { @ConfigDefBean(groups = {"KINESIS", "ADVANCED", "LEASE_TABLE"}) public KinesisConsumerConfigBean kinesisConfig; @Override protected PushSource createPushSource() { return new KinesisSource(kinesisConfig); } }
apache-2.0
alkaitz/starloot
src/gameengine/webSocketServer/lib/tornado-3.0.1/build/lib/tornado/gen.py
19915
"""``tornado.gen`` is a generator-based interface to make it easier to work in an asynchronous environment. Code using the ``gen`` module is technically asynchronous, but it is written as a single generator instead of a collection of separate functions. For example, the following asynchronous handler:: class AsyncHandler(RequestHandler): @asynchronous def get(self): http_client = AsyncHTTPClient() http_client.fetch("http://example.com", callback=self.on_fetch) def on_fetch(self, response): do_something_with_response(response) self.render("template.html") could be written with ``gen`` as:: class GenAsyncHandler(RequestHandler): @asynchronous @gen.coroutine def get(self): http_client = AsyncHTTPClient() response = yield http_client.fetch("http://example.com") do_something_with_response(response) self.render("template.html") Most asynchronous functions in Tornado return a `.Future`; yielding this object returns its `~.Future.result`. For functions that do not return ``Futures``, `Task` works with any function that takes a ``callback`` keyword argument (most Tornado functions can be used in either style, although the ``Future`` style is preferred since it is both shorter and provides better exception handling):: @gen.coroutine def get(self): yield gen.Task(AsyncHTTPClient().fetch, "http://example.com") You can also yield a list of ``Futures`` and/or ``Tasks``, which will be started at the same time and run in parallel; a list of results will be returned when they are all finished:: @gen.coroutine def get(self): http_client = AsyncHTTPClient() response1, response2 = yield [http_client.fetch(url1), http_client.fetch(url2)] For more complicated interfaces, `Task` can be split into two parts: `Callback` and `Wait`:: class GenAsyncHandler2(RequestHandler): @asynchronous @gen.coroutine def get(self): http_client = AsyncHTTPClient() http_client.fetch("http://example.com", callback=(yield gen.Callback("key")) response = yield gen.Wait("key") do_something_with_response(response) self.render("template.html") The ``key`` argument to `Callback` and `Wait` allows for multiple asynchronous operations to be started at different times and proceed in parallel: yield several callbacks with different keys, then wait for them once all the async operations have started. The result of a `Wait` or `Task` yield expression depends on how the callback was run. If it was called with no arguments, the result is ``None``. If it was called with one argument, the result is that argument. If it was called with more than one argument or any keyword arguments, the result is an `Arguments` object, which is a named tuple ``(args, kwargs)``. """ from __future__ import absolute_import, division, print_function, with_statement import collections import functools import itertools import sys import types from tornado.concurrent import Future, TracebackFuture from tornado.ioloop import IOLoop from tornado.stack_context import ExceptionStackContext, wrap class KeyReuseError(Exception): pass class UnknownKeyError(Exception): pass class LeakedCallbackError(Exception): pass class BadYieldError(Exception): pass class ReturnValueIgnoredError(Exception): pass def engine(func): """Callback-oriented decorator for asynchronous generators. This is an older interface; for new code that does not need to be compatible with versions of Tornado older than 3.0 the `coroutine` decorator is recommended instead. This decorator is similar to `coroutine`, except it does not return a `.Future` and the ``callback`` argument is not treated specially. In most cases, functions decorated with `engine` should take a ``callback`` argument and invoke it with their result when they are finished. One notable exception is the `~tornado.web.RequestHandler` ``get``/``post``/etc methods, which use ``self.finish()`` in place of a callback argument. """ @functools.wraps(func) def wrapper(*args, **kwargs): runner = None def handle_exception(typ, value, tb): # if the function throws an exception before its first "yield" # (or is not a generator at all), the Runner won't exist yet. # However, in that case we haven't reached anything asynchronous # yet, so we can just let the exception propagate. if runner is not None: return runner.handle_exception(typ, value, tb) return False with ExceptionStackContext(handle_exception) as deactivate: try: result = func(*args, **kwargs) except (Return, StopIteration) as e: result = getattr(e, 'value', None) else: if isinstance(result, types.GeneratorType): def final_callback(value): if value is not None: raise ReturnValueIgnoredError( "@gen.engine functions cannot return values: " "%r" % (value,)) assert value is None deactivate() runner = Runner(result, final_callback) runner.run() return if result is not None: raise ReturnValueIgnoredError( "@gen.engine functions cannot return values: %r" % (result,)) deactivate() # no yield, so we're done return wrapper def coroutine(func): """Decorator for asynchronous generators. Any generator that yields objects from this module must be wrapped in either this decorator or `engine`. These decorators only work on functions that are already asynchronous. For `~tornado.web.RequestHandler` ``get``/``post``/etc methods, this means that both the `tornado.web.asynchronous` and `tornado.gen.coroutine` decorators must be used (for proper exception handling, ``asynchronous`` should come before ``gen.coroutine``). Coroutines may "return" by raising the special exception `Return(value) <Return>`. In Python 3.3+, it is also possible for the function to simply use the ``return value`` statement (prior to Python 3.3 generators were not allowed to also return values). In all versions of Python a coroutine that simply wishes to exit early may use the ``return`` statement without a value. Functions with this decorator return a `.Future`. Additionally, they may be called with a ``callback`` keyword argument, which will be invoked with the future's result when it resolves. If the coroutine fails, the callback will not be run and an exception will be raised into the surrounding `.StackContext`. The ``callback`` argument is not visible inside the decorated function; it is handled by the decorator itself. From the caller's perspective, ``@gen.coroutine`` is similar to the combination of ``@return_future`` and ``@gen.engine``. """ @functools.wraps(func) def wrapper(*args, **kwargs): runner = None future = TracebackFuture() if 'callback' in kwargs: callback = kwargs.pop('callback') IOLoop.current().add_future( future, lambda future: callback(future.result())) def handle_exception(typ, value, tb): try: if runner is not None and runner.handle_exception(typ, value, tb): return True except Exception: typ, value, tb = sys.exc_info() future.set_exc_info((typ, value, tb)) return True with ExceptionStackContext(handle_exception) as deactivate: try: result = func(*args, **kwargs) except (Return, StopIteration) as e: result = getattr(e, 'value', None) except Exception: deactivate() future.set_exc_info(sys.exc_info()) return future else: if isinstance(result, types.GeneratorType): def final_callback(value): deactivate() future.set_result(value) runner = Runner(result, final_callback) runner.run() return future deactivate() future.set_result(result) return future return wrapper class Return(Exception): """Special exception to return a value from a `coroutine`. If this exception is raised, its value argument is used as the result of the coroutine:: @gen.coroutine def fetch_json(url): response = yield AsyncHTTPClient().fetch(url) raise gen.Return(json_decode(response.body)) In Python 3.3, this exception is no longer necessary: the ``return`` statement can be used directly to return a value (previously ``yield`` and ``return`` with a value could not be combined in the same function). By analogy with the return statement, the value argument is optional, but it is never necessary to ``raise gen.Return()``. The ``return`` statement can be used with no arguments instead. """ def __init__(self, value=None): super(Return, self).__init__() self.value = value class YieldPoint(object): """Base class for objects that may be yielded from the generator. Applications do not normally need to use this class, but it may be subclassed to provide additional yielding behavior. """ def start(self, runner): """Called by the runner after the generator has yielded. No other methods will be called on this object before ``start``. """ raise NotImplementedError() def is_ready(self): """Called by the runner to determine whether to resume the generator. Returns a boolean; may be called more than once. """ raise NotImplementedError() def get_result(self): """Returns the value to use as the result of the yield expression. This method will only be called once, and only after `is_ready` has returned true. """ raise NotImplementedError() class Callback(YieldPoint): """Returns a callable object that will allow a matching `Wait` to proceed. The key may be any value suitable for use as a dictionary key, and is used to match ``Callbacks`` to their corresponding ``Waits``. The key must be unique among outstanding callbacks within a single run of the generator function, but may be reused across different runs of the same function (so constants generally work fine). The callback may be called with zero or one arguments; if an argument is given it will be returned by `Wait`. """ def __init__(self, key): self.key = key def start(self, runner): self.runner = runner runner.register_callback(self.key) def is_ready(self): return True def get_result(self): return self.runner.result_callback(self.key) class Wait(YieldPoint): """Returns the argument passed to the result of a previous `Callback`.""" def __init__(self, key): self.key = key def start(self, runner): self.runner = runner def is_ready(self): return self.runner.is_ready(self.key) def get_result(self): return self.runner.pop_result(self.key) class WaitAll(YieldPoint): """Returns the results of multiple previous `Callbacks <Callback>`. The argument is a sequence of `Callback` keys, and the result is a list of results in the same order. `WaitAll` is equivalent to yielding a list of `Wait` objects. """ def __init__(self, keys): self.keys = keys def start(self, runner): self.runner = runner def is_ready(self): return all(self.runner.is_ready(key) for key in self.keys) def get_result(self): return [self.runner.pop_result(key) for key in self.keys] class Task(YieldPoint): """Runs a single asynchronous operation. Takes a function (and optional additional arguments) and runs it with those arguments plus a ``callback`` keyword argument. The argument passed to the callback is returned as the result of the yield expression. A `Task` is equivalent to a `Callback`/`Wait` pair (with a unique key generated automatically):: result = yield gen.Task(func, args) func(args, callback=(yield gen.Callback(key))) result = yield gen.Wait(key) """ def __init__(self, func, *args, **kwargs): assert "callback" not in kwargs self.args = args self.kwargs = kwargs self.func = func def start(self, runner): self.runner = runner self.key = object() runner.register_callback(self.key) self.kwargs["callback"] = runner.result_callback(self.key) self.func(*self.args, **self.kwargs) def is_ready(self): return self.runner.is_ready(self.key) def get_result(self): return self.runner.pop_result(self.key) class YieldFuture(YieldPoint): def __init__(self, future, io_loop=None): self.future = future self.io_loop = io_loop or IOLoop.current() def start(self, runner): self.runner = runner self.key = object() runner.register_callback(self.key) self.io_loop.add_future(self.future, runner.result_callback(self.key)) def is_ready(self): return self.runner.is_ready(self.key) def get_result(self): return self.runner.pop_result(self.key).result() class Multi(YieldPoint): """Runs multiple asynchronous operations in parallel. Takes a list of ``Tasks`` or other ``YieldPoints`` and returns a list of their responses. It is not necessary to call `Multi` explicitly, since the engine will do so automatically when the generator yields a list of ``YieldPoints``. """ def __init__(self, children): self.children = [] for i in children: if isinstance(i, Future): i = YieldFuture(i) self.children.append(i) assert all(isinstance(i, YieldPoint) for i in self.children) self.unfinished_children = set(self.children) def start(self, runner): for i in self.children: i.start(runner) def is_ready(self): finished = list(itertools.takewhile( lambda i: i.is_ready(), self.unfinished_children)) self.unfinished_children.difference_update(finished) return not self.unfinished_children def get_result(self): return [i.get_result() for i in self.children] class _NullYieldPoint(YieldPoint): def start(self, runner): pass def is_ready(self): return True def get_result(self): return None class Runner(object): """Internal implementation of `tornado.gen.engine`. Maintains information about pending callbacks and their results. ``final_callback`` is run after the generator exits. """ def __init__(self, gen, final_callback): self.gen = gen self.final_callback = final_callback self.yield_point = _NullYieldPoint() self.pending_callbacks = set() self.results = {} self.running = False self.finished = False self.exc_info = None self.had_exception = False def register_callback(self, key): """Adds ``key`` to the list of callbacks.""" if key in self.pending_callbacks: raise KeyReuseError("key %r is already pending" % (key,)) self.pending_callbacks.add(key) def is_ready(self, key): """Returns true if a result is available for ``key``.""" if key not in self.pending_callbacks: raise UnknownKeyError("key %r is not pending" % (key,)) return key in self.results def set_result(self, key, result): """Sets the result for ``key`` and attempts to resume the generator.""" self.results[key] = result self.run() def pop_result(self, key): """Returns the result for ``key`` and unregisters it.""" self.pending_callbacks.remove(key) return self.results.pop(key) def run(self): """Starts or resumes the generator, running until it reaches a yield point that is not ready. """ if self.running or self.finished: return try: self.running = True while True: if self.exc_info is None: try: if not self.yield_point.is_ready(): return next = self.yield_point.get_result() except Exception: self.exc_info = sys.exc_info() try: if self.exc_info is not None: self.had_exception = True exc_info = self.exc_info self.exc_info = None yielded = self.gen.throw(*exc_info) else: yielded = self.gen.send(next) except (StopIteration, Return) as e: self.finished = True if self.pending_callbacks and not self.had_exception: # If we ran cleanly without waiting on all callbacks # raise an error (really more of a warning). If we # had an exception then some callbacks may have been # orphaned, so skip the check in that case. raise LeakedCallbackError( "finished without waiting for callbacks %r" % self.pending_callbacks) self.final_callback(getattr(e, 'value', None)) self.final_callback = None return except Exception: self.finished = True raise if isinstance(yielded, list): yielded = Multi(yielded) elif isinstance(yielded, Future): yielded = YieldFuture(yielded) if isinstance(yielded, YieldPoint): self.yield_point = yielded try: self.yield_point.start(self) except Exception: self.exc_info = sys.exc_info() else: self.exc_info = (BadYieldError( "yielded unknown object %r" % (yielded,)),) finally: self.running = False def result_callback(self, key): def inner(*args, **kwargs): if kwargs or len(args) > 1: result = Arguments(args, kwargs) elif args: result = args[0] else: result = None self.set_result(key, result) return wrap(inner) def handle_exception(self, typ, value, tb): if not self.running and not self.finished: self.exc_info = (typ, value, tb) self.run() return True else: return False Arguments = collections.namedtuple('Arguments', ['args', 'kwargs'])
apache-2.0
chengduoZH/Paddle
paddle/fluid/framework/ir/memory_optimize_pass/op_graph_view.cc
2766
// Copyright (c) 2018 PaddlePaddle 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. #include "paddle/fluid/framework/ir/memory_optimize_pass/op_graph_view.h" #include <queue> #include <utility> namespace paddle { namespace framework { namespace ir { OpGraphView::OpGraphView(const std::vector<details::OpHandleBase *> &ops) { Build(ops); } void OpGraphView::Build(const std::vector<details::OpHandleBase *> &ops) { preceding_ops_.clear(); pending_ops_.clear(); for (auto &op : ops) { preceding_ops_[op]; pending_ops_[op]; for (auto &var : op->Outputs()) { for (auto &pending_op : var->PendingOps()) { preceding_ops_[pending_op].insert(op); pending_ops_[op].insert(pending_op); } } } PADDLE_ENFORCE( preceding_ops_.size() == ops.size() && pending_ops_.size() == ops.size(), "There are duplicate ops in graph."); } std::unordered_set<details::OpHandleBase *> OpGraphView::AllOps() const { std::unordered_set<details::OpHandleBase *> ret; ret.reserve(preceding_ops_.size()); for (auto &pair : preceding_ops_) { ret.insert(pair.first); } return ret; } bool OpGraphView::HasOp(details::OpHandleBase *op) const { return preceding_ops_.count(op) != 0; } void OpGraphView::EnforceHasOp(details::OpHandleBase *op) const { PADDLE_ENFORCE(HasOp(op), "Cannot find op %s in OpGraphView", op == nullptr ? "nullptr" : op->DebugString()); } const std::unordered_set<details::OpHandleBase *> &OpGraphView::PendingOps( details::OpHandleBase *op) const { EnforceHasOp(op); return pending_ops_.at(op); } const std::unordered_set<details::OpHandleBase *> &OpGraphView::PrecedingOps( details::OpHandleBase *op) const { EnforceHasOp(op); return preceding_ops_.at(op); } std::unordered_map<details::OpHandleBase *, size_t> OpGraphView::GetPrecedingDepNum() const { std::unordered_map<details::OpHandleBase *, size_t> result; result.reserve(preceding_ops_.size()); for (auto &pair : preceding_ops_) { result.emplace(pair.first, pair.second.size()); } return result; } size_t OpGraphView::OpNumber() const { return preceding_ops_.size(); } } // namespace ir } // namespace framework } // namespace paddle
apache-2.0
gpolitis/jitsi-meet
react/features/recording/components/LiveStream/web/LiveStreamButton.js
1176
// @flow import { getToolbarButtons } from '../../../../base/config'; import { translate } from '../../../../base/i18n'; import { connect } from '../../../../base/redux'; import AbstractLiveStreamButton, { _mapStateToProps as _abstractMapStateToProps, type Props } from '../AbstractLiveStreamButton'; /** * Maps (parts of) the redux state to the associated props for the * {@code LiveStreamButton} component. * * @param {Object} state - The Redux state. * @param {Props} ownProps - The own props of the Component. * @private * @returns {{ * _conference: Object, * _isLiveStreamRunning: boolean, * _disabled: boolean, * visible: boolean * }} */ function _mapStateToProps(state: Object, ownProps: Props) { const abstractProps = _abstractMapStateToProps(state, ownProps); const toolbarButtons = getToolbarButtons(state); let { visible } = ownProps; if (typeof visible === 'undefined') { visible = toolbarButtons.includes('livestreaming') && abstractProps.visible; } return { ...abstractProps, visible }; } export default translate(connect(_mapStateToProps)(AbstractLiveStreamButton));
apache-2.0
ccaballe/crossdata
crossdata-connector-inmemory/src/main/java/com/stratio/connector/inmemory/datastore/structures/InMemorySelector.java
1253
/* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.stratio.connector.inmemory.datastore.structures; /** * Class definition of a generic selector for the in-memory datastore. */ public class InMemorySelector { /** * Name of the selector. */ private final String name; /** * Class constructor. * @param name The selector name. */ public InMemorySelector(String name){ this.name = name; } public String getName() { return name; } }
apache-2.0
imron/scalyr-agent-2
tests/unit/builtin_monitors/apache_monitor_test.py
5370
# Copyright 2014-2020 Scalyr 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. from __future__ import unicode_literals from __future__ import absolute_import from scalyr_agent.builtin_monitors.apache_monitor import ApacheMonitor from scalyr_agent.test_base import ScalyrMockHttpServerTestCase import mock __all__ = ["ApacheMonitorTest"] MOCK_APACHE_STATUS_DATA = """ Total Accesses: 65 Total kBytes: 52 CPULoad: .00496689 Uptime: 604 ReqPerSec: .107616 BytesPerSec: 88.1589 BytesPerReq: 819.2 BusyWorkers: 2 IdleWorkers: 5 ConnsTotal: 1000 ConnsAsyncWriting: 10 ConnsAsyncKeepAlive: 2 ConnsAsyncClosing: 1 Scoreboard: __W___K............................................................................................................................................... """ MOCK_APACHE_STATUS_DATA_PARTIAL = """ BytesPerSec: 88.1589 BytesPerReq: 819.2 """ def mock_apache_server_status_view_func(): return MOCK_APACHE_STATUS_DATA def mock_apache_server_status_partial_view_func(): return MOCK_APACHE_STATUS_DATA_PARTIAL class ApacheMonitorTest(ScalyrMockHttpServerTestCase): @classmethod def setUpClass(cls): super(ApacheMonitorTest, cls).setUpClass() # Register mock routes cls.mock_http_server_thread.app.add_url_rule( "/server-status", view_func=mock_apache_server_status_view_func ) cls.mock_http_server_thread.app.add_url_rule( "/server-status-partial", view_func=mock_apache_server_status_partial_view_func, ) def test_gather_sample_200_success(self): url = "http://%s:%s/server-status?auto" % ( self.mock_http_server_thread.host, self.mock_http_server_thread.port, ) monitor_config = { "module": "apache_monitor", "status_url": url, } mock_logger = mock.Mock() monitor = ApacheMonitor(monitor_config, mock_logger) monitor.gather_sample() call_args_list = mock_logger.emit_value.call_args_list self.assertEqual(mock_logger.error.call_count, 0) self.assertEqual(mock_logger.emit_value.call_count, 6) self.assertEqual(call_args_list[0][0], ("apache.workers.active", 2)) self.assertEqual(call_args_list[1][0], ("apache.workers.idle", 5)) self.assertEqual(call_args_list[2][0], ("apache.connections.active", 1000)) self.assertEqual(call_args_list[3][0], ("apache.connections.writing", 10)) self.assertEqual(call_args_list[4][0], ("apache.connections.idle", 2)) self.assertEqual(call_args_list[5][0], ("apache.connections.closing", 1)) def test_gather_sample_200_incomplete_data_returned_returned(self): url = "http://%s:%s/server-status-partial" % ( self.mock_http_server_thread.host, self.mock_http_server_thread.port, ) monitor_config = { "module": "apache_monitor", "status_url": url, } mock_logger = mock.Mock() monitor = ApacheMonitor(monitor_config, mock_logger) monitor.gather_sample() self.assertEqual(mock_logger.emit_value.call_count, 0) self.assertEqual(mock_logger.error.call_count, 1) self.assertTrue( "Status page did not match expected format." in mock_logger.error.call_args_list[0][0][0] ) def test_gather_sample_404_no_data_returned(self): url = "http://%s:%s/invalid" % ( self.mock_http_server_thread.host, self.mock_http_server_thread.port, ) monitor_config = { "module": "apache_monitor", "status_url": url, } mock_logger = mock.Mock() monitor = ApacheMonitor(monitor_config, mock_logger) monitor.gather_sample() self.assertEqual(mock_logger.emit_value.call_count, 0) self.assertEqual(mock_logger.error.call_count, 2) self.assertTrue( "The URL used to request the status page appears to be incorrect" in mock_logger.error.call_args_list[0][0][0] ) self.assertTrue("No data returned" in mock_logger.error.call_args_list[1][0][0]) def test_gather_sample_invalid_url(self): url = "http://invalid" monitor_config = { "module": "apache_monitor", "status_url": url, } mock_logger = mock.Mock() monitor = ApacheMonitor(monitor_config, mock_logger) monitor.gather_sample() self.assertEqual(mock_logger.emit_value.call_count, 0) self.assertEqual(mock_logger.error.call_count, 2) self.assertTrue( "The was an error attempting to reach the server" in mock_logger.error.call_args_list[0][0][0] ) self.assertTrue("No data returned" in mock_logger.error.call_args_list[1][0][0])
apache-2.0
cisdev123/OpenGTS_2.6.0
src/org/opengts/db/RoleRecord.java
5584
// ---------------------------------------------------------------------------- // Copyright 2006-2010, GeoTelematic Solutions, 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. // // ---------------------------------------------------------------------------- // Change History: // 2008/10/16 Martin D. Flynn // -Initial release (cloned from UserRecord.java) // ---------------------------------------------------------------------------- package org.opengts.db; import java.lang.*; import java.util.*; import java.math.*; import java.io.*; import java.sql.*; import org.opengts.util.*; import org.opengts.dbtools.*; import org.opengts.db.*; import org.opengts.db.tables.Account; import org.opengts.db.tables.Role; public class RoleRecord<RT extends DBRecord> extends AccountRecord<RT> { // ------------------------------------------------------------------------ public static final String SYSTEM_ROLE_PREFIX = "!"; // ------------------------------------------------------------------------ /* common Asset/Device field definition */ public static final String FLD_roleID = "roleID"; /* create a new "accountID" key field definition */ protected static DBField newField_roleID(boolean key) { return new DBField(FLD_roleID, String.class, DBField.TYPE_ROLE_ID(), "Role ID", (key?"key=true":"edit=2")); } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ public static abstract class RoleKey<RT extends DBRecord> extends AccountKey<RT> { public RoleKey() { super(); } } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ /* Bean instance */ public RoleRecord() { super(); } /* database record */ public RoleRecord(RoleKey<RT> key) { super(key); } // ------------------------------------------------------------------------ /* Role ID */ public String getRoleID() { String v = (String)this.getFieldValue(FLD_roleID); return (v != null)? v : ""; } private void setRoleID(String v) { this.setFieldValue(FLD_roleID, ((v != null)? v : "")); } /* return true if the specified role is a system-wide/syste-admin role */ public static boolean isSystemAdminRoleID(String roleID) { if (StringTools.isBlank(roleID)) { return false; } else { return roleID.startsWith(SYSTEM_ROLE_PREFIX); } } /* return the displayed role ID */ public static String getDisplayRoleID(String roleID) { if (StringTools.isBlank(roleID)) { return ""; } else if (roleID.startsWith(RoleRecord.SYSTEM_ROLE_PREFIX)) { return roleID.substring(RoleRecord.SYSTEM_ROLE_PREFIX.length()) + " *"; } else { return roleID; } } // ------------------------------------------------------------------------ // The following is an optimization for holding the Role record while // processing this RoleRecord. Use with caution. private Role role = null; public final Role getRole() { if (this.role == null) { String roleID = this.getRoleID(); Print.logDebug("[Optimize] Retrieving Role record: " + roleID); try { this.role = Role.getRole(this.getAccount(), roleID); // may still be null if the role was not found } catch (DBException dbe) { // may be caused by "java.net.ConnectException: Connection refused: connect" Print.logError("Role not found: " + this.getAccountID() + "/" + roleID); this.role = null; } } return this.role; } public final void setRole(Role role) { if ((role != null) && role.getAccountID().equals(this.getAccountID()) && role.getRoleID().equals(this.getRoleID() ) ) { this.setAccount(role.getAccount()); this.role = role; } else { this.role = null; } } // ------------------------------------------------------------------------ private String roleDesc = null; public final String getRoleDescription() { if (this.roleDesc == null) { Role role = this.getRole(); this.roleDesc = (role != null)? role.getDescription() : this.getRoleID(); } return this.roleDesc; } // ------------------------------------------------------------------------ }
apache-2.0
allotria/intellij-community
plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleSettingsImportingTest.java
33058
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.importing; import com.intellij.codeInspection.ex.InspectionProfileImpl; import com.intellij.execution.BeforeRunTask; import com.intellij.execution.RunManager; import com.intellij.execution.RunManagerEx; import com.intellij.execution.RunnerAndConfigurationSettings; import com.intellij.execution.application.ApplicationConfiguration; import com.intellij.execution.application.JavaApplicationRunConfigurationImporter; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.execution.jar.JarApplicationRunConfigurationImporter; import com.intellij.ide.impl.ProjectUtil; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings; import com.intellij.openapi.externalSystem.service.execution.ExternalSystemBeforeRunTask; import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider; import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProviderImpl; import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManagerImpl; import com.intellij.openapi.externalSystem.service.project.manage.ExternalSystemTaskActivator; import com.intellij.openapi.externalSystem.service.project.manage.SourceFolderManager; import com.intellij.openapi.externalSystem.service.project.manage.SourceFolderManagerImpl; import com.intellij.openapi.externalSystem.service.project.settings.FacetConfigurationImporter; import com.intellij.openapi.externalSystem.service.project.settings.RunConfigurationImporter; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.SourceFolder; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.encoding.EncodingProjectManager; import com.intellij.openapi.vfs.encoding.EncodingProjectManagerImpl; import com.intellij.profile.codeInspection.InspectionProfileManager; import com.intellij.testFramework.ExtensionTestUtil; import com.intellij.testFramework.PlatformTestUtil; import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.gradle.settings.GradleProjectSettings; import org.jetbrains.plugins.gradle.settings.GradleSettings; import org.jetbrains.plugins.gradle.settings.TestRunner; import org.junit.Test; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; /** * Created by Nikita.Skvortsov */ public class GradleSettingsImportingTest extends GradleSettingsImportingTestCase { @Test public void testInspectionSettingsImport() throws Exception { importProject( withGradleIdeaExtPlugin( "import org.jetbrains.gradle.ext.*\n" + "idea {\n" + " project.settings {\n" + " inspections {\n" + " myInspection { enabled = false }\n" + " }\n" + " }\n" + "}") ); final InspectionProfileImpl profile = InspectionProfileManager.getInstance(myProject).getCurrentProfile(); assertEquals("Gradle Imported", profile.getName()); } @Test public void testApplicationRunConfigurationSettingsImport() throws Exception { TestRunConfigurationImporter testExtension = new TestRunConfigurationImporter("application"); maskRunImporter(testExtension); createSettingsFile("rootProject.name = 'moduleName'"); importProject( withGradleIdeaExtPlugin( "import org.jetbrains.gradle.ext.*\n" + "idea {\n" + " project.settings {\n" + " runConfigurations {\n" + " app1(Application) {\n" + " mainClass = 'my.app.Class'\n" + " jvmArgs = '-Xmx1g'\n" + " moduleName = 'moduleName'\n" + " }\n" + " app2(Application) {\n" + " mainClass = 'my.app.Class2'\n" + " moduleName = 'moduleName'\n" + " }\n" + " }\n" + " }\n" + "}") ); final Map<String, Map<String, Object>> configs = testExtension.getConfigs(); assertContain(new ArrayList<>(configs.keySet()), "app1", "app2"); Map<String, Object> app1Settings = configs.get("app1"); Map<String, Object> app2Settings = configs.get("app2"); assertEquals("my.app.Class", app1Settings.get("mainClass")); assertEquals("my.app.Class2", app2Settings.get("mainClass")); assertEquals("-Xmx1g", app1Settings.get("jvmArgs")); assertNull(app2Settings.get("jvmArgs")); } @Test public void testGradleRunConfigurationSettingsImport() throws Exception { TestRunConfigurationImporter testExtension = new TestRunConfigurationImporter("gradle"); maskRunImporter(testExtension); createSettingsFile("rootProject.name = 'moduleName'"); importProject( new GradleBuildScriptBuilderEx() .withGradleIdeaExtPluginIfCan(IDEA_EXT_PLUGIN_VERSION) .addPostfix( "import org.jetbrains.gradle.ext.*", "idea.project.settings {", " runConfigurations {", " gr1(Gradle) {", " project = rootProject", " taskNames = [':cleanTest', ':test']", " envs = ['env_key':'env_val']", " jvmArgs = '-DvmKey=vmVal'", " scriptParameters = '-PscriptParam'", " }", " }", "}" ).generate()); final Map<String, Map<String, Object>> configs = testExtension.getConfigs(); assertContain(new ArrayList<>(configs.keySet()), "gr1"); Map<String, Object> gradleSettings = configs.get("gr1"); assertEquals(myProjectRoot.getPath(), ((String)gradleSettings.get("projectPath")).replace('\\', '/')); assertTrue(((List)gradleSettings.get("taskNames")).contains(":cleanTest")); assertEquals("-DvmKey=vmVal", gradleSettings.get("jvmArgs")); assertTrue(((Map)gradleSettings.get("envs")).containsKey("env_key")); } private void maskRunImporter(@NotNull RunConfigurationImporter testExtension) { ExtensionTestUtil.maskExtensions(RunConfigurationImporter.EP_NAME, Collections.singletonList(testExtension), getTestRootDisposable()); } @Test public void testDefaultRCSettingsImport() throws Exception { RunConfigurationImporter appcConfigImporter = new JavaApplicationRunConfigurationImporter(); maskRunImporter(appcConfigImporter); importProject( withGradleIdeaExtPlugin( "import org.jetbrains.gradle.ext.*\n" + "idea {\n" + " project.settings {\n" + " runConfigurations {\n" + " defaults(Application) {\n" + " jvmArgs = '-DmyKey=myVal'\n" + " }\n" + " }\n" + " }\n" + "}") ); final RunManager runManager = RunManager.getInstance(myProject); final RunnerAndConfigurationSettings template = runManager.getConfigurationTemplate(appcConfigImporter.getConfigurationFactory()); final String parameters = ((ApplicationConfiguration)template.getConfiguration()).getVMParameters(); assertNotNull(parameters); assertTrue(parameters.contains("-DmyKey=myVal")); } @Test public void testDefaultsAreUsedDuringImport() throws Exception { RunConfigurationImporter appcConfigImporter = new JavaApplicationRunConfigurationImporter(); maskRunImporter(appcConfigImporter); createSettingsFile("rootProject.name = 'moduleName'"); importProject( withGradleIdeaExtPlugin( "import org.jetbrains.gradle.ext.*\n" + "idea {\n" + " project.settings {\n" + " runConfigurations {\n" + " defaults(Application) {\n" + " jvmArgs = '-DmyKey=myVal'\n" + " }\n" + " 'My Run'(Application) {\n" + " mainClass = 'my.app.Class'\n" + " moduleName = 'moduleName'\n" + " }\n" + " }\n" + " }\n" + "}") ); final RunManager runManager = RunManager.getInstance(myProject); final RunnerAndConfigurationSettings template = runManager.getConfigurationTemplate(appcConfigImporter.getConfigurationFactory()); final String parameters = ((ApplicationConfiguration)template.getConfiguration()).getVMParameters(); assertNotNull(parameters); assertTrue(parameters.contains("-DmyKey=myVal")); final ApplicationConfiguration myRun = (ApplicationConfiguration)runManager.findConfigurationByName("My Run").getConfiguration(); assertNotNull(myRun); final String actualParams = myRun.getVMParameters(); assertNotNull(actualParams); assertTrue(actualParams.contains("-DmyKey=myVal")); assertEquals("my.app.Class", myRun.getMainClassName()); } @Test public void testBeforeRunTaskImport() throws Exception { RunConfigurationImporter appcConfigImporter = new JavaApplicationRunConfigurationImporter(); maskRunImporter(appcConfigImporter); createSettingsFile("rootProject.name = 'moduleName'"); importProject( withGradleIdeaExtPlugin( "import org.jetbrains.gradle.ext.*\n" + "idea {\n" + " project.settings {\n" + " runConfigurations {\n" + " 'My Run'(Application) {\n" + " mainClass = 'my.app.Class'\n" + " moduleName = 'moduleName'\n" + " beforeRun {\n" + " gradle(GradleTask) { task = tasks['projects'] }\n" + " }\n" + " }\n" + " }\n" + " }\n" + "}") ); final RunManagerEx runManager = RunManagerEx.getInstanceEx(myProject); final ApplicationConfiguration myRun = (ApplicationConfiguration)runManager.findConfigurationByName("My Run").getConfiguration(); assertNotNull(myRun); final List<BeforeRunTask> tasks = runManager.getBeforeRunTasks(myRun); assertSize(2, tasks); final BeforeRunTask gradleBeforeRunTask = tasks.get(1); assertInstanceOf(gradleBeforeRunTask, ExternalSystemBeforeRunTask.class); final ExternalSystemTaskExecutionSettings settings = ((ExternalSystemBeforeRunTask)gradleBeforeRunTask).getTaskExecutionSettings(); assertContain(settings.getTaskNames(), "projects"); assertEquals(FileUtil.toSystemIndependentName(getProjectPath()), FileUtil.toSystemIndependentName(settings.getExternalProjectPath())); } @Test public void testJarApplicationRunConfigurationSettingsImport() throws Exception { TestRunConfigurationImporter testExtension = new TestRunConfigurationImporter("jarApplication"); maskRunImporter(testExtension); createSettingsFile("rootProject.name = 'moduleName'"); importProject( new GradleBuildScriptBuilderEx() .withGradleIdeaExtPluginIfCan(IDEA_EXT_PLUGIN_VERSION) .addPostfix( "import org.jetbrains.gradle.ext.*", "idea.project.settings {", " runConfigurations {", " jarApp1(JarApplication) {", " jarPath = 'my/app.jar'", " jvmArgs = '-DvmKey=vmVal'", " moduleName = 'moduleName'", " }", " jarApp2(JarApplication) {", " jarPath = 'my/app2.jar'", " moduleName = 'moduleName'", " }", " }", "}" ).generate()); final Map<String, Map<String, Object>> configs = testExtension.getConfigs(); assertContain(new ArrayList<>(configs.keySet()), "jarApp1", "jarApp2"); Map<String, Object> jarApp1Settings = configs.get("jarApp1"); Map<String, Object> jarApp2Settings = configs.get("jarApp2"); assertEquals("my/app.jar", jarApp1Settings.get("jarPath")); assertEquals("my/app2.jar", jarApp2Settings.get("jarPath")); assertEquals("-DvmKey=vmVal", jarApp1Settings.get("jvmArgs")); assertNull(jarApp2Settings.get("jvmArgs")); } @Test public void testJarApplicationBeforeRunGradleTaskImport() throws Exception { RunConfigurationImporter jarAppConfigImporter = new JarApplicationRunConfigurationImporter(); maskRunImporter(jarAppConfigImporter); createSettingsFile("rootProject.name = 'moduleName'"); importProject( withGradleIdeaExtPlugin( "import org.jetbrains.gradle.ext.*\n" + "idea.project.settings {\n" + " runConfigurations {\n" + " 'jarApp'(JarApplication) {\n" + " beforeRun {\n" + " 'gradleTask'(GradleTask) {\n" + " task = tasks['projects']\n" + " }\n" + " }\n" + " }\n" + " }\n" + "}" ) ); RunManagerEx runManager = RunManagerEx.getInstanceEx(myProject); RunConfiguration jarApp = runManager.findConfigurationByName("jarApp").getConfiguration(); assertNotNull(jarApp); List<BeforeRunTask> tasks = runManager.getBeforeRunTasks(jarApp); assertSize(1, tasks); BeforeRunTask gradleBeforeRunTask = tasks.get(0); assertInstanceOf(gradleBeforeRunTask, ExternalSystemBeforeRunTask.class); ExternalSystemTaskExecutionSettings settings = ((ExternalSystemBeforeRunTask)gradleBeforeRunTask).getTaskExecutionSettings(); assertContain(settings.getTaskNames(), "projects"); assertEquals(FileUtil.toSystemIndependentName(getProjectPath()), FileUtil.toSystemIndependentName(settings.getExternalProjectPath())); } @Test public void testFacetSettingsImport() throws Exception { TestFacetConfigurationImporter testExtension = new TestFacetConfigurationImporter("spring"); ExtensionTestUtil .maskExtensions(FacetConfigurationImporter.EP_NAME, Collections.<FacetConfigurationImporter>singletonList(testExtension), getTestRootDisposable()); importProject( withGradleIdeaExtPlugin( "import org.jetbrains.gradle.ext.*\n" + "idea {\n" + " module.settings {\n" + " facets {\n" + " spring(SpringFacet) {\n" + " contexts {\n" + " myParent {\n" + " file = 'parent_ctx.xml'\n" + " }\n" + " myChild {\n" + " file = 'child_ctx.xml'\n" + " parent = 'myParent'" + " }\n" + " }\n" + " }\n" + " }\n" + " }\n" + "}") ); final Map<String, Map<String, Object>> facetConfigs = testExtension.getConfigs(); assertContain(new ArrayList<>(facetConfigs.keySet()), "spring"); List<Map<String, Object>> springCtxConfigs = (List<Map<String, Object>>)facetConfigs.get("spring").get("contexts"); assertContain(springCtxConfigs.stream().map((Map m) -> m.get("name")).collect(Collectors.toList()), "myParent", "myChild"); Map<String, Object> parentSettings = springCtxConfigs.stream() .filter((Map m) -> m.get("name").equals("myParent")) .findFirst() .get(); Map<String, Object> childSettings = springCtxConfigs.stream() .filter((Map m) -> m.get("name").equals("myChild")) .findFirst() .get(); assertEquals("parent_ctx.xml", parentSettings.get("file")); assertEquals("child_ctx.xml", childSettings.get("file")); assertEquals("myParent", childSettings.get("parent")); } @Test public void testTaskTriggersImport() throws Exception { importProject( withGradleIdeaExtPlugin( "import org.jetbrains.gradle.ext.*\n" + "idea {\n" + " project.settings {\n" + " taskTriggers {\n" + " beforeSync tasks.getByName('projects'), tasks.getByName('tasks')\n" + " }\n" + " }\n" + "}") ); final List<ExternalProjectsManagerImpl.ExternalProjectsStateProvider.TasksActivation> activations = ExternalProjectsManagerImpl.getInstance(myProject).getStateProvider().getAllTasksActivation(); assertSize(1, activations); final ExternalProjectsManagerImpl.ExternalProjectsStateProvider.TasksActivation activation = activations.get(0); assertEquals(GradleSettings.getInstance(myProject).getLinkedProjectsSettings().iterator().next().getExternalProjectPath(), activation.projectPath); final List<String> beforeSyncTasks = activation.state.getTasks(ExternalSystemTaskActivator.Phase.BEFORE_SYNC); if (extPluginVersionIsAtLeast("0.5")) { assertContain(beforeSyncTasks, "projects", "tasks"); } else { assertContain(beforeSyncTasks, ":projects", ":tasks"); } } @Test public void testImportEncodingSettings() throws IOException { { importProject( new GradleBuildScriptBuilderEx() .withGradleIdeaExtPlugin(IDEA_EXT_PLUGIN_VERSION) .addImport("org.jetbrains.gradle.ext.EncodingConfiguration.BomPolicy") .addPostfix("idea {") .addPostfix(" project {") .addPostfix(" settings {") .addPostfix(" encodings {") .addPostfix(" encoding = 'IBM-Thai'") .addPostfix(" bomPolicy = BomPolicy.WITH_NO_BOM") .addPostfix(" properties {") .addPostfix(" encoding = 'GB2312'") .addPostfix(" transparentNativeToAsciiConversion = true") .addPostfix(" }") .addPostfix(" }") .addPostfix(" }") .addPostfix(" }") .addPostfix("}") .generate()); EncodingProjectManagerImpl encodingManager = (EncodingProjectManagerImpl)EncodingProjectManager.getInstance(myProject); assertEquals("IBM-Thai", encodingManager.getDefaultCharset().name()); assertEquals("GB2312", encodingManager.getDefaultCharsetForPropertiesFiles(null).name()); assertTrue(encodingManager.isNative2AsciiForPropertiesFiles()); assertFalse(encodingManager.shouldAddBOMForNewUtf8File()); } { importProject( new GradleBuildScriptBuilderEx() .withGradleIdeaExtPlugin(IDEA_EXT_PLUGIN_VERSION) .addImport("org.jetbrains.gradle.ext.EncodingConfiguration.BomPolicy") .addPostfix("idea {") .addPostfix(" project {") .addPostfix(" settings {") .addPostfix(" encodings {") .addPostfix(" encoding = 'UTF-8'") .addPostfix(" bomPolicy = BomPolicy.WITH_BOM") .addPostfix(" properties {") .addPostfix(" encoding = 'UTF-8'") .addPostfix(" transparentNativeToAsciiConversion = false") .addPostfix(" }") .addPostfix(" }") .addPostfix(" }") .addPostfix(" }") .addPostfix("}") .generate()); EncodingProjectManagerImpl encodingManager = (EncodingProjectManagerImpl)EncodingProjectManager.getInstance(myProject); assertEquals("UTF-8", encodingManager.getDefaultCharset().name()); assertEquals("UTF-8", encodingManager.getDefaultCharsetForPropertiesFiles(null).name()); assertFalse(encodingManager.isNative2AsciiForPropertiesFiles()); assertTrue(encodingManager.shouldAddBOMForNewUtf8File()); } } @Test public void testImportFileEncodingSettings() throws IOException { VirtualFile aDir = createProjectSubDir("src/main/java/a"); VirtualFile bDir = createProjectSubDir("src/main/java/b"); VirtualFile cDir = createProjectSubDir("src/main/java/c"); VirtualFile mainDir = createProjectSubDir("../sub-project/src/main/java"); createProjectSubFile("src/main/java/a/A.java"); createProjectSubFile("src/main/java/c/C.java"); createProjectSubFile("../sub-project/src/main/java/Main.java"); { importProject( new GradleBuildScriptBuilderEx() .withJavaPlugin() .withGradleIdeaExtPlugin(IDEA_EXT_PLUGIN_VERSION) .addImport("org.jetbrains.gradle.ext.EncodingConfiguration.BomPolicy") .addPostfix("sourceSets {") .addPostfix(" main.java.srcDirs += '../sub-project/src/main/java'") .addPostfix("}") .addPostfix("idea {") .addPostfix(" project {") .addPostfix(" settings {") .addPostfix(" encodings {") .addPostfix(" mapping['src/main/java/a'] = 'ISO-8859-9'") .addPostfix(" mapping['src/main/java/b'] = 'x-EUC-TW'") .addPostfix(" mapping['src/main/java/c'] = 'UTF-8'") .addPostfix(" mapping['../sub-project/src/main/java'] = 'KOI8-R'") .addPostfix(" }") .addPostfix(" }") .addPostfix(" }") .addPostfix("}") .generate()); EncodingProjectManagerImpl encodingManager = (EncodingProjectManagerImpl)EncodingProjectManager.getInstance(myProject); Map<String, String> allMappings = encodingManager.getAllMappings().entrySet().stream() .collect(Collectors.toMap(it -> it.getKey().getCanonicalPath(), it -> it.getValue().name())); assertEquals("ISO-8859-9", allMappings.get(aDir.getCanonicalPath())); assertEquals("x-EUC-TW", allMappings.get(bDir.getCanonicalPath())); assertEquals("UTF-8", allMappings.get(cDir.getCanonicalPath())); assertEquals("KOI8-R", allMappings.get(mainDir.getCanonicalPath())); } { importProject( new GradleBuildScriptBuilderEx() .withJavaPlugin() .withGradleIdeaExtPlugin(IDEA_EXT_PLUGIN_VERSION) .addImport("org.jetbrains.gradle.ext.EncodingConfiguration.BomPolicy") .addPostfix("sourceSets {") .addPostfix(" main.java.srcDirs += '../sub-project/src/main/java'") .addPostfix("}") .addPostfix("idea {") .addPostfix(" project {") .addPostfix(" settings {") .addPostfix(" encodings {") .addPostfix(" mapping['src/main/java/a'] = '<System Default>'") .addPostfix(" mapping['src/main/java/b'] = '<System Default>'") .addPostfix(" mapping['../sub-project/src/main/java'] = '<System Default>'") .addPostfix(" }") .addPostfix(" }") .addPostfix(" }") .addPostfix("}") .generate()); EncodingProjectManagerImpl encodingManager = (EncodingProjectManagerImpl)EncodingProjectManager.getInstance(myProject); Map<String, String> allMappings = encodingManager.getAllMappings().entrySet().stream() .collect(Collectors.toMap(it -> it.getKey().getCanonicalPath(), it -> it.getValue().name())); assertNull(allMappings.get(aDir.getCanonicalPath())); assertNull(allMappings.get(bDir.getCanonicalPath())); assertEquals("UTF-8", allMappings.get(cDir.getCanonicalPath())); assertNull(allMappings.get(mainDir.getCanonicalPath())); } } @Test public void testActionDelegationImport() throws Exception { importProject( withGradleIdeaExtPlugin( "import org.jetbrains.gradle.ext.*\n" + "import static org.jetbrains.gradle.ext.ActionDelegationConfig.TestRunner.*\n" + "idea {\n" + " project.settings {\n" + " delegateActions {\n" + " delegateBuildRunToGradle = true\n" + " testRunner = CHOOSE_PER_TEST\n" + " }\n" + " }\n" + "}") ); String projectPath = getCurrentExternalProjectSettings().getExternalProjectPath(); assertTrue(GradleProjectSettings.isDelegatedBuildEnabled(myProject, projectPath)); assertEquals(TestRunner.CHOOSE_PER_TEST, GradleProjectSettings.getTestRunner(myProject, projectPath)); } @Test public void testSavePackagePrefixAfterReOpenProject() throws IOException { @Language("Groovy") String buildScript = new GradleBuildScriptBuilderEx().withJavaPlugin().generate(); createProjectSubFile("src/main/java/Main.java", ""); importProject(buildScript); Application application = ApplicationManager.getApplication(); IdeModifiableModelsProvider modelsProvider = new IdeModifiableModelsProviderImpl(myProject); try { Module module = modelsProvider.findIdeModule("project.main"); ModifiableRootModel modifiableRootModel = modelsProvider.getModifiableRootModel(module); SourceFolder sourceFolder = findSource(modifiableRootModel, "src/main/java"); sourceFolder.setPackagePrefix("prefix.package.some"); application.invokeAndWait(() -> application.runWriteAction(() -> modelsProvider.commit())); } finally { application.invokeAndWait(() -> modelsProvider.dispose()); } assertSourcePackagePrefix("project.main", "src/main/java", "prefix.package.some"); importProject(buildScript); assertSourcePackagePrefix("project.main", "src/main/java", "prefix.package.some"); } @Test public void testRemovingSourceFolderManagerMemLeaking() throws IOException { SourceFolderManagerImpl sourceFolderManager = (SourceFolderManagerImpl)SourceFolderManager.getInstance(myProject); String javaSourcePath = FileUtil.toCanonicalPath(myProjectRoot.getPath() + "/java"); String javaSourceUrl = VfsUtilCore.pathToUrl(javaSourcePath); { importProject( new GradleBuildScriptBuilderEx() .withJavaPlugin() .addPostfix("sourceSets {") .addPostfix(" main.java.srcDirs += 'java'") .addPostfix("}") .generate()); Set<String> sourceFolders = sourceFolderManager.getSourceFolders("project.main"); assertTrue(sourceFolders.contains(javaSourceUrl)); } { importProject( new GradleBuildScriptBuilderEx() .withJavaPlugin() .generate()); Set<String> sourceFolders = sourceFolderManager.getSourceFolders("project.main"); assertFalse(sourceFolders.contains(javaSourceUrl)); } } @Test public void testSourceFolderIsDisposedAfterProjectDisposing() throws IOException { importProject(new GradleBuildScriptBuilder().generate()); Application application = ApplicationManager.getApplication(); Ref<Project> projectRef = new Ref<>(); application.invokeAndWait(() -> projectRef.set(ProjectUtil.openOrImport(myProjectRoot.toNioPath()))); Project project = projectRef.get(); SourceFolderManagerImpl sourceFolderManager = (SourceFolderManagerImpl)SourceFolderManager.getInstance(project); try { assertFalse(project.isDisposed()); assertFalse(sourceFolderManager.isDisposed()); } finally { PlatformTestUtil.forceCloseProjectWithoutSaving(project); } assertTrue(project.isDisposed()); assertTrue(sourceFolderManager.isDisposed()); } @Test public void testPostponedImportPackagePrefix() throws Exception { createProjectSubFile("src/main/java/Main.java", ""); importProject( new GradleBuildScriptBuilderEx() .withGradleIdeaExtPlugin(IDEA_EXT_PLUGIN_VERSION) .withJavaPlugin() .withKotlinPlugin("1.3.50") .addPostfix("idea {") .addPostfix(" module {") .addPostfix(" settings {") .addPostfix(" packagePrefix['src/main/java'] = 'prefix.package.some'") .addPostfix(" packagePrefix['src/main/kotlin'] = 'prefix.package.other'") .addPostfix(" packagePrefix['src/test/java'] = 'prefix.package.some.test'") .addPostfix(" }") .addPostfix(" }") .addPostfix("}") .generate()); assertSourcePackagePrefix("project.main", "src/main/java", "prefix.package.some"); assertSourceNotExists("project.main", "src/main/kotlin"); assertSourceNotExists("project.test", "src/test/java"); createProjectSubFile("src/main/kotlin/Main.kt", ""); edt(() -> { ((SourceFolderManagerImpl)SourceFolderManager.getInstance(myProject)).consumeBulkOperationsState(future -> { PlatformTestUtil.waitForFuture(future, 1000); return null; }); }); assertSourcePackagePrefix("project.main", "src/main/java", "prefix.package.some"); assertSourcePackagePrefix("project.main", "src/main/kotlin", "prefix.package.other"); assertSourceNotExists("project.test", "src/test/java"); } @Test public void testPartialImportPackagePrefix() throws IOException { createProjectSubFile("src/main/java/Main.java", ""); createProjectSubFile("src/main/kotlin/Main.kt", ""); importProject( new GradleBuildScriptBuilderEx() .withGradleIdeaExtPlugin(IDEA_EXT_PLUGIN_VERSION) .withJavaPlugin() .withKotlinPlugin("1.3.50") .addPostfix("idea {") .addPostfix(" module {") .addPostfix(" settings {") .addPostfix(" packagePrefix['src/main/java'] = 'prefix.package.some'") .addPostfix(" }") .addPostfix(" }") .addPostfix("}") .generate()); assertSourcePackagePrefix("project.main", "src/main/java", "prefix.package.some"); assertSourcePackagePrefix("project.main", "src/main/kotlin", ""); } @Test public void testImportPackagePrefixWithRemoteSourceRoot() throws IOException { createProjectSubFile("src/test/java/Main.java", ""); createProjectSubFile("../subproject/src/test/java/Main.java", ""); importProject( new GradleBuildScriptBuilderEx() .withGradleIdeaExtPlugin(IDEA_EXT_PLUGIN_VERSION) .withJavaPlugin() .addPostfix("sourceSets {") .addPostfix(" test.java.srcDirs += '../subproject/src/test/java'") .addPostfix("}") .addPostfix("idea {") .addPostfix(" module {") .addPostfix(" settings {") .addPostfix(" packagePrefix['src/test/java'] = 'prefix.package.some'") .addPostfix(" packagePrefix['../subproject/src/test/java'] = 'prefix.package.other'") .addPostfix(" }") .addPostfix(" }") .addPostfix("}") .generate()); printProjectStructure(); assertSourcePackagePrefix("project.test", "src/test/java", "prefix.package.some"); assertSourcePackagePrefix("project.test", "../subproject/src/test/java", "prefix.package.other"); } @Test public void testImportPackagePrefix() throws IOException { createProjectSubFile("src/main/java/Main.java", ""); importProject( new GradleBuildScriptBuilderEx() .withGradleIdeaExtPlugin(IDEA_EXT_PLUGIN_VERSION) .withJavaPlugin() .addPostfix("idea {") .addPostfix(" module {") .addPostfix(" settings {") .addPostfix(" packagePrefix['src/main/java'] = 'prefix.package.some'") .addPostfix(" }") .addPostfix(" }") .addPostfix("}") .generate()); assertSourcePackagePrefix("project.main", "src/main/java", "prefix.package.some"); } @Test public void testChangeImportPackagePrefix() throws IOException { createProjectSubFile("src/main/java/Main.java", ""); importProject( new GradleBuildScriptBuilderEx() .withGradleIdeaExtPlugin(IDEA_EXT_PLUGIN_VERSION) .withJavaPlugin() .addPostfix("idea {") .addPostfix(" module {") .addPostfix(" settings {") .addPostfix(" packagePrefix['src/main/java'] = 'prefix.package.some'") .addPostfix(" }") .addPostfix(" }") .addPostfix("}") .generate()); assertSourcePackagePrefix("project.main", "src/main/java", "prefix.package.some"); importProject( new GradleBuildScriptBuilderEx() .withGradleIdeaExtPlugin(IDEA_EXT_PLUGIN_VERSION) .withJavaPlugin() .addPostfix("idea {") .addPostfix(" module {") .addPostfix(" settings {") .addPostfix(" packagePrefix['src/main/java'] = 'prefix.package.other'") .addPostfix(" }") .addPostfix(" }") .addPostfix("}") .generate()); assertSourcePackagePrefix("project.main", "src/main/java", "prefix.package.other"); } @Test public void testModuleTypesImport() throws Exception { importProject( new GradleBuildScriptBuilderEx() .withGradleIdeaExtPluginIfCan(IDEA_EXT_PLUGIN_VERSION) .withJavaPlugin() .addPostfix( "import org.jetbrains.gradle.ext.*", "idea.module.settings {", " rootModuleType = 'EMPTY_MODULE'", " moduleType[sourceSets.main] = 'WEB_MODULE'", " }" ).generate()); assertThat(getModule("project").getModuleTypeName()).isEqualTo("EMPTY_MODULE"); assertThat(getModule("project.main").getModuleTypeName()).isEqualTo("WEB_MODULE"); assertThat(getModule("project.test").getModuleTypeName()).isEqualTo("JAVA_MODULE"); } }
apache-2.0
carlosgsouza/types-and-quality
experiments/1_vinyl_collection/a1/analysis/data/mateus/snapshots/1387294570511/src/main/groovy/carlosgsouza/vinylshop/view/ListArtistsView.java
467
package carlosgsouza.vinylshop.view; import java.util.List; import carlosgsouza.derails.View; class ListArtistsView extends View { public ListArtistsView(List<String> list) { if(list.size() > 1) { items.add("Listing " + list.size() + " artists"); items.addAll(list); } else if(lisf.size() == 1) { items.add("Listing 1 artist"); items.addAll(list); } else { items.add("Unexpected error. Artist list had " + Iist.size() + " items"); } } }
apache-2.0
zstackorg/zstack-woodpecker
integrationtest/vm/monitor/alert_host_all_cpus_idle.py
2656
''' Test about monitor trigger on all host cpu free ratio in one minute @author: Songtao,Haochen ''' import os import test_stub import random import time import zstacklib.utils.ssh as ssh import zstackwoodpecker.test_util as test_util import zstackwoodpecker.operations.resource_operations as res_ops import zstackwoodpecker.operations.monitor_operations as mon_ops def test(): global trigger global media global trigger_action test_item = "host.cpu.util" resource_type="HostVO" host_monitor_item = test_stub.get_monitor_item(resource_type) if test_item not in host_monitor_item: test_util.test_fail('%s is not available for monitor' % test_item) hosts = res_ops.get_resource(res_ops.HOST) host = hosts[0] duration = 60 expression = "host.cpu.util{cpu=-1,type=\"idle\"}<80.6" monitor_trigger = mon_ops.create_monitor_trigger(host.uuid, duration, expression) send_email = test_stub.create_email_media() media = send_email.uuid trigger_action_name = "trigger"+ ''.join(map(lambda xx:(hex(ord(xx))[2:]),os.urandom(8))) trigger = monitor_trigger.uuid receive_email = os.environ.get('receive_email') monitor_trigger_action = mon_ops.create_email_monitor_trigger_action(trigger_action_name, send_email.uuid, trigger.split(), receive_email) trigger_action = monitor_trigger_action.uuid host.password = os.environ.get('hostPassword') ssh_cmd = test_stub.ssh_cmd_line(host.managementIp, host.username, host.password, port=int(host.sshPort)) test_stub.run_all_cpus_load(ssh_cmd) time.sleep(30) status_problem, status_ok = test_stub.query_trigger_in_loop(trigger,50) test_util.action_logger('Trigger old status: %s triggered. Trigger new status: %s recovered' % (status_problem, status_ok )) if status_problem != 1 or status_ok != 1: test_util.test_fail('%s Monitor Test failed, expected Problem or OK status not triggered' % test_item) mail_list = test_stub.receive_email() keywords = "fired" mail_flag = test_stub.check_email(mail_list, keywords, trigger, host.uuid) if mail_flag == 0: test_util.test_fail('Failed to Get Target: %s for: %s Trigger Mail' % (vm_uuid, test_item)) mon_ops.delete_monitor_trigger_action(trigger_action) mon_ops.delete_monitor_trigger(trigger) mon_ops.delete_email_media(media) def error_cleanup(): global trigger global media global trigger_action mon_ops.delete_monitor_trigger_action(trigger_action) mon_ops.delete_monitor_trigger(trigger) mon_ops.delete_email_media(media)
apache-2.0
BigBoss424/portfolio
v6/node_modules/date-fns/esm/locale/ja/_lib/localize/index.js
2910
import buildLocalizeFn from '../../../_lib/buildLocalizeFn/index.js'; var eraValues = { narrow: ['BC', 'AC'], abbreviated: ['紀元前', '西暦'], wide: ['紀元前', '西暦'] }; var quarterValues = { narrow: ['1', '2', '3', '4'], abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'], wide: ['第1四半期', '第2四半期', '第3四半期', '第4四半期'] }; var monthValues = { narrow: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], abbreviated: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'], wide: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'] }; var dayValues = { narrow: ['日', '月', '火', '水', '木', '金', '土'], short: ['日', '月', '火', '水', '木', '金', '土'], abbreviated: ['日', '月', '火', '水', '木', '金', '土'], wide: ['日曜日', '月曜日', '火曜日', '水曜日', '木曜日', '金曜日', '土曜日'] }; var dayPeriodValues = { narrow: { am: '午前', pm: '午後', midnight: '深夜', noon: '正午', morning: '朝', afternoon: '午後', evening: '夜', night: '深夜' }, abbreviated: { am: '午前', pm: '午後', midnight: '深夜', noon: '正午', morning: '朝', afternoon: '午後', evening: '夜', night: '深夜' }, wide: { am: '午前', pm: '午後', midnight: '深夜', noon: '正午', morning: '朝', afternoon: '午後', evening: '夜', night: '深夜' } }; var formattingDayPeriodValues = { narrow: { am: '午前', pm: '午後', midnight: '深夜', noon: '正午', morning: '朝', afternoon: '午後', evening: '夜', night: '深夜' }, abbreviated: { am: '午前', pm: '午後', midnight: '深夜', noon: '正午', morning: '朝', afternoon: '午後', evening: '夜', night: '深夜' }, wide: { am: '午前', pm: '午後', midnight: '深夜', noon: '正午', morning: '朝', afternoon: '午後', evening: '夜', night: '深夜' } }; function ordinalNumber(dirtyNumber) { var number = Number(dirtyNumber); return number; } var localize = { ordinalNumber: ordinalNumber, era: buildLocalizeFn({ values: eraValues, defaultWidth: 'wide' }), quarter: buildLocalizeFn({ values: quarterValues, defaultWidth: 'wide', argumentCallback: function (quarter) { return Number(quarter) - 1; } }), month: buildLocalizeFn({ values: monthValues, defaultWidth: 'wide' }), day: buildLocalizeFn({ values: dayValues, defaultWidth: 'wide' }), dayPeriod: buildLocalizeFn({ values: dayPeriodValues, defaultWidth: 'wide', formattingValues: formattingDayPeriodValues, defaultFormattingWidth: 'wide' }) }; export default localize;
apache-2.0
hazendaz/classloader-leak-prevention
classloader-leak-prevention/classloader-leak-prevention-core/src/main/java/se/jiderhamn/classloader/leak/prevention/cleanup/MBeanCleanUp.java
9587
package se.jiderhamn.classloader.leak.prevention.cleanup; import java.lang.management.ManagementFactory; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import javax.management.MBeanServer; import javax.management.ObjectName; import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor; import se.jiderhamn.classloader.leak.prevention.ClassLoaderPreMortemCleanUp; /** * Unregister MBeans loaded by the protected class loader * @author Mattias Jiderhamn * @author rapla */ public class MBeanCleanUp implements ClassLoaderPreMortemCleanUp { @Override public void cleanUp(ClassLoaderLeakPreventor preventor) { try { final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); final Set<ObjectName> allMBeanNames = mBeanServer.queryNames(new ObjectName("*:*"), null); // Special treatment for Jetty, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=423255 JettyJMXRemover jettyJMXRemover = null; if(isJettyWithJMX(preventor)) { try { jettyJMXRemover = new JettyJMXRemover(preventor); } catch (Exception ex) { preventor.error(ex); } } // Look for custom MBeans for(ObjectName objectName : allMBeanNames) { try { if (jettyJMXRemover != null && jettyJMXRemover.unregisterJettyJMXBean(objectName)) { continue; } final ClassLoader mBeanClassLoader = mBeanServer.getClassLoaderFor(objectName); if(preventor.isClassLoaderOrChild(mBeanClassLoader)) { // MBean loaded by protected ClassLoader preventor.warn("MBean '" + objectName + "' was loaded by protected ClassLoader; unregistering"); mBeanServer.unregisterMBean(objectName); } /* else if(... instanceof NotificationBroadcasterSupport) { unregisterNotificationListeners((NotificationBroadcasterSupport) ...); } */ } catch(Exception e) { // MBeanRegistrationException / InstanceNotFoundException preventor.error(e); } } } catch (Exception e) { // MalformedObjectNameException preventor.error(e); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Methods and classes for Jetty, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=423255 /** Are we running in Jetty with JMX enabled? */ @SuppressWarnings("WeakerAccess") protected boolean isJettyWithJMX(ClassLoaderLeakPreventor preventor) { final ClassLoader classLoader = preventor.getClassLoader(); try { // If package org.eclipse.jetty is found, we may be running under jetty if (classLoader.getResource("org/eclipse/jetty") == null) { return false; } Class.forName("org.eclipse.jetty.jmx.MBeanContainer", false, classLoader.getParent()); // JMX enabled? Class.forName("org.eclipse.jetty.webapp.WebAppContext", false, classLoader.getParent()); } catch(Exception ex) { // For example ClassNotFoundException return false; } // Seems we are running in Jetty with JMX enabled return true; } /** * Inner utility class that helps dealing with Jetty MBeans class. * If you enable JMX support in Jetty 8 or 9 some MBeans (e.g. for the ServletHolder or SessionManager) are * instantiated in the web application thread and a reference to the WebappClassloader is stored in a private * ObjectMBean._loader which is unfortunately not the classloader that loaded the class. Therefore we need to access * the MBeanContainer class of the Jetty container and unregister the MBeans. */ private class JettyJMXRemover { private final ClassLoaderLeakPreventor preventor; /** List of objects that may be wrapped in MBean by Jetty. Should be allowed to contain null. */ private List<Object> objectsWrappedWithMBean; /** The org.eclipse.jetty.jmx.MBeanContainer instance */ private Object beanContainer; /** org.eclipse.jetty.jmx.MBeanContainer.findBean() */ private Method findBeanMethod; /** org.eclipse.jetty.jmx.MBeanContainer.removeBean() */ private Method removeBeanMethod; @SuppressWarnings("WeakerAccess") public JettyJMXRemover(ClassLoaderLeakPreventor preventor) throws Exception { this.preventor = preventor; // First we need access to the MBeanContainer to access the beans // WebAppContext webappContext = (WebAppContext)servletContext; final Object webappContext = findJettyClass("org.eclipse.jetty.webapp.WebAppClassLoader") .getMethod("getContext").invoke(preventor.getClassLoader()); if(webappContext == null) return; // Server server = (Server)webappContext.getServer(); final Class<?> webAppContextClass = findJettyClass("org.eclipse.jetty.webapp.WebAppContext"); final Object server = webAppContextClass.getMethod("getServer").invoke(webappContext); if(server == null) return; // MBeanContainer beanContainer = (MBeanContainer)server.getBean(MBeanContainer.class); final Class<?> mBeanContainerClass = findJettyClass("org.eclipse.jetty.jmx.MBeanContainer"); beanContainer = findJettyClass("org.eclipse.jetty.server.Server") .getMethod("getBean", Class.class).invoke(server, mBeanContainerClass); // Now we store all objects that belong to the web application and that will be wrapped by MBeans in a list if (beanContainer != null) { findBeanMethod = mBeanContainerClass.getMethod("findBean", ObjectName.class); try { removeBeanMethod = mBeanContainerClass.getMethod("removeBean", Object.class); } catch (NoSuchMethodException e) { preventor.warn("MBeanContainer.removeBean() method can not be found. giving up"); return; } objectsWrappedWithMBean = new ArrayList<Object>(); // SessionHandler sessionHandler = webappContext.getSessionHandler(); final Object sessionHandler = webAppContextClass.getMethod("getSessionHandler").invoke(webappContext); if(sessionHandler != null) { objectsWrappedWithMBean.add(sessionHandler); // SessionManager sessionManager = sessionHandler.getSessionManager(); final Object sessionManager = findJettyClass("org.eclipse.jetty.server.session.SessionHandler") .getMethod("getSessionManager").invoke(sessionHandler); if(sessionManager != null) { objectsWrappedWithMBean.add(sessionManager); // SessionIdManager sessionIdManager = sessionManager.getSessionIdManager(); final Object sessionIdManager = findJettyClass("org.eclipse.jetty.server.SessionManager") .getMethod("getSessionIdManager").invoke(sessionManager); objectsWrappedWithMBean.add(sessionIdManager); } } // SecurityHandler securityHandler = webappContext.getSecurityHandler(); objectsWrappedWithMBean.add(webAppContextClass.getMethod("getSecurityHandler").invoke(webappContext)); // ServletHandler servletHandler = webappContext.getServletHandler(); final Object servletHandler = webAppContextClass.getMethod("getServletHandler").invoke(webappContext); if(servletHandler != null) { objectsWrappedWithMBean.add(servletHandler); final Class<?> servletHandlerClass = findJettyClass("org.eclipse.jetty.servlet.ServletHandler"); // Object[] servletMappings = servletHandler.getServletMappings(); objectsWrappedWithMBean.add(Arrays.asList((Object[]) servletHandlerClass.getMethod("getServletMappings").invoke(servletHandler))); // Object[] servlets = servletHandler.getServlets(); objectsWrappedWithMBean.add(Arrays.asList((Object[]) servletHandlerClass.getMethod("getServlets").invoke(servletHandler))); } } } /** * Test if objectName denotes a wrapping Jetty MBean and if so unregister it. * @return {@code true} if Jetty MBean was unregistered, otherwise {@code false} */ boolean unregisterJettyJMXBean(ObjectName objectName) { if (objectsWrappedWithMBean == null || ! objectName.getDomain().contains("org.eclipse.jetty")) { return false; } else { // Possibly a Jetty MBean that needs to be unregistered try { final Object bean = findBeanMethod.invoke(beanContainer, objectName); if(bean == null) return false; // Search suspect list for (Object wrapped : objectsWrappedWithMBean) { if (wrapped == bean) { preventor.warn("Jetty MBean '" + objectName + "' is a suspect in causing memory leaks; unregistering"); removeBeanMethod.invoke(beanContainer, bean); // Remove it via the MBeanContainer return true; } } } catch (Exception ex) { preventor.error(ex); } return false; } } Class findJettyClass(String className) throws ClassNotFoundException { try { return Class.forName(className, false, preventor.getClassLoader()); } catch (ClassNotFoundException e1) { try { return Class.forName(className); } catch (ClassNotFoundException e2) { e2.addSuppressed(e1); throw e2; } } } } }
apache-2.0
apache/forrest
tools/eclipse/plugins/org.apache.forrest/src/org/apache/forrest/eclipse/ForrestPlugin.java
5602
/* * 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.forrest.eclipse; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.HashMap; import java.util.MissingResourceException; import java.util.ResourceBundle; import org.apache.forrest.eclipse.preference.ForrestPreferences; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** * The main plugin class to be used in the desktop. */ public class ForrestPlugin extends AbstractUIPlugin { public final static String ID = "org.apache.forrest"; /** * Logger for this class */ private static final Logger logger = Logger .getLogger(ForrestPlugin.class); //The shared instance. private static ForrestPlugin plugin; //Resource bundle. private ResourceBundle resourceBundle; private static final String LOG_PROPERTIES_FILE = "/conf/log4j.xml"; /** * The constructor. * */ public ForrestPlugin() { super(); plugin = this; try { resourceBundle = ResourceBundle .getBundle("org.apache.forrest.ForrestPluginResources"); //$NON-NLS-1$ } catch (MissingResourceException x) { resourceBundle = null; } } /** * Returns the shared instance. * * @return */ public static ForrestPlugin getDefault() { return plugin; } /** * Returns the string from the plugin's resource bundle, or 'key' if not * found. * * @param key * @return */ public static String getResourceString(String key) { ResourceBundle bundle = ForrestPlugin.getDefault().getResourceBundle(); try { return (bundle != null) ? bundle.getString(key) : key; } catch (MissingResourceException e) { return key; } } /** * Returns the plugin's resource bundle, * * @return */ public ResourceBundle getResourceBundle() { return resourceBundle; } /* (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#initializeDefaultPreferences(org.eclipse.jface.preference.IPreferenceStore) */ protected void initializeDefaultPreferences(IPreferenceStore store) { super.initializeDefaultPreferences(store); HashMap envVariables = new HashMap(); BufferedReader reader = null; //"env" works on Linux & Unix Variants but if we're on Windows, //use "cmd /c set". String envCommand = "env"; if (System.getProperty("os.name").toLowerCase().startsWith("win")) envCommand = "cmd /c set"; try { //First we launch the command and attach a Reader to the Output Process p = Runtime.getRuntime().exec(envCommand); reader = new BufferedReader(new InputStreamReader(p.getInputStream())); //Now we parse the output, filling up the Hashtable String theLine = null; while ( (theLine = reader.readLine()) != null) { int equalsIndex = theLine.indexOf("="); if (equalsIndex < 0) continue; String name = theLine.substring(0,equalsIndex); String value = ""; //Test for an empty value such as "FOO=" if ((equalsIndex + 1) < theLine.length()) value = theLine.substring(equalsIndex+1, theLine.length()); envVariables.put(name, value); } } catch (IOException e) { // FIXME: Handle this error e.printStackTrace(); } store = getPreferenceStore(); if (envVariables.containsKey(ForrestPreferences.FORREST_HOME)) { store.setDefault(ForrestPreferences.FORREST_HOME, (String)envVariables.get(ForrestPreferences.FORREST_HOME)); } } /** * Set the preference value for Forrest Home. * @param forrestHome */ public void setForrestHome(String forrestHome) { IPreferenceStore store = getPreferenceStore(); store.setDefault(ForrestPreferences.FORREST_HOME, forrestHome); } public void start(BundleContext context) throws Exception { super.start(context); configureLog(); } private void configureLog() { URL configURL = getBundle().getEntry(LOG_PROPERTIES_FILE); try { URL log4jConf = Platform.resolve(configURL); DOMConfigurator.configure(log4jConf); } catch (IOException e) { String message = "Error while initializing log properties." + e.getMessage(); IStatus status = new Status(IStatus.ERROR, getDefault().getBundle().getSymbolicName(), IStatus.ERROR, message, e); getLog().log(status); // having logged this problem we will continue without log4j logging } } }
apache-2.0
datacite/mds
src/main/java/org/datacite/mds/validation/constraints/URL.java
1104
package org.datacite.mds.validation.constraints; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; /** * This annotation is used for a String containing a URL. It checks if the URL * is well-formed and have one of http, https and ftp as protocol. Null is a * valid URL (use @NotNull annotation if you don't want this). */ @Documented @Size(max = 2048) @org.hibernate.validator.constraints.URL @Pattern(regexp = "(https?|ftp)://.*|\\s*", message = "{org.datacite.mds.validation.constraints.URL.protocol.message}") @Target( { ElementType.FIELD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = {}) public @interface URL { String message() default ""; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
apache-2.0
ananya-bhattacharya/hydrator-plugins
solrsearch-plugins/src/main/java/co/cask/hydrator/plugin/realtime/RealtimeSolrSearchSink.java
4188
/* * Copyright © 2016 Cask Data, 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 co.cask.hydrator.plugin.realtime; import co.cask.cdap.api.annotation.Description; import co.cask.cdap.api.annotation.Name; import co.cask.cdap.api.annotation.Plugin; import co.cask.cdap.api.data.format.StructuredRecord; import co.cask.cdap.api.data.schema.Schema; import co.cask.cdap.etl.api.PipelineConfigurer; import co.cask.cdap.etl.api.StageMetrics; import co.cask.cdap.etl.api.realtime.DataWriter; import co.cask.cdap.etl.api.realtime.RealtimeContext; import co.cask.cdap.etl.api.realtime.RealtimeSink; import co.cask.hydrator.plugin.common.SolrSearchSinkConfig; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.common.SolrInputDocument; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Realtime SolrSearch Sink Plugin - Writes data to a SingleNode Solr or to SolrCloud. */ @Plugin(type = "realtimesink") @Name("SolrSearch") @Description("This plugin allows users to build the pipelines to write data to Solr. The input fields coming from " + "the previous stage of the pipeline are mapped to Solr fields. User can also specify the mode of the Solr to " + "connect to. For example, SingleNode Solr or SolrCloud.") public class RealtimeSolrSearchSink extends RealtimeSink<StructuredRecord> { private final SolrSearchSinkConfig config; private String keyField; private Map<String, String> outputFieldMap; private SolrClient solrClient; private StageMetrics metrics; public RealtimeSolrSearchSink(SolrSearchSinkConfig config) { this.config = config; } @Override public void configurePipeline(PipelineConfigurer pipelineConfigurer) { Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); config.validateSolrConnectionString(); if (inputSchema != null) { config.validateKeyField(inputSchema); config.validateInputFieldsDataType(inputSchema); } config.validateOutputFieldMappings(); } @Override public void initialize(RealtimeContext context) throws Exception { keyField = config.getKeyField(); solrClient = config.getSolrConnection(); outputFieldMap = config.createOutputFieldMap(); metrics = context.getMetrics(); //Calling testSolrConnection() before each mapper, to ensure that the connection is alive and available for //indexing. config.testSolrConnection(); } @Override public int write(Iterable<StructuredRecord> structuredRecords, DataWriter dataWriter) throws Exception { int numRecordsWritten = 0; List<SolrInputDocument> documentList = new ArrayList<SolrInputDocument>(); for (StructuredRecord structuredRecord : structuredRecords) { config.validateKeyField(structuredRecord.getSchema()); config.validateInputFieldsDataType(structuredRecord.getSchema()); if (structuredRecord.get(keyField) == null) { metrics.count("invalid", 1); continue; } SolrInputDocument document = new SolrInputDocument(); for (Schema.Field field : structuredRecord.getSchema().getFields()) { String solrFieldName = field.getName(); if (outputFieldMap.containsKey(solrFieldName)) { document.addField(outputFieldMap.get(solrFieldName), structuredRecord.get(solrFieldName)); } else { document.addField(solrFieldName, structuredRecord.get(solrFieldName)); } } documentList.add(document); numRecordsWritten++; } solrClient.add(documentList); solrClient.commit(); return numRecordsWritten; } @Override public void destroy() { solrClient.shutdown(); } }
apache-2.0
apache/avro
lang/csharp/src/apache/ipc/HttpListenerServer.cs
3904
/** * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; using System.Diagnostics; namespace Avro.ipc { public class HttpListenerServer { IEnumerable<string> _prefixes; HttpListener _listener; Responder _responder; public HttpListenerServer(IEnumerable<string> listenOnPrefixes, Responder responder) { _responder = responder; _prefixes = listenOnPrefixes; } //TODO: apparently this doesn't compile in Mono - investigate //public Action<Exception, IAsyncResult> ExceptionHandler { get; set; } protected void HttpListenerCallback(IAsyncResult result) { try { HttpListener listener = (HttpListener)result.AsyncState; if (_listener != listener) //the server which began this callback was stopped - just exit return; HttpListenerContext context = listener.EndGetContext(result); listener.BeginGetContext(HttpListenerCallback, listener); //spawn listening for next request so it can be processed while we are dealing with this one //process this request if (!context.Request.HttpMethod.Equals("POST")) throw new AvroRuntimeException("HTTP method must be POST"); if (!context.Request.ContentType.Equals("avro/binary")) throw new AvroRuntimeException("Content-type must be avro/binary"); byte[] intBuffer = new byte[4]; var buffers = HttpTransceiver.ReadBuffers(context.Request.InputStream, intBuffer); buffers = _responder.Respond(buffers); context.Response.ContentType = "avro/binary"; context.Response.ContentLength64 = HttpTransceiver.CalculateLength(buffers); HttpTransceiver.WriteBuffers(buffers, context.Response.OutputStream); context.Response.OutputStream.Close(); context.Response.Close(); } catch (Exception ex) { //TODO: apparently this doesn't compile in Mono - investigate //if (ExceptionHandler != null) // ExceptionHandler(ex, result); //else // Debug.Print("Exception occured while processing a request, no exception handler was provided - ignoring", ex); Debug.Print("Exception occured while processing a web request, skipping this request: ", ex); } } public void Start() { _listener = new HttpListener(); foreach (string s in _prefixes) { _listener.Prefixes.Add(s); } _listener.Start(); _listener.BeginGetContext(HttpListenerCallback, _listener); } public void Stop() { _listener.Stop(); _listener.Close(); _listener = null; } } }
apache-2.0
biospi/mzmlb
pwiz/pwiz/data/msdata/SpectrumListBase.hpp
2185
// // $Id: SpectrumListBase.hpp 8725 2015-08-04 15:49:57Z pcbrefugee $ // // // Original author: Darren Kessner <darren@proteowizard.org> // // Copyright 2009 Spielberg Family Center for Applied Proteomics // Cedars-Sinai Medical Center, Los Angeles, California 90048 // // 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. // #ifndef _SPECTRUMLISTBASE_HPP_ #define _SPECTRUMLISTBASE_HPP_ #include "pwiz/data/msdata/MSData.hpp" #include "pwiz/utility/misc/IntegerSet.hpp" #include <boost/functional/hash.hpp> #include <stdexcept> #include <iostream> namespace pwiz { namespace msdata { /// common functionality for base SpectrumList implementations class PWIZ_API_DECL SpectrumListBase : public SpectrumList { public: SpectrumListBase() : MSLevelsNone() {}; /// implementation of SpectrumList virtual const boost::shared_ptr<const DataProcessing> dataProcessingPtr() const {return dp_;} /// set DataProcessing virtual void setDataProcessingPtr(DataProcessingPtr dp) { dp_ = dp; } /// issues a warning once per SpectrumList instance (based on string hash) virtual void warn_once(const char* msg) const { boost::hash<const char*> H; if (warn_msg_hashes.insert(H(msg)).second) // .second is true iff value is new { std::cerr << msg << std::endl; } } protected: DataProcessingPtr dp_; // Useful for avoiding repeated ctor when you just want an empty set const pwiz::util::IntegerSet MSLevelsNone; private: mutable std::set<size_t> warn_msg_hashes; // for warn_once use }; } // namespace msdata } // namespace pwiz #endif // _SPECTRUMLISTBASE_HPP_
apache-2.0
michaelgallacher/intellij-community
plugins/junit5_rt/src/com/intellij/junit5/JUnit5IdeaTestRunner.java
2882
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.junit5; import com.intellij.rt.execution.junit.IdeaTestRunner; import org.junit.platform.launcher.Launcher; import org.junit.platform.launcher.LauncherDiscoveryRequest; import org.junit.platform.launcher.TestIdentifier; import org.junit.platform.launcher.TestPlan; import org.junit.platform.launcher.core.LauncherFactory; import java.util.ArrayList; import java.util.List; import java.util.Set; public class JUnit5IdeaTestRunner implements IdeaTestRunner { private TestPlan myTestPlan; @Override public int startRunnerWithArgs(String[] args, ArrayList listeners, String name, int count, boolean sendTree) { Launcher launcher = LauncherFactory.create(); JUnit5TestExecutionListener listener = new JUnit5TestExecutionListener(); launcher.registerTestExecutionListeners(listener); final String[] packageNameRef = new String[1]; final LauncherDiscoveryRequest discoveryRequest = JUnit5TestRunnerUtil.buildRequest(args, packageNameRef); myTestPlan = launcher.discover(discoveryRequest); listener.sendTree(myTestPlan, packageNameRef[0]); launcher.execute(discoveryRequest); return 0; } @Override public Object getTestToStart(String[] args, String name) { final LauncherDiscoveryRequest discoveryRequest = JUnit5TestRunnerUtil.buildRequest(args, new String[1]); Launcher launcher = LauncherFactory.create(); myTestPlan = launcher.discover(discoveryRequest); final Set<TestIdentifier> roots = myTestPlan.getRoots(); return roots.isEmpty() ? null : roots.iterator().next(); } @Override public List getChildTests(Object description) { return new ArrayList<>(myTestPlan.getChildren((TestIdentifier)description)); } @Override public String getStartDescription(Object child) { final TestIdentifier testIdentifier = (TestIdentifier)child; final String className = JUnit5TestExecutionListener.getClassName(testIdentifier); final String methodName = JUnit5TestExecutionListener.getMethodName(testIdentifier); if (methodName != null) { return className + "#" + methodName; } return className != null ? className : (testIdentifier).getDisplayName(); } @Override public String getTestClassName(Object child) { return child.toString(); } }
apache-2.0
nashif/zephyr
scripts/west_commands/runners/dfu.py
4706
# Copyright (c) 2017 Linaro Limited. # # SPDX-License-Identifier: Apache-2.0 '''Runner for flashing with dfu-util.''' from collections import namedtuple import sys import time from runners.core import ZephyrBinaryRunner, RunnerCaps, \ BuildConfiguration DfuSeConfig = namedtuple('DfuSeConfig', ['address', 'options']) class DfuUtilBinaryRunner(ZephyrBinaryRunner): '''Runner front-end for dfu-util.''' def __init__(self, cfg, pid, alt, img, exe='dfu-util', dfuse_config=None): super().__init__(cfg) self.alt = alt self.img = img self.cmd = [exe, '-d,{}'.format(pid)] try: self.list_pattern = ', alt={},'.format(int(self.alt)) except ValueError: self.list_pattern = ', name="{}",'.format(self.alt) if dfuse_config is None: self.dfuse = False else: self.dfuse = True self.dfuse_config = dfuse_config self.reset = False @classmethod def name(cls): return 'dfu-util' @classmethod def capabilities(cls): return RunnerCaps(commands={'flash'}, flash_addr=True) @classmethod def do_add_parser(cls, parser): # Required: parser.add_argument("--pid", required=True, help="USB VID:PID of the board") parser.add_argument("--alt", required=True, help="interface alternate setting number or name") # Optional: parser.add_argument("--img", help="binary to flash, default is --bin-file") parser.add_argument("--dfuse", default=False, action='store_true', help='''use the DfuSe protocol extensions supported by STMicroelectronics devices (if given, the image flash address respects CONFIG_FLASH_BASE_ADDRESS and CONFIG_FLASH_LOAD_OFFSET)''') parser.add_argument("--dfuse-modifiers", default='leave', help='''colon-separated list of additional DfuSe modifiers for dfu-util's -s option (default is "-s <flash-address>:leave", which starts execution immediately); requires --dfuse ''') parser.add_argument('--dfu-util', default='dfu-util', help='dfu-util executable; defaults to "dfu-util"') @classmethod def do_create(cls, cfg, args): if args.img is None: args.img = cfg.bin_file if args.dfuse: args.dt_flash = True # --dfuse implies --dt-flash. build_conf = BuildConfiguration(cfg.build_dir) dcfg = DfuSeConfig(address=cls.get_flash_address(args, build_conf), options=args.dfuse_modifiers) else: dcfg = None ret = DfuUtilBinaryRunner(cfg, args.pid, args.alt, args.img, exe=args.dfu_util, dfuse_config=dcfg) ret.ensure_device() return ret def ensure_device(self): if not self.find_device(): self.reset = True print('Please reset your board to switch to DFU mode...') while not self.find_device(): time.sleep(0.1) def find_device(self): cmd = list(self.cmd) + ['-l'] output = self.check_output(cmd) output = output.decode(sys.getdefaultencoding()) return self.list_pattern in output def do_run(self, command, **kwargs): self.require(self.cmd[0]) self.ensure_output('bin') if not self.find_device(): raise RuntimeError('device not found') cmd = list(self.cmd) if self.dfuse: # http://dfu-util.sourceforge.net/dfuse.html dcfg = self.dfuse_config addr_opts = hex(dcfg.address) + ':' + dcfg.options cmd.extend(['-s', addr_opts]) cmd.extend(['-a', self.alt, '-D', self.img]) self.check_call(cmd) if self.dfuse and 'leave' in dcfg.options.split(':'): # Normal DFU devices generally need to be reset to switch # back to the flashed program. # # DfuSe targets do as well, except when 'leave' is given # as an option. self.reset = False if self.reset: print('Now reset your board again to switch back to runtime mode.')
apache-2.0
FSMaxB/mathjs
src/expression/node/AccessorNode.js
6687
import { isAccessorNode, isArrayNode, isConstantNode, isFunctionNode, isIndexNode, isNode, isObjectNode, isParenthesisNode, isSymbolNode } from '../../utils/is.js' import { getSafeProperty } from '../../utils/customs.js' import { factory } from '../../utils/factory.js' import { accessFactory } from './utils/access.js' const name = 'AccessorNode' const dependencies = [ 'subset', 'Node' ] export const createAccessorNode = /* #__PURE__ */ factory(name, dependencies, ({ subset, Node }) => { const access = accessFactory({ subset }) /** * @constructor AccessorNode * @extends {Node} * Access an object property or get a matrix subset * * @param {Node} object The object from which to retrieve * a property or subset. * @param {IndexNode} index IndexNode containing ranges */ function AccessorNode (object, index) { if (!(this instanceof AccessorNode)) { throw new SyntaxError('Constructor must be called with the new operator') } if (!isNode(object)) { throw new TypeError('Node expected for parameter "object"') } if (!isIndexNode(index)) { throw new TypeError('IndexNode expected for parameter "index"') } this.object = object || null this.index = index // readonly property name Object.defineProperty(this, 'name', { get: function () { if (this.index) { return (this.index.isObjectProperty()) ? this.index.getObjectProperty() : '' } else { return this.object.name || '' } }.bind(this), set: function () { throw new Error('Cannot assign a new name, name is read-only') } }) } AccessorNode.prototype = new Node() AccessorNode.prototype.type = 'AccessorNode' AccessorNode.prototype.isAccessorNode = true /** * Compile a node into a JavaScript function. * This basically pre-calculates as much as possible and only leaves open * calculations which depend on a dynamic scope with variables. * @param {Object} math Math.js namespace with functions and constants. * @param {Object} argNames An object with argument names as key and `true` * as value. Used in the SymbolNode to optimize * for arguments from user assigned functions * (see FunctionAssignmentNode) or special symbols * like `end` (see IndexNode). * @return {function} Returns a function which can be called like: * evalNode(scope: Object, args: Object, context: *) */ AccessorNode.prototype._compile = function (math, argNames) { const evalObject = this.object._compile(math, argNames) const evalIndex = this.index._compile(math, argNames) if (this.index.isObjectProperty()) { const prop = this.index.getObjectProperty() return function evalAccessorNode (scope, args, context) { // get a property from an object evaluated using the scope. return getSafeProperty(evalObject(scope, args, context), prop) } } else { return function evalAccessorNode (scope, args, context) { const object = evalObject(scope, args, context) const index = evalIndex(scope, args, object) // we pass object here instead of context return access(object, index) } } } /** * Execute a callback for each of the child nodes of this node * @param {function(child: Node, path: string, parent: Node)} callback */ AccessorNode.prototype.forEach = function (callback) { callback(this.object, 'object', this) callback(this.index, 'index', this) } /** * Create a new AccessorNode having it's childs be the results of calling * the provided callback function for each of the childs of the original node. * @param {function(child: Node, path: string, parent: Node): Node} callback * @returns {AccessorNode} Returns a transformed copy of the node */ AccessorNode.prototype.map = function (callback) { return new AccessorNode( this._ifNode(callback(this.object, 'object', this)), this._ifNode(callback(this.index, 'index', this)) ) } /** * Create a clone of this node, a shallow copy * @return {AccessorNode} */ AccessorNode.prototype.clone = function () { return new AccessorNode(this.object, this.index) } /** * Get string representation * @param {Object} options * @return {string} */ AccessorNode.prototype._toString = function (options) { let object = this.object.toString(options) if (needParenthesis(this.object)) { object = '(' + object + ')' } return object + this.index.toString(options) } /** * Get HTML representation * @param {Object} options * @return {string} */ AccessorNode.prototype.toHTML = function (options) { let object = this.object.toHTML(options) if (needParenthesis(this.object)) { object = '<span class="math-parenthesis math-round-parenthesis">(</span>' + object + '<span class="math-parenthesis math-round-parenthesis">)</span>' } return object + this.index.toHTML(options) } /** * Get LaTeX representation * @param {Object} options * @return {string} */ AccessorNode.prototype._toTex = function (options) { let object = this.object.toTex(options) if (needParenthesis(this.object)) { object = '\\left(\' + object + \'\\right)' } return object + this.index.toTex(options) } /** * Get a JSON representation of the node * @returns {Object} */ AccessorNode.prototype.toJSON = function () { return { mathjs: 'AccessorNode', object: this.object, index: this.index } } /** * Instantiate an AccessorNode from its JSON representation * @param {Object} json An object structured like * `{"mathjs": "AccessorNode", object: ..., index: ...}`, * where mathjs is optional * @returns {AccessorNode} */ AccessorNode.fromJSON = function (json) { return new AccessorNode(json.object, json.index) } /** * Are parenthesis needed? * @private */ function needParenthesis (node) { // TODO: maybe make a method on the nodes which tells whether they need parenthesis? return !( isAccessorNode(node) || isArrayNode(node) || isConstantNode(node) || isFunctionNode(node) || isObjectNode(node) || isParenthesisNode(node) || isSymbolNode(node)) } return AccessorNode }, { isClass: true, isNode: true })
apache-2.0
SuperQ/mtail
internal/vm/code/opcodes_test.go
345
// Copyright 2018 Google Inc. All Rights Reserved. // This file is available under the Apache license. package code import "testing" func TestOpcodeHasString(t *testing.T) { for o := Bad; o < lastOpcode; o++ { if o.String() != opNames[o] { t.Errorf("opcode string not match. Expected %s, received %s", opNames[o], o.String()) } } }
apache-2.0
JLyons1985/SmartVanityMirror
src/main/java/com/amazon/alexa/avs/auth/AuthConstants.java
2324
/** * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * You may not use this file except in compliance with the License. A copy of the License is located the "LICENSE.txt" * file accompanying this source. 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.amazon.alexa.avs.auth; /** * Constants related to authentication and device provisioning. */ @SuppressWarnings("javadoc") public class AuthConstants { public static final String SESSION_ID = "sessionId"; public static final String CLIENT_ID = "clientId"; public static final String REDIRECT_URI = "redirectUri"; public static final String AUTH_CODE = "authCode"; public static final String CODE_CHALLENGE = "codeChallenge"; public static final String CODE_CHALLENGE_METHOD = "codeChallengeMethod"; public static final String DSN = "dsn"; public static final String PRODUCT_ID = "productId"; public static final String REG_CODE = "regCode"; // ERRORS public static final String ERROR = "error"; public static final String MESSAGE = "message"; public static final String INVALID_PARAM_ERROR = "INVALID_PARAM"; public static final String INCORRECT_SESSION_ID_ERROR = "INCORRECT_SESSION_ID"; public static final String LWA_ERROR = "LWA_ERROR"; /** * Constants related specifically to OAuth 2.0 (http://tools.ietf.org/html/rfc6749) and draft 10 * of Proof Key for Code Exchange by OAuth (https://tools.ietf.org/html/draft-ietf-oauth-spop-10). */ public static class OAuth2 { public static final String AUTHORIZATION_CODE = "authorization_code"; public static final String GRANT_TYPE = "grant_type"; public static final String REDIRECT_URI = "redirect_uri"; public static final String CODE = "code"; public static final String CLIENT_ID = "client_id"; public static final String CODE_VERIFIER = "code_verifier"; public static final String ACCESS_TOKEN = "access_token"; public static final String REFRESH_TOKEN = "refresh_token"; public static final String EXPIRES_IN = "expires_in"; } }
apache-2.0
Namone/SimpleScene
SimpleScene/Objects/SSObjectTriangle.cs
909
// Copyright(C) David W. Jeske, 2013 // Released to the public domain. using System; using OpenTK; using OpenTK.Graphics.OpenGL; namespace SimpleScene { public class SSObjectTriangle : SSObject { public override void Render(ref SSRenderConfig renderConfig) { base.Render (ref renderConfig); // mode setup SSShaderProgram.DeactivateAll(); // disable GLSL GL.Disable(EnableCap.Texture2D); GL.Disable(EnableCap.Blend); GL.Disable(EnableCap.Lighting); // triangle draw... GL.Begin(PrimitiveType.Triangles); GL.Color3(1.0f, 1.0f, 0.0f); GL.Vertex3(-1.0f, -1.0f, 0.0f); GL.Color3(1.0f, 0.0f, 0.0f); GL.Vertex3(1.0f, -1.0f, 0.0f); GL.Color3(0.2f, 0.9f, 1.0f); GL.Vertex3(0.0f, 1.0f, 0.0f); GL.End(); } public SSObjectTriangle () : base() { this.boundingSphere = new SSObjectSphere(1.0f); } } }
apache-2.0
andrewsykim/kubernetes
cmd/kube-controller-manager/app/options/options_test.go
27931
/* Copyright 2017 The Kubernetes 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 options import ( "net" "reflect" "sort" "testing" "time" "github.com/spf13/pflag" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/diff" apiserveroptions "k8s.io/apiserver/pkg/server/options" cpconfig "k8s.io/cloud-provider/app/apis/config" cpoptions "k8s.io/cloud-provider/options" serviceconfig "k8s.io/cloud-provider/service/config" componentbaseconfig "k8s.io/component-base/config" "k8s.io/component-base/logs" "k8s.io/component-base/metrics" cmconfig "k8s.io/controller-manager/config" cmoptions "k8s.io/controller-manager/options" kubecontrollerconfig "k8s.io/kubernetes/cmd/kube-controller-manager/app/config" kubectrlmgrconfig "k8s.io/kubernetes/pkg/controller/apis/config" csrsigningconfig "k8s.io/kubernetes/pkg/controller/certificates/signer/config" daemonconfig "k8s.io/kubernetes/pkg/controller/daemon/config" deploymentconfig "k8s.io/kubernetes/pkg/controller/deployment/config" endpointconfig "k8s.io/kubernetes/pkg/controller/endpoint/config" endpointsliceconfig "k8s.io/kubernetes/pkg/controller/endpointslice/config" endpointslicemirroringconfig "k8s.io/kubernetes/pkg/controller/endpointslicemirroring/config" garbagecollectorconfig "k8s.io/kubernetes/pkg/controller/garbagecollector/config" jobconfig "k8s.io/kubernetes/pkg/controller/job/config" namespaceconfig "k8s.io/kubernetes/pkg/controller/namespace/config" nodeipamconfig "k8s.io/kubernetes/pkg/controller/nodeipam/config" nodelifecycleconfig "k8s.io/kubernetes/pkg/controller/nodelifecycle/config" poautosclerconfig "k8s.io/kubernetes/pkg/controller/podautoscaler/config" podgcconfig "k8s.io/kubernetes/pkg/controller/podgc/config" replicasetconfig "k8s.io/kubernetes/pkg/controller/replicaset/config" replicationconfig "k8s.io/kubernetes/pkg/controller/replication/config" resourcequotaconfig "k8s.io/kubernetes/pkg/controller/resourcequota/config" serviceaccountconfig "k8s.io/kubernetes/pkg/controller/serviceaccount/config" statefulsetconfig "k8s.io/kubernetes/pkg/controller/statefulset/config" ttlafterfinishedconfig "k8s.io/kubernetes/pkg/controller/ttlafterfinished/config" attachdetachconfig "k8s.io/kubernetes/pkg/controller/volume/attachdetach/config" persistentvolumeconfig "k8s.io/kubernetes/pkg/controller/volume/persistentvolume/config" ) var args = []string{ "--address=192.168.4.10", "--allocate-node-cidrs=true", "--attach-detach-reconcile-sync-period=30s", "--cidr-allocator-type=CloudAllocator", "--cloud-config=/cloud-config", "--cloud-provider=gce", "--cluster-cidr=1.2.3.4/24", "--cluster-name=k8s", "--cluster-signing-cert-file=/cluster-signing-cert", "--cluster-signing-key-file=/cluster-signing-key", "--cluster-signing-kubelet-serving-cert-file=/cluster-signing-kubelet-serving/cert-file", "--cluster-signing-kubelet-serving-key-file=/cluster-signing-kubelet-serving/key-file", "--cluster-signing-kubelet-client-cert-file=/cluster-signing-kubelet-client/cert-file", "--cluster-signing-kubelet-client-key-file=/cluster-signing-kubelet-client/key-file", "--cluster-signing-kube-apiserver-client-cert-file=/cluster-signing-kube-apiserver-client/cert-file", "--cluster-signing-kube-apiserver-client-key-file=/cluster-signing-kube-apiserver-client/key-file", "--cluster-signing-legacy-unknown-cert-file=/cluster-signing-legacy-unknown/cert-file", "--cluster-signing-legacy-unknown-key-file=/cluster-signing-legacy-unknown/key-file", "--concurrent-deployment-syncs=10", "--concurrent-statefulset-syncs=15", "--concurrent-endpoint-syncs=10", "--concurrent-service-endpoint-syncs=10", "--concurrent-gc-syncs=30", "--concurrent-namespace-syncs=20", "--concurrent-replicaset-syncs=10", "--concurrent-resource-quota-syncs=10", "--concurrent-service-syncs=2", "--concurrent-serviceaccount-token-syncs=10", "--concurrent_rc_syncs=10", "--configure-cloud-routes=false", "--contention-profiling=true", "--controller-start-interval=2m", "--controllers=foo,bar", "--deployment-controller-sync-period=45s", "--disable-attach-detach-reconcile-sync=true", "--enable-dynamic-provisioning=false", "--enable-garbage-collector=false", "--enable-hostpath-provisioner=true", "--enable-taint-manager=false", "--cluster-signing-duration=10h", "--flex-volume-plugin-dir=/flex-volume-plugin", "--volume-host-cidr-denylist=127.0.0.1/28,feed::/16", "--volume-host-allow-local-loopback=false", "--horizontal-pod-autoscaler-downscale-delay=2m", "--horizontal-pod-autoscaler-sync-period=45s", "--horizontal-pod-autoscaler-upscale-delay=1m", "--horizontal-pod-autoscaler-downscale-stabilization=3m", "--horizontal-pod-autoscaler-cpu-initialization-period=90s", "--horizontal-pod-autoscaler-initial-readiness-delay=50s", "--http2-max-streams-per-connection=47", "--kube-api-burst=100", "--kube-api-content-type=application/json", "--kube-api-qps=50.0", "--kubeconfig=/kubeconfig", "--large-cluster-size-threshold=100", "--leader-elect=false", "--leader-elect-lease-duration=30s", "--leader-elect-renew-deadline=15s", "--leader-elect-resource-lock=configmap", "--leader-elect-retry-period=5s", "--master=192.168.4.20", "--max-endpoints-per-slice=200", "--min-resync-period=8h", "--mirroring-concurrent-service-endpoint-syncs=2", "--mirroring-max-endpoints-per-subset=1000", "--namespace-sync-period=10m", "--node-cidr-mask-size=48", "--node-cidr-mask-size-ipv4=48", "--node-cidr-mask-size-ipv6=108", "--node-eviction-rate=0.2", "--node-monitor-grace-period=30s", "--node-monitor-period=10s", "--node-startup-grace-period=30s", "--pod-eviction-timeout=2m", "--port=10000", "--profiling=false", "--pv-recycler-increment-timeout-nfs=45", "--pv-recycler-minimum-timeout-hostpath=45", "--pv-recycler-minimum-timeout-nfs=200", "--pv-recycler-timeout-increment-hostpath=45", "--pvclaimbinder-sync-period=30s", "--resource-quota-sync-period=10m", "--route-reconciliation-period=30s", "--secondary-node-eviction-rate=0.05", "--service-account-private-key-file=/service-account-private-key", "--terminated-pod-gc-threshold=12000", "--unhealthy-zone-threshold=0.6", "--use-service-account-credentials=true", "--cert-dir=/a/b/c", "--bind-address=192.168.4.21", "--secure-port=10001", "--concurrent-ttl-after-finished-syncs=8", } func TestAddFlags(t *testing.T) { fs := pflag.NewFlagSet("addflagstest", pflag.ContinueOnError) s, _ := NewKubeControllerManagerOptions() for _, f := range s.Flags([]string{""}, []string{""}).FlagSets { fs.AddFlagSet(f) } fs.Parse(args) // Sort GCIgnoredResources because it's built from a map, which means the // insertion order is random. sort.Sort(sortedGCIgnoredResources(s.GarbageCollectorController.GCIgnoredResources)) expected := &KubeControllerManagerOptions{ Generic: &cmoptions.GenericControllerManagerConfigurationOptions{ GenericControllerManagerConfiguration: &cmconfig.GenericControllerManagerConfiguration{ Port: 10252, // Note: InsecureServingOptions.ApplyTo will write the flag value back into the component config Address: "0.0.0.0", // Note: InsecureServingOptions.ApplyTo will write the flag value back into the component config MinResyncPeriod: metav1.Duration{Duration: 8 * time.Hour}, ClientConnection: componentbaseconfig.ClientConnectionConfiguration{ ContentType: "application/json", QPS: 50.0, Burst: 100, }, ControllerStartInterval: metav1.Duration{Duration: 2 * time.Minute}, LeaderElection: componentbaseconfig.LeaderElectionConfiguration{ ResourceLock: "configmap", LeaderElect: false, LeaseDuration: metav1.Duration{Duration: 30 * time.Second}, RenewDeadline: metav1.Duration{Duration: 15 * time.Second}, RetryPeriod: metav1.Duration{Duration: 5 * time.Second}, ResourceName: "kube-controller-manager", ResourceNamespace: "kube-system", }, Controllers: []string{"foo", "bar"}, }, Debugging: &cmoptions.DebuggingOptions{ DebuggingConfiguration: &componentbaseconfig.DebuggingConfiguration{ EnableProfiling: false, EnableContentionProfiling: true, }, }, }, KubeCloudShared: &cpoptions.KubeCloudSharedOptions{ KubeCloudSharedConfiguration: &cpconfig.KubeCloudSharedConfiguration{ UseServiceAccountCredentials: true, RouteReconciliationPeriod: metav1.Duration{Duration: 30 * time.Second}, NodeMonitorPeriod: metav1.Duration{Duration: 10 * time.Second}, ClusterName: "k8s", ClusterCIDR: "1.2.3.4/24", AllocateNodeCIDRs: true, CIDRAllocatorType: "CloudAllocator", ConfigureCloudRoutes: false, }, CloudProvider: &cpoptions.CloudProviderOptions{ CloudProviderConfiguration: &cpconfig.CloudProviderConfiguration{ Name: "gce", CloudConfigFile: "/cloud-config", }, }, }, ServiceController: &cpoptions.ServiceControllerOptions{ ServiceControllerConfiguration: &serviceconfig.ServiceControllerConfiguration{ ConcurrentServiceSyncs: 2, }, }, AttachDetachController: &AttachDetachControllerOptions{ &attachdetachconfig.AttachDetachControllerConfiguration{ ReconcilerSyncLoopPeriod: metav1.Duration{Duration: 30 * time.Second}, DisableAttachDetachReconcilerSync: true, }, }, CSRSigningController: &CSRSigningControllerOptions{ &csrsigningconfig.CSRSigningControllerConfiguration{ ClusterSigningCertFile: "/cluster-signing-cert", ClusterSigningKeyFile: "/cluster-signing-key", ClusterSigningDuration: metav1.Duration{Duration: 10 * time.Hour}, KubeletServingSignerConfiguration: csrsigningconfig.CSRSigningConfiguration{ CertFile: "/cluster-signing-kubelet-serving/cert-file", KeyFile: "/cluster-signing-kubelet-serving/key-file", }, KubeletClientSignerConfiguration: csrsigningconfig.CSRSigningConfiguration{ CertFile: "/cluster-signing-kubelet-client/cert-file", KeyFile: "/cluster-signing-kubelet-client/key-file", }, KubeAPIServerClientSignerConfiguration: csrsigningconfig.CSRSigningConfiguration{ CertFile: "/cluster-signing-kube-apiserver-client/cert-file", KeyFile: "/cluster-signing-kube-apiserver-client/key-file", }, LegacyUnknownSignerConfiguration: csrsigningconfig.CSRSigningConfiguration{ CertFile: "/cluster-signing-legacy-unknown/cert-file", KeyFile: "/cluster-signing-legacy-unknown/key-file", }, }, }, DaemonSetController: &DaemonSetControllerOptions{ &daemonconfig.DaemonSetControllerConfiguration{ ConcurrentDaemonSetSyncs: 2, }, }, DeploymentController: &DeploymentControllerOptions{ &deploymentconfig.DeploymentControllerConfiguration{ ConcurrentDeploymentSyncs: 10, DeploymentControllerSyncPeriod: metav1.Duration{Duration: 45 * time.Second}, }, }, StatefulSetController: &StatefulSetControllerOptions{ &statefulsetconfig.StatefulSetControllerConfiguration{ ConcurrentStatefulSetSyncs: 15, }, }, DeprecatedFlags: &DeprecatedControllerOptions{ &kubectrlmgrconfig.DeprecatedControllerConfiguration{ DeletingPodsQPS: 0.1, RegisterRetryCount: 10, }, }, EndpointController: &EndpointControllerOptions{ &endpointconfig.EndpointControllerConfiguration{ ConcurrentEndpointSyncs: 10, }, }, EndpointSliceController: &EndpointSliceControllerOptions{ &endpointsliceconfig.EndpointSliceControllerConfiguration{ ConcurrentServiceEndpointSyncs: 10, MaxEndpointsPerSlice: 200, }, }, EndpointSliceMirroringController: &EndpointSliceMirroringControllerOptions{ &endpointslicemirroringconfig.EndpointSliceMirroringControllerConfiguration{ MirroringConcurrentServiceEndpointSyncs: 2, MirroringMaxEndpointsPerSubset: 1000, }, }, GarbageCollectorController: &GarbageCollectorControllerOptions{ &garbagecollectorconfig.GarbageCollectorControllerConfiguration{ ConcurrentGCSyncs: 30, GCIgnoredResources: []garbagecollectorconfig.GroupResource{ {Group: "", Resource: "events"}, }, EnableGarbageCollector: false, }, }, HPAController: &HPAControllerOptions{ &poautosclerconfig.HPAControllerConfiguration{ HorizontalPodAutoscalerSyncPeriod: metav1.Duration{Duration: 45 * time.Second}, HorizontalPodAutoscalerUpscaleForbiddenWindow: metav1.Duration{Duration: 1 * time.Minute}, HorizontalPodAutoscalerDownscaleForbiddenWindow: metav1.Duration{Duration: 2 * time.Minute}, HorizontalPodAutoscalerDownscaleStabilizationWindow: metav1.Duration{Duration: 3 * time.Minute}, HorizontalPodAutoscalerCPUInitializationPeriod: metav1.Duration{Duration: 90 * time.Second}, HorizontalPodAutoscalerInitialReadinessDelay: metav1.Duration{Duration: 50 * time.Second}, HorizontalPodAutoscalerTolerance: 0.1, HorizontalPodAutoscalerUseRESTClients: true, }, }, JobController: &JobControllerOptions{ &jobconfig.JobControllerConfiguration{ ConcurrentJobSyncs: 5, }, }, NamespaceController: &NamespaceControllerOptions{ &namespaceconfig.NamespaceControllerConfiguration{ NamespaceSyncPeriod: metav1.Duration{Duration: 10 * time.Minute}, ConcurrentNamespaceSyncs: 20, }, }, NodeIPAMController: &NodeIPAMControllerOptions{ &nodeipamconfig.NodeIPAMControllerConfiguration{ NodeCIDRMaskSize: 48, NodeCIDRMaskSizeIPv4: 48, NodeCIDRMaskSizeIPv6: 108, }, }, NodeLifecycleController: &NodeLifecycleControllerOptions{ &nodelifecycleconfig.NodeLifecycleControllerConfiguration{ EnableTaintManager: false, NodeEvictionRate: 0.2, SecondaryNodeEvictionRate: 0.05, NodeMonitorGracePeriod: metav1.Duration{Duration: 30 * time.Second}, NodeStartupGracePeriod: metav1.Duration{Duration: 30 * time.Second}, PodEvictionTimeout: metav1.Duration{Duration: 2 * time.Minute}, LargeClusterSizeThreshold: 100, UnhealthyZoneThreshold: 0.6, }, }, PersistentVolumeBinderController: &PersistentVolumeBinderControllerOptions{ &persistentvolumeconfig.PersistentVolumeBinderControllerConfiguration{ PVClaimBinderSyncPeriod: metav1.Duration{Duration: 30 * time.Second}, VolumeConfiguration: persistentvolumeconfig.VolumeConfiguration{ EnableDynamicProvisioning: false, EnableHostPathProvisioning: true, FlexVolumePluginDir: "/flex-volume-plugin", PersistentVolumeRecyclerConfiguration: persistentvolumeconfig.PersistentVolumeRecyclerConfiguration{ MaximumRetry: 3, MinimumTimeoutNFS: 200, IncrementTimeoutNFS: 45, MinimumTimeoutHostPath: 45, IncrementTimeoutHostPath: 45, }, }, VolumeHostCIDRDenylist: []string{"127.0.0.1/28", "feed::/16"}, VolumeHostAllowLocalLoopback: false, }, }, PodGCController: &PodGCControllerOptions{ &podgcconfig.PodGCControllerConfiguration{ TerminatedPodGCThreshold: 12000, }, }, ReplicaSetController: &ReplicaSetControllerOptions{ &replicasetconfig.ReplicaSetControllerConfiguration{ ConcurrentRSSyncs: 10, }, }, ReplicationController: &ReplicationControllerOptions{ &replicationconfig.ReplicationControllerConfiguration{ ConcurrentRCSyncs: 10, }, }, ResourceQuotaController: &ResourceQuotaControllerOptions{ &resourcequotaconfig.ResourceQuotaControllerConfiguration{ ResourceQuotaSyncPeriod: metav1.Duration{Duration: 10 * time.Minute}, ConcurrentResourceQuotaSyncs: 10, }, }, SAController: &SAControllerOptions{ &serviceaccountconfig.SAControllerConfiguration{ ServiceAccountKeyFile: "/service-account-private-key", ConcurrentSATokenSyncs: 10, }, }, TTLAfterFinishedController: &TTLAfterFinishedControllerOptions{ &ttlafterfinishedconfig.TTLAfterFinishedControllerConfiguration{ ConcurrentTTLSyncs: 8, }, }, SecureServing: (&apiserveroptions.SecureServingOptions{ BindPort: 10001, BindAddress: net.ParseIP("192.168.4.21"), ServerCert: apiserveroptions.GeneratableKeyCert{ CertDirectory: "/a/b/c", PairName: "kube-controller-manager", }, HTTP2MaxStreamsPerConnection: 47, }).WithLoopback(), InsecureServing: (&apiserveroptions.DeprecatedInsecureServingOptions{ BindAddress: net.ParseIP("192.168.4.10"), BindPort: int(10000), BindNetwork: "tcp", }).WithLoopback(), Authentication: &apiserveroptions.DelegatingAuthenticationOptions{ CacheTTL: 10 * time.Second, ClientCert: apiserveroptions.ClientCertAuthenticationOptions{}, RequestHeader: apiserveroptions.RequestHeaderAuthenticationOptions{ UsernameHeaders: []string{"x-remote-user"}, GroupHeaders: []string{"x-remote-group"}, ExtraHeaderPrefixes: []string{"x-remote-extra-"}, }, RemoteKubeConfigFileOptional: true, }, Authorization: &apiserveroptions.DelegatingAuthorizationOptions{ AllowCacheTTL: 10 * time.Second, DenyCacheTTL: 10 * time.Second, RemoteKubeConfigFileOptional: true, AlwaysAllowPaths: []string{"/healthz"}, // note: this does not match /healthz/ or /healthz/* }, Kubeconfig: "/kubeconfig", Master: "192.168.4.20", Metrics: &metrics.Options{}, Logs: logs.NewOptions(), } // Sort GCIgnoredResources because it's built from a map, which means the // insertion order is random. sort.Sort(sortedGCIgnoredResources(expected.GarbageCollectorController.GCIgnoredResources)) if !reflect.DeepEqual(expected, s) { t.Errorf("Got different run options than expected.\nDifference detected on:\n%s", diff.ObjectReflectDiff(expected, s)) } } func TestApplyTo(t *testing.T) { fs := pflag.NewFlagSet("addflagstest", pflag.ContinueOnError) s, _ := NewKubeControllerManagerOptions() // flag set to parse the args that are required to start the kube controller manager for _, f := range s.Flags([]string{""}, []string{""}).FlagSets { fs.AddFlagSet(f) } fs.Parse(args) // Sort GCIgnoredResources because it's built from a map, which means the // insertion order is random. sort.Sort(sortedGCIgnoredResources(s.GarbageCollectorController.GCIgnoredResources)) expected := &kubecontrollerconfig.Config{ ComponentConfig: kubectrlmgrconfig.KubeControllerManagerConfiguration{ Generic: cmconfig.GenericControllerManagerConfiguration{ Port: 10252, // Note: InsecureServingOptions.ApplyTo will write the flag value back into the component config Address: "0.0.0.0", // Note: InsecureServingOptions.ApplyTo will write the flag value back into the component config MinResyncPeriod: metav1.Duration{Duration: 8 * time.Hour}, ClientConnection: componentbaseconfig.ClientConnectionConfiguration{ ContentType: "application/json", QPS: 50.0, Burst: 100, }, ControllerStartInterval: metav1.Duration{Duration: 2 * time.Minute}, LeaderElection: componentbaseconfig.LeaderElectionConfiguration{ ResourceLock: "configmap", LeaderElect: false, LeaseDuration: metav1.Duration{Duration: 30 * time.Second}, RenewDeadline: metav1.Duration{Duration: 15 * time.Second}, RetryPeriod: metav1.Duration{Duration: 5 * time.Second}, ResourceName: "kube-controller-manager", ResourceNamespace: "kube-system", }, Controllers: []string{"foo", "bar"}, Debugging: componentbaseconfig.DebuggingConfiguration{ EnableProfiling: false, EnableContentionProfiling: true, }, }, KubeCloudShared: cpconfig.KubeCloudSharedConfiguration{ UseServiceAccountCredentials: true, RouteReconciliationPeriod: metav1.Duration{Duration: 30 * time.Second}, NodeMonitorPeriod: metav1.Duration{Duration: 10 * time.Second}, ClusterName: "k8s", ClusterCIDR: "1.2.3.4/24", AllocateNodeCIDRs: true, CIDRAllocatorType: "CloudAllocator", ConfigureCloudRoutes: false, CloudProvider: cpconfig.CloudProviderConfiguration{ Name: "gce", CloudConfigFile: "/cloud-config", }, }, ServiceController: serviceconfig.ServiceControllerConfiguration{ ConcurrentServiceSyncs: 2, }, AttachDetachController: attachdetachconfig.AttachDetachControllerConfiguration{ ReconcilerSyncLoopPeriod: metav1.Duration{Duration: 30 * time.Second}, DisableAttachDetachReconcilerSync: true, }, CSRSigningController: csrsigningconfig.CSRSigningControllerConfiguration{ ClusterSigningCertFile: "/cluster-signing-cert", ClusterSigningKeyFile: "/cluster-signing-key", ClusterSigningDuration: metav1.Duration{Duration: 10 * time.Hour}, KubeletServingSignerConfiguration: csrsigningconfig.CSRSigningConfiguration{ CertFile: "/cluster-signing-kubelet-serving/cert-file", KeyFile: "/cluster-signing-kubelet-serving/key-file", }, KubeletClientSignerConfiguration: csrsigningconfig.CSRSigningConfiguration{ CertFile: "/cluster-signing-kubelet-client/cert-file", KeyFile: "/cluster-signing-kubelet-client/key-file", }, KubeAPIServerClientSignerConfiguration: csrsigningconfig.CSRSigningConfiguration{ CertFile: "/cluster-signing-kube-apiserver-client/cert-file", KeyFile: "/cluster-signing-kube-apiserver-client/key-file", }, LegacyUnknownSignerConfiguration: csrsigningconfig.CSRSigningConfiguration{ CertFile: "/cluster-signing-legacy-unknown/cert-file", KeyFile: "/cluster-signing-legacy-unknown/key-file", }, }, DaemonSetController: daemonconfig.DaemonSetControllerConfiguration{ ConcurrentDaemonSetSyncs: 2, }, DeploymentController: deploymentconfig.DeploymentControllerConfiguration{ ConcurrentDeploymentSyncs: 10, DeploymentControllerSyncPeriod: metav1.Duration{Duration: 45 * time.Second}, }, StatefulSetController: statefulsetconfig.StatefulSetControllerConfiguration{ ConcurrentStatefulSetSyncs: 15, }, DeprecatedController: kubectrlmgrconfig.DeprecatedControllerConfiguration{ DeletingPodsQPS: 0.1, RegisterRetryCount: 10, }, EndpointController: endpointconfig.EndpointControllerConfiguration{ ConcurrentEndpointSyncs: 10, }, EndpointSliceController: endpointsliceconfig.EndpointSliceControllerConfiguration{ ConcurrentServiceEndpointSyncs: 10, MaxEndpointsPerSlice: 200, }, EndpointSliceMirroringController: endpointslicemirroringconfig.EndpointSliceMirroringControllerConfiguration{ MirroringConcurrentServiceEndpointSyncs: 2, MirroringMaxEndpointsPerSubset: 1000, }, GarbageCollectorController: garbagecollectorconfig.GarbageCollectorControllerConfiguration{ ConcurrentGCSyncs: 30, GCIgnoredResources: []garbagecollectorconfig.GroupResource{ {Group: "", Resource: "events"}, }, EnableGarbageCollector: false, }, HPAController: poautosclerconfig.HPAControllerConfiguration{ HorizontalPodAutoscalerSyncPeriod: metav1.Duration{Duration: 45 * time.Second}, HorizontalPodAutoscalerUpscaleForbiddenWindow: metav1.Duration{Duration: 1 * time.Minute}, HorizontalPodAutoscalerDownscaleForbiddenWindow: metav1.Duration{Duration: 2 * time.Minute}, HorizontalPodAutoscalerDownscaleStabilizationWindow: metav1.Duration{Duration: 3 * time.Minute}, HorizontalPodAutoscalerCPUInitializationPeriod: metav1.Duration{Duration: 90 * time.Second}, HorizontalPodAutoscalerInitialReadinessDelay: metav1.Duration{Duration: 50 * time.Second}, HorizontalPodAutoscalerTolerance: 0.1, HorizontalPodAutoscalerUseRESTClients: true, }, JobController: jobconfig.JobControllerConfiguration{ ConcurrentJobSyncs: 5, }, NamespaceController: namespaceconfig.NamespaceControllerConfiguration{ NamespaceSyncPeriod: metav1.Duration{Duration: 10 * time.Minute}, ConcurrentNamespaceSyncs: 20, }, NodeIPAMController: nodeipamconfig.NodeIPAMControllerConfiguration{ NodeCIDRMaskSize: 48, NodeCIDRMaskSizeIPv4: 48, NodeCIDRMaskSizeIPv6: 108, }, NodeLifecycleController: nodelifecycleconfig.NodeLifecycleControllerConfiguration{ EnableTaintManager: false, NodeEvictionRate: 0.2, SecondaryNodeEvictionRate: 0.05, NodeMonitorGracePeriod: metav1.Duration{Duration: 30 * time.Second}, NodeStartupGracePeriod: metav1.Duration{Duration: 30 * time.Second}, PodEvictionTimeout: metav1.Duration{Duration: 2 * time.Minute}, LargeClusterSizeThreshold: 100, UnhealthyZoneThreshold: 0.6, }, PersistentVolumeBinderController: persistentvolumeconfig.PersistentVolumeBinderControllerConfiguration{ PVClaimBinderSyncPeriod: metav1.Duration{Duration: 30 * time.Second}, VolumeConfiguration: persistentvolumeconfig.VolumeConfiguration{ EnableDynamicProvisioning: false, EnableHostPathProvisioning: true, FlexVolumePluginDir: "/flex-volume-plugin", PersistentVolumeRecyclerConfiguration: persistentvolumeconfig.PersistentVolumeRecyclerConfiguration{ MaximumRetry: 3, MinimumTimeoutNFS: 200, IncrementTimeoutNFS: 45, MinimumTimeoutHostPath: 45, IncrementTimeoutHostPath: 45, }, }, VolumeHostCIDRDenylist: []string{"127.0.0.1/28", "feed::/16"}, VolumeHostAllowLocalLoopback: false, }, PodGCController: podgcconfig.PodGCControllerConfiguration{ TerminatedPodGCThreshold: 12000, }, ReplicaSetController: replicasetconfig.ReplicaSetControllerConfiguration{ ConcurrentRSSyncs: 10, }, ReplicationController: replicationconfig.ReplicationControllerConfiguration{ ConcurrentRCSyncs: 10, }, ResourceQuotaController: resourcequotaconfig.ResourceQuotaControllerConfiguration{ ResourceQuotaSyncPeriod: metav1.Duration{Duration: 10 * time.Minute}, ConcurrentResourceQuotaSyncs: 10, }, SAController: serviceaccountconfig.SAControllerConfiguration{ ServiceAccountKeyFile: "/service-account-private-key", ConcurrentSATokenSyncs: 10, }, TTLAfterFinishedController: ttlafterfinishedconfig.TTLAfterFinishedControllerConfiguration{ ConcurrentTTLSyncs: 8, }, }, } // Sort GCIgnoredResources because it's built from a map, which means the // insertion order is random. sort.Sort(sortedGCIgnoredResources(expected.ComponentConfig.GarbageCollectorController.GCIgnoredResources)) c := &kubecontrollerconfig.Config{} s.ApplyTo(c) if !reflect.DeepEqual(expected.ComponentConfig, c.ComponentConfig) { t.Errorf("Got different configuration than expected.\nDifference detected on:\n%s", diff.ObjectReflectDiff(expected.ComponentConfig, c.ComponentConfig)) } } type sortedGCIgnoredResources []garbagecollectorconfig.GroupResource func (r sortedGCIgnoredResources) Len() int { return len(r) } func (r sortedGCIgnoredResources) Less(i, j int) bool { if r[i].Group < r[j].Group { return true } else if r[i].Group > r[j].Group { return false } return r[i].Resource < r[j].Resource } func (r sortedGCIgnoredResources) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
apache-2.0
atdt/gerrit
gerrit-server/src/main/java/com/google/gerrit/server/config/GerritRequestModule.java
5322
// Copyright (C) 2009 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.config; import static com.google.inject.Scopes.SINGLETON; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.server.ApprovalsUtil; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.RequestCleanup; import com.google.gerrit.server.account.AccountControl; import com.google.gerrit.server.account.AccountResolver; import com.google.gerrit.server.account.GroupDetailFactory; import com.google.gerrit.server.account.GroupMembers; import com.google.gerrit.server.account.PerformCreateGroup; import com.google.gerrit.server.account.PerformRenameGroup; import com.google.gerrit.server.account.VisibleGroups; import com.google.gerrit.server.changedetail.DeleteDraftPatchSet; import com.google.gerrit.server.changedetail.PublishDraft; import com.google.gerrit.server.changedetail.Submit; import com.google.gerrit.server.git.AsyncReceiveCommits; import com.google.gerrit.server.git.BanCommit; import com.google.gerrit.server.git.CreateCodeReviewNotes; import com.google.gerrit.server.git.MergeOp; import com.google.gerrit.server.git.MetaDataUpdate; import com.google.gerrit.server.git.NotesBranchUtil; import com.google.gerrit.server.git.SubmoduleOp; import com.google.gerrit.server.mail.AbandonedSender; import com.google.gerrit.server.mail.AddReviewerSender; import com.google.gerrit.server.mail.CommentSender; import com.google.gerrit.server.mail.CreateChangeSender; import com.google.gerrit.server.mail.MergeFailSender; import com.google.gerrit.server.mail.MergedSender; import com.google.gerrit.server.mail.RebasedPatchSetSender; import com.google.gerrit.server.mail.ReplacePatchSetSender; import com.google.gerrit.server.mail.RestoredSender; import com.google.gerrit.server.mail.RevertedSender; import com.google.gerrit.server.patch.AddReviewer; import com.google.gerrit.server.patch.PublishComments; import com.google.gerrit.server.patch.RemoveReviewer; import com.google.gerrit.server.project.ChangeControl; import com.google.gerrit.server.project.CreateProject; import com.google.gerrit.server.project.ListProjects; import com.google.gerrit.server.project.PerRequestProjectControlCache; import com.google.gerrit.server.project.ProjectControl; import com.google.gerrit.server.project.SuggestParentCandidates; import com.google.gerrit.server.query.change.ChangeQueryBuilder; import com.google.gerrit.server.query.change.ChangeQueryRewriter; import com.google.inject.servlet.RequestScoped; /** Bindings for {@link RequestScoped} entities. */ public class GerritRequestModule extends FactoryModule { @Override protected void configure() { bind(RequestCleanup.class).in(RequestScoped.class); bind(ReviewDb.class).toProvider(RequestScopedReviewDbProvider.class).in( RequestScoped.class); bind(IdentifiedUser.RequestFactory.class).in(SINGLETON); bind(MetaDataUpdate.User.class).in(RequestScoped.class); bind(AccountResolver.class); bind(ChangeQueryRewriter.class); bind(ListProjects.class); bind(ApprovalsUtil.class); bind(PerRequestProjectControlCache.class).in(RequestScoped.class); bind(ChangeControl.Factory.class).in(SINGLETON); bind(ProjectControl.Factory.class).in(SINGLETON); bind(AccountControl.Factory.class).in(SINGLETON); factory(ChangeQueryBuilder.Factory.class); factory(SubmoduleOp.Factory.class); factory(MergeOp.Factory.class); factory(CreateCodeReviewNotes.Factory.class); factory(NotesBranchUtil.Factory.class); install(new AsyncReceiveCommits.Module()); // Not really per-request, but dammit, I don't know where else to // easily park this stuff. // factory(AddReviewer.Factory.class); factory(AddReviewerSender.Factory.class); factory(CreateChangeSender.Factory.class); factory(DeleteDraftPatchSet.Factory.class); factory(PublishComments.Factory.class); factory(PublishDraft.Factory.class); factory(ReplacePatchSetSender.Factory.class); factory(RebasedPatchSetSender.Factory.class); factory(AbandonedSender.Factory.class); factory(RemoveReviewer.Factory.class); factory(RestoredSender.Factory.class); factory(RevertedSender.Factory.class); factory(CommentSender.Factory.class); factory(MergedSender.Factory.class); factory(MergeFailSender.Factory.class); factory(PerformCreateGroup.Factory.class); factory(PerformRenameGroup.Factory.class); factory(VisibleGroups.Factory.class); factory(GroupDetailFactory.Factory.class); factory(GroupMembers.Factory.class); factory(CreateProject.Factory.class); factory(Submit.Factory.class); factory(SuggestParentCandidates.Factory.class); factory(BanCommit.Factory.class); } }
apache-2.0
Esri/arcgis-pro-sdk-community-samples
Map-Authoring/GeocodingTools/CustomGeocodeDockpaneViewModel.cs
4768
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ArcGIS.Desktop.Framework; using ArcGIS.Desktop.Framework.Contracts; using ArcGIS.Desktop.Framework.Threading.Tasks; using ArcGIS.Desktop.Mapping; namespace GeocodingTools { /// <summary> /// Provide geocoding functionality using the API functions from the ArcGIS.Desktop.Mapping.Geocoding namespace with a custom UI. The /// UI contains a search box, and a listbox to display the geocode results. When a specific listbox item is selected, zoom to the /// extent of the result and add a symbol to the mapView overlay at it's location. /// </summary> internal class CustomGeocodeDockpaneViewModel : DockPane { private const string _dockPaneID = "GeocodingTools_CustomGeocodeDockpane"; protected CustomGeocodeDockpaneViewModel() { } /// <summary> /// Show the DockPane. /// </summary> internal static void Show() { DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID); if (pane == null) return; pane.Activate(); } /// <summary> /// Dispose of any overlay objects. /// </summary> protected override void OnHidden() { base.OnHidden(); if (disposable != null) { disposable.Dispose(); disposable = null; } } /// <summary> /// Binds the geocode results to the ListBox. /// </summary> private List<ArcGIS.Desktop.Mapping.Geocoding.GeocodeResult> _results; public IReadOnlyList<ArcGIS.Desktop.Mapping.Geocoding.GeocodeResult> Results { get { return _results; } } private IDisposable disposable; /// <summary> /// The selected geocode result in the listbox. /// </summary> private ArcGIS.Desktop.Mapping.Geocoding.GeocodeResult _selectedResult; public ArcGIS.Desktop.Mapping.Geocoding.GeocodeResult SelectedResult { get { return _selectedResult; } set { SetProperty(ref _selectedResult, value, () => SelectedResult); // remove any existing item from the overlay if (disposable != null) { disposable.Dispose(); disposable = null; } if (_selectedResult == null) return; // if the result has a location if (_selectedResult.DisplayLocation != null) { QueuedTask.Run(() => { // zoom to the extent if (_selectedResult.Extent != null) MapView.Active.ZoomTo(_selectedResult.Extent); // add to the overlay disposable = MapView.Active.AddOverlay(_selectedResult.DisplayLocation, SymbolFactory.Instance.ConstructPointSymbol( ColorFactory.Instance.RedRGB, 15.0, SimpleMarkerStyle.Star).MakeSymbolReference()); }); } } } /// <summary> /// Performs a geocode operation using the static GeocodeAsync method. /// </summary> /// <param name="text"></param> /// <returns></returns> internal async Task Search(string text) { // clean the overlay if (disposable != null) { disposable.Dispose(); disposable = null; } // check the text if (string.IsNullOrEmpty(text)) return; // do the geocode - pass false and false because we want to control the display and zoom ourselves IEnumerable<ArcGIS.Desktop.Mapping.Geocoding.GeocodeResult> results = await MapView.Active.LocatorManager.GeocodeAsync(text, false, false); // check result count - if no results, most likely no locators if ((results == null) || (results.Count() == 0)) _results = new List<ArcGIS.Desktop.Mapping.Geocoding.GeocodeResult>(); else _results = results.ToList(); // update UI NotifyPropertyChanged(() => Results); } } /// <summary> /// Button implementation to show the DockPane. /// </summary> internal class CustomGeocodeDockpane_ShowButton : Button { protected override void OnClick() { CustomGeocodeDockpaneViewModel.Show(); } } }
apache-2.0
ghanoz/google-api-dfp-php
src/Google/Api/Ads/Dfp/v201306/CreativeTemplateService.php
79992
<?php /** * Contains all client objects for the CreativeTemplateService service. * * PHP version 5 * * Copyright 2013, Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @package GoogleApiAdsDfp * @subpackage v201306 * @category WebServices * @copyright 2013, Google Inc. All Rights Reserved. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, * Version 2.0 * @author Vincent Tsao */ /** Required classes. **/ require_once "Google/Api/Ads/Dfp/Lib/DfpSoapClient.php"; if (!class_exists("ApiError", FALSE)) { /** * The API error base class that provides details about an error that occurred * while processing a service request. * * <p>The OGNL field path is provided for parsers to identify the request data * element that may have caused the error.</p> * @package GoogleApiAdsDfp * @subpackage v201306 */ class ApiError { /** * @access public * @var string */ public $fieldPath; /** * @access public * @var string */ public $trigger; /** * @access public * @var string */ public $errorString; /** * @access public * @var string */ public $ApiErrorType; private $_parameterMap = array ( "ApiError.Type" => "ApiErrorType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get. * @return mixed Variable value */ public function __get($var) { if (!array_key_exists($var, $this->_parameterMap)) { return NULL; } else { return $this->{$this->_parameterMap[$var]}; } } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ApiError"; } public function __construct($fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("ApiVersionError", FALSE)) { /** * Errors related to the usage of API versions. * @package GoogleApiAdsDfp * @subpackage v201306 */ class ApiVersionError extends ApiError { /** * @access public * @var tnsApiVersionErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ApiVersionError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("ApplicationException", FALSE)) { /** * Base class for exceptions. * @package GoogleApiAdsDfp * @subpackage v201306 */ class ApplicationException { /** * @access public * @var string */ public $message; /** * @access public * @var string */ public $ApplicationExceptionType; private $_parameterMap = array ( "ApplicationException.Type" => "ApplicationExceptionType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get. * @return mixed Variable value */ public function __get($var) { if (!array_key_exists($var, $this->_parameterMap)) { return NULL; } else { return $this->{$this->_parameterMap[$var]}; } } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ApplicationException"; } public function __construct($message = NULL, $ApplicationExceptionType = NULL) { $this->message = $message; $this->ApplicationExceptionType = $ApplicationExceptionType; } }} if (!class_exists("Authentication", FALSE)) { /** * A representation of the authentication protocols that can be used. * @package GoogleApiAdsDfp * @subpackage v201306 */ class Authentication { /** * @access public * @var string */ public $AuthenticationType; private $_parameterMap = array ( "Authentication.Type" => "AuthenticationType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get. * @return mixed Variable value */ public function __get($var) { if (!array_key_exists($var, $this->_parameterMap)) { return NULL; } else { return $this->{$this->_parameterMap[$var]}; } } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "Authentication"; } public function __construct($AuthenticationType = NULL) { $this->AuthenticationType = $AuthenticationType; } }} if (!class_exists("AuthenticationError", FALSE)) { /** * An error for an exception that occurred when authenticating. * @package GoogleApiAdsDfp * @subpackage v201306 */ class AuthenticationError extends ApiError { /** * @access public * @var tnsAuthenticationErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "AuthenticationError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("ClientLogin", FALSE)) { /** * The credentials for the {@code ClientLogin} API authentication protocol. * * See {@link http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html}. * @package GoogleApiAdsDfp * @subpackage v201306 */ class ClientLogin extends Authentication { /** * @access public * @var string */ public $token; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ClientLogin"; } public function __construct($token = NULL, $AuthenticationType = NULL) { parent::__construct(); $this->token = $token; $this->AuthenticationType = $AuthenticationType; } }} if (!class_exists("CommonError", FALSE)) { /** * A place for common errors that can be used across services. * @package GoogleApiAdsDfp * @subpackage v201306 */ class CommonError extends ApiError { /** * @access public * @var tnsCommonErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "CommonError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("CreativeTemplate", FALSE)) { /** * A template upon which a creative can be created. * @package GoogleApiAdsDfp * @subpackage v201306 */ class CreativeTemplate { /** * @access public * @var integer */ public $id; /** * @access public * @var string */ public $name; /** * @access public * @var string */ public $description; /** * @access public * @var CreativeTemplateVariable[] */ public $variables; /** * @access public * @var tnsCreativeTemplateStatus */ public $status; /** * @access public * @var tnsCreativeTemplateType */ public $type; /** * @access public * @var boolean */ public $isInterstitial; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "CreativeTemplate"; } public function __construct($id = NULL, $name = NULL, $description = NULL, $variables = NULL, $status = NULL, $type = NULL, $isInterstitial = NULL) { $this->id = $id; $this->name = $name; $this->description = $description; $this->variables = $variables; $this->status = $status; $this->type = $type; $this->isInterstitial = $isInterstitial; } }} if (!class_exists("CreativeTemplateError", FALSE)) { /** * A catch-all error that lists all generic errors associated with CreativeTemplate. * @package GoogleApiAdsDfp * @subpackage v201306 */ class CreativeTemplateError extends ApiError { /** * @access public * @var tnsCreativeTemplateErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "CreativeTemplateError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("ListStringCreativeTemplateVariableVariableChoice", FALSE)) { /** * Stores variable choices that users can select from * @package GoogleApiAdsDfp * @subpackage v201306 */ class ListStringCreativeTemplateVariableVariableChoice { /** * @access public * @var string */ public $label; /** * @access public * @var string */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ListStringCreativeTemplateVariable.VariableChoice"; } public function __construct($label = NULL, $value = NULL) { $this->label = $label; $this->value = $value; } }} if (!class_exists("CreativeTemplatePage", FALSE)) { /** * Captures a page of {@link CreativeTemplate} objects. * @package GoogleApiAdsDfp * @subpackage v201306 */ class CreativeTemplatePage { /** * @access public * @var integer */ public $totalResultSetSize; /** * @access public * @var integer */ public $startIndex; /** * @access public * @var CreativeTemplate[] */ public $results; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "CreativeTemplatePage"; } public function __construct($totalResultSetSize = NULL, $startIndex = NULL, $results = NULL) { $this->totalResultSetSize = $totalResultSetSize; $this->startIndex = $startIndex; $this->results = $results; } }} if (!class_exists("CreativeTemplateVariable", FALSE)) { /** * Represents a variable defined in a creative template. * @package GoogleApiAdsDfp * @subpackage v201306 */ class CreativeTemplateVariable { /** * @access public * @var string */ public $label; /** * @access public * @var string */ public $uniqueName; /** * @access public * @var string */ public $description; /** * @access public * @var boolean */ public $isRequired; /** * @access public * @var string */ public $CreativeTemplateVariableType; private $_parameterMap = array ( "CreativeTemplateVariable.Type" => "CreativeTemplateVariableType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get. * @return mixed Variable value */ public function __get($var) { if (!array_key_exists($var, $this->_parameterMap)) { return NULL; } else { return $this->{$this->_parameterMap[$var]}; } } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "CreativeTemplateVariable"; } public function __construct($label = NULL, $uniqueName = NULL, $description = NULL, $isRequired = NULL, $CreativeTemplateVariableType = NULL) { $this->label = $label; $this->uniqueName = $uniqueName; $this->description = $description; $this->isRequired = $isRequired; $this->CreativeTemplateVariableType = $CreativeTemplateVariableType; } }} if (!class_exists("Date", FALSE)) { /** * Represents a date. * @package GoogleApiAdsDfp * @subpackage v201306 */ class Date { /** * @access public * @var integer */ public $year; /** * @access public * @var integer */ public $month; /** * @access public * @var integer */ public $day; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "Date"; } public function __construct($year = NULL, $month = NULL, $day = NULL) { $this->year = $year; $this->month = $month; $this->day = $day; } }} if (!class_exists("DfpDateTime", FALSE)) { /** * Represents a date combined with the time of day. * @package GoogleApiAdsDfp * @subpackage v201306 */ class DfpDateTime { /** * @access public * @var Date */ public $date; /** * @access public * @var integer */ public $hour; /** * @access public * @var integer */ public $minute; /** * @access public * @var integer */ public $second; /** * @access public * @var string */ public $timeZoneID; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "DateTime"; } public function __construct($date = NULL, $hour = NULL, $minute = NULL, $second = NULL, $timeZoneID = NULL) { $this->date = $date; $this->hour = $hour; $this->minute = $minute; $this->second = $second; $this->timeZoneID = $timeZoneID; } }} if (!class_exists("FeatureError", FALSE)) { /** * Errors related to feature management. If you attempt using a feature that is not available to * the current network you'll receive a FeatureError with the missing feature as the trigger. * @package GoogleApiAdsDfp * @subpackage v201306 */ class FeatureError extends ApiError { /** * @access public * @var tnsFeatureErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "FeatureError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("InternalApiError", FALSE)) { /** * Indicates that a server-side error has occured. {@code InternalApiError}s * are generally not the result of an invalid request or message sent by the * client. * @package GoogleApiAdsDfp * @subpackage v201306 */ class InternalApiError extends ApiError { /** * @access public * @var tnsInternalApiErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "InternalApiError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("InvalidUrlError", FALSE)) { /** * Lists all errors associated with URLs. * @package GoogleApiAdsDfp * @subpackage v201306 */ class InvalidUrlError extends ApiError { /** * @access public * @var tnsInvalidUrlErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "InvalidUrlError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("NotNullError", FALSE)) { /** * Caused by supplying a null value for an attribute that cannot be null. * @package GoogleApiAdsDfp * @subpackage v201306 */ class NotNullError extends ApiError { /** * @access public * @var tnsNotNullErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "NotNullError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("NullError", FALSE)) { /** * Errors associated with violation of a NOT NULL check. * @package GoogleApiAdsDfp * @subpackage v201306 */ class NullError extends ApiError { /** * @access public * @var tnsNullErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "NullError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("DfpOAuth", FALSE)) { /** * The credentials for the {@code OAuth} authentication protocol. * * See {@link http://oauth.net/}. * @package GoogleApiAdsDfp * @subpackage v201306 */ class DfpOAuth extends Authentication { /** * @access public * @var string */ public $parameters; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "OAuth"; } public function __construct($parameters = NULL, $AuthenticationType = NULL) { parent::__construct(); $this->parameters = $parameters; $this->AuthenticationType = $AuthenticationType; } }} if (!class_exists("ParseError", FALSE)) { /** * Lists errors related to parsing. * @package GoogleApiAdsDfp * @subpackage v201306 */ class ParseError extends ApiError { /** * @access public * @var tnsParseErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ParseError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("PermissionError", FALSE)) { /** * Errors related to incorrect permission. * @package GoogleApiAdsDfp * @subpackage v201306 */ class PermissionError extends ApiError { /** * @access public * @var tnsPermissionErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "PermissionError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("PublisherQueryLanguageContextError", FALSE)) { /** * An error that occurs while executing a PQL query contained in * a {@link Statement} object. * @package GoogleApiAdsDfp * @subpackage v201306 */ class PublisherQueryLanguageContextError extends ApiError { /** * @access public * @var tnsPublisherQueryLanguageContextErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "PublisherQueryLanguageContextError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("PublisherQueryLanguageSyntaxError", FALSE)) { /** * An error that occurs while parsing a PQL query contained in a * {@link Statement} object. * @package GoogleApiAdsDfp * @subpackage v201306 */ class PublisherQueryLanguageSyntaxError extends ApiError { /** * @access public * @var tnsPublisherQueryLanguageSyntaxErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "PublisherQueryLanguageSyntaxError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("QuotaError", FALSE)) { /** * Describes a client-side error on which a user is attempting * to perform an action to which they have no quota remaining. * @package GoogleApiAdsDfp * @subpackage v201306 */ class QuotaError extends ApiError { /** * @access public * @var tnsQuotaErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "QuotaError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("RangeError", FALSE)) { /** * A list of all errors associated with the Range constraint. * @package GoogleApiAdsDfp * @subpackage v201306 */ class RangeError extends ApiError { /** * @access public * @var tnsRangeErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "RangeError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("RequiredError", FALSE)) { /** * Errors due to missing required field. * @package GoogleApiAdsDfp * @subpackage v201306 */ class RequiredError extends ApiError { /** * @access public * @var tnsRequiredErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "RequiredError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("RequiredNumberError", FALSE)) { /** * A list of all errors to be used in conjunction with required number * validators. * @package GoogleApiAdsDfp * @subpackage v201306 */ class RequiredNumberError extends ApiError { /** * @access public * @var tnsRequiredNumberErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "RequiredNumberError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("ServerError", FALSE)) { /** * Errors related to the server. * @package GoogleApiAdsDfp * @subpackage v201306 */ class ServerError extends ApiError { /** * @access public * @var tnsServerErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ServerError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("SoapRequestHeader", FALSE)) { /** * Represents the SOAP request header used by API requests. * @package GoogleApiAdsDfp * @subpackage v201306 */ class SoapRequestHeader { /** * @access public * @var string */ public $networkCode; /** * @access public * @var string */ public $applicationName; /** * @access public * @var Authentication */ public $authentication; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "SoapRequestHeader"; } public function __construct($networkCode = NULL, $applicationName = NULL, $authentication = NULL) { $this->networkCode = $networkCode; $this->applicationName = $applicationName; $this->authentication = $authentication; } }} if (!class_exists("SoapResponseHeader", FALSE)) { /** * Represents the SOAP request header used by API responses. * @package GoogleApiAdsDfp * @subpackage v201306 */ class SoapResponseHeader { /** * @access public * @var string */ public $requestId; /** * @access public * @var integer */ public $responseTime; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "SoapResponseHeader"; } public function __construct($requestId = NULL, $responseTime = NULL) { $this->requestId = $requestId; $this->responseTime = $responseTime; } }} if (!class_exists("Statement", FALSE)) { /** * Captures the {@code WHERE}, {@code ORDER BY} and {@code LIMIT} clauses of a * PQL query. Statements are typically used to retrieve objects of a predefined * domain type, which makes SELECT clause unnecessary. * <p> * An example query text might be {@code "WHERE status = 'ACTIVE' ORDER BY id * LIMIT 30"}. * </p> * <p> * Statements support bind variables. These are substitutes for literals * and can be thought of as input parameters to a PQL query. * </p> * <p> * An example of such a query might be {@code "WHERE id = :idValue"}. * </p> * <p> * Statements also support use of the LIKE keyword. This provides partial and * wildcard string matching. * </p> * <p> * An example of such a query might be {@code "WHERE name LIKE 'startswith%'"}. * </p> * If using an API version newer than V201010, the value for the variable * idValue must then be set with an object of type {@link Value} and is one of * {@link NumberValue}, {@link TextValue} or {@link BooleanValue}. * <p> * If using an API version older than or equal to V201010, the value for the * variable idValue must then be set with an object of type {@link Param} and is * one of {@link DoubleParam}, {@link LongParam} or {@link StringParam}. * </p> * @package GoogleApiAdsDfp * @subpackage v201306 */ class Statement { /** * @access public * @var string */ public $query; /** * @access public * @var String_ValueMapEntry[] */ public $values; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "Statement"; } public function __construct($query = NULL, $values = NULL) { $this->query = $query; $this->values = $values; } }} if (!class_exists("StatementError", FALSE)) { /** * An error that occurs while parsing {@link Statement} objects. * @package GoogleApiAdsDfp * @subpackage v201306 */ class StatementError extends ApiError { /** * @access public * @var tnsStatementErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "StatementError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("StringLengthError", FALSE)) { /** * Errors for Strings which do not meet given length constraints. * @package GoogleApiAdsDfp * @subpackage v201306 */ class StringLengthError extends ApiError { /** * @access public * @var tnsStringLengthErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "StringLengthError"; } public function __construct($reason = NULL, $fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("String_ValueMapEntry", FALSE)) { /** * This represents an entry in a map with a key of type String * and value of type Value. * @package GoogleApiAdsDfp * @subpackage v201306 */ class String_ValueMapEntry { /** * @access public * @var string */ public $key; /** * @access public * @var Value */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "String_ValueMapEntry"; } public function __construct($key = NULL, $value = NULL) { $this->key = $key; $this->value = $value; } }} if (!class_exists("UniqueError", FALSE)) { /** * An error for a field which must satisfy a uniqueness constraint * @package GoogleApiAdsDfp * @subpackage v201306 */ class UniqueError extends ApiError { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "UniqueError"; } public function __construct($fieldPath = NULL, $trigger = NULL, $errorString = NULL, $ApiErrorType = NULL) { parent::__construct(); $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } }} if (!class_exists("Value", FALSE)) { /** * {@code Value} represents a value. * @package GoogleApiAdsDfp * @subpackage v201306 */ class Value { /** * @access public * @var string */ public $ValueType; private $_parameterMap = array ( "Value.Type" => "ValueType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get. * @return mixed Variable value */ public function __get($var) { if (!array_key_exists($var, $this->_parameterMap)) { return NULL; } else { return $this->{$this->_parameterMap[$var]}; } } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "Value"; } public function __construct($ValueType = NULL) { $this->ValueType = $ValueType; } }} if (!class_exists("ApiVersionErrorReason", FALSE)) { /** * Indicates that the operation is not allowed in the version the request * was made in. * @package GoogleApiAdsDfp * @subpackage v201306 */ class ApiVersionErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ApiVersionError.Reason"; } public function __construct() { } }} if (!class_exists("AuthenticationErrorReason", FALSE)) { /** * The SOAP message contains a request header with an ambiguous definition * of the authentication header fields. This means either the {@code * authToken} and {@code oAuthToken} fields were both null or both were * specified. Exactly one value should be specified with each request. * @package GoogleApiAdsDfp * @subpackage v201306 */ class AuthenticationErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "AuthenticationError.Reason"; } public function __construct() { } }} if (!class_exists("CommonErrorReason", FALSE)) { /** * Describes reasons for common errors * @package GoogleApiAdsDfp * @subpackage v201306 */ class CommonErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "CommonError.Reason"; } public function __construct() { } }} if (!class_exists("AssetCreativeTemplateVariableMimeType", FALSE)) { /** * Different mime type that the asset variable supports. * @package GoogleApiAdsDfp * @subpackage v201306 */ class AssetCreativeTemplateVariableMimeType { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "AssetCreativeTemplateVariable.MimeType"; } public function __construct() { } }} if (!class_exists("CreativeTemplateErrorReason", FALSE)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201306 */ class CreativeTemplateErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "CreativeTemplateError.Reason"; } public function __construct() { } }} if (!class_exists("CreativeTemplateStatus", FALSE)) { /** * Describes status of the creative template * @package GoogleApiAdsDfp * @subpackage v201306 */ class CreativeTemplateStatus { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "CreativeTemplateStatus"; } public function __construct() { } }} if (!class_exists("CreativeTemplateType", FALSE)) { /** * Describes type of the creative template. * @package GoogleApiAdsDfp * @subpackage v201306 */ class CreativeTemplateType { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "CreativeTemplateType"; } public function __construct() { } }} if (!class_exists("FeatureErrorReason", FALSE)) { /** * A feature is being used that is not enabled on the current network. * @package GoogleApiAdsDfp * @subpackage v201306 */ class FeatureErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "FeatureError.Reason"; } public function __construct() { } }} if (!class_exists("InternalApiErrorReason", FALSE)) { /** * The single reason for the internal API error. * @package GoogleApiAdsDfp * @subpackage v201306 */ class InternalApiErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "InternalApiError.Reason"; } public function __construct() { } }} if (!class_exists("InvalidUrlErrorReason", FALSE)) { /** * The URL contains invalid characters. * @package GoogleApiAdsDfp * @subpackage v201306 */ class InvalidUrlErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "InvalidUrlError.Reason"; } public function __construct() { } }} if (!class_exists("NotNullErrorReason", FALSE)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201306 */ class NotNullErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "NotNullError.Reason"; } public function __construct() { } }} if (!class_exists("NullErrorReason", FALSE)) { /** * The reasons for the validation error. * @package GoogleApiAdsDfp * @subpackage v201306 */ class NullErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "NullError.Reason"; } public function __construct() { } }} if (!class_exists("ParseErrorReason", FALSE)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201306 */ class ParseErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ParseError.Reason"; } public function __construct() { } }} if (!class_exists("PermissionErrorReason", FALSE)) { /** * Describes reasons for permission errors. * @package GoogleApiAdsDfp * @subpackage v201306 */ class PermissionErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "PermissionError.Reason"; } public function __construct() { } }} if (!class_exists("PublisherQueryLanguageContextErrorReason", FALSE)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201306 */ class PublisherQueryLanguageContextErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "PublisherQueryLanguageContextError.Reason"; } public function __construct() { } }} if (!class_exists("PublisherQueryLanguageSyntaxErrorReason", FALSE)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201306 */ class PublisherQueryLanguageSyntaxErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "PublisherQueryLanguageSyntaxError.Reason"; } public function __construct() { } }} if (!class_exists("QuotaErrorReason", FALSE)) { /** * The number of requests made per second is too high and has exceeded the * allowable limit. The recommended approach to handle this error is to wait * about 5 seconds and then retry the request. Note that this does not * guarantee the request will succeed. If it fails again, try increasing the * wait time. * <p> * Another way to mitigate this error is to limit requests to 2 per second. * Once again this does not guarantee that every request will succeed, but * may help reduce the number of times you receive this error. * </p> * @package GoogleApiAdsDfp * @subpackage v201306 */ class QuotaErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "QuotaError.Reason"; } public function __construct() { } }} if (!class_exists("RangeErrorReason", FALSE)) { /** * The value returned if the actual value is not exposed by the requested API version. * @package GoogleApiAdsDfp * @subpackage v201306 */ class RangeErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "RangeError.Reason"; } public function __construct() { } }} if (!class_exists("RequiredErrorReason", FALSE)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201306 */ class RequiredErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "RequiredError.Reason"; } public function __construct() { } }} if (!class_exists("RequiredNumberErrorReason", FALSE)) { /** * Describes reasons for a number to be invalid. * @package GoogleApiAdsDfp * @subpackage v201306 */ class RequiredNumberErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "RequiredNumberError.Reason"; } public function __construct() { } }} if (!class_exists("ServerErrorReason", FALSE)) { /** * Describes reasons for server errors * @package GoogleApiAdsDfp * @subpackage v201306 */ class ServerErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ServerError.Reason"; } public function __construct() { } }} if (!class_exists("StatementErrorReason", FALSE)) { /** * A bind variable has not been bound to a value. * @package GoogleApiAdsDfp * @subpackage v201306 */ class StatementErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "StatementError.Reason"; } public function __construct() { } }} if (!class_exists("StringLengthErrorReason", FALSE)) { /** * The value returned if the actual value is not exposed by the requested API version. * @package GoogleApiAdsDfp * @subpackage v201306 */ class StringLengthErrorReason { /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "StringLengthError.Reason"; } public function __construct() { } }} if (!class_exists("getCreativeTemplate", FALSE)) { /** * Returns the {@link CreativeTemplate} uniquely identified by the given ID. * * @param creativeTemplateId the ID of the creative template, which must already exist * @return the {@code CreativeTemplate} uniquely identified by the given ID * @package GoogleApiAdsDfp * @subpackage v201306 */ class getCreativeTemplate { /** * @access public * @var integer */ public $creativeTemplateId; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return ""; } public function __construct($creativeTemplateId = NULL) { $this->creativeTemplateId = $creativeTemplateId; } }} if (!class_exists("getCreativeTemplateResponse", FALSE)) { /** * * @package GoogleApiAdsDfp * @subpackage v201306 */ class getCreativeTemplateResponse { /** * @access public * @var CreativeTemplate */ public $rval; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return ""; } public function __construct($rval = NULL) { $this->rval = $rval; } }} if (!class_exists("getCreativeTemplatesByStatement", FALSE)) { /** * Gets a {@link CreativeTemplatePage} of {@link CreativeTemplate} objects that satisfy the * given {@link Statement#query}. The following fields are supported for * filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link CreativeTemplate#id}</td> * </tr> * <tr> * <td>{@code name}</td> * <td>{@link CreativeTemplate#name}</td> * </tr> * <tr> * <td>{@code type}</td> * <td>{@link CreativeTemplate#type}</td> * </tr> * <tr> * <td>{@code status}</td> * <td>{@link CreativeTemplate#status}</td> * </tr> * </table> * * @param filterStatement a Publisher Query Language statement used to filter * a set of creative templates. * @return the creative templates that match the given filter * @package GoogleApiAdsDfp * @subpackage v201306 */ class getCreativeTemplatesByStatement { /** * @access public * @var Statement */ public $filterStatement; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return ""; } public function __construct($filterStatement = NULL) { $this->filterStatement = $filterStatement; } }} if (!class_exists("getCreativeTemplatesByStatementResponse", FALSE)) { /** * * @package GoogleApiAdsDfp * @subpackage v201306 */ class getCreativeTemplatesByStatementResponse { /** * @access public * @var CreativeTemplatePage */ public $rval; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return ""; } public function __construct($rval = NULL) { $this->rval = $rval; } }} if (!class_exists("ApiException", FALSE)) { /** * Exception class for holding a list of service errors. * @package GoogleApiAdsDfp * @subpackage v201306 */ class ApiException extends ApplicationException { /** * @access public * @var ApiError[] */ public $errors; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ApiException"; } public function __construct($errors = NULL, $message = NULL, $ApplicationExceptionType = NULL) { parent::__construct(); $this->errors = $errors; $this->message = $message; $this->ApplicationExceptionType = $ApplicationExceptionType; } }} if (!class_exists("BooleanValue", FALSE)) { /** * Contains a boolean value. * @package GoogleApiAdsDfp * @subpackage v201306 */ class BooleanValue extends Value { /** * @access public * @var boolean */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "BooleanValue"; } public function __construct($value = NULL, $ValueType = NULL) { parent::__construct(); $this->value = $value; $this->ValueType = $ValueType; } }} if (!class_exists("AssetCreativeTemplateVariable", FALSE)) { /** * Represents a file asset variable defined in a creative template. * <p> * Use {@link AssetCreativeTemplateVariableValue} to specify the value * for this variable when creating {@link TemplateCreative} from the {@link TemplateCreative}. * @package GoogleApiAdsDfp * @subpackage v201306 */ class AssetCreativeTemplateVariable extends CreativeTemplateVariable { /** * @access public * @var tnsAssetCreativeTemplateVariableMimeType[] */ public $mimeTypes; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "AssetCreativeTemplateVariable"; } public function __construct($mimeTypes = NULL, $label = NULL, $uniqueName = NULL, $description = NULL, $isRequired = NULL, $CreativeTemplateVariableType = NULL) { parent::__construct(); $this->mimeTypes = $mimeTypes; $this->label = $label; $this->uniqueName = $uniqueName; $this->description = $description; $this->isRequired = $isRequired; $this->CreativeTemplateVariableType = $CreativeTemplateVariableType; } }} if (!class_exists("LongCreativeTemplateVariable", FALSE)) { /** * Represents a long variable defined in a creative template. * @package GoogleApiAdsDfp * @subpackage v201306 */ class LongCreativeTemplateVariable extends CreativeTemplateVariable { /** * @access public * @var integer */ public $defaultValue; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "LongCreativeTemplateVariable"; } public function __construct($defaultValue = NULL, $label = NULL, $uniqueName = NULL, $description = NULL, $isRequired = NULL, $CreativeTemplateVariableType = NULL) { parent::__construct(); $this->defaultValue = $defaultValue; $this->label = $label; $this->uniqueName = $uniqueName; $this->description = $description; $this->isRequired = $isRequired; $this->CreativeTemplateVariableType = $CreativeTemplateVariableType; } }} if (!class_exists("StringCreativeTemplateVariable", FALSE)) { /** * Represents a string variable defined in a creative template. * <p> * Use {@link StringCreativeTemplateVariableValue} to specify the value * for this variable when creating {@link TemplateCreative} from the {@link TemplateCreative}. * @package GoogleApiAdsDfp * @subpackage v201306 */ class StringCreativeTemplateVariable extends CreativeTemplateVariable { /** * @access public * @var string */ public $defaultValue; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "StringCreativeTemplateVariable"; } public function __construct($defaultValue = NULL, $label = NULL, $uniqueName = NULL, $description = NULL, $isRequired = NULL, $CreativeTemplateVariableType = NULL) { parent::__construct(); $this->defaultValue = $defaultValue; $this->label = $label; $this->uniqueName = $uniqueName; $this->description = $description; $this->isRequired = $isRequired; $this->CreativeTemplateVariableType = $CreativeTemplateVariableType; } }} if (!class_exists("UrlCreativeTemplateVariable", FALSE)) { /** * Represents a url variable defined in a creative template. * <p> * Use {@link UrlCreativeTemplateVariableValue} to specify the value * for this variable when creating {@link TemplateCreative} from the {@link TemplateCreative} * @package GoogleApiAdsDfp * @subpackage v201306 */ class UrlCreativeTemplateVariable extends CreativeTemplateVariable { /** * @access public * @var string */ public $defaultValue; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "UrlCreativeTemplateVariable"; } public function __construct($defaultValue = NULL, $label = NULL, $uniqueName = NULL, $description = NULL, $isRequired = NULL, $CreativeTemplateVariableType = NULL) { parent::__construct(); $this->defaultValue = $defaultValue; $this->label = $label; $this->uniqueName = $uniqueName; $this->description = $description; $this->isRequired = $isRequired; $this->CreativeTemplateVariableType = $CreativeTemplateVariableType; } }} if (!class_exists("DateTimeValue", FALSE)) { /** * Contains a date-time value. * @package GoogleApiAdsDfp * @subpackage v201306 */ class DateTimeValue extends Value { /** * @access public * @var DateTime */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "DateTimeValue"; } public function __construct($value = NULL, $ValueType = NULL) { parent::__construct(); $this->value = $value; $this->ValueType = $ValueType; } }} if (!class_exists("DateValue", FALSE)) { /** * Contains a date value. * @package GoogleApiAdsDfp * @subpackage v201306 */ class DateValue extends Value { /** * @access public * @var Date */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "DateValue"; } public function __construct($value = NULL, $ValueType = NULL) { parent::__construct(); $this->value = $value; $this->ValueType = $ValueType; } }} if (!class_exists("NumberValue", FALSE)) { /** * Contains a numeric value. * @package GoogleApiAdsDfp * @subpackage v201306 */ class NumberValue extends Value { /** * @access public * @var string */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "NumberValue"; } public function __construct($value = NULL, $ValueType = NULL) { parent::__construct(); $this->value = $value; $this->ValueType = $ValueType; } }} if (!class_exists("TextValue", FALSE)) { /** * Contains a string value. * @package GoogleApiAdsDfp * @subpackage v201306 */ class TextValue extends Value { /** * @access public * @var string */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "TextValue"; } public function __construct($value = NULL, $ValueType = NULL) { parent::__construct(); $this->value = $value; $this->ValueType = $ValueType; } }} if (!class_exists("ListStringCreativeTemplateVariable", FALSE)) { /** * Represents a list variable defined in a creative template. This is similar to * {@link StringCreativeTemplateVariable}, except that there are possible choices to * choose from. * <p> * Use {@link StringCreativeTemplateVariableValue} to specify the value * for this variable when creating {@link TemplateCreative} from the {@link TemplateCreative}. * @package GoogleApiAdsDfp * @subpackage v201306 */ class ListStringCreativeTemplateVariable extends StringCreativeTemplateVariable { /** * @access public * @var ListStringCreativeTemplateVariableVariableChoice[] */ public $choices; /** * @access public * @var boolean */ public $allowOtherChoice; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return "https://www.google.com/apis/ads/publisher/v201306"; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return "ListStringCreativeTemplateVariable"; } public function __construct($choices = NULL, $allowOtherChoice = NULL, $defaultValue = NULL, $label = NULL, $uniqueName = NULL, $description = NULL, $isRequired = NULL, $CreativeTemplateVariableType = NULL) { parent::__construct(); $this->choices = $choices; $this->allowOtherChoice = $allowOtherChoice; $this->defaultValue = $defaultValue; $this->label = $label; $this->uniqueName = $uniqueName; $this->description = $description; $this->isRequired = $isRequired; $this->CreativeTemplateVariableType = $CreativeTemplateVariableType; } }} if (!class_exists("CreativeTemplateService", FALSE)) { /** * CreativeTemplateService * @package GoogleApiAdsDfp * @subpackage v201306 * @author WSDLInterpreter */ class CreativeTemplateService extends DfpSoapClient { /** * Default class map for wsdl=>php * @access private * @var array */ public static $classmap = array( "DateTime" => "DfpDateTime", "Location" => "DfpLocation", "OAuth" => "DfpOAuth", "ApiError" => "ApiError", "ApiException" => "ApiException", "ApplicationException" => "ApplicationException", "ApiVersionError" => "ApiVersionError", "Authentication" => "Authentication", "AuthenticationError" => "AuthenticationError", "BooleanValue" => "BooleanValue", "Value" => "Value", "ClientLogin" => "ClientLogin", "CommonError" => "CommonError", "AssetCreativeTemplateVariable" => "AssetCreativeTemplateVariable", "CreativeTemplateVariable" => "CreativeTemplateVariable", "CreativeTemplate" => "CreativeTemplate", "CreativeTemplateError" => "CreativeTemplateError", "ListStringCreativeTemplateVariable" => "ListStringCreativeTemplateVariable", "StringCreativeTemplateVariable" => "StringCreativeTemplateVariable", "ListStringCreativeTemplateVariable.VariableChoice" => "ListStringCreativeTemplateVariableVariableChoice", "LongCreativeTemplateVariable" => "LongCreativeTemplateVariable", "CreativeTemplatePage" => "CreativeTemplatePage", "UrlCreativeTemplateVariable" => "UrlCreativeTemplateVariable", "Date" => "Date", "DateTimeValue" => "DateTimeValue", "DateValue" => "DateValue", "FeatureError" => "FeatureError", "InternalApiError" => "InternalApiError", "InvalidUrlError" => "InvalidUrlError", "NotNullError" => "NotNullError", "NullError" => "NullError", "NumberValue" => "NumberValue", "ParseError" => "ParseError", "PermissionError" => "PermissionError", "PublisherQueryLanguageContextError" => "PublisherQueryLanguageContextError", "PublisherQueryLanguageSyntaxError" => "PublisherQueryLanguageSyntaxError", "QuotaError" => "QuotaError", "RangeError" => "RangeError", "RequiredError" => "RequiredError", "RequiredNumberError" => "RequiredNumberError", "ServerError" => "ServerError", "SoapRequestHeader" => "SoapRequestHeader", "SoapResponseHeader" => "SoapResponseHeader", "Statement" => "Statement", "StatementError" => "StatementError", "StringLengthError" => "StringLengthError", "String_ValueMapEntry" => "String_ValueMapEntry", "TextValue" => "TextValue", "UniqueError" => "UniqueError", "ApiVersionError.Reason" => "ApiVersionErrorReason", "AuthenticationError.Reason" => "AuthenticationErrorReason", "CommonError.Reason" => "CommonErrorReason", "AssetCreativeTemplateVariable.MimeType" => "AssetCreativeTemplateVariableMimeType", "CreativeTemplateError.Reason" => "CreativeTemplateErrorReason", "CreativeTemplateStatus" => "CreativeTemplateStatus", "CreativeTemplateType" => "CreativeTemplateType", "FeatureError.Reason" => "FeatureErrorReason", "InternalApiError.Reason" => "InternalApiErrorReason", "InvalidUrlError.Reason" => "InvalidUrlErrorReason", "NotNullError.Reason" => "NotNullErrorReason", "NullError.Reason" => "NullErrorReason", "ParseError.Reason" => "ParseErrorReason", "PermissionError.Reason" => "PermissionErrorReason", "PublisherQueryLanguageContextError.Reason" => "PublisherQueryLanguageContextErrorReason", "PublisherQueryLanguageSyntaxError.Reason" => "PublisherQueryLanguageSyntaxErrorReason", "QuotaError.Reason" => "QuotaErrorReason", "RangeError.Reason" => "RangeErrorReason", "RequiredError.Reason" => "RequiredErrorReason", "RequiredNumberError.Reason" => "RequiredNumberErrorReason", "ServerError.Reason" => "ServerErrorReason", "StatementError.Reason" => "StatementErrorReason", "StringLengthError.Reason" => "StringLengthErrorReason", "getCreativeTemplate" => "getCreativeTemplate", "getCreativeTemplateResponse" => "getCreativeTemplateResponse", "getCreativeTemplatesByStatement" => "getCreativeTemplatesByStatement", "getCreativeTemplatesByStatementResponse" => "getCreativeTemplatesByStatementResponse", ); /** * The endpoint of the service * @var string */ public static $endpoint = "https://www.google.com/apis/ads/publisher/v201306/CreativeTemplateService"; /** * Constructor using wsdl location and options array * @param string $wsdl WSDL location for this service * @param array $options Options for the SoapClient */ public function __construct($wsdl=null, $options, $user) { $options["classmap"] = CreativeTemplateService::$classmap; parent::__construct($wsdl, $options, $user, 'CreativeTemplateService', 'https://www.google.com/apis/ads/publisher/v201306'); } /** * Returns the {@link CreativeTemplate} uniquely identified by the given ID. * * @param creativeTemplateId the ID of the creative template, which must already exist * @return the {@code CreativeTemplate} uniquely identified by the given ID */ public function getCreativeTemplate($creativeTemplateId) { $arg = new getCreativeTemplate($creativeTemplateId); $result = $this->__soapCall("getCreativeTemplate", array($arg)); return $result->rval; } /** * Gets a {@link CreativeTemplatePage} of {@link CreativeTemplate} objects that satisfy the * given {@link Statement#query}. The following fields are supported for * filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link CreativeTemplate#id}</td> * </tr> * <tr> * <td>{@code name}</td> * <td>{@link CreativeTemplate#name}</td> * </tr> * <tr> * <td>{@code type}</td> * <td>{@link CreativeTemplate#type}</td> * </tr> * <tr> * <td>{@code status}</td> * <td>{@link CreativeTemplate#status}</td> * </tr> * </table> * * @param filterStatement a Publisher Query Language statement used to filter * a set of creative templates. * @return the creative templates that match the given filter */ public function getCreativeTemplatesByStatement($filterStatement) { $arg = new getCreativeTemplatesByStatement($filterStatement); $result = $this->__soapCall("getCreativeTemplatesByStatement", array($arg)); return $result->rval; } }}
apache-2.0
panpf/sketch
sketch/src/main/java/me/panpf/sketch/zoom/block/DecodeHandler.java
9631
/* * Copyright (C) 2019 Peng fei Pan <panpfpanpf@outlook.me> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.panpf.sketch.zoom.block; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Point; import android.graphics.Rect; import android.os.Handler; import android.os.Looper; import android.os.Message; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.lang.ref.WeakReference; import me.panpf.sketch.Configuration; import me.panpf.sketch.ErrorTracker; import me.panpf.sketch.SLog; import me.panpf.sketch.Sketch; import me.panpf.sketch.cache.BitmapPool; import me.panpf.sketch.cache.BitmapPoolUtils; import me.panpf.sketch.decode.ImageDecodeUtils; import me.panpf.sketch.decode.ImageOrientationCorrector; import me.panpf.sketch.decode.ImageType; /** * 解码处理器,运行在解码线程中,负责解码 */ @SuppressWarnings("WeakerAccess") public class DecodeHandler extends Handler { private static final String NAME = "DecodeHandler"; private static final int WHAT_DECODE = 1001; private boolean disableInBitmap; @NonNull private WeakReference<BlockExecutor> reference; @NonNull private BitmapPool bitmapPool; @NonNull private ErrorTracker errorTracker; @NonNull private ImageOrientationCorrector orientationCorrector; public DecodeHandler(@NonNull Looper looper, @NonNull BlockExecutor executor) { super(looper); this.reference = new WeakReference<>(executor); Configuration configuration = Sketch.with(executor.callback.getContext()).getConfiguration(); this.bitmapPool = configuration.getBitmapPool(); this.errorTracker = configuration.getErrorTracker(); this.orientationCorrector = configuration.getOrientationCorrector(); } @Override public void handleMessage(@NonNull Message msg) { BlockExecutor decodeExecutor = reference.get(); if (decodeExecutor != null) { decodeExecutor.callbackHandler.cancelDelayDestroyThread(); } if (msg.what == WHAT_DECODE) { decode(decodeExecutor, msg.arg1, (Block) msg.obj); } if (decodeExecutor != null) { decodeExecutor.callbackHandler.postDelayRecycleDecodeThread(); } } public void postDecode(int key, @NonNull Block block) { Message message = obtainMessage(DecodeHandler.WHAT_DECODE); message.arg1 = key; message.obj = block; message.sendToTarget(); } private void decode(@Nullable BlockExecutor executor, int key, @NonNull Block block) { if (executor == null) { SLog.w(NAME, "weak reference break. key: %d, block=%s", key, block.getInfo()); return; } if (block.isExpired(key)) { executor.callbackHandler.postDecodeError(key, block, new DecodeErrorException(DecodeErrorException.CAUSE_BEFORE_KEY_EXPIRED)); return; } if (block.isDecodeParamEmpty()) { executor.callbackHandler.postDecodeError(key, block, new DecodeErrorException(DecodeErrorException.CAUSE_DECODE_PARAM_EMPTY)); return; } ImageRegionDecoder regionDecoder = block.decoder; if (regionDecoder == null || !regionDecoder.isReady()) { executor.callbackHandler.postDecodeError(key, block, new DecodeErrorException(DecodeErrorException.CAUSE_DECODER_NULL_OR_NOT_READY)); return; } Rect srcRect = new Rect(block.srcRect); int inSampleSize = block.inSampleSize; // 根据图片方向恢复src区域的真实位置 Point imageSize = regionDecoder.getImageSize(); orientationCorrector.reverseRotate(srcRect, imageSize.x, imageSize.y, regionDecoder.getExifOrientation()); BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = inSampleSize; ImageType imageType = regionDecoder.getImageType(); if (imageType != null) { options.inPreferredConfig = imageType.getConfig(false); } if (!disableInBitmap && BitmapPoolUtils.sdkSupportInBitmapForRegionDecoder()) { BitmapPoolUtils.setInBitmapFromPoolForRegionDecoder(options, srcRect, bitmapPool); } long time = System.currentTimeMillis(); Bitmap bitmap = null; try { bitmap = regionDecoder.decodeRegion(srcRect, options); } catch (Throwable throwable) { throwable.printStackTrace(); if (ImageDecodeUtils.isInBitmapDecodeError(throwable, options, true)) { disableInBitmap = true; ImageDecodeUtils.recycleInBitmapOnDecodeError(errorTracker, bitmapPool, regionDecoder.getImageUri(), regionDecoder.getImageSize().x, regionDecoder.getImageSize().y, regionDecoder.getImageType().getMimeType(), throwable, options, true); try { bitmap = regionDecoder.decodeRegion(srcRect, options); } catch (Throwable throwable1) { throwable1.printStackTrace(); } } else if (ImageDecodeUtils.isSrcRectDecodeError(throwable, regionDecoder.getImageSize().x, regionDecoder.getImageSize().y, srcRect)) { errorTracker.onDecodeRegionError(regionDecoder.getImageUri(), regionDecoder.getImageSize().x, regionDecoder.getImageSize().y, regionDecoder.getImageType().getMimeType(), throwable, srcRect, options.inSampleSize); } } int useTime = (int) (System.currentTimeMillis() - time); if (bitmap == null || bitmap.isRecycled()) { executor.callbackHandler.postDecodeError(key, block, new DecodeErrorException(DecodeErrorException.CAUSE_BITMAP_NULL)); return; } if (block.isExpired(key)) { BitmapPoolUtils.freeBitmapToPoolForRegionDecoder(bitmap, Sketch.with(executor.callback.getContext()).getConfiguration().getBitmapPool()); executor.callbackHandler.postDecodeError(key, block, new DecodeErrorException(DecodeErrorException.CAUSE_AFTER_KEY_EXPIRED)); return; } // 旋转图片 Bitmap newBitmap = orientationCorrector.rotate(bitmap, regionDecoder.getExifOrientation(), bitmapPool); if (newBitmap != null && newBitmap != bitmap) { if (!newBitmap.isRecycled()) { BitmapPoolUtils.freeBitmapToPool(bitmap, bitmapPool); bitmap = newBitmap; } else { executor.callbackHandler.postDecodeError(key, block, new DecodeErrorException(DecodeErrorException.CAUSE_ROTATE_BITMAP_RECYCLED)); return; } } if (bitmap.isRecycled()) { executor.callbackHandler.postDecodeError(key, block, new DecodeErrorException(DecodeErrorException.CAUSE_BITMAP_RECYCLED)); return; } executor.callbackHandler.postDecodeCompleted(key, block, bitmap, useTime); } public void clean(@NonNull String why) { if (SLog.isLoggable(SLog.LEVEL_DEBUG | SLog.TYPE_ZOOM_BLOCK_DISPLAY)) { SLog.d(NAME, "clean. %s", why); } removeMessages(WHAT_DECODE); } public static class DecodeErrorException extends Exception { public static final int CAUSE_BITMAP_RECYCLED = 1100; public static final int CAUSE_BITMAP_NULL = 1101; public static final int CAUSE_BEFORE_KEY_EXPIRED = 1102; public static final int CAUSE_AFTER_KEY_EXPIRED = 1103; public static final int CAUSE_CALLBACK_KEY_EXPIRED = 1104; public static final int CAUSE_DECODE_PARAM_EMPTY = 1105; public static final int CAUSE_DECODER_NULL_OR_NOT_READY = 1106; public static final int CAUSE_ROTATE_BITMAP_RECYCLED = 1107; private int cause; public DecodeErrorException(int cause) { this.cause = cause; } public int getErrorCause() { return cause; } public String getCauseMessage() { if (cause == CAUSE_BITMAP_RECYCLED) { return "bitmap is recycled"; } else if (cause == CAUSE_BITMAP_NULL) { return "bitmap is null or recycled"; } else if (cause == CAUSE_BEFORE_KEY_EXPIRED) { return "key expired before decode"; } else if (cause == CAUSE_AFTER_KEY_EXPIRED) { return "key expired after decode"; } else if (cause == CAUSE_CALLBACK_KEY_EXPIRED) { return "key expired before callback"; } else if (cause == CAUSE_DECODE_PARAM_EMPTY) { return "decode param is empty"; } else if (cause == CAUSE_DECODER_NULL_OR_NOT_READY) { return "decoder is null or not ready"; } else if (cause == CAUSE_ROTATE_BITMAP_RECYCLED) { return "rotate result bitmap is recycled"; } else { return "unknown"; } } } }
apache-2.0
oaastest/azure-linux-extensions
AzureEnhancedMonitor/ext/test/test_aem.py
15614
#!/usr/bin/env python # #CustomScript extension # # Copyright 2014 Microsoft Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Requires Python 2.6+ # import sys import unittest import env import os import json import datetime from Utils.WAAgentUtil import waagent import aem import handler TestPublicConfig = """\ { "cfg": [{ "key": "vmsize", "value": "Small (A1)" },{ "key": "vm.roleinstance", "value": "osupdate" },{ "key": "vm.role", "value": "IaaS" },{ "key": "vm.deploymentid", "value": "cd98461b43364478a908d03d0c3135a7" },{ "key": "vm.memory.isovercommitted", "value": 0 },{ "key": "vm.cpu.isovercommitted", "value": 0 },{ "key": "script.version", "value": "1.2.0.0" },{ "key": "verbose", "value": "0" },{ "key": "osdisk.connminute", "value": "asdf.minute" },{ "key": "osdisk.connhour", "value": "asdf.hour" },{ "key": "osdisk.name", "value": "osupdate-osupdate-2015-02-12.vhd" },{ "key": "asdf.hour.uri", "value": "https://asdf.table.core.windows.net/$metricshourprimarytransactionsblob" },{ "key": "asdf.minute.uri", "value": "https://asdf.table.core.windows.net/$metricsminuteprimarytransactionsblob" },{ "key": "asdf.hour.name", "value": "asdf" },{ "key": "asdf.minute.name", "value": "asdf" },{ "key": "wad.name", "value": "asdf" },{ "key": "wad.isenabled", "value": "1" },{ "key": "wad.uri", "value": "https://asdf.table.core.windows.net/wadperformancecounterstable" }] } """ TestPrivateConfig = """\ { "cfg" : [{ "key" : "asdf.minute.key", "value" : "qwer" },{ "key" : "wad.key", "value" : "qwer" }] } """ class TestAEM(unittest.TestCase): def setUp(self): waagent.LoggerInit("/dev/null", "/dev/stdout") def test_config(self): publicConfig = json.loads(TestPublicConfig) privateConfig = json.loads(TestPrivateConfig) config = aem.EnhancedMonitorConfig(publicConfig, privateConfig) self.assertNotEquals(None, config) self.assertEquals(".table.core.windows.net", config.getStorageHostBase('asdf')) self.assertEquals(".table.core.windows.net", config.getLADHostBase()) return config def test_static_datasource(self): config = self.test_config() dataSource = aem.StaticDataSource(config) counters = dataSource.collect() self.assertNotEquals(None, counters) self.assertNotEquals(0, len(counters)) name = "Cloud Provider" counter = next((c for c in counters if c.name == name)) self.assertNotEquals(None, counter) self.assertEquals("Microsoft Azure", counter.value) name = "Virtualization Solution Version" counter = next((c for c in counters if c.name == name)) self.assertNotEquals(None, counter) self.assertNotEquals(None, counter.value) name = "Virtualization Solution" counter = next((c for c in counters if c.name == name)) self.assertNotEquals(None, counter) self.assertNotEquals(None, counter.value) name = "Instance Type" counter = next((c for c in counters if c.name == name)) self.assertNotEquals(None, counter) self.assertEquals("Small (A1)", counter.value) name = "Data Sources" counter = next((c for c in counters if c.name == name)) self.assertNotEquals(None, counter) self.assertEquals("wad", counter.value) name = "Data Provider Version" counter = next((c for c in counters if c.name == name)) self.assertNotEquals(None, counter) self.assertEquals("1.0.0", counter.value) name = "Memory Over-Provisioning" counter = next((c for c in counters if c.name == name)) self.assertNotEquals(None, counter) self.assertEquals("no", counter.value) name = "CPU Over-Provisioning" counter = next((c for c in counters if c.name == name)) self.assertNotEquals(None, counter) self.assertEquals("no", counter.value) def test_cpuinfo(self): cpuinfo = aem.CPUInfo.getCPUInfo() self.assertNotEquals(None, cpuinfo) self.assertNotEquals(0, cpuinfo.getNumOfCoresPerCPU()) self.assertNotEquals(0, cpuinfo.getNumOfCores()) self.assertNotEquals(None, cpuinfo.getProcessorType()) self.assertEquals(float, type(cpuinfo.getFrequency())) self.assertEquals(bool, type(cpuinfo.isHyperThreadingOn())) percent = cpuinfo.getCPUPercent() self.assertEquals(float, type(percent)) self.assertTrue(percent >= 0 and percent <= 100) def test_meminfo(self): meminfo = aem.MemoryInfo() self.assertNotEquals(None, meminfo.getMemSize()) self.assertEquals(long, type(meminfo.getMemSize())) percent = meminfo.getMemPercent() self.assertEquals(float, type(percent)) self.assertTrue(percent >= 0 and percent <= 100) def test_networkinfo(self): netinfo = aem.NetworkInfo() adapterIds = netinfo.getAdapterIds() self.assertNotEquals(None, adapterIds) self.assertNotEquals(0, len(adapterIds)) adapterId = adapterIds[0] self.assertNotEquals(None, aem.getMacAddress(adapterId)) self.assertNotEquals(None, netinfo.getNetworkReadBytes()) self.assertNotEquals(None, netinfo.getNetworkWriteBytes()) self.assertNotEquals(None, netinfo.getNetworkPacketRetransmitted()) def test_hwchangeinfo(self): netinfo = aem.NetworkInfo() testHwInfoFile = "/tmp/HwInfo" aem.HwInfoFile = testHwInfoFile if os.path.isfile(testHwInfoFile): os.remove(testHwInfoFile) hwChangeInfo = aem.HardwareChangeInfo(netinfo) self.assertNotEquals(None, hwChangeInfo.getLastHardwareChange()) self.assertTrue(os.path.isfile, aem.HwInfoFile) #No hardware change lastChange = hwChangeInfo.getLastHardwareChange() hwChangeInfo = aem.HardwareChangeInfo(netinfo) self.assertEquals(lastChange, hwChangeInfo.getLastHardwareChange()) #Create mock hardware waagent.SetFileContents(testHwInfoFile, ("0\nma-ca-sa-ds-02")) hwChangeInfo = aem.HardwareChangeInfo(netinfo) self.assertNotEquals(None, hwChangeInfo.getLastHardwareChange()) def test_linux_metric(self): config = self.test_config() metric = aem.LinuxMetric(config) self.validate_cnm_metric(metric) #Metric for CPU, network and memory def validate_cnm_metric(self, metric): self.assertNotEquals(None, metric.getCurrHwFrequency()) self.assertNotEquals(None, metric.getMaxHwFrequency()) self.assertNotEquals(None, metric.getCurrVMProcessingPower()) self.assertNotEquals(None, metric.getGuaranteedMemAssigned()) self.assertNotEquals(None, metric.getMaxVMProcessingPower()) self.assertNotEquals(None, metric.getNumOfCoresPerCPU()) self.assertNotEquals(None, metric.getNumOfThreadsPerCore()) self.assertNotEquals(None, metric.getPhysProcessingPowerPerVCPU()) self.assertNotEquals(None, metric.getProcessorType()) self.assertNotEquals(None, metric.getReferenceComputeUnit()) self.assertNotEquals(None, metric.getVCPUMapping()) self.assertNotEquals(None, metric.getVMProcessingPowerConsumption()) self.assertNotEquals(None, metric.getCurrMemAssigned()) self.assertNotEquals(None, metric.getGuaranteedMemAssigned()) self.assertNotEquals(None, metric.getMaxMemAssigned()) self.assertNotEquals(None, metric.getVMMemConsumption()) adapterIds = metric.getNetworkAdapterIds() self.assertNotEquals(None, adapterIds) self.assertNotEquals(0, len(adapterIds)) adapterId = adapterIds[0] self.assertNotEquals(None, metric.getNetworkAdapterMapping(adapterId)) self.assertNotEquals(None, metric.getMaxNetworkBandwidth(adapterId)) self.assertNotEquals(None, metric.getMinNetworkBandwidth(adapterId)) self.assertNotEquals(None, metric.getNetworkReadBytes()) self.assertNotEquals(None, metric.getNetworkWriteBytes()) self.assertNotEquals(None, metric.getNetworkPacketRetransmitted()) self.assertNotEquals(None, metric.getLastHardwareChange()) def test_vm_datasource(self): config = self.test_config() config.configData["wad.isenabled"] = "0" dataSource = aem.VMDataSource(config) counters = dataSource.collect() self.assertNotEquals(None, counters) self.assertNotEquals(0, len(counters)) counterNames = [ "Current Hw Frequency", "Current VM Processing Power", "Guaranteed VM Processing Power", "Max Hw Frequency", "Max. VM Processing Power", "Number of Cores per CPU", "Number of Threads per Core", "Phys. Processing Power per vCPU", "Processor Type", "Reference Compute Unit", "vCPU Mapping", "VM Processing Power Consumption", "Current Memory assigned", "Guaranteed Memory assigned", "Max Memory assigned", "VM Memory Consumption", "Adapter Id", "Mapping", "Maximum Network Bandwidth", "Minimum Network Bandwidth", "Network Read Bytes", "Network Write Bytes", "Packets Retransmitted" ] #print "\n".join(map(lambda c: str(c), counters)) for name in counterNames: #print name counter = next((c for c in counters if c.name == name)) self.assertNotEquals(None, counter) self.assertNotEquals(None, counter.value) def test_storagemetric(self): metrics = mock_getStorageMetrics() self.assertNotEquals(None, metrics) stat = aem.AzureStorageStat(metrics) self.assertNotEquals(None, stat.getReadBytes()) self.assertNotEquals(None, stat.getReadOps()) self.assertNotEquals(None, stat.getReadOpE2ELatency()) self.assertNotEquals(None, stat.getReadOpServerLatency()) self.assertNotEquals(None, stat.getReadOpThroughput()) self.assertNotEquals(None, stat.getWriteBytes()) self.assertNotEquals(None, stat.getWriteOps()) self.assertNotEquals(None, stat.getWriteOpE2ELatency()) self.assertNotEquals(None, stat.getWriteOpServerLatency()) self.assertNotEquals(None, stat.getWriteOpThroughput()) def test_disk_info(self): config = self.test_config() mapping = aem.DiskInfo(config).getDiskMapping() self.assertNotEquals(None, mapping) def test_get_storage_key_range(self): startKey, endKey = aem.getStorageTableKeyRange() self.assertNotEquals(None, startKey) self.assertEquals(13, len(startKey)) self.assertNotEquals(None, endKey) self.assertEquals(13, len(endKey)) def test_storage_datasource(self): aem.getStorageMetrics = mock_getStorageMetrics config = self.test_config() dataSource = aem.StorageDataSource(config) counters = dataSource.collect() self.assertNotEquals(None, counters) self.assertNotEquals(0, len(counters)) counterNames = [ "Phys. Disc to Storage Mapping", "Storage ID", "Storage Read Bytes", "Storage Read Op Latency E2E msec", "Storage Read Op Latency Server msec", "Storage Read Ops", "Storage Read Throughput E2E MB/sec", "Storage Write Bytes", "Storage Write Op Latency E2E msec", "Storage Write Op Latency Server msec", "Storage Write Ops", "Storage Write Throughput E2E MB/sec" ] #print "\n".join(map(lambda c: str(c), counters)) for name in counterNames: #print name counter = next((c for c in counters if c.name == name)) self.assertNotEquals(None, counter) self.assertNotEquals(None, counter.value) def test_writer(self): testEventFile = "/tmp/Event" if os.path.isfile(testEventFile): os.remove(testEventFile) writer = aem.PerfCounterWriter() counters = [aem.PerfCounter(counterType = 0, category = "test", name = "test", value = "test", unit = "test")] writer.write(counters, eventFile = testEventFile) with open(testEventFile) as F: content = F.read() self.assertEquals(str(counters[0]), content) testEventFile = "/dev/console" print "==============================" print "The warning below is expected." self.assertRaises(IOError, writer.write, counters, 2, testEventFile) print "==============================" def test_easyHash(self): hashVal = aem.easyHash('a') self.assertEquals(97, hashVal) hashVal = aem.easyHash('ab') self.assertEquals(87, hashVal) hashVal = aem.easyHash(("ciextension-SUSELinuxEnterpriseServer11SP3" "___role1___" "ciextension-SUSELinuxEnterpriseServer11SP3")) self.assertEquals(5, hashVal) def test_get_ad_key_range(self): startKey, endKey = aem.getAzureDiagnosticKeyRange() print startKey print endKey def test_get_mds_timestamp(self): date = datetime.datetime(2015, 1, 26, 3, 54) epoch = datetime.datetime.utcfromtimestamp(0) unixTimestamp = (int((date - epoch).total_seconds())) mdsTimestamp = aem.getMDSTimestamp(unixTimestamp) self.assertEquals(635578412400000000, mdsTimestamp) def test_get_storage_timestamp(self): date = datetime.datetime(2015, 1, 26, 3, 54) epoch = datetime.datetime.utcfromtimestamp(0) unixTimestamp = (int((date - epoch).total_seconds())) storageTimestamp = aem.getStorageTimestamp(unixTimestamp) self.assertEquals("20150126T0354", storageTimestamp) def mock_getStorageMetrics(*args, **kwargs): with open(os.path.join(env.test_dir, "storage_metrics")) as F: test_data = F.read() jsonObjs = json.loads(test_data) class ObjectView(object): def __init__(self, data): self.__dict__ = data metrics = map(lambda x : ObjectView(x), jsonObjs) return metrics if __name__ == '__main__': unittest.main()
apache-2.0
dncuug/scaffolder
Scaffolder.API/Application/ControllerBase.cs
1574
using System; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Scaffolder.API.Application.Security; using Scaffolder.Core.Meta; using System.Security.Claims; using NLog; namespace Scaffolder.API.Application { public class ControllerBase : Controller { private ApplicationContext _applicationContext; private static readonly Object Lock = new Object(); protected static Logger Logger = LogManager.GetCurrentClassLogger(); protected ApplicationContext ApplicationContext { get { if (_applicationContext == null) { lock (Lock) { if (_applicationContext == null) { var login = User.FindFirst(ClaimTypes.NameIdentifier).Value; var authorizationManager = new AuthorizationManager(Settings.WorkingDirectory); var configuratoinLocation = authorizationManager.GetConfiguratoinLocationForUser(login); _applicationContext = ApplicationContext.Load(configuratoinLocation); } } } return _applicationContext; } } protected AppSettings Settings { get; private set; } public ControllerBase(IOptions<AppSettings> settings) { Settings = settings.Value; } } }
apache-2.0
TestInABox/openstackinabox
openstackinabox/tests/services/keystone/v2/user/test_listing.py
6944
""" Stack-In-A-Box: Basic Test """ import unittest import requests import stackinabox.util.requests_mock.core from stackinabox.stack import StackInABox from openstackinabox.services.keystone import KeystoneV2Service class TestKeystoneV2UserListing(unittest.TestCase): def setUp(self): super(TestKeystoneV2UserListing, self).setUp() self.keystone = KeystoneV2Service() self.headers = { 'x-auth-token': self.keystone.model.tokens.admin_token } StackInABox.register_service(self.keystone) def tearDown(self): super(TestKeystoneV2UserListing, self).tearDown() StackInABox.reset_services() def test_user_listing_no_token(self): with stackinabox.util.requests_mock.core.activate(): stackinabox.util.requests_mock.core.requests_mock_registration( 'localhost') res = requests.get('http://localhost/keystone/v2.0/users') self.assertEqual(res.status_code, 403) def test_user_listing_bad_token(self): with stackinabox.util.requests_mock.core.activate(): stackinabox.util.requests_mock.core.requests_mock_registration( 'localhost') self.headers['x-auth-token'] = 'new_token' res = requests.get('http://localhost/keystone/v2.0/users', headers=self.headers) self.assertEqual(res.status_code, 401) def test_user_listing(self): with stackinabox.util.requests_mock.core.activate(): stackinabox.util.requests_mock.core.requests_mock_registration( 'localhost') neo_tenant_id = self.keystone.model.tenants.add( tenant_name='neo', description='The One') tom = self.keystone.model.users.add( neo_tenant_id, 'tom', 'tom@theone.matrix', 'bluepill', 'iamnottheone', enabled=True ) self.keystone.model.roles.add_user_role_by_role_name( neo_tenant_id, tom, 'identity:user-admin') self.keystone.model.tokens.add(neo_tenant_id, tom) user_data = self.keystone.model.tokens.get_by_user_id(tom) self.headers['x-auth-token'] = user_data['token'] res = requests.get('http://localhost/keystone/v2.0/users', headers=self.headers) self.assertEqual(res.status_code, 200) user_data = res.json() self.assertEqual(len(user_data['users']), 1) self.keystone.model.users.add( neo_tenant_id, 'neo', 'neo@theone.matrix', 'redpill', 'iamtheone', enabled=True ) res = requests.get('http://localhost/keystone/v2.0/users', headers=self.headers) self.assertEqual(res.status_code, 200) user_data = res.json() self.assertEqual(len(user_data['users']), 2) def test_user_listing_by_name(self): with stackinabox.util.requests_mock.core.activate(): stackinabox.util.requests_mock.core.requests_mock_registration( 'localhost') neo_tenant_id = self.keystone.model.tenants.add( tenant_name='neo', description='The One') tom = self.keystone.model.users.add( neo_tenant_id, 'tom', 'tom@theone.matrix', 'bluepill', 'iamnottheone', enabled=True ) self.keystone.model.roles.add_user_role_by_role_name( neo_tenant_id, tom, 'identity:user-admin') self.keystone.model.tokens.add(neo_tenant_id, tom) user_data = self.keystone.model.tokens.get_by_user_id(tom) self.headers['x-auth-token'] = user_data['token'] res = requests.get('http://localhost/keystone/v2.0/users', headers=self.headers) self.assertEqual(res.status_code, 200) user_data = res.json() self.assertEqual(len(user_data['users']), 1) self.keystone.model.users.add( neo_tenant_id, 'neo', 'neo@theone.matrix', 'redpill', 'iamtheone', enabled=True ) res = requests.get('http://localhost/keystone/v2.0/users?name=tom', headers=self.headers) self.assertEqual(res.status_code, 200) user_data = res.json() self.assertIn('user', user_data) self.assertEqual(len(user_data), 1) self.assertEqual(user_data['user']['username'], 'tom') def test_user_listing_with_invalid_query_param(self): with stackinabox.util.requests_mock.core.activate(): stackinabox.util.requests_mock.core.requests_mock_registration( 'localhost') neo_tenant_id = self.keystone.model.tenants.add( tenant_name='neo', description='The One' ) tom = self.keystone.model.users.add( tenant_id=neo_tenant_id, username='tom', email='tom@theone.matrix', password='bluepill', apikey='iamnottheone', enabled=True ) self.keystone.model.roles.add_user_role_by_role_name( tenant_id=neo_tenant_id, user_id=tom, role_name='identity:user-admin' ) self.keystone.model.tokens.add( tenant_id=neo_tenant_id, user_id=tom ) user_data = self.keystone.model.tokens.get_by_user_id(tom) self.headers['x-auth-token'] = user_data['token'] res = requests.get( 'http://localhost/keystone/v2.0/users?honesty=False', headers=self.headers ) self.assertEqual(res.status_code, 200) user_data = res.json() self.assertEqual(len(user_data['users']), 1) self.keystone.model.users.add( tenant_id=neo_tenant_id, username='neo', email='neo@theone.matrix', password='redpill', apikey='iamtheone', enabled=True ) res = requests.get( 'http://localhost/keystone/v2.0/users', headers=self.headers ) self.assertEqual(res.status_code, 200) user_data = res.json() self.assertEqual(len(user_data['users']), 2)
apache-2.0
guijun/MCServer
src/Generating/CompoGenBiomal.cpp
17254
// CompoGenBiomal.cpp // Implements the cCompoGenBiomal class representing the biome-aware composition generator #include "Globals.h" #include "ComposableGenerator.h" #include "../IniFile.h" #include "../Noise/Noise.h" #include "../LinearUpscale.h" //////////////////////////////////////////////////////////////////////////////// // cPattern: /** This class is used to store a column pattern initialized at runtime, so that the program doesn't need to explicitly set 256 values for each pattern Each pattern has 256 blocks so that there's no need to check pattern bounds when assigning the pattern - there will always be enough pattern left, even for the whole-chunk-height columns. */ class cPattern { public: struct BlockInfo { BLOCKTYPE m_BlockType; NIBBLETYPE m_BlockMeta; }; cPattern(BlockInfo * a_TopBlocks, size_t a_Count) { // Copy the pattern into the top: for (size_t i = 0; i < a_Count; i++) { m_Pattern[i] = a_TopBlocks[i]; } // Fill the rest with stone: static BlockInfo Stone = {E_BLOCK_STONE, 0}; for (int i = static_cast<int>(a_Count); i < cChunkDef::Height; i++) { m_Pattern[i] = Stone; } } const BlockInfo * Get(void) const { return m_Pattern; } protected: BlockInfo m_Pattern[cChunkDef::Height]; } ; //////////////////////////////////////////////////////////////////////////////// // The arrays to use for the top block pattern definitions: static cPattern::BlockInfo tbGrass[] = { {E_BLOCK_GRASS, 0}, {E_BLOCK_DIRT, E_META_DIRT_NORMAL}, {E_BLOCK_DIRT, E_META_DIRT_NORMAL}, {E_BLOCK_DIRT, E_META_DIRT_NORMAL}, } ; static cPattern::BlockInfo tbSand[] = { { E_BLOCK_SAND, 0}, { E_BLOCK_SAND, 0}, { E_BLOCK_SAND, 0}, { E_BLOCK_SANDSTONE, 0}, } ; static cPattern::BlockInfo tbDirt[] = { {E_BLOCK_DIRT, E_META_DIRT_NORMAL}, {E_BLOCK_DIRT, E_META_DIRT_NORMAL}, {E_BLOCK_DIRT, E_META_DIRT_NORMAL}, {E_BLOCK_DIRT, E_META_DIRT_NORMAL}, } ; static cPattern::BlockInfo tbPodzol[] = { {E_BLOCK_DIRT, E_META_DIRT_PODZOL}, {E_BLOCK_DIRT, E_META_DIRT_NORMAL}, {E_BLOCK_DIRT, E_META_DIRT_NORMAL}, {E_BLOCK_DIRT, E_META_DIRT_NORMAL}, } ; static cPattern::BlockInfo tbGrassLess[] = { {E_BLOCK_DIRT, E_META_DIRT_GRASSLESS}, {E_BLOCK_DIRT, E_META_DIRT_NORMAL}, {E_BLOCK_DIRT, E_META_DIRT_NORMAL}, {E_BLOCK_DIRT, E_META_DIRT_NORMAL}, } ; static cPattern::BlockInfo tbMycelium[] = { {E_BLOCK_MYCELIUM, 0}, {E_BLOCK_DIRT, 0}, {E_BLOCK_DIRT, 0}, {E_BLOCK_DIRT, 0}, } ; static cPattern::BlockInfo tbGravel[] = { {E_BLOCK_GRAVEL, 0}, {E_BLOCK_GRAVEL, 0}, {E_BLOCK_GRAVEL, 0}, {E_BLOCK_STONE, 0}, } ; static cPattern::BlockInfo tbStone[] = { {E_BLOCK_STONE, 0}, {E_BLOCK_STONE, 0}, {E_BLOCK_STONE, 0}, {E_BLOCK_STONE, 0}, } ; //////////////////////////////////////////////////////////////////////////////// // Ocean floor pattern top-block definitions: static cPattern::BlockInfo tbOFSand[] = { {E_BLOCK_SAND, 0}, {E_BLOCK_SAND, 0}, {E_BLOCK_SAND, 0}, {E_BLOCK_SANDSTONE, 0} } ; static cPattern::BlockInfo tbOFClay[] = { { E_BLOCK_CLAY, 0}, { E_BLOCK_CLAY, 0}, { E_BLOCK_SAND, 0}, { E_BLOCK_SAND, 0}, } ; static cPattern::BlockInfo tbOFOrangeClay[] = { { E_BLOCK_STAINED_CLAY, E_META_STAINED_GLASS_ORANGE}, { E_BLOCK_STAINED_CLAY, E_META_STAINED_GLASS_ORANGE}, { E_BLOCK_STAINED_CLAY, E_META_STAINED_GLASS_ORANGE}, } ; //////////////////////////////////////////////////////////////////////////////// // Individual patterns to use: static cPattern patGrass (tbGrass, ARRAYCOUNT(tbGrass)); static cPattern patSand (tbSand, ARRAYCOUNT(tbSand)); static cPattern patDirt (tbDirt, ARRAYCOUNT(tbDirt)); static cPattern patPodzol (tbPodzol, ARRAYCOUNT(tbPodzol)); static cPattern patGrassLess(tbGrassLess, ARRAYCOUNT(tbGrassLess)); static cPattern patMycelium (tbMycelium, ARRAYCOUNT(tbMycelium)); static cPattern patGravel (tbGravel, ARRAYCOUNT(tbGravel)); static cPattern patStone (tbStone, ARRAYCOUNT(tbStone)); static cPattern patOFSand (tbOFSand, ARRAYCOUNT(tbOFSand)); static cPattern patOFClay (tbOFClay, ARRAYCOUNT(tbOFClay)); static cPattern patOFOrangeClay(tbOFOrangeClay, ARRAYCOUNT(tbOFOrangeClay)); //////////////////////////////////////////////////////////////////////////////// // cCompoGenBiomal: class cCompoGenBiomal : public cTerrainCompositionGen { public: cCompoGenBiomal(int a_Seed) : m_SeaLevel(62), m_OceanFloorSelect(a_Seed + 1), m_MesaFloor(a_Seed + 2) { initMesaPattern(a_Seed); } protected: /** The block height at which water is generated instead of air. */ int m_SeaLevel; /** The pattern used for mesa biomes. Initialized by seed on generator creation. */ cPattern::BlockInfo m_MesaPattern[2 * cChunkDef::Height]; /** Noise used for selecting between dirt and sand on the ocean floor. */ cNoise m_OceanFloorSelect; /** Noise used for the floor of the clay blocks in mesa biomes. */ cNoise m_MesaFloor; // cTerrainCompositionGen overrides: virtual void ComposeTerrain(cChunkDesc & a_ChunkDesc, const cChunkDesc::Shape & a_Shape) override { a_ChunkDesc.FillBlocks(E_BLOCK_AIR, 0); for (int z = 0; z < cChunkDef::Width; z++) { for (int x = 0; x < cChunkDef::Width; x++) { ComposeColumn(a_ChunkDesc, x, z, &(a_Shape[x * 256 + z * 16 * 256])); } // for x } // for z } virtual void InitializeCompoGen(cIniFile & a_IniFile) override { m_SeaLevel = a_IniFile.GetValueSetI("Generator", "SeaLevel", m_SeaLevel); } /** Initializes the m_MesaPattern with a pattern based on the generator's seed. */ void initMesaPattern(int a_Seed) { // In a loop, choose whether to use one, two or three layers of stained clay, then choose a color and width for each layer // Separate each group with another layer of hardened clay cNoise patternNoise((unsigned)a_Seed); static NIBBLETYPE allowedColors[] = { E_META_STAINED_CLAY_YELLOW, E_META_STAINED_CLAY_YELLOW, E_META_STAINED_CLAY_RED, E_META_STAINED_CLAY_RED, E_META_STAINED_CLAY_WHITE, E_META_STAINED_CLAY_BROWN, E_META_STAINED_CLAY_BROWN, E_META_STAINED_CLAY_BROWN, E_META_STAINED_CLAY_ORANGE, E_META_STAINED_CLAY_ORANGE, E_META_STAINED_CLAY_ORANGE, E_META_STAINED_CLAY_ORANGE, E_META_STAINED_CLAY_ORANGE, E_META_STAINED_CLAY_ORANGE, E_META_STAINED_CLAY_LIGHTGRAY, } ; static int layerSizes[] = // Adjust the chance so that thinner layers occur more commonly { 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, } ; int idx = ARRAYCOUNT(m_MesaPattern) - 1; while (idx >= 0) { // A layer group of 1 - 2 color stained clay: int rnd = patternNoise.IntNoise1DInt(idx) / 7; int numLayers = (rnd % 2) + 1; rnd /= 2; for (int lay = 0; lay < numLayers; lay++) { int numBlocks = layerSizes[(rnd % ARRAYCOUNT(layerSizes))]; NIBBLETYPE Color = allowedColors[(rnd / 4) % ARRAYCOUNT(allowedColors)]; if ( ((numBlocks == 3) && (numLayers == 2)) || // In two-layer mode disallow the 3-high layers: (Color == E_META_STAINED_CLAY_WHITE)) // White stained clay can ever be only 1 block high { numBlocks = 1; } numBlocks = std::min(idx + 1, numBlocks); // Limit by idx so that we don't have to check inside the loop rnd /= 32; for (int block = 0; block < numBlocks; block++, idx--) { m_MesaPattern[idx].m_BlockMeta = Color; m_MesaPattern[idx].m_BlockType = E_BLOCK_STAINED_CLAY; } // for block } // for lay // A layer of hardened clay in between the layer group: int numBlocks = (rnd % 4) + 1; // All heights the same probability if ((numLayers == 2) && (numBlocks < 4)) { // For two layers of stained clay, add an extra block of hardened clay: numBlocks++; } numBlocks = std::min(idx + 1, numBlocks); // Limit by idx so that we don't have to check inside the loop for (int block = 0; block < numBlocks; block++, idx--) { m_MesaPattern[idx].m_BlockMeta = 0; m_MesaPattern[idx].m_BlockType = E_BLOCK_HARDENED_CLAY; } // for block } // while (idx >= 0) } /** Composes a single column in a_ChunkDesc. Chooses what to do based on the biome in that column. */ void ComposeColumn(cChunkDesc & a_ChunkDesc, int a_RelX, int a_RelZ, const Byte * a_ShapeColumn) { // Frequencies for the podzol floor selecting noise: const NOISE_DATATYPE FrequencyX = 8; const NOISE_DATATYPE FrequencyZ = 8; EMCSBiome Biome = a_ChunkDesc.GetBiome(a_RelX, a_RelZ); switch (Biome) { case biOcean: case biPlains: case biForest: case biTaiga: case biSwampland: case biRiver: case biFrozenOcean: case biFrozenRiver: case biIcePlains: case biIceMountains: case biForestHills: case biTaigaHills: case biExtremeHillsEdge: case biExtremeHillsPlus: case biExtremeHills: case biJungle: case biJungleHills: case biJungleEdge: case biDeepOcean: case biStoneBeach: case biColdBeach: case biBirchForest: case biBirchForestHills: case biRoofedForest: case biColdTaiga: case biColdTaigaHills: case biSavanna: case biSavannaPlateau: case biSunflowerPlains: case biFlowerForest: case biTaigaM: case biSwamplandM: case biIcePlainsSpikes: case biJungleM: case biJungleEdgeM: case biBirchForestM: case biBirchForestHillsM: case biRoofedForestM: case biColdTaigaM: case biSavannaM: case biSavannaPlateauM: { FillColumnPattern(a_ChunkDesc, a_RelX, a_RelZ, patGrass.Get(), a_ShapeColumn); return; } case biMegaTaiga: case biMegaTaigaHills: case biMegaSpruceTaiga: case biMegaSpruceTaigaHills: { // Select the pattern to use - podzol, grass or grassless dirt: NOISE_DATATYPE NoiseX = ((NOISE_DATATYPE)(a_ChunkDesc.GetChunkX() * cChunkDef::Width + a_RelX)) / FrequencyX; NOISE_DATATYPE NoiseY = ((NOISE_DATATYPE)(a_ChunkDesc.GetChunkZ() * cChunkDef::Width + a_RelZ)) / FrequencyZ; NOISE_DATATYPE Val = m_OceanFloorSelect.CubicNoise2D(NoiseX, NoiseY); const cPattern::BlockInfo * Pattern = (Val < -0.9) ? patGrassLess.Get() : ((Val > 0) ? patPodzol.Get() : patGrass.Get()); FillColumnPattern(a_ChunkDesc, a_RelX, a_RelZ, Pattern, a_ShapeColumn); return; } case biDesertHills: case biDesert: case biDesertM: case biBeach: { FillColumnPattern(a_ChunkDesc, a_RelX, a_RelZ, patSand.Get(), a_ShapeColumn); return; } case biMushroomIsland: case biMushroomShore: { FillColumnPattern(a_ChunkDesc, a_RelX, a_RelZ, patMycelium.Get(), a_ShapeColumn); return; } case biMesa: case biMesaPlateauF: case biMesaPlateau: case biMesaBryce: case biMesaPlateauFM: case biMesaPlateauM: { // Mesa biomes need special handling, because they don't follow the usual "4 blocks from top pattern", // instead, they provide a "from bottom" pattern with varying base height, // usually 4 blocks below the ocean level FillColumnMesa(a_ChunkDesc, a_RelX, a_RelZ, a_ShapeColumn); return; } case biExtremeHillsPlusM: case biExtremeHillsM: { // Select the pattern to use - gravel, stone or grass: NOISE_DATATYPE NoiseX = ((NOISE_DATATYPE)(a_ChunkDesc.GetChunkX() * cChunkDef::Width + a_RelX)) / FrequencyX; NOISE_DATATYPE NoiseY = ((NOISE_DATATYPE)(a_ChunkDesc.GetChunkZ() * cChunkDef::Width + a_RelZ)) / FrequencyZ; NOISE_DATATYPE Val = m_OceanFloorSelect.CubicNoise2D(NoiseX, NoiseY); const cPattern::BlockInfo * Pattern = (Val < 0.0) ? patStone.Get() : patGrass.Get(); FillColumnPattern(a_ChunkDesc, a_RelX, a_RelZ, Pattern, a_ShapeColumn); return; } default: { ASSERT(!"Unhandled biome"); return; } } // switch (Biome) } /** Fills the specified column with the specified pattern; restarts the pattern when air is reached, switches to ocean floor pattern if ocean is reached. Always adds bedrock at the very bottom. */ void FillColumnPattern(cChunkDesc & a_ChunkDesc, int a_RelX, int a_RelZ, const cPattern::BlockInfo * a_Pattern, const Byte * a_ShapeColumn) { bool HasHadWater = false; int PatternIdx = 0; int top = std::max(m_SeaLevel, a_ChunkDesc.GetHeight(a_RelX, a_RelZ)); for (int y = top; y > 0; y--) { if (a_ShapeColumn[y] > 0) { // "ground" part, use the pattern: a_ChunkDesc.SetBlockTypeMeta(a_RelX, y, a_RelZ, a_Pattern[PatternIdx].m_BlockType, a_Pattern[PatternIdx].m_BlockMeta); PatternIdx++; continue; } // "air" or "water" part: // Reset the pattern index to zero, so that the pattern is repeated from the top again: PatternIdx = 0; if (y >= m_SeaLevel) { // "air" part, do nothing continue; } a_ChunkDesc.SetBlockType(a_RelX, y, a_RelZ, E_BLOCK_STATIONARY_WATER); if (HasHadWater) { continue; } // Select the ocean-floor pattern to use: if (a_ChunkDesc.GetBiome(a_RelX, a_RelZ) == biDeepOcean) { a_Pattern = patGravel.Get(); } else { a_Pattern = ChooseOceanFloorPattern(a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ(), a_RelX, a_RelZ); } HasHadWater = true; } // for y a_ChunkDesc.SetBlockType(a_RelX, 0, a_RelZ, E_BLOCK_BEDROCK); } /** Fills the specified column with mesa pattern, based on the column height */ void FillColumnMesa(cChunkDesc & a_ChunkDesc, int a_RelX, int a_RelZ, const Byte * a_ShapeColumn) { // Frequencies for the clay floor noise: const NOISE_DATATYPE FrequencyX = 50; const NOISE_DATATYPE FrequencyZ = 50; int Top = a_ChunkDesc.GetHeight(a_RelX, a_RelZ); if (Top < m_SeaLevel) { // The terrain is below sealevel, handle as regular ocean with red sand floor: FillColumnPattern(a_ChunkDesc, a_RelX, a_RelZ, patOFOrangeClay.Get(), a_ShapeColumn); return; } NOISE_DATATYPE NoiseX = ((NOISE_DATATYPE)(a_ChunkDesc.GetChunkX() * cChunkDef::Width + a_RelX)) / FrequencyX; NOISE_DATATYPE NoiseY = ((NOISE_DATATYPE)(a_ChunkDesc.GetChunkZ() * cChunkDef::Width + a_RelZ)) / FrequencyZ; int ClayFloor = m_SeaLevel - 6 + (int)(4.f * m_MesaFloor.CubicNoise2D(NoiseX, NoiseY)); if (ClayFloor >= Top) { ClayFloor = Top - 1; } if (Top - m_SeaLevel < 5) { // Simple case: top is red sand, then hardened clay down to ClayFloor, then stone: a_ChunkDesc.SetBlockTypeMeta(a_RelX, Top, a_RelZ, E_BLOCK_SAND, E_META_SAND_RED); for (int y = Top - 1; y >= ClayFloor; y--) { a_ChunkDesc.SetBlockType(a_RelX, y, a_RelZ, E_BLOCK_HARDENED_CLAY); } for (int y = ClayFloor - 1; y > 0; y--) { a_ChunkDesc.SetBlockType(a_RelX, y, a_RelZ, E_BLOCK_STONE); } a_ChunkDesc.SetBlockType(a_RelX, 0, a_RelZ, E_BLOCK_BEDROCK); return; } // Difficult case: use the mesa pattern and watch for overhangs: int PatternIdx = cChunkDef::Height - (Top - ClayFloor); // We want the block at index ClayFloor to be pattern's 256th block (first stone) const cPattern::BlockInfo * Pattern = m_MesaPattern; bool HasHadWater = false; for (int y = Top; y > 0; y--) { if (a_ShapeColumn[y] > 0) { // "ground" part, use the pattern: a_ChunkDesc.SetBlockTypeMeta(a_RelX, y, a_RelZ, Pattern[PatternIdx].m_BlockType, Pattern[PatternIdx].m_BlockMeta); PatternIdx++; continue; } if (y >= m_SeaLevel) { // "air" part, do nothing continue; } // "water" part, fill with water and choose new pattern for ocean floor, if not chosen already: PatternIdx = 0; a_ChunkDesc.SetBlockType(a_RelX, y, a_RelZ, E_BLOCK_STATIONARY_WATER); if (HasHadWater) { continue; } // Select the ocean-floor pattern to use: Pattern = ChooseOceanFloorPattern(a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ(), a_RelX, a_RelZ); HasHadWater = true; } // for y a_ChunkDesc.SetBlockType(a_RelX, 0, a_RelZ, E_BLOCK_BEDROCK); EMCSBiome MesaVersion = a_ChunkDesc.GetBiome(a_RelX, a_RelZ); if ((MesaVersion == biMesaPlateauF) || (MesaVersion == biMesaPlateauFM)) { if (Top < 95 + static_cast<int>(m_MesaFloor.CubicNoise2D(NoiseY * 2, NoiseX * 2) * 6)) { return; } BLOCKTYPE Block = (m_MesaFloor.CubicNoise2D(NoiseX * 4, NoiseY * 4) < 0) ? E_BLOCK_DIRT : E_BLOCK_GRASS; NIBBLETYPE Meta = (Block == E_BLOCK_GRASS) ? 0 : 1; a_ChunkDesc.SetBlockTypeMeta(a_RelX, Top, a_RelZ, Block, Meta); } } /** Returns the pattern to use for an ocean floor in the specified column. The returned pattern is guaranteed to be 256 blocks long. */ const cPattern::BlockInfo * ChooseOceanFloorPattern(int a_ChunkX, int a_ChunkZ, int a_RelX, int a_RelZ) { // Frequencies for the ocean floor selecting noise: const NOISE_DATATYPE FrequencyX = 3; const NOISE_DATATYPE FrequencyZ = 3; // Select the ocean-floor pattern to use: NOISE_DATATYPE NoiseX = ((NOISE_DATATYPE)(a_ChunkX * cChunkDef::Width + a_RelX)) / FrequencyX; NOISE_DATATYPE NoiseY = ((NOISE_DATATYPE)(a_ChunkZ * cChunkDef::Width + a_RelZ)) / FrequencyZ; NOISE_DATATYPE Val = m_OceanFloorSelect.CubicNoise2D(NoiseX, NoiseY); if (Val < -0.95) { return patOFClay.Get(); } else if (Val < 0) { return patOFSand.Get(); } else { return patDirt.Get(); } } } ; cTerrainCompositionGenPtr CreateCompoGenBiomal(int a_Seed) { return std::make_shared<cCompoGenBiomal>(a_Seed); }
apache-2.0
deleidos/digitaledge-platform
webapp-alertsapi/src/main/java/com/deleidos/rtws/webapp/alertsapi/client/NamedFilterRestClient.java
25978
/** * 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 {yyyy} {name of copyright owner} * * 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.deleidos.rtws.webapp.alertsapi.client; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import javax.ws.rs.core.MediaType; import net.sf.json.JSONException; import net.sf.json.JSONObject; import net.sf.json.JSONSerializer; import net.sf.json.util.JSONStringer; import org.apache.log4j.Logger; import com.deleidos.rtws.commons.model.response.ErrorResponse; import com.deleidos.rtws.commons.model.response.PropertiesResponse; import com.deleidos.rtws.commons.model.response.StandardResponse; import com.deleidos.rtws.commons.model.user.Filter; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.representation.Form; /** * NamedFilterRestClient provides a Jersey REST Client that can be * used to access, create, modify, and delete Named Filters in the * database. */ public class NamedFilterRestClient extends DbApiRestClient { Logger logger = Logger.getLogger(NamedFilterRestClient.class); /* Static settings */ private static final String FILTER_DB_SCHEMA = "APPLICATION"; private static final String FILTER_DB_TABLE = "NAMED_FILTER"; private static final String FILTER_DB_SEQUENCE = "APPLICATION.NAMED_FILTER_SEQ"; /** * Default Constructor. */ public NamedFilterRestClient() { super(); } /** * Insert a new Filter. * * @param filter * a Filter object without an id * @param jsonDefinition * JSON formatted filter definition * @return a StandardResponse containing the new Filter object */ public StandardResponse<?> createFilter(Filter filter, String jsonDefinition) { try { // Get next primary key from the sequence long key = nextSequenceValue(FILTER_DB_SEQUENCE); // Create body of what we will insert JSONStringer json = new JSONStringer(); json .object().key("insert").array() .array() .object().key("KEY").value(key).endObject() .object().key("NAME").value(filter.getName()).endObject() .object().key("MODEL").value(filter.getModel()).endObject() .object().key("DEFINITION").value(jsonDefinition.replaceAll("'", "''")).endObject(); if (filter.getEmailSubject() != null) { json.object().key("EMAIL_SUBJECT").value(filter.getEmailSubject().replaceAll("'", "''")).endObject(); } if (filter.getEmailMessage() != null) { json.object().key("EMAIL_MESSAGE").value(filter.getEmailMessage().replaceAll("'", "''")).endObject(); } json .endArray() .endArray().endObject(); // Send POST to DB API WebResource resource = getClient().resource(DBAPI_BASE_URL); resource = resource.path("json/update/insert") .path(DB_HOST) // database .path(FILTER_DB_SCHEMA) // schema .path(FILTER_DB_TABLE); // table Form f = new Form(); f.add("jsondef", json.toString()); String response = resource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE) .post(String.class, f); // Check response and build appropriate return value JSONObject jsonResp = JSONObject.fromObject(response); if (jsonResp.has("Operation Status")) { if ("FAILED".equals(jsonResp.getString("Operation Status"))) { throw new RestClientException("Create failed - " + jsonResp.getString("Message")); } if ("Completed".equals(jsonResp.getString("Operation Status"))) { if (jsonResp.has("Rows Modified")) { if (jsonResp.getInt("Rows Modified") == 0) { throw new RestClientException("Cannot create a filter for name " + filter.getName()); } } } } // fill in filter object filter.setKey(Long.valueOf(key)); filter.setDefinition(JSONSerializer.toJSON(jsonDefinition)); StandardResponse<Filter> result = new StandardResponse<Filter>(); result.setResponseBody(filter); return result; } catch (UniformInterfaceException uie) { ClientResponse cr = uie.getResponse(); logger.warn("Received [" + cr.getStatus() + "] response from DB - " + uie.getMessage()); ErrorResponse response = new ErrorResponse(); response.setStandardHeaderCode(500); response.setMessage(uie.getMessage()); return response; } catch (JSONException je) { logger.warn("Malformed JSON from DB - " + je.toString()); ErrorResponse response = new ErrorResponse(); response.setStandardHeaderCode(500); response.setMessage(je.getMessage()); return response; } catch (Throwable e) { logger.error(e); ErrorResponse response = new ErrorResponse(); response.setStandardHeaderCode(500); response.setMessage(e.getMessage()); return response; } } /** * Delete an existing Filter. * * @param id * filter id * @return a StandardResponse */ public StandardResponse<?> deleteFilter(Long id) { try { String where = "KEY=" + id; // Send DELETE to DB API WebResource resource = getClient().resource(DBAPI_BASE_URL); resource = resource.path("json/update/delete") .path(DB_HOST) // database .path(FILTER_DB_SCHEMA) // schema .path(FILTER_DB_TABLE) // table .path(where); // where expression String response = resource.delete(String.class); // Check response and build appropriate return value JSONObject jsonResp = JSONObject.fromObject(response); if (jsonResp.has("Operation Status")) { if ("FAILED".equals(jsonResp.getString("Operation Status"))) { throw new RestClientException("Delete failed - " + jsonResp.getString("Message")); } if ("Completed".equals(jsonResp.getString("Operation Status"))) { if (jsonResp.has("Rows Modified")) { if (jsonResp.getInt("Rows Modified") == 0) { throw new RestClientException("Cannot find a configuration for filter " + id); } } } } PropertiesResponse result = new PropertiesResponse(); result.setStandardHeaderCode(200); result.setProperty("Status", "true"); return result; } catch (UniformInterfaceException uie) { ClientResponse cr = uie.getResponse(); logger.warn("Received [" + cr.getStatus() + "] response from DB - " + uie.getMessage()); ErrorResponse response = new ErrorResponse(); response.setStandardHeaderCode(500); response.setMessage(uie.getMessage()); return response; } catch (JSONException je) { logger.warn("Malformed JSON from DB - " + je.toString()); ErrorResponse response = new ErrorResponse(); response.setStandardHeaderCode(500); response.setMessage(je.getMessage()); return response; } catch (Throwable e) { logger.error(e); ErrorResponse response = new ErrorResponse(); response.setStandardHeaderCode(500); response.setMessage(e.getMessage()); return response; } } /** * Get all filters. * * @return Collection of filters */ @SuppressWarnings("rawtypes") public Collection<Filter> getAll() { try { // Send GET to DB API WebResource resource = getClient().resource(DBAPI_BASE_URL); resource = resource.path("json/select/all") .path(DB_HOST) // database .path(FILTER_DB_SCHEMA) // schema .path(FILTER_DB_TABLE); // table String response = resource.get(String.class); // Build return collection from REST response Collection<Filter> results = new LinkedList<Filter>(); JSONObject json = JSONObject.fromObject(response); if (json.has("Operation Status")) { if ("FAILED".equals(json.getString("Operation Status"))) { throw new RestClientException("Retrieve failed - " + json.getString("Message")); } } Iterator rowit = json.getJSONArray("result").iterator(); while (rowit.hasNext()) { JSONObject row = (JSONObject) rowit.next(); // Output from each row is a Filter Filter filter = new Filter(); if (row.has("KEY")) { filter.setKey(Long.parseLong(row.getString("KEY"))); } if (row.has("NAME")) { filter.setName(row.getString("NAME")); } if (row.has("MODEL")) { filter.setModel(row.getString("MODEL")); } if (row.has("DEFINITION")) { filter.setDefinition(JSONSerializer.toJSON(row.getString("DEFINITION"))); } if (row.has("EMAIL_SUBJECT")) { filter.setEmailSubject(row.getString("EMAIL_SUBJECT")); } if (row.has("EMAIL_MESSAGE")) { filter.setEmailMessage(row.getString("EMAIL_MESSAGE")); } results.add(filter); } return results; } catch (UniformInterfaceException uie) { ClientResponse cr = uie.getResponse(); logger.warn("Received [" + cr.getStatus() + "] response from DB - " + uie.getMessage()); return null; } catch (JSONException je) { logger.warn("Malformed JSON from DB - " + je.toString()); return null; } catch (Throwable e) { logger.error(e); return null; } } /** * Get filters for a specific data model. * * @return Collection of filters */ @SuppressWarnings("rawtypes") public Collection<Filter> getByModel(String model) { try { String where = "MODEL='" + model + "'"; // Send GET to DB API WebResource resource = getClient().resource(DBAPI_BASE_URL); resource = resource.path("json/select/all") .path(DB_HOST) // database .path(FILTER_DB_SCHEMA) // schema .path(FILTER_DB_TABLE) // table .path(where); // where expression String response = resource.get(String.class); // Build return collection from REST response Collection<Filter> results = new LinkedList<Filter>(); JSONObject json = JSONObject.fromObject(response); if (json.has("Operation Status")) { if ("FAILED".equals(json.getString("Operation Status"))) { throw new RestClientException("Retrieve failed - " + json.getString("Message")); } } Iterator rowit = json.getJSONArray("result").iterator(); while (rowit.hasNext()) { JSONObject row = (JSONObject) rowit.next(); // Output from each row is a Filter Filter filter = new Filter(); if (row.has("KEY")) { filter.setKey(Long.parseLong(row.getString("KEY"))); } if (row.has("NAME")) { filter.setName(row.getString("NAME")); } if (row.has("MODEL")) { filter.setModel(row.getString("MODEL")); } if (row.has("DEFINITION")) { filter.setDefinition(JSONSerializer.toJSON(row.getString("DEFINITION"))); } if (row.has("EMAIL_SUBJECT")) { filter.setEmailSubject(row.getString("EMAIL_SUBJECT")); } if (row.has("EMAIL_MESSAGE")) { filter.setEmailMessage(row.getString("EMAIL_MESSAGE")); } results.add(filter); } return results; } catch (UniformInterfaceException uie) { ClientResponse cr = uie.getResponse(); logger.warn("Received [" + cr.getStatus() + "] response from DB - " + uie.getMessage()); return null; } catch (JSONException je) { logger.warn("Malformed JSON from DB - " + je.toString()); return null; } catch (Throwable e) { logger.error(e); return null; } } /** * Update an existing Filter. * * @param filter * a Filter object with id set * @param jsonDefinition * JSON formatted filter definition * @return a StandardResponse containing the new Filter object */ public StandardResponse<?> updateFilter(Filter filter, String jsonDefinition) { try { String where = "KEY=" + filter.getKey(); // Create body of what we will modify JSONStringer json = new JSONStringer(); json .object().key("update").array() .object().key("NAME").value(filter.getName()).endObject() .object().key("MODEL").value(filter.getModel()).endObject(); if (jsonDefinition != null) { json.object().key("DEFINITION").value(jsonDefinition.replaceAll("'", "''")).endObject(); } if (filter.getEmailSubject() != null) { json.object().key("EMAIL_SUBJECT").value(filter.getEmailSubject().replaceAll("'", "''")).endObject(); } if (filter.getEmailMessage() != null) { json.object().key("EMAIL_MESSAGE").value(filter.getEmailMessage().replaceAll("'", "''")).endObject(); } json.endArray().endObject(); // Send PUT to DB API WebResource resource = getClient().resource(DBAPI_BASE_URL); resource = resource.path("json/update/update") .path(DB_HOST) // database .path(FILTER_DB_SCHEMA) // schema .path(FILTER_DB_TABLE) // table .path(where); // where expression Form f = new Form(); f.add("jsondef", json.toString()); String response = resource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE) .put(String.class, f); // Check response and build appropriate return value JSONObject jsonResp = JSONObject.fromObject(response); if (jsonResp.has("Operation Status")) { if ("FAILED".equals(jsonResp.getString("Operation Status"))) { throw new RestClientException("Update failed - " + jsonResp.getString("Message")); } if ("Completed".equals(jsonResp.getString("Operation Status"))) { if (jsonResp.has("Rows Modified")) { if (jsonResp.getInt("Rows Modified") == 0) { throw new RestClientException("Cannot find a configuration for filter " + filter.getKey()); } } } } // fill in filter object filter.setDefinition(JSONSerializer.toJSON(jsonDefinition)); StandardResponse<Filter> result = new StandardResponse<Filter>(); result.setResponseBody(filter); return result; } catch (UniformInterfaceException uie) { ClientResponse cr = uie.getResponse(); logger.warn("Received [" + cr.getStatus() + "] response from DB - " + uie.getMessage()); ErrorResponse response = new ErrorResponse(); response.setStandardHeaderCode(500); response.setMessage(uie.getMessage()); return response; } catch (JSONException je) { logger.warn("Malformed JSON from DB - " + je.toString()); ErrorResponse response = new ErrorResponse(); response.setStandardHeaderCode(500); response.setMessage(je.getMessage()); return response; } catch (Throwable e) { logger.error(e); ErrorResponse response = new ErrorResponse(); response.setStandardHeaderCode(500); response.setMessage(e.getMessage()); return response; } } }
apache-2.0
afiantara/apache-wicket-1.5.7
src/wicket-core/src/main/java/org/apache/wicket/markup/ComponentTag.java
21260
/* * 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.wicket.markup; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.wicket.Component; import org.apache.wicket.behavior.Behavior; import org.apache.wicket.markup.parser.XmlTag; import org.apache.wicket.markup.parser.XmlTag.TagType; import org.apache.wicket.markup.parser.filter.HtmlHandler; import org.apache.wicket.request.Response; import org.apache.wicket.util.lang.Generics; import org.apache.wicket.util.string.AppendingStringBuffer; import org.apache.wicket.util.string.StringValue; import org.apache.wicket.util.string.Strings; import org.apache.wicket.util.value.IValueMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A subclass of MarkupElement which represents a "significant" markup tag, such as a component open * tag. Insignificant markup tags (those which are merely concerned with markup formatting * operations and do not denote components or component nesting) are coalesced into instances of * RawMarkup (also a subclass of MarkupElement). * * @author Jonathan Locke */ public class ComponentTag extends MarkupElement { /** Log. */ private static final Logger log = LoggerFactory.getLogger(ComponentTag.class); /** True if a href attribute is available and autolinking is on */ private final static int AUTOLINK = 0x0001; /** True, if attributes have been modified or added */ private final static int MODIFIED = 0x0002; /** If true, than the MarkupParser will ignore (remove) it. Temporary working variable */ private final static int IGNORE = 0x0004; /** If true, than the tag contain an automatically created wicket id */ private final static int AUTO_COMPONENT = 0x0008; /** Some HTML tags are allow to have no close tag, e.g. 'br' */ private final static int NO_CLOSE_TAG = 0x0010; /** Render the tag as RawMarkup even if no Component can be found */ public final static int RENDER_RAW = 0x0020; /** If close tag, than reference to the corresponding close tag */ private ComponentTag openTag; /** The underlying xml tag */ protected final XmlTag xmlTag; /** Boolean flags. See above */ private int flags = 0; /** * By default this is equal to the wicket:id="xxx" attribute value, but may be provided e.g. for * auto-tags */ private String id; /** * In case of inherited markup, the base and the extended markups are merged and the information * about the tags origin is lost. In some cases like wicket:head and wicket:link this * information however is required. */ private WeakReference<Class<? extends Component>> markupClassRef = null; /** added behaviors */ private List<Behavior> behaviors; /** Filters and Handlers may add their own attributes to the tag */ private Map<String, Object> userData; /** * Automatically create a XmlTag, assign the name and the type, and construct a ComponentTag * based on this XmlTag. * * @param name * The name of html tag * @param type * The type of tag */ public ComponentTag(final String name, final XmlTag.TagType type) { final XmlTag tag = new XmlTag(); tag.setName(name); tag.setType(type); xmlTag = tag; } /** * Construct. * * @param tag * The underlying xml tag */ public ComponentTag(final XmlTag tag) { super(); xmlTag = tag; } /** * Constructor * * @param tag * The ComponentTag tag which this wicket tag is based upon. */ public ComponentTag(final ComponentTag tag) { this(tag.getXmlTag()); tag.copyPropertiesTo(this); } /** * THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT! * * @param flag * The flag to set * @param set * True to turn the flag on, false to turn it off */ public final void setFlag(final int flag, final boolean set) { if (set) { flags |= flag; } else { flags &= ~flag; } } /** * THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT USE IT! * * @param flag * The flag to test * @return True if the flag is set */ public final boolean getFlag(final int flag) { return (flags & flag) != 0; } /** * Adds a behavior to this component tag. * * @param behavior */ public final void addBehavior(final Behavior behavior) { if (behavior == null) { throw new IllegalArgumentException("Argument [behavior] cannot be null"); } if (behaviors == null) { behaviors = Generics.newArrayList(); } behaviors.add(behavior); } /** * @return true if this tag has any behaviors added, false otherwise */ public final boolean hasBehaviors() { return behaviors != null; } /** * @return read only iterator over added behaviors * @TODO change to return unmodifiable list which will never be null. See Component.getBehavior */ public final Iterator<? extends Behavior> getBehaviors() { if (behaviors == null) { List<Behavior> lst = Collections.emptyList(); return lst.iterator(); } return Collections.unmodifiableCollection(behaviors).iterator(); } /** * Gets whether this tag closes the provided open tag. * * @param open * The open tag * @return True if this tag closes the given open tag */ @Override public final boolean closes(final MarkupElement open) { if (open instanceof ComponentTag) { return (openTag == open) || getXmlTag().closes(((ComponentTag)open).getXmlTag()); } return false; } /** * If autolink is set to true, href attributes will automatically be converted into Wicket * bookmarkable URLs. * * @param autolink * enable/disable automatic href conversion */ public final void enableAutolink(final boolean autolink) { setFlag(AUTOLINK, autolink); } /** * @see org.apache.wicket.markup.parser.XmlTag#getAttributes() * @return The tag#s attributes */ public final IValueMap getAttributes() { return xmlTag.getAttributes(); } /** * A convenient method. The same as getAttributes().getString(name) * * @param name * @return The attributes value */ public final String getAttribute(String name) { return xmlTag.getAttributes().getString(name); } /** * Please use {@link #getAttribute(String)} instead * * @param name * @return The attribute * @deprecated since 1.5 */ @Deprecated public final String getString(String name) { return getAttribute(name); } /** * Get the tag's component id * * @return The component id attribute of this tag */ public final String getId() { return id; } /** * Gets the length of the tag in characters. * * @return The tag's length */ public final int getLength() { return xmlTag.getLength(); } /** * @return The tag's name */ public final String getName() { return xmlTag.getName(); } /** * @return The tag's namespace */ public final String getNamespace() { return xmlTag.getNamespace(); } /** * If set, return the corresponding open tag (ComponentTag). * * @return The corresponding open tag */ public final ComponentTag getOpenTag() { return openTag; } /** * @see org.apache.wicket.markup.parser.XmlTag#getPos() * @return Tag location (index in input string) */ public final int getPos() { return xmlTag.getPos(); } /** * @return the tag type (OPEN, CLOSE or OPEN_CLOSE). */ public final TagType getType() { return xmlTag.getType(); } /** * True if autolink is enabled and the tag contains a href attribute. * * @return True, if the href contained should automatically be converted */ public final boolean isAutolinkEnabled() { return getFlag(AUTOLINK); } /** * @see org.apache.wicket.markup.parser.XmlTag#isClose() * @return True if this tag is a close tag */ public final boolean isClose() { return xmlTag.isClose(); } /** * @see org.apache.wicket.markup.parser.XmlTag#isOpen() * @return True if this tag is an open tag */ public final boolean isOpen() { return xmlTag.isOpen(); } /** * @param id * Required component id * @return True if this tag is an open tag with the given component name * @see org.apache.wicket.markup.parser.XmlTag#isOpen() */ public final boolean isOpen(String id) { return xmlTag.isOpen() && this.id.equals(id); } /** * @see org.apache.wicket.markup.parser.XmlTag#isOpenClose() * @return True if this tag is an open and a close tag */ public final boolean isOpenClose() { return xmlTag.isOpenClose(); } /** * @param id * Required component id * @return True if this tag is an openclose tag with the given component id * @see org.apache.wicket.markup.parser.XmlTag#isOpenClose() */ public final boolean isOpenClose(String id) { return xmlTag.isOpenClose() && this.id.equals(id); } /** * Makes this tag object immutable by making the attribute map unmodifiable. Immutable tags * cannot be made mutable again. They can only be copied into new mutable tag objects. */ public final void makeImmutable() { xmlTag.makeImmutable(); } /** * Gets this tag if it is already mutable, or a mutable copy of this tag if it is immutable. * * @return This tag if it is already mutable, or a mutable copy of this tag if it is immutable. */ public ComponentTag mutable() { if (xmlTag.isMutable()) { return this; } else { ComponentTag tag = new ComponentTag(xmlTag.mutable()); copyPropertiesTo(tag); return tag; } } /** * Copies all internal properties from this tag to <code>dest</code>. This is basically cloning * without instance creation. * * @param dest * tag whose properties will be set */ void copyPropertiesTo(final ComponentTag dest) { dest.id = id; dest.flags = flags; if (markupClassRef != null) { dest.setMarkupClass(markupClassRef.get()); } if (behaviors != null) { dest.behaviors = new ArrayList<Behavior>(behaviors.size()); dest.behaviors.addAll(behaviors); } } /** * @see org.apache.wicket.markup.parser.XmlTag#put(String, boolean) * @param key * The key * @param value * The value */ public final void put(final String key, final boolean value) { xmlTag.put(key, value); setModified(true); } /** * @see org.apache.wicket.markup.parser.XmlTag#put(String, int) * @param key * The key * @param value * The value */ public final void put(final String key, final int value) { xmlTag.put(key, value); setModified(true); } /** * @see org.apache.wicket.markup.parser.XmlTag#put(String, CharSequence) * @param key * The key * @param value * The value */ public final void put(String key, CharSequence value) { checkIdAttribute(key); putInternal(key, value); } /** * THIS METHOD IS NOT PART OF THE PUBLIC API, DO NOT CALL IT * * @see org.apache.wicket.markup.parser.XmlTag#put(String, CharSequence) * @param key * The key * @param value * The value */ public final void putInternal(String key, CharSequence value) { xmlTag.put(key, value); setModified(true); } /** * @param key */ private void checkIdAttribute(String key) { if ((key != null) && (key.equalsIgnoreCase("id"))) { log.warn("Please use component.setMarkupId(String) to change the tag's 'id' attribute."); } } /** * Appends specified {@code value} to the attribute * * @param key * The key * @param value * The value * @param separator * The separator used to append the value */ public final void append(String key, CharSequence value, String separator) { String current = getAttribute(key); if (Strings.isEmpty(current)) { xmlTag.put(key, value); } else { xmlTag.put(key, current + separator + value); } setModified(true); } /** * @see org.apache.wicket.markup.parser.XmlTag#put(String, StringValue) * @param key * The key * @param value * The value */ public final void put(String key, StringValue value) { xmlTag.put(key, value); setModified(true); } /** * @see org.apache.wicket.markup.parser.XmlTag#putAll(Map) * @param map * a key/value map */ public final void putAll(final Map<String, Object> map) { xmlTag.putAll(map); setModified(true); } /** * @see org.apache.wicket.markup.parser.XmlTag#remove(String) * @param key * The key to remove */ public final void remove(String key) { xmlTag.remove(key); setModified(true); } /** * Gets whether this tag does not require a closing tag. * * @return True if this tag does not require a closing tag */ public final boolean requiresCloseTag() { if (getNamespace() == null) { return HtmlHandler.requiresCloseTag(getName()); } else { return HtmlHandler.requiresCloseTag(getNamespace() + ":" + getName()); } } /** * Set the component's id. The value is usually taken from the tag's id attribute, e.g. * wicket:id="componentId". * * @param id * The component's id assigned to the tag. */ public final void setId(final String id) { this.id = id; } /** * @see org.apache.wicket.markup.parser.XmlTag#setName(String) * @param name * New tag name */ public final void setName(String name) { xmlTag.setName(name); } /** * @see org.apache.wicket.markup.parser.XmlTag#setNamespace(String) * @param namespace * New tag name namespace */ public final void setNamespace(String namespace) { xmlTag.setNamespace(namespace); } /** * Assuming this is a close tag, assign it's corresponding open tag. * * @param tag * the open-tag * @throws RuntimeException * if 'this' is not a close tag */ public final void setOpenTag(final ComponentTag tag) { openTag = tag; getXmlTag().setOpenTag(tag.getXmlTag()); } /** * THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL IT. * * @param type * The new type */ public final void setType(final TagType type) { if (type != xmlTag.getType()) { xmlTag.setType(type); setModified(true); } } /** * @return A synthetic close tag for this tag */ public final CharSequence syntheticCloseTagString() { AppendingStringBuffer buf = new AppendingStringBuffer(); buf.append("</"); if (getNamespace() != null) { buf.append(getNamespace()).append(":"); } buf.append(getName()).append(">"); return buf; } /** * @see org.apache.wicket.markup.MarkupElement#toCharSequence() */ @Override public CharSequence toCharSequence() { return xmlTag.toCharSequence(); } /** * Converts this object to a string representation. * * @return String version of this object */ @Override public final String toString() { return toCharSequence().toString(); } /** * Write the tag to the response * * @param response * The response to write to * @param stripWicketAttributes * if true, wicket:id are removed from output * @param namespace * Wicket's namespace to use * @param escapeAttributeValue */ public final void writeOutput(final Response response, final boolean stripWicketAttributes, final String namespace) { response.write("<"); if (getType() == TagType.CLOSE) { response.write("/"); } if (getNamespace() != null) { response.write(getNamespace()); response.write(":"); } response.write(getName()); String namespacePrefix = null; if (stripWicketAttributes == true) { namespacePrefix = namespace + ":"; } if (getAttributes().size() > 0) { for (String key : getAttributes().keySet()) { if (key == null) { continue; } if ((namespacePrefix == null) || (key.startsWith(namespacePrefix) == false)) { response.write(" "); response.write(key); CharSequence value = getAttribute(key); // attributes without values are possible, e.g.' disabled' if (value != null) { response.write("=\""); value = Strings.escapeMarkup(value); response.write(value); response.write("\""); } } } } if (getType() == TagType.OPEN_CLOSE) { response.write("/"); } response.write(">"); } /** * Converts this object to a string representation including useful information for debugging * * @return String version of this object */ @Override public final String toUserDebugString() { return xmlTag.toUserDebugString(); } /** * @return Returns the underlying xml tag. */ public final XmlTag getXmlTag() { return xmlTag; } /** * Manually mark the ComponentTag being modified. Flagging the tag being modified does not * happen automatically. * * @param modified */ public final void setModified(final boolean modified) { setFlag(MODIFIED, modified); } /** * * @return True, if the component tag has been marked modified */ final boolean isModified() { return getFlag(MODIFIED); } /** * * @return True if the HTML tag (e.g. br) has no close tag */ public boolean hasNoCloseTag() { return getFlag(NO_CLOSE_TAG); } /** * True if the HTML tag (e.g. br) has no close tag * * @param hasNoCloseTag */ public void setHasNoCloseTag(boolean hasNoCloseTag) { setFlag(NO_CLOSE_TAG, hasNoCloseTag); } /** * In case of inherited markup, the base and the extended markups are merged and the information * about the tags origin is lost. In some cases like wicket:head and wicket:link this * information however is required. * * @return wicketHeaderClass */ public Class<? extends Component> getMarkupClass() { return (markupClassRef == null ? null : markupClassRef.get()); } /** * Set the class of wicket component which contains the wicket:head tag. * * @param <C> * * @param wicketHeaderClass * wicketHeaderClass */ public <C extends Component> void setMarkupClass(Class<C> wicketHeaderClass) { if (wicketHeaderClass == null) { markupClassRef = null; } else { markupClassRef = new WeakReference<Class<? extends Component>>(wicketHeaderClass); } } /** * @see org.apache.wicket.markup.MarkupElement#equalTo(org.apache.wicket.markup.MarkupElement) */ @Override public boolean equalTo(final MarkupElement element) { if (element instanceof ComponentTag) { final ComponentTag that = (ComponentTag)element; return getXmlTag().equalTo(that.getXmlTag()); } return false; } /** * Gets ignore. * * @return If true than MarkupParser will remove it from the markup */ public boolean isIgnore() { return getFlag(IGNORE); } /** * Sets ignore. * * @param ignore * If true than MarkupParser will remove it from the markup */ public void setIgnore(boolean ignore) { setFlag(IGNORE, ignore); } /** * @return True, if wicket:id has been automatically created (internal component) */ public boolean isAutoComponentTag() { return getFlag(AUTO_COMPONENT); } /** * @param auto * True, if wicket:id has been automatically created (internal component) */ public void setAutoComponentTag(boolean auto) { setFlag(AUTO_COMPONENT, auto); } /** * Gets userData. * * @param key * The key to store and retrieve the value * @return userData */ public Object getUserData(final String key) { if (userData == null) { return null; } return userData.get(key); } /** * Sets userData. * * @param key * The key to store and retrieve the value * @param value * The user specific value to store */ public void setUserData(final String key, final Object value) { if (userData == null) { userData = new HashMap<String, Object>(); } userData.put(key, value); } /** * For subclasses to override. Gets called just before a Component gets rendered. It is * guaranteed that the markupStream is set on the Component and determineVisibility is not yet * called. * * @param component * The component that is about to be rendered * @param markupStream * The current amrkup stream */ public void onBeforeRender(final Component component, final MarkupStream markupStream) { } }
apache-2.0
melvinthemok/readable
public/client_side_helpers/allStudentChecksToSubmit.js
4379
document.addEventListener('DOMContentLoaded', function () { var listeningInputs = document.querySelectorAll('.required-group > input, #generalComment') // enable submit only if other client-side helper checks succeed var name = document.getElementById('name') var generalComment = document.getElementById('generalComment') var saturdatesCheckboxes = document.querySelectorAll("input[name='saturdates']") var submitButton = document.getElementById('submitButton') function runAllRequiredChecks () { // checking if required form elements have values var requiredGroups = document.querySelectorAll('.required-group') var required = document.querySelectorAll('.required-group > input, .required-group > select') requiredGroups.forEach(function (requiredGroup) { var input = requiredGroup.querySelector('input:not(#name):not(.form-check-input)') // to avoid encroaching on responsibility of individual checks var select = requiredGroup.querySelector('select') if (input) { if (input.value !== '') { requiredGroup.classList.add('has-success') requiredGroup.classList.remove('has-warning') input.classList.add('form-control-success') input.classList.remove('form-control-warning') if (requiredGroup.querySelector('.form-control-feedback')) { requiredGroup.querySelector('.form-control-feedback').textContent = '' } } else { requiredGroup.classList.remove('has-success') requiredGroup.classList.add('has-warning') input.classList.remove('form-control-success') input.classList.add('form-control-warning') if (requiredGroup.querySelector('.form-control-feedback')) { requiredGroup.querySelector('.form-control-feedback').textContent = 'Required' } } } if (select) { if (select.value !== '') { requiredGroup.classList.add('has-success') requiredGroup.classList.remove('has-warning') select.classList.add('form-control-success') select.classList.remove('form-control-warning') if (requiredGroup.querySelector('.form-control-feedback')) { requiredGroup.querySelector('.form-control-feedback').textContent = '' } } else { requiredGroup.classList.remove('has-success') requiredGroup.classList.add('has-warning') select.classList.remove('form-control-success') select.classList.add('form-control-warning') if (requiredGroup.querySelector('.form-control-feedback')) { requiredGroup.querySelector('.form-control-feedback').textContent = 'Required' } } } }) if (!Array.prototype.some.call(required, function (item) { return item.value === '' }) && name.value.length > 2 && name.value.length < 41 && generalComment.value.length < 501) { submitButton.removeAttribute('disabled') submitButton.setAttribute('style', 'cursor:pointer;') } else { submitButton.setAttribute('disabled', true) submitButton.removeAttribute('style') } } function attachEventListenersToSelects () { var requiredSelects = document.querySelectorAll(".required-group > select:not([name='fitzroyBooks'])") requiredSelects.forEach(function (requiredSelect) { requiredSelect.addEventListener('change', runAllRequiredChecks) }) } attachEventListenersToSelects() listeningInputs.forEach(function (requiredInput) { requiredInput.addEventListener('input', runAllRequiredChecks) }) saturdatesCheckboxes.forEach(function (checkbox, index) { var tutor = document.getElementById('student.' + index + '.tutor') function prepareCheckboxDependentElementsAndRunChecks () { if (checkbox.checked) { tutor.classList.add('required-group') tutor.removeAttribute('style') } else { tutor.classList.remove('required-group') tutor.querySelector('select').selectedIndex = 0 tutor.setAttribute('style', 'display:none; visibility:hidden') } attachEventListenersToSelects() runAllRequiredChecks() } prepareCheckboxDependentElementsAndRunChecks() checkbox.addEventListener('change', prepareCheckboxDependentElementsAndRunChecks) }) runAllRequiredChecks() })
apache-2.0
motlin/gs-collections
unit-tests/src/test/java/com/gs/collections/impl/utility/ArrayListIterateTest.java
71433
/* * Copyright 2015 Goldman Sachs. * * 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.gs.collections.impl.utility; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import com.gs.collections.api.block.function.Function; import com.gs.collections.api.block.function.Function3; import com.gs.collections.api.block.procedure.primitive.ObjectIntProcedure; import com.gs.collections.api.list.MutableList; import com.gs.collections.api.list.primitive.MutableBooleanList; import com.gs.collections.api.list.primitive.MutableByteList; import com.gs.collections.api.list.primitive.MutableCharList; import com.gs.collections.api.list.primitive.MutableDoubleList; import com.gs.collections.api.list.primitive.MutableFloatList; import com.gs.collections.api.list.primitive.MutableIntList; import com.gs.collections.api.list.primitive.MutableLongList; import com.gs.collections.api.list.primitive.MutableShortList; import com.gs.collections.api.multimap.MutableMultimap; import com.gs.collections.api.partition.list.PartitionMutableList; import com.gs.collections.api.tuple.Pair; import com.gs.collections.api.tuple.Twin; import com.gs.collections.impl.block.factory.HashingStrategies; import com.gs.collections.impl.block.factory.ObjectIntProcedures; import com.gs.collections.impl.block.factory.Predicates; import com.gs.collections.impl.block.factory.Predicates2; import com.gs.collections.impl.block.factory.PrimitiveFunctions; import com.gs.collections.impl.block.factory.Procedures2; import com.gs.collections.impl.block.function.AddFunction; import com.gs.collections.impl.block.function.MaxSizeFunction; import com.gs.collections.impl.block.function.MinSizeFunction; import com.gs.collections.impl.block.procedure.CollectionAddProcedure; import com.gs.collections.impl.factory.Lists; import com.gs.collections.impl.list.Interval; import com.gs.collections.impl.list.mutable.FastList; import com.gs.collections.impl.list.mutable.primitive.BooleanArrayList; import com.gs.collections.impl.list.mutable.primitive.ByteArrayList; import com.gs.collections.impl.list.mutable.primitive.CharArrayList; import com.gs.collections.impl.list.mutable.primitive.DoubleArrayList; import com.gs.collections.impl.list.mutable.primitive.FloatArrayList; import com.gs.collections.impl.list.mutable.primitive.IntArrayList; import com.gs.collections.impl.list.mutable.primitive.LongArrayList; import com.gs.collections.impl.list.mutable.primitive.ShortArrayList; import com.gs.collections.impl.map.mutable.UnifiedMap; import com.gs.collections.impl.math.IntegerSum; import com.gs.collections.impl.math.Sum; import com.gs.collections.impl.multimap.list.FastListMultimap; import com.gs.collections.impl.test.Verify; import com.gs.collections.impl.tuple.Tuples; import org.junit.Assert; import org.junit.Test; import static com.gs.collections.impl.factory.Iterables.iList; import static com.gs.collections.impl.factory.Iterables.mList; /** * JUnit test for {@link ArrayListIterate}. */ public class ArrayListIterateTest { private static final int OVER_OPTIMIZED_LIMIT = 101; private static final class ThisIsNotAnArrayList<T> extends ArrayList<T> { private static final long serialVersionUID = 1L; private ThisIsNotAnArrayList(Collection<? extends T> collection) { super(collection); } } @Test public void testThisIsNotAnArrayList() { ThisIsNotAnArrayList<Integer> undertest = new ThisIsNotAnArrayList<>(FastList.newListWith(1, 2, 3)); Assert.assertNotSame(undertest.getClass(), ArrayList.class); } @Test public void sortOnListWithLessThan10Elements() { ArrayList<Integer> integers = this.newArrayList(2, 3, 4, 1, 5, 7, 6, 9, 8); Verify.assertStartsWith(ArrayListIterate.sortThis(integers), 1, 2, 3, 4, 5, 6, 7, 8, 9); ArrayList<Integer> integers2 = this.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9); Verify.assertStartsWith( ArrayListIterate.sortThis(integers2, Collections.<Integer>reverseOrder()), 9, 8, 7, 6, 5, 4, 3, 2, 1); ArrayList<Integer> integers3 = this.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9); Verify.assertStartsWith(ArrayListIterate.sortThis(integers3), 1, 2, 3, 4, 5, 6, 7, 8, 9); ArrayList<Integer> integers4 = this.newArrayList(9, 8, 7, 6, 5, 4, 3, 2, 1); Verify.assertStartsWith(ArrayListIterate.sortThis(integers4), 1, 2, 3, 4, 5, 6, 7, 8, 9); ThisIsNotAnArrayList<Integer> arrayListThatIsnt = new ThisIsNotAnArrayList<>(FastList.newListWith(9, 8, 7, 6, 5, 4, 3, 2, 1)); Verify.assertStartsWith(ArrayListIterate.sortThis(arrayListThatIsnt), 1, 2, 3, 4, 5, 6, 7, 8, 9); } @Test public void sortingWithoutAccessToInternalArray() { ThisIsNotAnArrayList<Integer> arrayListThatIsnt = new ThisIsNotAnArrayList<>(FastList.newListWith(5, 3, 4, 1, 2)); Verify.assertStartsWith(ArrayListIterate.sortThis(arrayListThatIsnt, Integer::compareTo), 1, 2, 3, 4, 5); } @Test public void copyToArray() { ThisIsNotAnArrayList<Integer> notAnArrayList = this.newNotAnArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Integer[] target1 = {1, 2, null, null}; ArrayListIterate.toArray(notAnArrayList, target1, 2, 2); Assert.assertArrayEquals(target1, new Integer[]{1, 2, 1, 2}); ArrayList<Integer> arrayList = this.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Integer[] target2 = {1, 2, null, null}; ArrayListIterate.toArray(arrayList, target2, 2, 2); Assert.assertArrayEquals(target2, new Integer[]{1, 2, 1, 2}); } @Test public void sortOnListWithMoreThan10Elements() { ArrayList<Integer> integers = this.newArrayList(2, 3, 4, 1, 5, 7, 6, 8, 10, 9); Verify.assertStartsWith(ArrayListIterate.sortThis(integers), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); ArrayList<Integer> integers2 = this.newArrayList(1, 2, 3, 4, 5, 6, 7, 8); Verify.assertStartsWith(ArrayListIterate.sortThis(integers2, Collections.<Integer>reverseOrder()), 8, 7, 6, 5, 4, 3, 2, 1); ArrayList<Integer> integers3 = this.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Verify.assertStartsWith(ArrayListIterate.sortThis(integers3), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } @Test public void forEachUsingFromTo() { ArrayList<Integer> integers = Interval.oneTo(5).addAllTo(new ArrayList<>()); ArrayList<Integer> results = new ArrayList<>(); ArrayListIterate.forEach(integers, 0, 4, results::add); Assert.assertEquals(integers, results); MutableList<Integer> reverseResults = Lists.mutable.of(); ArrayListIterate.forEach(integers, 4, 0, reverseResults::add); Assert.assertEquals(ListIterate.reverseThis(integers), reverseResults); Verify.assertThrows(IndexOutOfBoundsException.class, () -> ArrayListIterate.forEach(integers, 4, -1, reverseResults::add)); Verify.assertThrows(IndexOutOfBoundsException.class, () -> ArrayListIterate.forEach(integers, -1, 4, reverseResults::add)); } @Test public void forEachUsingFromToWithOptimisable() { ArrayList<Integer> expected = Interval.oneTo(5).addAllTo(new ArrayList<>()); ArrayList<Integer> optimisableList = Interval.oneTo(105).addAllTo(new ArrayList<>()); ArrayList<Integer> results = new ArrayList<>(); ArrayListIterate.forEach(optimisableList, 0, 4, results::add); Assert.assertEquals(expected, results); MutableList<Integer> reverseResults = Lists.mutable.of(); ArrayListIterate.forEach(optimisableList, 4, 0, reverseResults::add); Assert.assertEquals(ListIterate.reverseThis(expected), reverseResults); Verify.assertThrows(IndexOutOfBoundsException.class, () -> ArrayListIterate.forEach(optimisableList, 104, -1, reverseResults::add)); Verify.assertThrows(IndexOutOfBoundsException.class, () -> ArrayListIterate.forEach(optimisableList, -1, 4, reverseResults::add)); } @Test public void forEachWithIndexUsingFromTo() { ArrayList<Integer> integers = Interval.oneTo(5).addAllTo(new ArrayList<>()); ArrayList<Integer> results = new ArrayList<>(); ArrayListIterate.forEachWithIndex(integers, 0, 4, ObjectIntProcedures.fromProcedure(results::add)); Assert.assertEquals(integers, results); MutableList<Integer> reverseResults = Lists.mutable.of(); ObjectIntProcedure<Integer> objectIntProcedure = ObjectIntProcedures.fromProcedure(reverseResults::add); ArrayListIterate.forEachWithIndex(integers, 4, 0, objectIntProcedure); Assert.assertEquals(ListIterate.reverseThis(integers), reverseResults); Verify.assertThrows(IndexOutOfBoundsException.class, () -> ArrayListIterate.forEachWithIndex(integers, 4, -1, objectIntProcedure)); Verify.assertThrows(IndexOutOfBoundsException.class, () -> ArrayListIterate.forEachWithIndex(integers, -1, 4, objectIntProcedure)); } @Test public void forEachWithIndexUsingFromToWithOptimisableList() { ArrayList<Integer> optimisableList = Interval.oneTo(105).addAllTo(new ArrayList<>()); ArrayList<Integer> expected = Interval.oneTo(105).addAllTo(new ArrayList<>()); ArrayList<Integer> results = new ArrayList<>(); ArrayListIterate.forEachWithIndex(optimisableList, 0, 104, ObjectIntProcedures.fromProcedure(results::add)); Assert.assertEquals(expected, results); MutableList<Integer> reverseResults = Lists.mutable.of(); ObjectIntProcedure<Integer> objectIntProcedure = ObjectIntProcedures.fromProcedure(reverseResults::add); ArrayListIterate.forEachWithIndex(expected, 104, 0, objectIntProcedure); Assert.assertEquals(ListIterate.reverseThis(expected), reverseResults); Verify.assertThrows(IndexOutOfBoundsException.class, () -> ArrayListIterate.forEachWithIndex(expected, 104, -1, objectIntProcedure)); Verify.assertThrows(IndexOutOfBoundsException.class, () -> ArrayListIterate.forEachWithIndex(expected, -1, 104, objectIntProcedure)); } @Test public void reverseForEach() { ArrayList<Integer> integers = Interval.oneTo(5).addAllTo(new ArrayList<>()); MutableList<Integer> reverseResults = Lists.mutable.of(); ArrayListIterate.reverseForEach(integers, reverseResults::add); Assert.assertEquals(ListIterate.reverseThis(integers), reverseResults); } @Test public void reverseForEach_emptyList() { ArrayList<Integer> integers = new ArrayList<>(); MutableList<Integer> results = Lists.mutable.of(); ArrayListIterate.reverseForEach(integers, results::add); Assert.assertEquals(integers, results); } @Test public void injectInto() { ArrayList<Integer> list = this.newArrayList(1, 2, 3); Assert.assertEquals(Integer.valueOf(1 + 1 + 2 + 3), ArrayListIterate.injectInto(1, list, AddFunction.INTEGER)); } @Test public void injectIntoOver100() { ArrayList<Integer> list = this.oneHundredAndOneOnes(); Assert.assertEquals(Integer.valueOf(102), ArrayListIterate.injectInto(1, list, AddFunction.INTEGER)); } @Test public void injectIntoDoubleOver100() { ArrayList<Integer> list = this.oneHundredAndOneOnes(); Assert.assertEquals(102.0, ArrayListIterate.injectInto(1.0d, list, AddFunction.INTEGER_TO_DOUBLE), 0.0001); } private ArrayList<Integer> oneHundredAndOneOnes() { return new ArrayList<>(Collections.nCopies(101, 1)); } @Test public void injectIntoIntegerOver100() { ArrayList<Integer> list = this.oneHundredAndOneOnes(); Assert.assertEquals(102, ArrayListIterate.injectInto(1, list, AddFunction.INTEGER_TO_INT)); } @Test public void injectIntoLongOver100() { ArrayList<Integer> list = this.oneHundredAndOneOnes(); Assert.assertEquals(102, ArrayListIterate.injectInto(1L, list, AddFunction.INTEGER_TO_LONG)); } @Test public void injectIntoDouble() { ArrayList<Double> list = new ArrayList<>(); list.add(1.0); list.add(2.0); list.add(3.0); Assert.assertEquals( new Double(7.0), ArrayListIterate.injectInto(1.0, list, AddFunction.DOUBLE)); } @Test public void injectIntoFloat() { ArrayList<Float> list = new ArrayList<>(); list.add(1.0f); list.add(2.0f); list.add(3.0f); Assert.assertEquals( new Float(7.0f), ArrayListIterate.injectInto(1.0f, list, AddFunction.FLOAT)); } @Test public void injectIntoString() { ArrayList<String> list = new ArrayList<>(); list.add("1"); list.add("2"); list.add("3"); Assert.assertEquals("0123", ArrayListIterate.injectInto("0", list, AddFunction.STRING)); } @Test public void injectIntoMaxString() { ArrayList<String> list = new ArrayList<>(); list.add("1"); list.add("12"); list.add("123"); Assert.assertEquals(Integer.valueOf(3), ArrayListIterate.injectInto(Integer.MIN_VALUE, list, MaxSizeFunction.STRING)); } @Test public void injectIntoMinString() { ArrayList<String> list = new ArrayList<>(); list.add("1"); list.add("12"); list.add("123"); Assert.assertEquals(Integer.valueOf(1), ArrayListIterate.injectInto(Integer.MAX_VALUE, list, MinSizeFunction.STRING)); } @Test public void collect() { ArrayList<Boolean> list = new ArrayList<>(); list.add(Boolean.TRUE); list.add(Boolean.FALSE); list.add(Boolean.TRUE); list.add(Boolean.TRUE); list.add(Boolean.FALSE); list.add(null); list.add(null); list.add(Boolean.FALSE); list.add(Boolean.TRUE); list.add(null); ArrayList<String> newCollection = ArrayListIterate.collect(list, String::valueOf); //List<String> newCollection = ArrayListIterate.collect(list, ArrayListIterateTest.TO_STRING_FUNCTION); Verify.assertSize(10, newCollection); Verify.assertContainsAll(newCollection, "null", "false", "true"); } @Test public void collectBoolean() { ArrayList<Integer> list = this.createIntegerList(); MutableBooleanList actual = ArrayListIterate.collectBoolean(list, PrimitiveFunctions.integerIsPositive()); Assert.assertEquals(BooleanArrayList.newListWith(false, false, true), actual); } @Test public void collectBooleanWithTarget() { ArrayList<Integer> list = this.createIntegerList(); MutableBooleanList target = new BooleanArrayList(); MutableBooleanList actual = ArrayListIterate.collectBoolean(list, PrimitiveFunctions.integerIsPositive(), target); Assert.assertSame("Target list sent as parameter not returned", target, actual); Assert.assertEquals(BooleanArrayList.newListWith(false, false, true), actual); } @Test public void collectBooleanOverOptimizeLimit() { ArrayList<Integer> list = new ArrayList<>(Interval.zeroTo(OVER_OPTIMIZED_LIMIT)); MutableBooleanList actual = ArrayListIterate.collectBoolean(list, PrimitiveFunctions.integerIsPositive()); BooleanArrayList expected = new BooleanArrayList(list.size()); expected.add(false); for (int i = 1; i <= OVER_OPTIMIZED_LIMIT; i++) { expected.add(true); } Assert.assertEquals(expected, actual); } @Test public void collectBooleanWithTargetOverOptimizeLimit() { ArrayList<Integer> list = new ArrayList<>(Interval.zeroTo(OVER_OPTIMIZED_LIMIT)); MutableBooleanList target = new BooleanArrayList(); MutableBooleanList actual = ArrayListIterate.collectBoolean(list, PrimitiveFunctions.integerIsPositive(), target); BooleanArrayList expected = new BooleanArrayList(list.size()); expected.add(false); for (int i = 1; i <= OVER_OPTIMIZED_LIMIT; i++) { expected.add(true); } Assert.assertEquals(expected, actual); Assert.assertSame("Target sent as parameter was not returned as result", target, actual); } @Test public void collectByte() { ArrayList<Integer> list = this.createIntegerList(); MutableByteList actual = ArrayListIterate.collectByte(list, PrimitiveFunctions.unboxIntegerToByte()); Assert.assertEquals(ByteArrayList.newListWith((byte) -1, (byte) 0, (byte) 4), actual); } @Test public void collectByteWithTarget() { ArrayList<Integer> list = this.createIntegerList(); MutableByteList target = new ByteArrayList(); MutableByteList actual = ArrayListIterate.collectByte(list, PrimitiveFunctions.unboxIntegerToByte(), target); Assert.assertSame("Target list sent as parameter not returned", target, actual); Assert.assertEquals(ByteArrayList.newListWith((byte) -1, (byte) 0, (byte) 4), actual); } @Test public void collectByteOverOptimizeLimit() { ArrayList<Integer> list = new ArrayList<>(Interval.zeroTo(OVER_OPTIMIZED_LIMIT)); MutableByteList actual = ArrayListIterate.collectByte(list, PrimitiveFunctions.unboxIntegerToByte()); ByteArrayList expected = new ByteArrayList(list.size()); for (int i = 0; i <= OVER_OPTIMIZED_LIMIT; i++) { expected.add((byte) i); } Assert.assertEquals(expected, actual); } @Test public void collectByteWithTargetOverOptimizeLimit() { ArrayList<Integer> list = new ArrayList<>(Interval.zeroTo(OVER_OPTIMIZED_LIMIT)); MutableByteList target = new ByteArrayList(); MutableByteList actual = ArrayListIterate.collectByte(list, PrimitiveFunctions.unboxIntegerToByte(), target); ByteArrayList expected = new ByteArrayList(list.size()); for (int i = 0; i <= OVER_OPTIMIZED_LIMIT; i++) { expected.add((byte) i); } Assert.assertEquals(expected, actual); Assert.assertSame("Target sent as parameter was not returned as result", target, actual); } @Test public void collectChar() { ArrayList<Integer> list = this.createIntegerList(); MutableCharList actual = ArrayListIterate.collectChar(list, PrimitiveFunctions.unboxIntegerToChar()); Assert.assertEquals(CharArrayList.newListWith((char) -1, (char) 0, (char) 4), actual); } @Test public void collectCharWithTarget() { ArrayList<Integer> list = this.createIntegerList(); MutableCharList target = new CharArrayList(); MutableCharList actual = ArrayListIterate.collectChar(list, PrimitiveFunctions.unboxIntegerToChar(), target); Assert.assertSame("Target list sent as parameter not returned", target, actual); Assert.assertEquals(CharArrayList.newListWith((char) -1, (char) 0, (char) 4), actual); } @Test public void collectCharOverOptimizeLimit() { ArrayList<Integer> list = new ArrayList<>(Interval.zeroTo(OVER_OPTIMIZED_LIMIT)); MutableCharList actual = ArrayListIterate.collectChar(list, PrimitiveFunctions.unboxIntegerToChar()); CharArrayList expected = new CharArrayList(list.size()); for (int i = 0; i <= OVER_OPTIMIZED_LIMIT; i++) { expected.add((char) i); } Assert.assertEquals(expected, actual); } @Test public void collectCharWithTargetOverOptimizeLimit() { ArrayList<Integer> list = new ArrayList<>(Interval.zeroTo(OVER_OPTIMIZED_LIMIT)); MutableCharList target = new CharArrayList(); MutableCharList actual = ArrayListIterate.collectChar(list, PrimitiveFunctions.unboxIntegerToChar(), target); CharArrayList expected = new CharArrayList(list.size()); for (int i = 0; i <= OVER_OPTIMIZED_LIMIT; i++) { expected.add((char) i); } Assert.assertEquals(expected, actual); Assert.assertSame("Target sent as parameter was not returned as result", target, actual); } @Test public void collectDouble() { ArrayList<Integer> list = this.createIntegerList(); MutableDoubleList actual = ArrayListIterate.collectDouble(list, PrimitiveFunctions.unboxIntegerToDouble()); Assert.assertEquals(DoubleArrayList.newListWith(-1.0d, 0.0d, 4.0d), actual); } @Test public void collectDoubleWithTarget() { ArrayList<Integer> list = this.createIntegerList(); MutableDoubleList target = new DoubleArrayList(); MutableDoubleList actual = ArrayListIterate.collectDouble(list, PrimitiveFunctions.unboxIntegerToDouble(), target); Assert.assertSame("Target list sent as parameter not returned", target, actual); Assert.assertEquals(DoubleArrayList.newListWith(-1.0d, 0.0d, 4.0d), actual); } @Test public void collectDoubleOverOptimizeLimit() { ArrayList<Integer> list = new ArrayList<>(Interval.zeroTo(OVER_OPTIMIZED_LIMIT)); MutableDoubleList actual = ArrayListIterate.collectDouble(list, PrimitiveFunctions.unboxIntegerToDouble()); DoubleArrayList expected = new DoubleArrayList(list.size()); for (int i = 0; i <= OVER_OPTIMIZED_LIMIT; i++) { expected.add((double) i); } Assert.assertEquals(expected, actual); } @Test public void collectDoubleWithTargetOverOptimizeLimit() { ArrayList<Integer> list = new ArrayList<>(Interval.zeroTo(OVER_OPTIMIZED_LIMIT)); MutableDoubleList target = new DoubleArrayList(); MutableDoubleList actual = ArrayListIterate.collectDouble(list, PrimitiveFunctions.unboxIntegerToDouble(), target); DoubleArrayList expected = new DoubleArrayList(list.size()); for (int i = 0; i <= OVER_OPTIMIZED_LIMIT; i++) { expected.add((double) i); } Assert.assertEquals(expected, actual); Assert.assertSame("Target sent as parameter was not returned as result", target, actual); } @Test public void collectFloat() { ArrayList<Integer> list = this.createIntegerList(); MutableFloatList actual = ArrayListIterate.collectFloat(list, PrimitiveFunctions.unboxIntegerToFloat()); Assert.assertEquals(FloatArrayList.newListWith(-1.0f, 0.0f, 4.0f), actual); } @Test public void collectFloatWithTarget() { ArrayList<Integer> list = this.createIntegerList(); MutableFloatList target = new FloatArrayList(); MutableFloatList actual = ArrayListIterate.collectFloat(list, PrimitiveFunctions.unboxIntegerToFloat(), target); Assert.assertSame("Target list sent as parameter not returned", target, actual); Assert.assertEquals(FloatArrayList.newListWith(-1.0f, 0.0f, 4.0f), actual); } @Test public void collectFloatOverOptimizeLimit() { ArrayList<Integer> list = new ArrayList<>(Interval.zeroTo(OVER_OPTIMIZED_LIMIT)); MutableFloatList actual = ArrayListIterate.collectFloat(list, PrimitiveFunctions.unboxIntegerToFloat()); FloatArrayList expected = new FloatArrayList(list.size()); for (int i = 0; i <= OVER_OPTIMIZED_LIMIT; i++) { expected.add((float) i); } Assert.assertEquals(expected, actual); } @Test public void collectFloatWithTargetOverOptimizeLimit() { ArrayList<Integer> list = new ArrayList<>(Interval.zeroTo(OVER_OPTIMIZED_LIMIT)); MutableFloatList target = new FloatArrayList(); MutableFloatList actual = ArrayListIterate.collectFloat(list, PrimitiveFunctions.unboxIntegerToFloat(), target); FloatArrayList expected = new FloatArrayList(list.size()); for (int i = 0; i <= OVER_OPTIMIZED_LIMIT; i++) { expected.add((float) i); } Assert.assertEquals(expected, actual); Assert.assertSame("Target sent as parameter was not returned as result", target, actual); } @Test public void collectInt() { ArrayList<Integer> list = this.createIntegerList(); MutableIntList actual = ArrayListIterate.collectInt(list, PrimitiveFunctions.unboxIntegerToInt()); Assert.assertEquals(IntArrayList.newListWith(-1, 0, 4), actual); } @Test public void collectIntWithTarget() { ArrayList<Integer> list = this.createIntegerList(); MutableIntList target = new IntArrayList(); MutableIntList actual = ArrayListIterate.collectInt(list, PrimitiveFunctions.unboxIntegerToInt(), target); Assert.assertSame("Target list sent as parameter not returned", target, actual); Assert.assertEquals(IntArrayList.newListWith(-1, 0, 4), actual); } @Test public void collectIntOverOptimizeLimit() { ArrayList<Integer> list = new ArrayList<>(Interval.zeroTo(OVER_OPTIMIZED_LIMIT)); MutableIntList actual = ArrayListIterate.collectInt(list, PrimitiveFunctions.unboxIntegerToInt()); IntArrayList expected = new IntArrayList(list.size()); for (int i = 0; i <= OVER_OPTIMIZED_LIMIT; i++) { expected.add(i); } Assert.assertEquals(expected, actual); } @Test public void collectIntWithTargetOverOptimizeLimit() { ArrayList<Integer> list = new ArrayList<>(Interval.zeroTo(OVER_OPTIMIZED_LIMIT)); MutableIntList target = new IntArrayList(); MutableIntList actual = ArrayListIterate.collectInt(list, PrimitiveFunctions.unboxIntegerToInt(), target); IntArrayList expected = new IntArrayList(list.size()); for (int i = 0; i <= OVER_OPTIMIZED_LIMIT; i++) { expected.add(i); } Assert.assertEquals(expected, actual); Assert.assertSame("Target sent as parameter was not returned as result", target, actual); } @Test public void collectLong() { ArrayList<Integer> list = this.createIntegerList(); MutableLongList actual = ArrayListIterate.collectLong(list, PrimitiveFunctions.unboxIntegerToLong()); Assert.assertEquals(LongArrayList.newListWith(-1L, 0L, 4L), actual); } @Test public void collectLongWithTarget() { ArrayList<Integer> list = this.createIntegerList(); MutableLongList target = new LongArrayList(); MutableLongList actual = ArrayListIterate.collectLong(list, PrimitiveFunctions.unboxIntegerToLong(), target); Assert.assertSame("Target list sent as parameter not returned", target, actual); Assert.assertEquals(LongArrayList.newListWith(-1L, 0L, 4L), actual); } @Test public void collectLongOverOptimizeLimit() { ArrayList<Integer> list = new ArrayList<>(Interval.zeroTo(OVER_OPTIMIZED_LIMIT)); MutableLongList actual = ArrayListIterate.collectLong(list, PrimitiveFunctions.unboxIntegerToLong()); LongArrayList expected = new LongArrayList(list.size()); for (int i = 0; i <= OVER_OPTIMIZED_LIMIT; i++) { expected.add((long) i); } Assert.assertEquals(expected, actual); } @Test public void collectLongWithTargetOverOptimizeLimit() { ArrayList<Integer> list = new ArrayList<>(Interval.zeroTo(OVER_OPTIMIZED_LIMIT)); MutableLongList target = new LongArrayList(); MutableLongList actual = ArrayListIterate.collectLong(list, PrimitiveFunctions.unboxIntegerToLong(), target); LongArrayList expected = new LongArrayList(list.size()); for (int i = 0; i <= OVER_OPTIMIZED_LIMIT; i++) { expected.add((long) i); } Assert.assertEquals(expected, actual); Assert.assertSame("Target sent as parameter was not returned as result", target, actual); } @Test public void collectShort() { ArrayList<Integer> list = this.createIntegerList(); MutableShortList actual = ArrayListIterate.collectShort(list, PrimitiveFunctions.unboxIntegerToShort()); Assert.assertEquals(ShortArrayList.newListWith((short) -1, (short) 0, (short) 4), actual); } @Test public void collectShortWithTarget() { ArrayList<Integer> list = this.createIntegerList(); MutableShortList target = new ShortArrayList(); MutableShortList actual = ArrayListIterate.collectShort(list, PrimitiveFunctions.unboxIntegerToShort(), target); Assert.assertSame("Target list sent as parameter not returned", target, actual); Assert.assertEquals(ShortArrayList.newListWith((short) -1, (short) 0, (short) 4), actual); } @Test public void collectShortOverOptimizeLimit() { ArrayList<Integer> list = new ArrayList<>(Interval.zeroTo(OVER_OPTIMIZED_LIMIT)); MutableShortList actual = ArrayListIterate.collectShort(list, PrimitiveFunctions.unboxIntegerToShort()); ShortArrayList expected = new ShortArrayList(list.size()); for (int i = 0; i <= OVER_OPTIMIZED_LIMIT; i++) { expected.add((short) i); } Assert.assertEquals(expected, actual); } @Test public void collectShortWithTargetOverOptimizeLimit() { ArrayList<Integer> list = new ArrayList<>(Interval.zeroTo(OVER_OPTIMIZED_LIMIT)); MutableShortList target = new ShortArrayList(); MutableShortList actual = ArrayListIterate.collectShort(list, PrimitiveFunctions.unboxIntegerToShort(), target); ShortArrayList expected = new ShortArrayList(list.size()); for (int i = 0; i <= OVER_OPTIMIZED_LIMIT; i++) { expected.add((short) i); } Assert.assertEquals(expected, actual); Assert.assertSame("Target sent as parameter was not returned as result", target, actual); } private ArrayList<Integer> createIntegerList() { ArrayList<Integer> list = new ArrayList<>(); list.add(-1); list.add(0); list.add(4); return list; } @Test public void collectOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); ArrayList<Class<?>> newCollection = ArrayListIterate.collect(list, Object::getClass); Verify.assertSize(101, newCollection); Verify.assertContains(Integer.class, newCollection); } private ArrayList<Integer> getIntegerList() { return new ArrayList<>(Interval.toReverseList(1, 5)); } private ArrayList<Integer> getOver100IntegerList() { return new ArrayList<>(Interval.toReverseList(1, 105)); } @Test public void forEachWithIndex() { ArrayList<Integer> list = this.getIntegerList(); Iterate.sortThis(list); ArrayListIterate.forEachWithIndex(list, (object, index) -> Assert.assertEquals(index, object - 1)); } @Test public void forEachWithIndexOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); Iterate.sortThis(list); ArrayListIterate.forEachWithIndex(list, (object, index) -> Assert.assertEquals(index, object - 1)); } @Test public void forEach() { ArrayList<Integer> list = this.getIntegerList(); Iterate.sortThis(list); MutableList<Integer> result = Lists.mutable.of(); ArrayListIterate.forEach(list, CollectionAddProcedure.on(result)); Verify.assertListsEqual(list, result); } @Test public void forEachOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); Iterate.sortThis(list); FastList<Integer> result = FastList.newList(101); ArrayListIterate.forEach(list, CollectionAddProcedure.on(result)); Verify.assertListsEqual(list, result); } @Test public void forEachWith() { ArrayList<Integer> list = this.getIntegerList(); Iterate.sortThis(list); MutableList<Integer> result = Lists.mutable.of(); ArrayListIterate.forEachWith( list, Procedures2.fromProcedure(CollectionAddProcedure.on(result)), null); Verify.assertListsEqual(list, result); } @Test public void forEachWithOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); Iterate.sortThis(list); MutableList<Integer> result = FastList.newList(101); ArrayListIterate.forEachWith( list, Procedures2.fromProcedure(CollectionAddProcedure.on(result)), null); Verify.assertListsEqual(list, result); } @Test public void forEachInBoth() { MutableList<Pair<String, String>> list = Lists.mutable.of(); ArrayList<String> list1 = new ArrayList<>(mList("1", "2")); ArrayList<String> list2 = new ArrayList<>(mList("a", "b")); ArrayListIterate.forEachInBoth(list1, list2, (argument1, argument2) -> list.add(Tuples.twin(argument1, argument2))); Assert.assertEquals(FastList.newListWith(Tuples.twin("1", "a"), Tuples.twin("2", "b")), list); } @Test public void detect() { ArrayList<Integer> list = this.getIntegerList(); Assert.assertEquals(Integer.valueOf(1), ArrayListIterate.detect(list, Integer.valueOf(1)::equals)); //noinspection CachedNumberConstructorCall,UnnecessaryBoxing ArrayList<Integer> list2 = this.newArrayList(1, new Integer(2), 2); // test relies on having a unique instance of "2" Assert.assertSame(list2.get(1), ArrayListIterate.detect(list2, Integer.valueOf(2)::equals)); } @Test public void detectOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); Assert.assertEquals(Integer.valueOf(1), ArrayListIterate.detect(list, Integer.valueOf(1)::equals)); } @Test public void detectWith() { ArrayList<Integer> list = this.getIntegerList(); Assert.assertEquals(Integer.valueOf(1), ArrayListIterate.detectWith(list, Object::equals, 1)); //noinspection CachedNumberConstructorCall,UnnecessaryBoxing ArrayList<Integer> list2 = this.newArrayList(1, new Integer(2), 2); // test relies on having a unique instance of "2" Assert.assertSame(list2.get(1), ArrayListIterate.detectWith(list2, Object::equals, 2)); } @Test public void detectWithOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); Assert.assertEquals(Integer.valueOf(1), ArrayListIterate.detectWith(list, Object::equals, 1)); } @Test public void detectIfNone() { ArrayList<Integer> list = this.getIntegerList(); Assert.assertEquals(Integer.valueOf(7), ArrayListIterate.detectIfNone(list, Integer.valueOf(6)::equals, 7)); Assert.assertEquals(Integer.valueOf(2), ArrayListIterate.detectIfNone(list, Integer.valueOf(2)::equals, 7)); } @Test public void detectIfNoneOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); Assert.assertNull(ArrayListIterate.detectIfNone(list, Integer.valueOf(102)::equals, null)); } @Test public void detectWithIfNone() { ArrayList<Integer> list = this.getIntegerList(); Assert.assertEquals(Integer.valueOf(7), ArrayListIterate.detectWithIfNone(list, Object::equals, 6, 7)); Assert.assertEquals(Integer.valueOf(2), ArrayListIterate.detectWithIfNone(list, Object::equals, 2, 7)); } @Test public void detectWithIfNoneOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); Assert.assertNull(ArrayListIterate.detectWithIfNone(list, Object::equals, 102, null)); } @Test public void select() { ArrayList<Integer> list = this.getIntegerList(); ArrayList<Integer> results = ArrayListIterate.select(list, Integer.class::isInstance); Verify.assertSize(5, results); } @Test public void selectOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); ArrayList<Integer> results = ArrayListIterate.select(list, Integer.class::isInstance); Verify.assertSize(101, results); } @Test public void selectWith() { ArrayList<Integer> list = this.getIntegerList(); ArrayList<Integer> results = ArrayListIterate.selectWith(list, Predicates2.instanceOf(), Integer.class); Verify.assertSize(5, results); } @Test public void selectWithOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); ArrayList<Integer> results = ArrayListIterate.selectWith(list, Predicates2.instanceOf(), Integer.class); Verify.assertSize(101, results); } @Test public void reject() { ArrayList<Integer> list = this.getIntegerList(); ArrayList<Integer> results = ArrayListIterate.reject(list, Integer.class::isInstance); Verify.assertEmpty(results); } @Test public void rejectOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); List<Integer> results = ArrayListIterate.reject(list, Integer.class::isInstance); Verify.assertEmpty(results); } @Test public void distinct() { ArrayList<Integer> list = new ArrayList<>(); list.addAll(FastList.newListWith(9, 4, 7, 7, 5, 6, 2, 4)); List<Integer> result = ArrayListIterate.distinct(list); Verify.assertListsEqual(FastList.newListWith(9, 4, 7, 5, 6, 2), result); ArrayList<Integer> target = new ArrayList<>(); ArrayListIterate.distinct(list, target); Verify.assertListsEqual(FastList.newListWith(9, 4, 7, 5, 6, 2), target); Assert.assertEquals(FastList.newListWith(9, 4, 7, 7, 5, 6, 2, 4), list); ArrayList<Integer> list2 = new ArrayList<>(Interval.oneTo(103)); list2.add(103); ArrayList<Integer> target2 = new ArrayList<>(); List<Integer> result2 = ArrayListIterate.distinct(list2, target2); Assert.assertEquals(Interval.fromTo(1, 103), result2); } @Test public void distinctWithHashingStrategy() { ArrayList<String> list = new ArrayList<>(); list.addAll(FastList.newListWith("A", "a", "b", "c", "B", "D", "e", "e", "E", "D")); list = ArrayListIterate.distinct(list, HashingStrategies.fromFunction(String::toLowerCase)); Assert.assertEquals(FastList.newListWith("A", "b", "c", "D", "e"), list); ArrayList<Integer> list2 = new ArrayList<>(Interval.oneTo(103)); list2.add(103); List<Integer> result2 = ArrayListIterate.distinct(list2, HashingStrategies.fromFunction(String::valueOf)); Assert.assertEquals(Interval.fromTo(1, 103), result2); } @Test public void selectInstancesOfOver100() { ArrayList<Number> list = new ArrayList<>(Interval.oneTo(101)); list.add(102.0); MutableList<Double> results = ArrayListIterate.selectInstancesOf(list, Double.class); Assert.assertEquals(iList(102.0), results); } public static final class CollectionCreator { private final int data; private CollectionCreator(int data) { this.data = data; } public Collection<Integer> getCollection() { return FastList.newListWith(this.data, this.data); } } @Test public void flatCollect() { ArrayList<CollectionCreator> list = new ArrayList<>(); list.add(new CollectionCreator(1)); list.add(new CollectionCreator(2)); List<Integer> results1 = ArrayListIterate.flatCollect(list, CollectionCreator::getCollection); Verify.assertListsEqual(FastList.newListWith(1, 1, 2, 2), results1); MutableList<Integer> target1 = Lists.mutable.of(); MutableList<Integer> results2 = ArrayListIterate.flatCollect(list, CollectionCreator::getCollection, target1); Assert.assertSame(results2, target1); Verify.assertListsEqual(FastList.newListWith(1, 1, 2, 2), results2); } @Test public void rejectWith() { ArrayList<Integer> list = this.getIntegerList(); ArrayList<Integer> results = ArrayListIterate.rejectWith(list, Predicates2.instanceOf(), Integer.class); Verify.assertEmpty(results); } @Test public void rejectWithOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); ArrayList<Integer> results = ArrayListIterate.rejectWith(list, Predicates2.instanceOf(), Integer.class); Verify.assertEmpty(results); } @Test public void selectAndRejectWith() { ArrayList<Integer> list = this.getIntegerList(); Twin<MutableList<Integer>> result = ArrayListIterate.selectAndRejectWith(list, Predicates2.in(), Lists.immutable.of(1)); Verify.assertSize(1, result.getOne()); Verify.assertSize(4, result.getTwo()); } @Test public void selectAndRejectWithOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); Twin<MutableList<Integer>> result = ArrayListIterate.selectAndRejectWith(list, Predicates2.in(), Lists.immutable.of(1)); Verify.assertSize(1, result.getOne()); Verify.assertSize(100, result.getTwo()); } @Test public void partition() { ArrayList<Integer> smallList = new ArrayList<>(Interval.oneTo(99)); PartitionMutableList<Integer> smallPartition = ArrayListIterate.partition(smallList, Predicates.in(Interval.oneToBy(99, 2))); Assert.assertEquals(Interval.oneToBy(99, 2), smallPartition.getSelected()); Assert.assertEquals(Interval.fromToBy(2, 98, 2), smallPartition.getRejected()); ArrayList<Integer> bigList = new ArrayList<>(Interval.oneTo(101)); PartitionMutableList<Integer> bigPartition = ArrayListIterate.partition(bigList, Predicates.in(Interval.oneToBy(101, 2))); Assert.assertEquals(Interval.oneToBy(101, 2), bigPartition.getSelected()); Assert.assertEquals(Interval.fromToBy(2, 100, 2), bigPartition.getRejected()); } @Test public void partitionWith() { ArrayList<Integer> smallList = new ArrayList<>(Interval.oneTo(99)); PartitionMutableList<Integer> smallPartition = ArrayListIterate.partitionWith(smallList, Predicates2.in(), Interval.oneToBy(99, 2)); Assert.assertEquals(Interval.oneToBy(99, 2), smallPartition.getSelected()); Assert.assertEquals(Interval.fromToBy(2, 98, 2), smallPartition.getRejected()); ArrayList<Integer> bigList = new ArrayList<>(Interval.oneTo(101)); PartitionMutableList<Integer> bigPartition = ArrayListIterate.partitionWith(bigList, Predicates2.in(), Interval.oneToBy(101, 2)); Assert.assertEquals(Interval.oneToBy(101, 2), bigPartition.getSelected()); Assert.assertEquals(Interval.fromToBy(2, 100, 2), bigPartition.getRejected()); } @Test public void anySatisfyWith() { ArrayList<Integer> list = this.getIntegerList(); Assert.assertTrue(ArrayListIterate.anySatisfyWith(list, Predicates2.instanceOf(), Integer.class)); Assert.assertFalse(ArrayListIterate.anySatisfyWith(list, Predicates2.instanceOf(), Double.class)); } @Test public void anySatisfy() { ArrayList<Integer> list = this.getIntegerList(); Assert.assertTrue(ArrayListIterate.anySatisfy(list, Integer.class::isInstance)); Assert.assertFalse(ArrayListIterate.anySatisfy(list, Double.class::isInstance)); } @Test public void anySatisfyWithOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); Assert.assertTrue(ArrayListIterate.anySatisfyWith(list, Predicates2.instanceOf(), Integer.class)); Assert.assertFalse(ArrayListIterate.anySatisfyWith(list, Predicates2.instanceOf(), Double.class)); } @Test public void anySatisfyOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); Assert.assertTrue(ArrayListIterate.anySatisfy(list, Integer.class::isInstance)); Assert.assertFalse(ArrayListIterate.anySatisfy(list, Double.class::isInstance)); } @Test public void allSatisfyWith() { ArrayList<Integer> list = this.getIntegerList(); Assert.assertTrue(ArrayListIterate.allSatisfyWith(list, Predicates2.instanceOf(), Integer.class)); Assert.assertFalse(ArrayListIterate.allSatisfyWith(list, Predicates2.greaterThan(), 2)); } @Test public void allSatisfy() { ArrayList<Integer> list = this.getIntegerList(); Assert.assertTrue(ArrayListIterate.allSatisfy(list, Integer.class::isInstance)); Assert.assertFalse(ArrayListIterate.allSatisfy(list, Predicates.greaterThan(2))); } @Test public void allSatisfyWithOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); Assert.assertTrue(ArrayListIterate.allSatisfyWith(list, Predicates2.instanceOf(), Integer.class)); Assert.assertFalse(ArrayListIterate.allSatisfyWith(list, Predicates2.greaterThan(), 2)); } @Test public void allSatisfyOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); Assert.assertTrue(ArrayListIterate.allSatisfy(list, Integer.class::isInstance)); Assert.assertFalse(ArrayListIterate.allSatisfy(list, Predicates.greaterThan(2))); } @Test public void noneSatisfyOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); Assert.assertFalse(ArrayListIterate.noneSatisfy(list, Integer.class::isInstance)); Assert.assertTrue(ArrayListIterate.noneSatisfy(list, Predicates.greaterThan(150))); } @Test public void noneSatisfyWithOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); Assert.assertFalse(ArrayListIterate.noneSatisfyWith(list, Predicates2.instanceOf(), Integer.class)); Assert.assertTrue(ArrayListIterate.noneSatisfyWith(list, Predicates2.greaterThan(), 150)); } @Test public void countWith() { ArrayList<Integer> list = this.getIntegerList(); Assert.assertEquals(5, ArrayListIterate.countWith(list, Predicates2.instanceOf(), Integer.class)); Assert.assertEquals(0, ArrayListIterate.countWith(list, Predicates2.instanceOf(), Double.class)); } @Test public void countWithOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); Assert.assertEquals(101, ArrayListIterate.countWith(list, Predicates2.instanceOf(), Integer.class)); Assert.assertEquals(0, ArrayListIterate.countWith(list, Predicates2.instanceOf(), Double.class)); } @Test public void collectIfOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); ArrayList<Class<?>> result = ArrayListIterate.collectIf(list, Integer.valueOf(101)::equals, Object::getClass); Assert.assertEquals(FastList.newListWith(Integer.class), result); } @Test public void collectWithOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(101)); ArrayList<String> result = ArrayListIterate.collectWith(list, (argument1, argument2) -> argument1.equals(argument2) ? "101" : null, 101); Verify.assertSize(101, result); Verify.assertContainsAll(result, null, "101"); Assert.assertEquals(100, Iterate.count(result, Predicates.isNull())); } @Test public void detectIndexOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.toReverseList(1, 101)); list.add(3); list.add(2); Assert.assertEquals(100, ArrayListIterate.detectIndex(list, Integer.valueOf(1)::equals)); Assert.assertEquals(99, ArrayListIterate.detectIndex(list, Integer.valueOf(2)::equals)); Assert.assertEquals(98, ArrayListIterate.detectIndex(list, Integer.valueOf(3)::equals)); Assert.assertEquals(0, Iterate.detectIndex(list, Integer.valueOf(101)::equals)); Assert.assertEquals(-1, Iterate.detectIndex(list, Integer.valueOf(200)::equals)); } @Test public void detectIndexSmallList() { ArrayList<Integer> list = new ArrayList<>(Interval.toReverseList(1, 5)); list.add(3); list.add(2); Assert.assertEquals(4, ArrayListIterate.detectIndex(list, Integer.valueOf(1)::equals)); Assert.assertEquals(3, ArrayListIterate.detectIndex(list, Integer.valueOf(2)::equals)); Assert.assertEquals(2, ArrayListIterate.detectIndex(list, Integer.valueOf(3)::equals)); Assert.assertEquals(0, Iterate.detectIndex(list, Integer.valueOf(5)::equals)); Assert.assertEquals(-1, Iterate.detectIndex(list, Integer.valueOf(10)::equals)); } @Test public void detectLastIndexOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.toReverseList(1, 101)); list.add(3); list.add(2); Assert.assertEquals(100, ArrayListIterate.detectLastIndex(list, Integer.valueOf(1)::equals)); Assert.assertEquals(102, ArrayListIterate.detectLastIndex(list, Integer.valueOf(2)::equals)); Assert.assertEquals(101, ArrayListIterate.detectLastIndex(list, Integer.valueOf(3)::equals)); Assert.assertEquals(0, ArrayListIterate.detectLastIndex(list, Integer.valueOf(101)::equals)); Assert.assertEquals(-1, ArrayListIterate.detectLastIndex(list, Integer.valueOf(200)::equals)); } @Test public void detectLastIndexSmallList() { ArrayList<Integer> list = new ArrayList<>(Interval.toReverseList(1, 5)); list.add(3); list.add(2); Assert.assertEquals(4, ArrayListIterate.detectLastIndex(list, Integer.valueOf(1)::equals)); Assert.assertEquals(6, ArrayListIterate.detectLastIndex(list, Integer.valueOf(2)::equals)); Assert.assertEquals(5, ArrayListIterate.detectLastIndex(list, Integer.valueOf(3)::equals)); Assert.assertEquals(0, ArrayListIterate.detectLastIndex(list, Integer.valueOf(5)::equals)); Assert.assertEquals(-1, ArrayListIterate.detectLastIndex(list, Integer.valueOf(10)::equals)); } @Test public void detectIndexWithOver100() { ArrayList<Integer> list = new ArrayList<>(Interval.toReverseList(1, 101)); Assert.assertEquals(100, Iterate.detectIndexWith(list, Object::equals, 1)); Assert.assertEquals(0, Iterate.detectIndexWith(list, Object::equals, 101)); Assert.assertEquals(-1, Iterate.detectIndexWith(list, Object::equals, 200)); } @Test public void detectIndexWithSmallList() { ArrayList<Integer> list = new ArrayList<>(Interval.toReverseList(1, 5)); Assert.assertEquals(4, Iterate.detectIndexWith(list, Object::equals, 1)); Assert.assertEquals(0, Iterate.detectIndexWith(list, Object::equals, 5)); Assert.assertEquals(-1, Iterate.detectIndexWith(list, Object::equals, 10)); } @Test public void injectIntoWithOver100() { Sum result = new IntegerSum(0); Integer parameter = 2; Function3<Sum, Integer, Integer, Sum> function = (sum, element, withValue) -> sum.add((element.intValue() - element.intValue()) * withValue.intValue()); Sum sumOfDoubledValues = ArrayListIterate.injectIntoWith(result, this.getOver100IntegerList(), function, parameter); Assert.assertEquals(0, sumOfDoubledValues.getValue().intValue()); } @Test public void removeIf() { ArrayList<Integer> objects = this.newArrayList(1, 2, 3, null); ArrayListIterate.removeIf(objects, Predicates.isNull()); Verify.assertSize(3, objects); Verify.assertContainsAll(objects, 1, 2, 3); ArrayList<Integer> objects5 = this.newArrayList(null, 1, 2, 3); ArrayListIterate.removeIf(objects5, Predicates.isNull()); Verify.assertSize(3, objects5); Verify.assertContainsAll(objects5, 1, 2, 3); ArrayList<Integer> objects4 = this.newArrayList(1, null, 2, 3); ArrayListIterate.removeIf(objects4, Predicates.isNull()); Verify.assertSize(3, objects4); Verify.assertContainsAll(objects4, 1, 2, 3); ArrayList<Integer> objects3 = this.newArrayList(null, null, null, null); ArrayListIterate.removeIf(objects3, Predicates.isNull()); Verify.assertEmpty(objects3); ArrayList<Integer> objects2 = this.newArrayList(null, 1, 2, 3, null); ArrayListIterate.removeIf(objects2, Predicates.isNull()); Verify.assertSize(3, objects2); Verify.assertContainsAll(objects2, 1, 2, 3); ArrayList<Integer> objects1 = this.newArrayList(1, 2, 3); ArrayListIterate.removeIf(objects1, Predicates.isNull()); Verify.assertSize(3, objects1); Verify.assertContainsAll(objects1, 1, 2, 3); ThisIsNotAnArrayList<Integer> objects6 = this.newNotAnArrayList(1, 2, 3); ArrayListIterate.removeIf(objects6, Predicates.isNull()); Verify.assertSize(3, objects6); Verify.assertContainsAll(objects6, 1, 2, 3); } @Test public void removeIfWith() { ArrayList<Integer> objects = this.newArrayList(1, 2, 3, null); ArrayListIterate.removeIfWith(objects, (each6, ignored6) -> each6 == null, null); Verify.assertSize(3, objects); Verify.assertContainsAll(objects, 1, 2, 3); ArrayList<Integer> objects5 = this.newArrayList(null, 1, 2, 3); ArrayListIterate.removeIfWith(objects5, (each5, ignored5) -> each5 == null, null); Verify.assertSize(3, objects5); Verify.assertContainsAll(objects5, 1, 2, 3); ArrayList<Integer> objects4 = this.newArrayList(1, null, 2, 3); ArrayListIterate.removeIfWith(objects4, (each4, ignored4) -> each4 == null, null); Verify.assertSize(3, objects4); Verify.assertContainsAll(objects4, 1, 2, 3); ArrayList<Integer> objects3 = this.newArrayList(null, null, null, null); ArrayListIterate.removeIfWith(objects3, (each3, ignored3) -> each3 == null, null); Verify.assertEmpty(objects3); ArrayList<Integer> objects2 = this.newArrayList(null, 1, 2, 3, null); ArrayListIterate.removeIfWith(objects2, (each2, ignored2) -> each2 == null, null); Verify.assertSize(3, objects2); Verify.assertContainsAll(objects2, 1, 2, 3); ArrayList<Integer> objects1 = this.newArrayList(1, 2, 3); ArrayListIterate.removeIfWith(objects1, (each1, ignored1) -> each1 == null, null); Verify.assertSize(3, objects1); Verify.assertContainsAll(objects1, 1, 2, 3); ThisIsNotAnArrayList<Integer> objects6 = this.newNotAnArrayList(1, 2, 3); ArrayListIterate.removeIfWith(objects6, (each, ignored) -> each == null, null); Verify.assertSize(3, objects6); Verify.assertContainsAll(objects6, 1, 2, 3); } @Test public void take() { ArrayList<Integer> list = this.getIntegerList(); Verify.assertListsEqual(FastList.newList(list).take(0), ArrayListIterate.take(list, 0)); Verify.assertListsEqual(FastList.newList(list).take(1), ArrayListIterate.take(list, 1)); Verify.assertListsEqual(FastList.newList(list).take(2), ArrayListIterate.take(list, 2)); Verify.assertListsEqual(FastList.newList(list).take(5), ArrayListIterate.take(list, 5)); Verify.assertListsEqual(FastList.newList(list).take(list.size() - 1), ArrayListIterate.take(list, list.size() - 1)); Verify.assertListsEqual(FastList.newList(list).take(list.size()), ArrayListIterate.take(list, list.size())); Verify.assertListsEqual(FastList.newList().take(2), ArrayListIterate.take(new ArrayList<>(), 2)); ArrayList<Integer> list1 = new ArrayList<>(); list1.addAll(Interval.oneTo(120)); Verify.assertListsEqual(FastList.newList(list1).take(125), ArrayListIterate.take(list1, 125)); Verify.assertListsEqual(FastList.newList(list1).take(Integer.MAX_VALUE), ArrayListIterate.take(list1, Integer.MAX_VALUE)); } @Test(expected = IllegalArgumentException.class) public void take_throws() { ArrayListIterate.take(this.getIntegerList(), -1); } @Test public void take_target() { ArrayList<Integer> list1 = this.getIntegerList(); MutableList<Integer> expected1 = FastList.newListWith(-1); expected1.addAll(FastList.newList(list1).take(2)); Verify.assertListsEqual(expected1, ArrayListIterate.take(list1, 2, FastList.newListWith(-1))); MutableList<Integer> expected2 = FastList.newListWith(-1); expected2.addAll(FastList.newList(list1).take(0)); Verify.assertListsEqual(expected2, ArrayListIterate.take(list1, 0, FastList.newListWith(-1))); MutableList<Integer> expected3 = FastList.newListWith(-1); expected3.addAll(FastList.newList(list1).take(5)); Verify.assertListsEqual(expected3, ArrayListIterate.take(list1, 5, FastList.newListWith(-1))); Verify.assertListsEqual(FastList.newListWith(-1), ArrayListIterate.take(new ArrayList<>(), 2, FastList.newListWith(-1))); ArrayList<Integer> list2 = new ArrayList<>(); list2.addAll(Interval.oneTo(120)); FastList<Integer> integers = FastList.newList(list2); MutableList<Integer> expected4 = FastList.newListWith(-1); expected4.addAll(integers.take(125)); Verify.assertListsEqual(expected4, ArrayListIterate.take(list2, 125, FastList.newListWith(-1))); MutableList<Integer> expected5 = FastList.newListWith(-1); expected5.addAll(integers.take(Integer.MAX_VALUE)); Verify.assertListsEqual(expected5, ArrayListIterate.take(list2, Integer.MAX_VALUE, FastList.newListWith(-1))); } @Test(expected = IllegalArgumentException.class) public void take_target_throws() { ArrayListIterate.take(this.getIntegerList(), -1, FastList.newList()); } @Test public void takeWhile_small() { ArrayList<Integer> arrayList = new ArrayList<>(Interval.oneTo(100)); Assert.assertEquals( iList(1, 2, 3), ArrayListIterate.takeWhile(arrayList, Predicates.lessThan(4))); Assert.assertEquals( Interval.fromTo(1, 100), ArrayListIterate.takeWhile(arrayList, Predicates.lessThan(1000))); Assert.assertEquals( iList(), ArrayListIterate.takeWhile(arrayList, Predicates.lessThan(0))); } @Test public void drop() { ArrayList<Integer> list = this.getIntegerList(); MutableList<Integer> expected = FastList.newList(list); Verify.assertListsEqual(expected.drop(0), ArrayListIterate.drop(list, 0)); Verify.assertListsEqual(expected.drop(1), ArrayListIterate.drop(list, 1)); Verify.assertListsEqual(expected.drop(2), ArrayListIterate.drop(list, 2)); Verify.assertListsEqual(expected.drop(5), ArrayListIterate.drop(list, 5)); Verify.assertListsEqual(expected.drop(6), ArrayListIterate.drop(list, 6)); Verify.assertListsEqual(expected.drop(list.size() - 1), ArrayListIterate.drop(list, list.size() - 1)); Verify.assertListsEqual(expected.drop(list.size()), ArrayListIterate.drop(list, list.size())); Verify.assertListsEqual(FastList.newList(), ArrayListIterate.drop(new ArrayList<>(), 2)); Verify.assertListsEqual(expected.drop(Integer.MAX_VALUE), ArrayListIterate.drop(list, Integer.MAX_VALUE)); ArrayList<Integer> list1 = new ArrayList<>(); list1.addAll(Interval.oneTo(120)); Verify.assertListsEqual(FastList.newList(list1).drop(100), ArrayListIterate.drop(list1, 100)); Verify.assertListsEqual(FastList.newList(list1).drop(125), ArrayListIterate.drop(list1, 125)); Verify.assertListsEqual(FastList.newList(list1).drop(Integer.MAX_VALUE), ArrayListIterate.drop(list1, Integer.MAX_VALUE)); } @Test(expected = IllegalArgumentException.class) public void drop_throws() { ArrayListIterate.drop(this.getIntegerList(), -1); } @Test public void drop_target() { ArrayList<Integer> list = this.getIntegerList(); MutableList<Integer> integers1 = FastList.newList(list); MutableList<Integer> expected1 = FastList.newListWith(-1); expected1.addAll(integers1.drop(2)); Verify.assertListsEqual(expected1, ArrayListIterate.drop(list, 2, FastList.newListWith(-1))); MutableList<Integer> expected2 = FastList.newListWith(-1); expected2.addAll(integers1.drop(5)); Verify.assertListsEqual(expected2, ArrayListIterate.drop(list, 5, FastList.newListWith(-1))); MutableList<Integer> expected3 = FastList.newListWith(-1); expected3.addAll(integers1.drop(6)); Verify.assertListsEqual(expected3, ArrayListIterate.drop(list, 6, FastList.newListWith(-1))); MutableList<Integer> expected4 = FastList.newListWith(-1); expected4.addAll(integers1.drop(0)); Verify.assertListsEqual(expected4, ArrayListIterate.drop(list, 0, FastList.newListWith(-1))); MutableList<Integer> expected5 = FastList.newListWith(-1); expected5.addAll(integers1.drop(Integer.MAX_VALUE)); Verify.assertListsEqual(expected5, ArrayListIterate.drop(list, Integer.MAX_VALUE, FastList.newListWith(-1))); Verify.assertListsEqual(FastList.newListWith(-1), ArrayListIterate.drop(new ArrayList<>(), 2, FastList.newListWith(-1))); ArrayList<Integer> list2 = new ArrayList<>(); list2.addAll(Interval.oneTo(125)); FastList<Integer> integers2 = FastList.newList(list2); MutableList<Integer> expected6 = FastList.newListWith(-1); expected6.addAll(integers2.drop(120)); Verify.assertListsEqual(expected6, ArrayListIterate.drop(list2, 120, FastList.newListWith(-1))); MutableList<Integer> expected7 = FastList.newListWith(-1); expected7.addAll(integers2.drop(125)); Verify.assertListsEqual(expected7, ArrayListIterate.drop(list2, 125, FastList.newListWith(-1))); Verify.assertListsEqual(FastList.newListWith(-1), ArrayListIterate.drop(list2, Integer.MAX_VALUE, FastList.newListWith(-1))); } @Test(expected = IllegalArgumentException.class) public void drop_target_throws() { ArrayListIterate.drop(this.getIntegerList(), -1, FastList.newList()); } @Test public void dropWhile_small() { ArrayList<Integer> arrayList = new ArrayList<>(Interval.oneTo(100)); Assert.assertEquals( Interval.fromTo(4, 100), ArrayListIterate.dropWhile(arrayList, Predicates.lessThan(4))); Assert.assertEquals( iList(), ArrayListIterate.dropWhile(arrayList, Predicates.lessThan(1000))); Assert.assertEquals( Interval.fromTo(1, 100), ArrayListIterate.dropWhile(arrayList, Predicates.lessThan(0))); } @Test public void partitionWhile_small() { ArrayList<Integer> arrayList = new ArrayList<>(Interval.oneTo(100)); PartitionMutableList<Integer> partition1 = ArrayListIterate.partitionWhile(arrayList, Predicates.lessThan(4)); Assert.assertEquals(iList(1, 2, 3), partition1.getSelected()); Assert.assertEquals(Interval.fromTo(4, 100), partition1.getRejected()); PartitionMutableList<Integer> partition2 = ArrayListIterate.partitionWhile(arrayList, Predicates.lessThan(0)); Assert.assertEquals(iList(), partition2.getSelected()); Assert.assertEquals(Interval.fromTo(1, 100), partition2.getRejected()); PartitionMutableList<Integer> partition3 = ArrayListIterate.partitionWhile(arrayList, Predicates.lessThan(1000)); Assert.assertEquals(Interval.fromTo(1, 100), partition3.getSelected()); Assert.assertEquals(iList(), partition3.getRejected()); } @Test public void takeWhile() { ArrayList<Integer> arrayList = new ArrayList<>(Interval.oneTo(101)); Assert.assertEquals( iList(1, 2, 3), ArrayListIterate.takeWhile(arrayList, Predicates.lessThan(4))); Assert.assertEquals( Interval.fromTo(1, 101), ArrayListIterate.takeWhile(arrayList, Predicates.lessThan(1000))); Assert.assertEquals( iList(), ArrayListIterate.takeWhile(arrayList, Predicates.lessThan(0))); } @Test public void dropWhile() { ArrayList<Integer> arrayList = new ArrayList<>(Interval.oneTo(101)); Assert.assertEquals( Interval.fromTo(4, 101), ArrayListIterate.dropWhile(arrayList, Predicates.lessThan(4))); Assert.assertEquals( iList(), ArrayListIterate.dropWhile(arrayList, Predicates.lessThan(1000))); Assert.assertEquals( Interval.fromTo(1, 101), ArrayListIterate.dropWhile(arrayList, Predicates.lessThan(0))); } @Test public void partitionWhile() { ArrayList<Integer> arrayList = new ArrayList<>(Interval.oneTo(101)); PartitionMutableList<Integer> partition1 = ArrayListIterate.partitionWhile(arrayList, Predicates.lessThan(4)); Assert.assertEquals(iList(1, 2, 3), partition1.getSelected()); Assert.assertEquals(Interval.fromTo(4, 101), partition1.getRejected()); PartitionMutableList<Integer> partition2 = ArrayListIterate.partitionWhile(arrayList, Predicates.lessThan(0)); Assert.assertEquals(iList(), partition2.getSelected()); Assert.assertEquals(Interval.fromTo(1, 101), partition2.getRejected()); PartitionMutableList<Integer> partition3 = ArrayListIterate.partitionWhile(arrayList, Predicates.lessThan(1000)); Assert.assertEquals(Interval.fromTo(1, 101), partition3.getSelected()); Assert.assertEquals(iList(), partition3.getRejected()); } private ArrayList<Integer> newArrayList(Integer... items) { return new ArrayList<>(mList(items)); } private ThisIsNotAnArrayList<Integer> newNotAnArrayList(Integer... items) { return new ThisIsNotAnArrayList<>(mList(items)); } @Test public void groupByWithOptimisedList() { ArrayList<Integer> list = new ArrayList<>(Interval.toReverseList(1, 105)); MutableMultimap<String, Integer> target = new FastListMultimap<>(); MutableMultimap<String, Integer> result = ArrayListIterate.groupBy(list, String::valueOf, target); Assert.assertEquals(result.get("105"), FastList.newListWith(105)); } @Test public void groupByEachWithOptimisedList() { ArrayList<Integer> list = new ArrayList<>(Interval.toReverseList(1, 105)); Function<Integer, Iterable<String>> function = object -> FastList.newListWith(object.toString(), object.toString() + '*'); MutableMultimap<String, Integer> target = new FastListMultimap<>(); MutableMultimap<String, Integer> result = ArrayListIterate.groupByEach(list, function, target); Assert.assertEquals(result.get("105"), FastList.newListWith(105)); Assert.assertEquals(result.get("105*"), FastList.newListWith(105)); } @Test public void groupByUniqueKeyWithOptimisedList() { ArrayList<Integer> list1 = new ArrayList<>(Interval.toReverseList(1, 3)); Assert.assertEquals( UnifiedMap.newWithKeysValues(1, 1, 2, 2, 3, 3), ArrayListIterate.groupByUniqueKey(list1, id -> id)); ArrayList<Integer> list2 = new ArrayList<>(Interval.toReverseList(1, 105)); Assert.assertEquals( Lists.mutable.ofAll(list2).groupByUniqueKey(id -> id), ArrayListIterate.groupByUniqueKey(list2, id -> id)); } @Test(expected = IllegalArgumentException.class) public void groupByUniqueKey_throws_for_null() { ArrayListIterate.groupByUniqueKey(null, id -> id); } @Test(expected = IllegalStateException.class) public void groupByUniqueKeyUniqueKey_throws_for_duplicate() { ArrayList<Integer> list = new ArrayList<>(Interval.toReverseList(1, 105)); list.add(2); ArrayListIterate.groupByUniqueKey(list, id -> id); } @Test public void groupByUniqueKeyWithOptimisedList_target() { ArrayList<Integer> list1 = new ArrayList<>(Interval.toReverseList(1, 3)); Assert.assertEquals( UnifiedMap.newWithKeysValues(0, 0, 1, 1, 2, 2, 3, 3), ArrayListIterate.groupByUniqueKey(list1, id -> id, UnifiedMap.newWithKeysValues(0, 0))); ArrayList<Integer> list2 = new ArrayList<>(Interval.toReverseList(1, 105)); Assert.assertEquals( Lists.mutable.ofAll(list2).groupByUniqueKey(id -> id, UnifiedMap.newWithKeysValues(0, 0)), ArrayListIterate.groupByUniqueKey(list2, id -> id, UnifiedMap.newWithKeysValues(0, 0))); } @Test(expected = IllegalArgumentException.class) public void groupByUniqueKey_target_throws_for_null() { ArrayListIterate.groupByUniqueKey(null, id -> id, UnifiedMap.newWithKeysValues(0, 0)); } @Test(expected = IllegalStateException.class) public void groupByUniqueKeyUniqueKey_target_throws_for_duplicate() { ArrayList<Integer> list = new ArrayList<>(Interval.toReverseList(1, 105)); ArrayListIterate.groupByUniqueKey(list, id -> id, UnifiedMap.newWithKeysValues(2, 2)); } @Test public void flattenWithOptimisedArrays() { ArrayList<Integer> list = new ArrayList<>(Interval.toReverseList(1, 105)); ArrayList<Integer> result = ArrayListIterate.flatCollect(list, new CollectionWrappingFunction<>(), new ArrayList<>()); Assert.assertEquals(105, result.get(0).intValue()); } private static class CollectionWrappingFunction<T> implements Function<T, Collection<T>> { private static final long serialVersionUID = 1L; @Override public Collection<T> valueOf(T value) { return FastList.newListWith(value); } } @Test public void classIsNonInstantiable() { Verify.assertClassNonInstantiable(ArrayListIterate.class); } }
apache-2.0
aragozin/jvm-tools
sjk-stacktrace/src/main/java/org/gridkit/jvmtool/stacktrace/CounterCollection.java
183
package org.gridkit.jvmtool.stacktrace; public interface CounterCollection extends Iterable<String> { public long getValue(String key); public CounterCollection clone(); }
apache-2.0
bigsuperangel/AutoCreate
autopath/template/project/jsp/${keyUpperFirst}Controller.java
1830
package com.jflyfox.modules.@{crud.urlKey}; import com.jflyfox.jfinal.base.BaseController; import com.jflyfox.jfinal.component.db.SQLUtils; import com.jfinal.plugin.activerecord.Page; /** * @{crud.table.remarks} * * @author flyfox 2014-4-24 */ public class @{strutils.toUpperCaseFirst(crud.urlKey)}Controller extends BaseController { private static final String path = "/pages/@{crud.urlKey}/@{crud.urlKey}_"; public void list() { @{crud.table.className} model = getModelByAttr(@{crud.table.className}.class); SQLUtils sql = new SQLUtils(" from @{crud.table.tableName} t where 1=1 "); if (model.getAttrValues().length != 0) { sql.setAlias("t"); // 查询条件 } Page<@{crud.table.className}> page = @{crud.table.className}.dao.paginate(getPaginator(), "select t.* ", // sql.toString().toString()); // 下拉框 setAttr("page", page); setAttr("attr", model); render(path + "list.html"); } public void add() { render(path + "add.html"); } public void view() { @{crud.table.className} model = @{crud.table.className}.dao.findById(getParaToInt()); setAttr("model", model); render(path + "view.html"); } public void delete() { @{crud.table.className}.dao.deleteById(getParaToInt()); list(); } public void edit() { @{crud.table.className} model = @{crud.table.className}.dao.findById(getParaToInt()); setAttr("model", model); render(path + "edit.html"); } public void save() { Integer pid = getParaToInt(); @{crud.table.className} model = getModel(@{crud.table.className}.class); if (pid != null && pid > 0) { // 更新 model.update(); } else { // 新增 model.remove("@{crud.primaryKey}"); model.put("create_id", getSessionUser().getUserID()); model.put("create_time", getNow()); model.save(); } renderMessage("保存成功"); } }
apache-2.0
suogongy/jsqlparser
src/main/java/net/sf/jsqlparser/expression/SignedExpression.java
1684
/* * #%L * JSQLParser library * %% * Copyright (C) 2004 - 2013 JSQLParser * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ package net.sf.jsqlparser.expression; /** * It represents a "-" or "+" before an expression */ public class SignedExpression implements Expression { private char sign; private Expression expression; public SignedExpression(char sign, Expression expression) { setSign(sign); setExpression(expression); } public char getSign() { return sign; } public final void setSign(char sign) { this.sign = sign; if (sign != '+' && sign != '-') { throw new IllegalArgumentException("illegal sign character, only + - allowed"); } } public Expression getExpression() { return expression; } public final void setExpression(Expression expression) { this.expression = expression; } @Override public void accept(ExpressionVisitor expressionVisitor) { expressionVisitor.visit(this); } @Override public String toString() { return getSign() + expression.toString(); } }
apache-2.0
gucce/citrus
modules/citrus-mail/src/main/java/com/consol/citrus/mail/config/annotation/MailServerConfig.java
1919
/* * Copyright 2006-2016 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 com.consol.citrus.mail.config.annotation; import com.consol.citrus.annotations.CitrusEndpointConfig; import java.lang.annotation.*; /** * @author Christoph Deppisch * @since 2.5 */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD }) @CitrusEndpointConfig(qualifier = "endpoint.parser.mail.server") public @interface MailServerConfig { /** * Port. * @return */ int port() default 25; /** * Auto accept. * @return */ boolean autoAccept() default true; /** * Split multipart messages. * @return */ boolean splitMultipart() default false; /** * Mail marshaller. * @return */ String marshaller() default ""; /** * Java mail properties. * @return */ String javaMailProperties() default ""; /** * Message converter. * @return */ String messageConverter() default ""; /** * Auto start. * @return */ boolean autoStart() default false; /** * Endpoint adapter reference. * @return */ String endpointAdapter() default ""; /** * Timeout. * @return */ long timeout() default 5000L; /** * Test actor. * @return */ String actor() default ""; }
apache-2.0
ionutbarau/petstore
petstore-app/src/main/resources/static/node_modules/fsevents/node_modules/sshpk/lib/key.js
8153
// Copyright 2015 Joyent, Inc. module.exports = Key; var assert = require('assert-plus'); var algs = require('./algs'); var crypto = require('crypto'); var Fingerprint = require('./fingerprint'); var Signature = require('./signature'); var DiffieHellman = require('./dhe'); var errs = require('./errors'); var utils = require('./utils'); var PrivateKey = require('./private-key'); var edCompat; try { edCompat = require('./ed-compat'); } catch (e) { /* Just continue through, and bail out if we try to use it. */ } var InvalidAlgorithmError = errs.InvalidAlgorithmError; var KeyParseError = errs.KeyParseError; var formats = {}; formats['auto'] = require('./formats/auto'); formats['pem'] = require('./formats/pem'); formats['pkcs1'] = require('./formats/pkcs1'); formats['pkcs8'] = require('./formats/pkcs8'); formats['rfc4253'] = require('./formats/rfc4253'); formats['ssh'] = require('./formats/ssh'); formats['ssh-private'] = require('./formats/ssh-private'); formats['openssh'] = formats['ssh-private']; function Key(opts) { assert.object(opts, 'options'); assert.arrayOfObject(opts.parts, 'options.parts'); assert.string(opts.type, 'options.type'); assert.optionalString(opts.comment, 'options.comment'); var algInfo = algs.info[opts.type]; if (typeof (algInfo) !== 'object') throw (new InvalidAlgorithmError(opts.type)); var partLookup = {}; for (var i = 0; i < opts.parts.length; ++i) { var part = opts.parts[i]; partLookup[part.name] = part; } this.type = opts.type; this.parts = opts.parts; this.part = partLookup; this.comment = undefined; this.source = opts.source; /* for speeding up hashing/fingerprint operations */ this._rfc4253Cache = opts._rfc4253Cache; this._hashCache = {}; var sz; this.curve = undefined; if (this.type === 'ecdsa') { var curve = this.part.curve.data.toString(); this.curve = curve; sz = algs.curves[curve].size; } else if (this.type === 'ed25519') { sz = 256; this.curve = 'curve25519'; } else { var szPart = this.part[algInfo.sizePart]; sz = szPart.data.length; sz = sz * 8 - utils.countZeros(szPart.data); } this.size = sz; } Key.formats = formats; Key.prototype.toBuffer = function (format, options) { if (format === undefined) format = 'ssh'; assert.string(format, 'format'); assert.object(formats[format], 'formats[format]'); assert.optionalObject(options, 'options'); if (format === 'rfc4253') { if (this._rfc4253Cache === undefined) this._rfc4253Cache = formats['rfc4253'].write(this); return (this._rfc4253Cache); } return (formats[format].write(this, options)); }; Key.prototype.toString = function (format, options) { return (this.toBuffer(format, options).toString()); }; Key.prototype.hash = function (algo) { assert.string(algo, 'algorithm'); algo = algo.toLowerCase(); if (algs.hashAlgs[algo] === undefined) throw (new InvalidAlgorithmError(algo)); if (this._hashCache[algo]) return (this._hashCache[algo]); var hash = crypto.createHash(algo).update(this.toBuffer('rfc4253')).digest(); this._hashCache[algo] = hash; return (hash); }; Key.prototype.fingerprint = function (algo) { if (algo === undefined) algo = 'sha256'; assert.string(algo, 'algorithm'); var opts = { type: 'key', hash: this.hash(algo), algorithm: algo }; return (new Fingerprint(opts)); }; Key.prototype.defaultHashAlgorithm = function () { var hashAlgo = 'sha1'; if (this.type === 'rsa') hashAlgo = 'sha256'; if (this.type === 'dsa' && this.size > 1024) hashAlgo = 'sha256'; if (this.type === 'ed25519') hashAlgo = 'sha512'; if (this.type === 'ecdsa') { if (this.size <= 256) hashAlgo = 'sha256'; else if (this.size <= 384) hashAlgo = 'sha384'; else hashAlgo = 'sha512'; } return (hashAlgo); }; Key.prototype.createVerify = function (hashAlgo) { if (hashAlgo === undefined) hashAlgo = this.defaultHashAlgorithm(); assert.string(hashAlgo, 'hash algorithm'); /* ED25519 is not supported by OpenSSL, use a javascript impl. */ if (this.type === 'ed25519' && edCompat !== undefined) return (new edCompat.Verifier(this, hashAlgo)); if (this.type === 'curve25519') throw (new Error('Curve25519 keys are not suitable for ' + 'signing or verification')); var v, nm, err; try { nm = hashAlgo.toUpperCase(); v = crypto.createVerify(nm); } catch (e) { err = e; } if (v === undefined || (err instanceof Error && err.message.match(/Unknown message digest/))) { nm = 'RSA-'; nm += hashAlgo.toUpperCase(); v = crypto.createVerify(nm); } assert.ok(v, 'failed to create verifier'); var oldVerify = v.verify.bind(v); var key = this.toBuffer('pkcs8'); var self = this; v.verify = function (signature, fmt) { if (Signature.isSignature(signature, [2, 0])) { if (signature.type !== self.type) return (false); if (signature.hashAlgorithm && signature.hashAlgorithm !== hashAlgo) return (false); return (oldVerify(key, signature.toBuffer('asn1'))); } else if (typeof (signature) === 'string' || Buffer.isBuffer(signature)) { return (oldVerify(key, signature, fmt)); /* * Avoid doing this on valid arguments, walking the prototype * chain can be quite slow. */ } else if (Signature.isSignature(signature, [1, 0])) { throw (new Error('signature was created by too old ' + 'a version of sshpk and cannot be verified')); } else { throw (new TypeError('signature must be a string, ' + 'Buffer, or Signature object')); } }; return (v); }; Key.prototype.createDiffieHellman = function () { if (this.type === 'rsa') throw (new Error('RSA keys do not support Diffie-Hellman')); return (new DiffieHellman(this)); }; Key.prototype.createDH = Key.prototype.createDiffieHellman; Key.parse = function (data, format, options) { if (typeof (data) !== 'string') assert.buffer(data, 'data'); if (format === undefined) format = 'auto'; assert.string(format, 'format'); if (typeof (options) === 'string') options = {filename: options}; assert.optionalObject(options, 'options'); if (options === undefined) options = {}; assert.optionalString(options.filename, 'options.filename'); if (options.filename === undefined) options.filename = '(unnamed)'; assert.object(formats[format], 'formats[format]'); try { var k = formats[format].read(data, options); if (k instanceof PrivateKey) k = k.toPublic(); if (!k.comment) k.comment = options.filename; return (k); } catch (e) { if (e.name === 'KeyEncryptedError') throw (e); throw (new KeyParseError(options.filename, format, e)); } }; Key.isKey = function (obj, ver) { return (utils.isCompatible(obj, Key, ver)); }; /* * API versions for Key: * [1,0] -- initial ver, may take Signature for createVerify or may not * [1,1] -- added pkcs1, pkcs8 formats * [1,2] -- added auto, ssh-private, openssh formats * [1,3] -- added defaultHashAlgorithm * [1,4] -- added ed support, createDH * [1,5] -- first explicitly tagged version */ Key.prototype._sshpkApiVersion = [1, 5]; Key._oldVersionDetect = function (obj) { assert.func(obj.toBuffer); assert.func(obj.fingerprint); if (obj.createDH) return ([1, 4]); if (obj.defaultHashAlgorithm) return ([1, 3]); if (obj.formats['auto']) return ([1, 2]); if (obj.formats['pkcs1']) return ([1, 1]); return ([1, 0]); };
apache-2.0
PriceLab/snapr
SNAPLib/exit.cpp
405
/*++ Module Name: exit.cpp Abstract: SNAP soft exit function Authors: Bill Bolosky, February, 2013 Environment: User mode service. Revision History: --*/ #include "stdafx.h" #include "exit.h" void soft_exit_function(int n, const char *fileName, int lineNum) { fprintf(stderr,"SNAP exited with exit code %d from line %d of file %s\n", n, lineNum, fileName); exit(n); }
apache-2.0
yugangw-msft/azure-sdk-for-net
sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpConsumer.cs
22463
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Globalization; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using Azure.Core; using Azure.Core.Diagnostics; using Azure.Messaging.EventHubs.Consumer; using Azure.Messaging.EventHubs.Core; using Azure.Messaging.EventHubs.Diagnostics; using Microsoft.Azure.Amqp; namespace Azure.Messaging.EventHubs.Amqp { /// <summary> /// A transport client abstraction responsible for brokering operations for AMQP-based connections. /// It is intended that the public <see cref="EventHubConsumerClient" /> make use of an instance /// via containment and delegate operations to it. /// </summary> /// /// <seealso cref="Azure.Messaging.EventHubs.Core.TransportConsumer" /> /// internal class AmqpConsumer : TransportConsumer { /// <summary>The default prefetch count to use for the consumer.</summary> private const uint DefaultPrefetchCount = 300; /// <summary>An empty set of events which can be dispatched when no events are available.</summary> private static readonly IReadOnlyList<EventData> EmptyEventSet = Array.Empty<EventData>(); /// <summary>Indicates whether or not this instance has been closed.</summary> private volatile bool _closed; /// <summary> /// Indicates whether or not this consumer has been closed. /// </summary> /// /// <value> /// <c>true</c> if the consumer is closed; otherwise, <c>false</c>. /// </value> /// public override bool IsClosed => _closed; /// <summary> /// The name of the Event Hub to which the client is bound. /// </summary> /// private string EventHubName { get; } /// <summary> /// The name of the consumer group that this consumer is associated with. Events will be read /// only in the context of this group. /// </summary> /// private string ConsumerGroup { get; } /// <summary> /// The identifier of the Event Hub partition that this consumer is associated with. Events will be read /// only from this partition. /// </summary> /// private string PartitionId { get; } /// <summary> /// The current position for the consumer, updated as events are received from the /// partition. /// </summary> /// /// <remarks> /// When creating or recovering the associated AMQP link, this value is used /// to set the position. It is intended to primarily support recreating links /// transparently to callers, allowing progress in the stream to be remembered. /// </remarks> /// private EventPosition CurrentEventPosition { get; set; } /// <summary> /// Indicates whether or not the consumer should request information on the last enqueued event on the partition /// associated with a given event, and track that information as events are received. /// </summary> /// /// <value><c>true</c> if information about a partition's last event should be requested and tracked; otherwise, <c>false</c>.</value> /// private bool TrackLastEnqueuedEventProperties { get; } /// <summary> /// The policy to use for determining retry behavior for when an operation fails. /// </summary> /// private EventHubsRetryPolicy RetryPolicy { get; } /// <summary> /// The converter to use for translating between AMQP messages and client library /// types. /// </summary> /// private AmqpMessageConverter MessageConverter { get; } /// <summary> /// The AMQP connection scope responsible for managing transport constructs for this instance. /// </summary> /// private AmqpConnectionScope ConnectionScope { get; } /// <summary> /// The AMQP link intended for use with receiving operations. /// </summary> /// private FaultTolerantAmqpObject<ReceivingAmqpLink> ReceiveLink { get; } /// <summary> /// Initializes a new instance of the <see cref="AmqpConsumer"/> class. /// </summary> /// /// <param name="eventHubName">The name of the Event Hub from which events will be consumed.</param> /// <param name="consumerGroup">The name of the consumer group this consumer is associated with. Events are read in the context of this group.</param> /// <param name="partitionId">The identifier of the Event Hub partition from which events will be received.</param> /// <param name="eventPosition">The position of the event in the partition where the consumer should begin reading.</param> /// <param name="prefetchCount">Controls the number of events received and queued locally without regard to whether an operation was requested. If <c>null</c> a default will be used.</param> /// <param name="prefetchSizeInBytes">The cache size of the prefetch queue. When set, the link makes a best effort to ensure prefetched messages fit into the specified size.</param> /// <param name="ownerLevel">The relative priority to associate with the link; for a non-exclusive link, this value should be <c>null</c>.</param> /// <param name="trackLastEnqueuedEventProperties">Indicates whether information on the last enqueued event on the partition is sent as events are received.</param> /// <param name="connectionScope">The AMQP connection context for operations .</param> /// <param name="messageConverter">The converter to use for translating between AMQP messages and client types.</param> /// <param name="retryPolicy">The retry policy to consider when an operation fails.</param> /// /// <remarks> /// As an internal type, this class performs only basic sanity checks against its arguments. It /// is assumed that callers are trusted and have performed deep validation. /// /// Any parameters passed are assumed to be owned by this instance and safe to mutate or dispose; /// creation of clones or otherwise protecting the parameters is assumed to be the purview of the /// caller. /// </remarks> /// public AmqpConsumer(string eventHubName, string consumerGroup, string partitionId, EventPosition eventPosition, bool trackLastEnqueuedEventProperties, long? ownerLevel, uint? prefetchCount, long? prefetchSizeInBytes, AmqpConnectionScope connectionScope, AmqpMessageConverter messageConverter, EventHubsRetryPolicy retryPolicy) { Argument.AssertNotNullOrEmpty(eventHubName, nameof(eventHubName)); Argument.AssertNotNullOrEmpty(consumerGroup, nameof(consumerGroup)); Argument.AssertNotNullOrEmpty(partitionId, nameof(partitionId)); Argument.AssertNotNull(connectionScope, nameof(connectionScope)); Argument.AssertNotNull(messageConverter, nameof(messageConverter)); Argument.AssertNotNull(retryPolicy, nameof(retryPolicy)); EventHubName = eventHubName; ConsumerGroup = consumerGroup; PartitionId = partitionId; CurrentEventPosition = eventPosition; TrackLastEnqueuedEventProperties = trackLastEnqueuedEventProperties; ConnectionScope = connectionScope; RetryPolicy = retryPolicy; MessageConverter = messageConverter; ReceiveLink = new FaultTolerantAmqpObject<ReceivingAmqpLink>( timeout => CreateConsumerLinkAsync( consumerGroup, partitionId, CurrentEventPosition, prefetchCount ?? DefaultPrefetchCount, prefetchSizeInBytes, ownerLevel, trackLastEnqueuedEventProperties, timeout, CancellationToken.None), link => { link.Session?.SafeClose(); link.SafeClose(); }); } /// <summary> /// Receives a batch of <see cref="EventData" /> from the Event Hub partition. /// </summary> /// /// <param name="maximumEventCount">The maximum number of messages to receive in this batch.</param> /// <param name="maximumWaitTime">The maximum amount of time to wait for events to become available, if no events can be read from the prefetch queue. If not specified, the per-try timeout specified by the retry policy will be used.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>The batch of <see cref="EventData" /> from the Event Hub partition this consumer is associated with. If no events are present, an empty set is returned.</returns> /// /// <remarks> /// When events are available in the prefetch queue, they will be used to form the batch as quickly as possible without waiting for additional events from the /// Event Hubs service to try and meet the requested <paramref name="maximumEventCount" />. When no events are available in prefetch, the receiver will wait up /// to the <paramref name="maximumWaitTime"/> for events to be read from the service. Once any events are available, they will be used to form the batch immediately. /// </remarks> /// public override async Task<IReadOnlyList<EventData>> ReceiveAsync(int maximumEventCount, TimeSpan? maximumWaitTime, CancellationToken cancellationToken) { Argument.AssertNotClosed(_closed, nameof(AmqpConsumer)); Argument.AssertAtLeast(maximumEventCount, 1, nameof(maximumEventCount)); var receivedEventCount = 0; var failedAttemptCount = 0; var tryTimeout = RetryPolicy.CalculateTryTimeout(0); var waitTime = (maximumWaitTime ?? tryTimeout); var operationId = Guid.NewGuid().ToString("D", CultureInfo.InvariantCulture); var link = default(ReceivingAmqpLink); var retryDelay = default(TimeSpan?); var amqpMessages = default(IEnumerable<AmqpMessage>); var receivedEvents = default(List<EventData>); var lastReceivedEvent = default(EventData); var stopWatch = ValueStopwatch.StartNew(); try { while ((!cancellationToken.IsCancellationRequested) && (!_closed)) { try { // Creation of the link happens without explicit knowledge of the cancellation token // used for this operation; validate the token state before attempting link creation and // again after the operation completes to provide best efforts in respecting it. EventHubsEventSource.Log.EventReceiveStart(EventHubName, ConsumerGroup, PartitionId, operationId); cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); link = await ReceiveLink.GetOrCreateAsync(UseMinimum(ConnectionScope.SessionTimeout, tryTimeout)).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); var messagesReceived = await Task.Factory.FromAsync ( (callback, state) => link.BeginReceiveMessages(maximumEventCount, waitTime, callback, state), (asyncResult) => link.EndReceiveMessages(asyncResult, out amqpMessages), TaskCreationOptions.RunContinuationsAsynchronously ).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); // If event messages were received, then package them for consumption and // return them. if ((messagesReceived) && (amqpMessages != null)) { receivedEvents ??= new List<EventData>(); foreach (AmqpMessage message in amqpMessages) { link.DisposeDelivery(message, true, AmqpConstants.AcceptedOutcome); receivedEvents.Add(MessageConverter.CreateEventFromMessage(message)); message.Dispose(); } receivedEventCount = receivedEvents.Count; if (receivedEventCount > 0) { lastReceivedEvent = receivedEvents[receivedEventCount - 1]; if (lastReceivedEvent.Offset > long.MinValue) { CurrentEventPosition = EventPosition.FromOffset(lastReceivedEvent.Offset, false); } if (TrackLastEnqueuedEventProperties) { LastReceivedEvent = lastReceivedEvent; } } return receivedEvents; } // No events were available. return EmptyEventSet; } catch (EventHubsException ex) when (ex.Reason == EventHubsException.FailureReason.ServiceTimeout) { // Because the timeout specified with the request is intended to be the maximum // amount of time to wait for events, a timeout isn't considered an error condition, // rather a sign that no events were available in the requested period. return EmptyEventSet; } catch (Exception ex) { Exception activeEx = ex.TranslateServiceException(EventHubName); // Determine if there should be a retry for the next attempt; if so enforce the delay but do not quit the loop. // Otherwise, bubble the exception. ++failedAttemptCount; retryDelay = RetryPolicy.CalculateRetryDelay(activeEx, failedAttemptCount); if ((retryDelay.HasValue) && (!ConnectionScope.IsDisposed) && (!_closed) && (!cancellationToken.IsCancellationRequested)) { EventHubsEventSource.Log.EventReceiveError(EventHubName, ConsumerGroup, PartitionId, operationId, activeEx.Message); await Task.Delay(UseMinimum(retryDelay.Value, waitTime.CalculateRemaining(stopWatch.GetElapsedTime())), cancellationToken).ConfigureAwait(false); tryTimeout = RetryPolicy.CalculateTryTimeout(failedAttemptCount); } else if (ex is AmqpException) { ExceptionDispatchInfo.Capture(activeEx).Throw(); } else { throw; } } } // If no value has been returned nor exception thrown by this point, // then cancellation has been requested. throw new TaskCanceledException(); } catch (TaskCanceledException) { throw; } catch (Exception ex) { EventHubsEventSource.Log.EventReceiveError(EventHubName, ConsumerGroup, PartitionId, operationId, ex.Message); throw; } finally { EventHubsEventSource.Log.EventReceiveComplete(EventHubName, ConsumerGroup, PartitionId, operationId, failedAttemptCount, receivedEventCount); } } /// <summary> /// Closes the connection to the transport consumer instance. /// </summary> /// /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// public override async Task CloseAsync(CancellationToken cancellationToken) { if (_closed) { return; } _closed = true; var clientId = GetHashCode().ToString(CultureInfo.InvariantCulture); var clientType = GetType().Name; try { EventHubsEventSource.Log.ClientCloseStart(clientType, EventHubName, clientId); cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); if (ReceiveLink?.TryGetOpenedObject(out var _) == true) { cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); await ReceiveLink.CloseAsync().ConfigureAwait(false); } ReceiveLink?.Dispose(); } catch (Exception ex) { _closed = false; EventHubsEventSource.Log.ClientCloseError(clientType, EventHubName, clientId, ex.Message); throw; } finally { EventHubsEventSource.Log.ClientCloseComplete(clientType, EventHubName, clientId); } } /// <summary> /// Creates the AMQP link to be used for consumer-related operations. /// </summary> /// /// <param name="consumerGroup">The consumer group of the Event Hub to which the link is bound.</param> /// <param name="partitionId">The identifier of the Event Hub partition to which the link is bound.</param> /// <param name="eventStartingPosition">The place within the partition's event stream to begin consuming events.</param> /// <param name="prefetchCount">Controls the number of events received and queued locally without regard to whether an operation was requested.</param> /// <param name="prefetchSizeInBytes">The cache size of the prefetch queue. When set, the link makes a best effort to ensure prefetched messages fit into the specified size.</param> /// <param name="ownerLevel">The relative priority to associate with the link; for a non-exclusive link, this value should be <c>null</c>.</param> /// <param name="trackLastEnqueuedEventProperties">Indicates whether information on the last enqueued event on the partition is sent as events are received.</param> /// <param name="timeout">The timeout to apply when creating the link.</param> /// <param name="cancellationToken">The cancellation token to consider when creating the link.</param> /// /// <returns>The AMQP link to use for consumer-related operations.</returns> /// private async Task<ReceivingAmqpLink> CreateConsumerLinkAsync(string consumerGroup, string partitionId, EventPosition eventStartingPosition, uint prefetchCount, long? prefetchSizeInBytes, long? ownerLevel, bool trackLastEnqueuedEventProperties, TimeSpan timeout, CancellationToken cancellationToken) { var link = default(ReceivingAmqpLink); try { link = await ConnectionScope.OpenConsumerLinkAsync( consumerGroup, partitionId, eventStartingPosition, timeout, prefetchCount, prefetchSizeInBytes, ownerLevel, trackLastEnqueuedEventProperties, cancellationToken).ConfigureAwait(false); } catch (Exception ex) { ExceptionDispatchInfo.Capture(ex.TranslateConnectionCloseDuringLinkCreationException(EventHubName)).Throw(); } return link; } /// <summary> /// Uses the minimum value of the two specified <see cref="TimeSpan" /> instances. /// </summary> /// /// <param name="firstOption">The first option to consider.</param> /// <param name="secondOption">The second option to consider.</param> /// /// <returns>The smaller of the two specified intervals.</returns> /// private static TimeSpan UseMinimum(TimeSpan firstOption, TimeSpan secondOption) => (firstOption < secondOption) ? firstOption : secondOption; } }
apache-2.0
stankovski/azure-sdk-for-net
sdk/iotcentral/Microsoft.Azure.Management.IotCentral/src/Properties/AssemblyInfo.cs
790
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Reflection; using System.Resources; [assembly: AssemblyTitle("Microsoft Azure IotCentral Management Library")] [assembly: AssemblyDescription("Provides management functionality for Microsoft Azure IotCentral Resources.")] [assembly: AssemblyVersion("2.3.0.0")] [assembly: AssemblyFileVersion("2.3.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
apache-2.0
fengshao0907/wasp
lib/ruby/shell/commands/enable.rb
1131
# # Copyright 2010 The Apache Software Foundation # # 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. # module Shell module Commands class Enable < Command def help return <<-EOF Start enable of named table: e.g. "wasp> enable 't1'" EOF end def command(table) format_simple_command do admin.enable(table) end end end end end
apache-2.0
NickrenREN/kubernetes
staging/src/k8s.io/legacy-cloud-providers/gce/gce_annotations.go
4415
/* Copyright 2017 The Kubernetes 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 gce import ( "fmt" "k8s.io/klog" "github.com/GoogleCloudPlatform/k8s-cloud-provider/pkg/cloud" "k8s.io/api/core/v1" ) // LoadBalancerType defines a specific type for holding load balancer types (eg. Internal) type LoadBalancerType string const ( // ServiceAnnotationLoadBalancerType is annotated on a service with type LoadBalancer // dictates what specific kind of GCP LB should be assembled. // Currently, only "internal" is supported. ServiceAnnotationLoadBalancerType = "cloud.google.com/load-balancer-type" // LBTypeInternal is the constant for the official internal type. LBTypeInternal LoadBalancerType = "Internal" // Deprecating the lowercase spelling of Internal. deprecatedTypeInternalLowerCase LoadBalancerType = "internal" // ServiceAnnotationILBBackendShare is annotated on a service with "true" when users // want to share GCP Backend Services for a set of internal load balancers. // ALPHA feature - this may be removed in a future release. ServiceAnnotationILBBackendShare = "alpha.cloud.google.com/load-balancer-backend-share" // This annotation did not correctly specify "alpha", so both annotations will be checked. deprecatedServiceAnnotationILBBackendShare = "cloud.google.com/load-balancer-backend-share" // NetworkTierAnnotationKey is annotated on a Service object to indicate which // network tier a GCP LB should use. The valid values are "Standard" and // "Premium" (default). NetworkTierAnnotationKey = "cloud.google.com/network-tier" // NetworkTierAnnotationStandard is an annotation to indicate the Service is on the Standard network tier NetworkTierAnnotationStandard = cloud.NetworkTierStandard // NetworkTierAnnotationPremium is an annotation to indicate the Service is on the Premium network tier NetworkTierAnnotationPremium = cloud.NetworkTierPremium // NEGAnnotation is an annotation to indicate that the loadbalancer service is using NEGs instead of InstanceGroups NEGAnnotation = "cloud.google.com/neg" ) // GetLoadBalancerAnnotationType returns the type of GCP load balancer which should be assembled. func GetLoadBalancerAnnotationType(service *v1.Service) (LoadBalancerType, bool) { v := LoadBalancerType("") if service.Spec.Type != v1.ServiceTypeLoadBalancer { return v, false } l, ok := service.Annotations[ServiceAnnotationLoadBalancerType] v = LoadBalancerType(l) if !ok { return v, false } switch v { case LBTypeInternal, deprecatedTypeInternalLowerCase: return LBTypeInternal, true default: return v, false } } // GetLoadBalancerAnnotationBackendShare returns whether this service's backend service should be // shared with other load balancers. Health checks and the healthcheck firewall will be shared regardless. func GetLoadBalancerAnnotationBackendShare(service *v1.Service) bool { if l, exists := service.Annotations[ServiceAnnotationILBBackendShare]; exists && l == "true" { return true } // Check for deprecated annotation key if l, exists := service.Annotations[deprecatedServiceAnnotationILBBackendShare]; exists && l == "true" { klog.Warningf("Annotation %q is deprecated and replaced with an alpha-specific key: %q", deprecatedServiceAnnotationILBBackendShare, ServiceAnnotationILBBackendShare) return true } return false } // GetServiceNetworkTier returns the network tier of GCP load balancer // which should be assembled, and an error if the specified tier is not // supported. func GetServiceNetworkTier(service *v1.Service) (cloud.NetworkTier, error) { l, ok := service.Annotations[NetworkTierAnnotationKey] if !ok { return cloud.NetworkTierDefault, nil } v := cloud.NetworkTier(l) switch v { case cloud.NetworkTierStandard: fallthrough case cloud.NetworkTierPremium: return v, nil default: return cloud.NetworkTierDefault, fmt.Errorf("unsupported network tier: %q", v) } }
apache-2.0
nknize/elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/job/process/autodetect/state/ModelSnapshot.java
17185
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.core.ml.job.process.autodetect.state; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.Version; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.xcontent.LoggingDeprecationHandler; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.ObjectParser; import org.elasticsearch.common.xcontent.ObjectParser.ValueType; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.xpack.core.common.time.TimeUtils; import org.elasticsearch.xpack.core.ml.job.config.Job; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Objects; /** * ModelSnapshot Result POJO */ public class ModelSnapshot implements ToXContentObject, Writeable { /** * Field Names */ public static final ParseField TIMESTAMP = new ParseField("timestamp"); public static final ParseField DESCRIPTION = new ParseField("description"); public static final ParseField SNAPSHOT_DOC_COUNT = new ParseField("snapshot_doc_count"); public static final ParseField LATEST_RECORD_TIME = new ParseField("latest_record_time_stamp"); public static final ParseField LATEST_RESULT_TIME = new ParseField("latest_result_time_stamp"); public static final ParseField QUANTILES = new ParseField("quantiles"); public static final ParseField RETAIN = new ParseField("retain"); public static final ParseField MIN_VERSION = new ParseField("min_version"); // Used for QueryPage public static final ParseField RESULTS_FIELD = new ParseField("model_snapshots"); /** * Legacy type, now used only as a discriminant in the document ID */ public static final ParseField TYPE = new ParseField("model_snapshot"); public static final ObjectParser<Builder, Void> STRICT_PARSER = createParser(false); public static final ObjectParser<Builder, Void> LENIENT_PARSER = createParser(true); private static ObjectParser<Builder, Void> createParser(boolean ignoreUnknownFields) { ObjectParser<Builder, Void> parser = new ObjectParser<>(TYPE.getPreferredName(), ignoreUnknownFields, Builder::new); parser.declareString(Builder::setJobId, Job.ID); parser.declareString(Builder::setMinVersion, MIN_VERSION); parser.declareField(Builder::setTimestamp, p -> TimeUtils.parseTimeField(p, TIMESTAMP.getPreferredName()), TIMESTAMP, ValueType.VALUE); parser.declareString(Builder::setDescription, DESCRIPTION); parser.declareString(Builder::setSnapshotId, ModelSnapshotField.SNAPSHOT_ID); parser.declareInt(Builder::setSnapshotDocCount, SNAPSHOT_DOC_COUNT); parser.declareObject(Builder::setModelSizeStats, ignoreUnknownFields ? ModelSizeStats.LENIENT_PARSER : ModelSizeStats.STRICT_PARSER, ModelSizeStats.RESULT_TYPE_FIELD); parser.declareField(Builder::setLatestRecordTimeStamp, p -> TimeUtils.parseTimeField(p, LATEST_RECORD_TIME.getPreferredName()), LATEST_RECORD_TIME, ValueType.VALUE); parser.declareField(Builder::setLatestResultTimeStamp, p -> TimeUtils.parseTimeField(p, LATEST_RESULT_TIME.getPreferredName()), LATEST_RESULT_TIME, ValueType.VALUE); parser.declareObject(Builder::setQuantiles, ignoreUnknownFields ? Quantiles.LENIENT_PARSER : Quantiles.STRICT_PARSER, QUANTILES); parser.declareBoolean(Builder::setRetain, RETAIN); return parser; } public static String EMPTY_SNAPSHOT_ID = "empty"; private final String jobId; /** * The minimum version a node should have to be able * to read this model snapshot. */ private final Version minVersion; /** * This is model snapshot's creation wall clock time. * Use {@code latestResultTimeStamp} if you need model time instead. */ private final Date timestamp; private final String description; private final String snapshotId; private final int snapshotDocCount; private final ModelSizeStats modelSizeStats; private final Date latestRecordTimeStamp; private final Date latestResultTimeStamp; private final Quantiles quantiles; private final boolean retain; private ModelSnapshot(String jobId, Version minVersion, Date timestamp, String description, String snapshotId, int snapshotDocCount, ModelSizeStats modelSizeStats, Date latestRecordTimeStamp, Date latestResultTimeStamp, Quantiles quantiles, boolean retain) { this.jobId = jobId; this.minVersion = minVersion; this.timestamp = timestamp; this.description = description; this.snapshotId = snapshotId; this.snapshotDocCount = snapshotDocCount; this.modelSizeStats = modelSizeStats; this.latestRecordTimeStamp = latestRecordTimeStamp; this.latestResultTimeStamp = latestResultTimeStamp; this.quantiles = quantiles; this.retain = retain; } public ModelSnapshot(StreamInput in) throws IOException { jobId = in.readString(); minVersion = Version.readVersion(in); timestamp = in.readBoolean() ? new Date(in.readVLong()) : null; description = in.readOptionalString(); snapshotId = in.readOptionalString(); snapshotDocCount = in.readInt(); modelSizeStats = in.readOptionalWriteable(ModelSizeStats::new); latestRecordTimeStamp = in.readBoolean() ? new Date(in.readVLong()) : null; latestResultTimeStamp = in.readBoolean() ? new Date(in.readVLong()) : null; quantiles = in.readOptionalWriteable(Quantiles::new); retain = in.readBoolean(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(jobId); Version.writeVersion(minVersion, out); if (timestamp != null) { out.writeBoolean(true); out.writeVLong(timestamp.getTime()); } else { out.writeBoolean(false); } out.writeOptionalString(description); out.writeOptionalString(snapshotId); out.writeInt(snapshotDocCount); out.writeOptionalWriteable(modelSizeStats); if (latestRecordTimeStamp != null) { out.writeBoolean(true); out.writeVLong(latestRecordTimeStamp.getTime()); } else { out.writeBoolean(false); } if (latestResultTimeStamp != null) { out.writeBoolean(true); out.writeVLong(latestResultTimeStamp.getTime()); } else { out.writeBoolean(false); } out.writeOptionalWriteable(quantiles); out.writeBoolean(retain); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(Job.ID.getPreferredName(), jobId); builder.field(MIN_VERSION.getPreferredName(), minVersion); if (timestamp != null) { builder.timeField(TIMESTAMP.getPreferredName(), TIMESTAMP.getPreferredName() + "_string", timestamp.getTime()); } if (description != null) { builder.field(DESCRIPTION.getPreferredName(), description); } if (snapshotId != null) { builder.field(ModelSnapshotField.SNAPSHOT_ID.getPreferredName(), snapshotId); } builder.field(SNAPSHOT_DOC_COUNT.getPreferredName(), snapshotDocCount); if (modelSizeStats != null) { builder.field(ModelSizeStats.RESULT_TYPE_FIELD.getPreferredName(), modelSizeStats); } if (latestRecordTimeStamp != null) { builder.timeField(LATEST_RECORD_TIME.getPreferredName(), LATEST_RECORD_TIME.getPreferredName() + "_string", latestRecordTimeStamp.getTime()); } if (latestResultTimeStamp != null) { builder.timeField(LATEST_RESULT_TIME.getPreferredName(), LATEST_RESULT_TIME.getPreferredName() + "_string", latestResultTimeStamp.getTime()); } if (quantiles != null) { builder.field(QUANTILES.getPreferredName(), quantiles); } builder.field(RETAIN.getPreferredName(), retain); builder.endObject(); return builder; } public String getJobId() { return jobId; } public Version getMinVersion() { return minVersion; } public Date getTimestamp() { return timestamp; } public String getDescription() { return description; } public String getSnapshotId() { return snapshotId; } public int getSnapshotDocCount() { return snapshotDocCount; } public ModelSizeStats getModelSizeStats() { return modelSizeStats; } public Quantiles getQuantiles() { return quantiles; } public Date getLatestRecordTimeStamp() { return latestRecordTimeStamp; } public Date getLatestResultTimeStamp() { return latestResultTimeStamp; } public boolean isRetain() { return retain; } @Override public int hashCode() { return Objects.hash(jobId, minVersion, timestamp, description, snapshotId, quantiles, snapshotDocCount, modelSizeStats, latestRecordTimeStamp, latestResultTimeStamp, retain); } /** * Compare all the fields. */ @Override public boolean equals(Object other) { if (this == other) { return true; } if (other instanceof ModelSnapshot == false) { return false; } ModelSnapshot that = (ModelSnapshot) other; return Objects.equals(this.jobId, that.jobId) && Objects.equals(this.minVersion, that.minVersion) && Objects.equals(this.timestamp, that.timestamp) && Objects.equals(this.description, that.description) && Objects.equals(this.snapshotId, that.snapshotId) && this.snapshotDocCount == that.snapshotDocCount && Objects.equals(this.modelSizeStats, that.modelSizeStats) && Objects.equals(this.quantiles, that.quantiles) && Objects.equals(this.latestRecordTimeStamp, that.latestRecordTimeStamp) && Objects.equals(this.latestResultTimeStamp, that.latestResultTimeStamp) && this.retain == that.retain; } public List<String> stateDocumentIds() { List<String> stateDocumentIds = new ArrayList<>(snapshotDocCount); // The state documents count suffices are 1-based for (int i = 1; i <= snapshotDocCount; i++) { stateDocumentIds.add(ModelState.documentId(jobId, snapshotId, i)); } return stateDocumentIds; } public boolean isTheEmptySnapshot() { return isTheEmptySnapshot(snapshotId); } public static boolean isTheEmptySnapshot(String snapshotId) { return EMPTY_SNAPSHOT_ID.equals(snapshotId); } public static String documentIdPrefix(String jobId) { return jobId + "_" + TYPE + "_"; } public static String annotationDocumentId(ModelSnapshot snapshot) { return "annotation_for_" + documentId(snapshot); } public static String documentId(ModelSnapshot snapshot) { return documentId(snapshot.getJobId(), snapshot.getSnapshotId()); } /** * This is how the IDs were formed in v5.4 */ public static String v54DocumentId(ModelSnapshot snapshot) { return v54DocumentId(snapshot.getJobId(), snapshot.getSnapshotId()); } public static String documentId(String jobId, String snapshotId) { return documentIdPrefix(jobId) + snapshotId; } /** * This is how the IDs were formed in v5.4 */ public static String v54DocumentId(String jobId, String snapshotId) { return jobId + "-" + snapshotId; } public static ModelSnapshot fromJson(BytesReference bytesReference) { try (InputStream stream = bytesReference.streamInput(); XContentParser parser = XContentFactory.xContent(XContentType.JSON) .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, stream)) { return LENIENT_PARSER.apply(parser, null).build(); } catch (IOException e) { throw new ElasticsearchParseException("failed to parse modelSnapshot", e); } } public static class Builder { private String jobId; // Stored snapshot documents created prior to 6.3.0 will have no // value for min_version. private Version minVersion = Version.fromString("6.3.0"); private Date timestamp; private String description; private String snapshotId; private int snapshotDocCount; private ModelSizeStats modelSizeStats; private Date latestRecordTimeStamp; private Date latestResultTimeStamp; private Quantiles quantiles; private boolean retain; public Builder() { } public Builder(String jobId) { this(); this.jobId = jobId; } public Builder(ModelSnapshot modelSnapshot) { this.jobId = modelSnapshot.jobId; this.timestamp = modelSnapshot.timestamp; this.description = modelSnapshot.description; this.snapshotId = modelSnapshot.snapshotId; this.snapshotDocCount = modelSnapshot.snapshotDocCount; this.modelSizeStats = modelSnapshot.modelSizeStats; this.latestRecordTimeStamp = modelSnapshot.latestRecordTimeStamp; this.latestResultTimeStamp = modelSnapshot.latestResultTimeStamp; this.quantiles = modelSnapshot.quantiles; this.retain = modelSnapshot.retain; this.minVersion = modelSnapshot.minVersion; } public Builder setJobId(String jobId) { this.jobId = jobId; return this; } public Builder setMinVersion(Version minVersion) { this.minVersion = minVersion; return this; } public Builder setMinVersion(String minVersion) { this.minVersion = Version.fromString(minVersion); return this; } public Builder setTimestamp(Date timestamp) { this.timestamp = timestamp; return this; } public Builder setDescription(String description) { this.description = description; return this; } public Builder setSnapshotId(String snapshotId) { this.snapshotId = snapshotId; return this; } public Builder setSnapshotDocCount(int snapshotDocCount) { this.snapshotDocCount = snapshotDocCount; return this; } public Builder setModelSizeStats(ModelSizeStats.Builder modelSizeStats) { this.modelSizeStats = modelSizeStats.build(); return this; } public Builder setModelSizeStats(ModelSizeStats modelSizeStats) { this.modelSizeStats = modelSizeStats; return this; } public Builder setLatestRecordTimeStamp(Date latestRecordTimeStamp) { this.latestRecordTimeStamp = latestRecordTimeStamp; return this; } public Builder setLatestResultTimeStamp(Date latestResultTimeStamp) { this.latestResultTimeStamp = latestResultTimeStamp; return this; } public Builder setQuantiles(Quantiles quantiles) { this.quantiles = quantiles; return this; } public Builder setRetain(boolean value) { this.retain = value; return this; } public ModelSnapshot build() { return new ModelSnapshot(jobId, minVersion, timestamp, description, snapshotId, snapshotDocCount, modelSizeStats, latestRecordTimeStamp, latestResultTimeStamp, quantiles, retain); } } public static ModelSnapshot emptySnapshot(String jobId) { return new ModelSnapshot(jobId, Version.CURRENT, new Date(), "empty snapshot", EMPTY_SNAPSHOT_ID, 0, new ModelSizeStats.Builder(jobId).build(), null, null, null, false); } }
apache-2.0
arnotixe/androidbible
Alkitab/src/main/java/yuku/alkitab/base/widget/CallbackSpan.java
726
package yuku.alkitab.base.widget; import android.text.style.ClickableSpan; import android.view.View; public class CallbackSpan<T> extends ClickableSpan { public static interface OnClickListener<T> { void onClick(View widget, T data); } final T data_; private OnClickListener<T> onClickListener_; public CallbackSpan() { data_ = null; } public CallbackSpan(T data, OnClickListener<T> onClickListener) { data_ = data; onClickListener_ = onClickListener; } public void setOnClickListener(OnClickListener<T> onClickListener) { onClickListener_ = onClickListener; } @Override public void onClick(View widget) { if (onClickListener_ != null) { onClickListener_.onClick(widget, data_); } } }
apache-2.0