code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "common/debug.h"
#include "common/memstream.h"
#include "common/stream.h"
#include "audio/midiparser.h"
#include "audio/soundfont/rawfile.h"
#include "audio/soundfont/vab/vab.h"
#include "audio/soundfont/vgmcoll.h"
#include "midimusicplayer.h"
namespace Dragons {
MidiMusicPlayer::MidiMusicPlayer(BigfileArchive *bigFileArchive): _midiDataSize(0) {
_midiData = nullptr;
MidiPlayer::createDriver(MDT_PREFER_FLUID | MDT_MIDI);
if (_driver->acceptsSoundFontData()) {
_driver->setEngineSoundFont(loadSoundFont(bigFileArchive));
} else {
//If the selected driver doesn't support loading soundfont we should assume we got a fluid Synth V1 and reload
delete _driver;
MidiPlayer::createDriver();
}
int ret = _driver->open();
if (ret == 0) {
if (_nativeMT32)
_driver->sendMT32Reset();
else
_driver->sendGMReset();
_driver->setTimerCallback(this, &timerCallback);
}
}
MidiMusicPlayer::~MidiMusicPlayer() {
if (isPlaying()) {
stop();
}
}
void MidiMusicPlayer::playSong(Common::SeekableReadStream *seqData) {
Common::StackLock lock(_mutex);
if (isPlaying()) {
stop();
}
if (seqData->readUint32LE() != MKTAG('S', 'E', 'Q', 'p'))
error("Failed to find SEQp tag");
// Make sure we don't have a SEP file (with multiple SEQ's inside)
if (seqData->readUint32BE() != 1)
error("Can only play SEQ files, not SEP");
uint16 ppqn = seqData->readUint16BE();
uint32 tempo = seqData->readUint16BE() << 8;
tempo |= seqData->readByte();
/* uint16 beat = */ seqData->readUint16BE();
// SEQ is directly based on SMF and we'll use that to our advantage here
// and convert to SMF and then use the SMF MidiParser.
// Calculate the SMF size we'll need
uint32 dataSize = seqData->size() - 15;
uint32 actualSize = dataSize + 7 + 22;
// Resize the buffer if necessary
byte *midiData = resizeMidiBuffer(actualSize);
// Now construct the header
WRITE_BE_UINT32(midiData, MKTAG('M', 'T', 'h', 'd'));
WRITE_BE_UINT32(midiData + 4, 6); // header size
WRITE_BE_UINT16(midiData + 8, 0); // type 0
WRITE_BE_UINT16(midiData + 10, 1); // one track
WRITE_BE_UINT16(midiData + 12, ppqn);
WRITE_BE_UINT32(midiData + 14, MKTAG('M', 'T', 'r', 'k'));
WRITE_BE_UINT32(midiData + 18, dataSize + 7); // SEQ data size + tempo change event size
// Add in a fake tempo change event
WRITE_BE_UINT32(midiData + 22, 0x00FF5103); // no delta, meta event, tempo change, param size = 3
WRITE_BE_UINT16(midiData + 26, tempo >> 8);
midiData[28] = tempo & 0xFF;
// Now copy in the rest of the events
seqData->read(midiData + 29, dataSize);
MidiParser *parser = MidiParser::createParser_SMF();
if (parser->loadMusic(midiData, actualSize)) {
parser->setTrack(0);
parser->setMidiDriver(this);
parser->setTimerRate(getBaseTempo());
parser->property(MidiParser::mpCenterPitchWheelOnUnload, 1);
parser->property(MidiParser::mpSendSustainOffOnNotesOff, 1);
_parser = parser;
_isLooping = true;
_isPlaying = true;
} else {
delete parser;
}
}
byte *MidiMusicPlayer::resizeMidiBuffer(uint32 desiredSize) {
if (_midiData == nullptr) {
_midiData = (byte *)malloc(desiredSize);
_midiDataSize = desiredSize;
} else {
if (desiredSize > _midiDataSize) {
_midiData = (byte *)realloc(_midiData, desiredSize);
_midiDataSize = desiredSize;
}
}
return _midiData;
}
void MidiMusicPlayer::setVolume(int volume) {
// _vm->_mixer->setVolumeForSoundType(Audio::Mixer::kMusicSoundType, volume); TODO do we need this?
MidiPlayer::setVolume(volume);
}
void MidiMusicPlayer::sendToChannel(byte channel, uint32 b) {
if (!_channelsTable[channel]) {
_channelsTable[channel] = (channel == 9) ? _driver->getPercussionChannel() : _driver->allocateChannel();
// If a new channel is allocated during the playback, make sure
// its volume is correctly initialized.
if (_channelsTable[channel])
_channelsTable[channel]->volume(_channelsVolume[channel] * _masterVolume / 255);
}
if (_channelsTable[channel])
_channelsTable[channel]->send(b);
}
Common::SeekableReadStream *MidiMusicPlayer::loadSoundFont(BigfileArchive *bigFileArchive) {
uint32 headSize, bodySize;
byte *headData = bigFileArchive->load("musx.vh", headSize);
byte *bodyData = bigFileArchive->load("musx.vb", bodySize);
byte *vabData = (byte *)malloc(headSize + bodySize);
memcpy(vabData, headData, headSize);
memcpy(vabData + headSize, bodyData, bodySize);
free(headData);
free(bodyData);
MemFile *memFile = new MemFile(vabData, headSize + bodySize);
debug("Loading soundfont2 from musx vab file.");
Vab *vab = new Vab(memFile, 0);
vab->LoadVGMFile();
VGMColl vabCollection;
SF2File *file = vabCollection.CreateSF2File(vab);
const byte *bytes = (const byte *)file->SaveToMem();
uint32 size = file->GetSize();
delete file;
delete vab;
delete memFile;
return new Common::MemoryReadStream(bytes, size, DisposeAfterUse::YES);
}
} // End of namespace Dragons
| vanfanel/scummvm | engines/dragons/midimusicplayer.cpp | C++ | gpl-2.0 | 5,842 |
// PR c++/91353 - P1331R2: Allow trivial default init in constexpr contexts.
// { dg-do compile { target c++20 } }
// In c++2a we don't emit a call to _ZN3FooI3ArgEC1Ev.
struct Arg;
struct Base {
int i;
virtual ~Base();
};
template <class> struct Foo : Base { };
Foo<Arg> a;
| Gurgel100/gcc | gcc/testsuite/g++.dg/cpp2a/constexpr-init10.C | C++ | gpl-2.0 | 280 |
/**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'button', 'sq', {
selectedLabel: '%1 (Përzgjedhur)'
} );
| SeeyaSia/www | web/libraries/ckeditor/plugins/button/lang/sq.js | JavaScript | gpl-2.0 | 246 |
/*
* Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "media/engine/multiplex_codec_factory.h"
#include <map>
#include <string>
#include <utility>
#include "absl/strings/match.h"
#include "api/video_codecs/sdp_video_format.h"
#include "media/base/codec.h"
#include "media/base/media_constants.h"
#include "modules/video_coding/codecs/multiplex/include/multiplex_decoder_adapter.h"
#include "modules/video_coding/codecs/multiplex/include/multiplex_encoder_adapter.h"
#include "rtc_base/logging.h"
namespace {
bool IsMultiplexCodec(const cricket::VideoCodec& codec) {
return absl::EqualsIgnoreCase(codec.name.c_str(),
cricket::kMultiplexCodecName);
}
} // anonymous namespace
namespace webrtc {
constexpr const char* kMultiplexAssociatedCodecName = cricket::kVp9CodecName;
MultiplexEncoderFactory::MultiplexEncoderFactory(
std::unique_ptr<VideoEncoderFactory> factory,
bool supports_augmenting_data)
: factory_(std::move(factory)),
supports_augmenting_data_(supports_augmenting_data) {}
std::vector<SdpVideoFormat> MultiplexEncoderFactory::GetSupportedFormats()
const {
std::vector<SdpVideoFormat> formats = factory_->GetSupportedFormats();
for (const auto& format : formats) {
if (absl::EqualsIgnoreCase(format.name, kMultiplexAssociatedCodecName)) {
SdpVideoFormat multiplex_format = format;
multiplex_format.parameters[cricket::kCodecParamAssociatedCodecName] =
format.name;
multiplex_format.name = cricket::kMultiplexCodecName;
formats.push_back(multiplex_format);
break;
}
}
return formats;
}
std::unique_ptr<VideoEncoder> MultiplexEncoderFactory::CreateVideoEncoder(
const SdpVideoFormat& format) {
if (!IsMultiplexCodec(cricket::VideoCodec(format)))
return factory_->CreateVideoEncoder(format);
const auto& it =
format.parameters.find(cricket::kCodecParamAssociatedCodecName);
if (it == format.parameters.end()) {
RTC_LOG(LS_ERROR) << "No assicated codec for multiplex.";
return nullptr;
}
SdpVideoFormat associated_format = format;
associated_format.name = it->second;
return std::unique_ptr<VideoEncoder>(new MultiplexEncoderAdapter(
factory_.get(), associated_format, supports_augmenting_data_));
}
MultiplexDecoderFactory::MultiplexDecoderFactory(
std::unique_ptr<VideoDecoderFactory> factory,
bool supports_augmenting_data)
: factory_(std::move(factory)),
supports_augmenting_data_(supports_augmenting_data) {}
std::vector<SdpVideoFormat> MultiplexDecoderFactory::GetSupportedFormats()
const {
std::vector<SdpVideoFormat> formats = factory_->GetSupportedFormats();
for (const auto& format : formats) {
if (absl::EqualsIgnoreCase(format.name, kMultiplexAssociatedCodecName)) {
SdpVideoFormat multiplex_format = format;
multiplex_format.parameters[cricket::kCodecParamAssociatedCodecName] =
format.name;
multiplex_format.name = cricket::kMultiplexCodecName;
formats.push_back(multiplex_format);
}
}
return formats;
}
std::unique_ptr<VideoDecoder> MultiplexDecoderFactory::CreateVideoDecoder(
const SdpVideoFormat& format) {
if (!IsMultiplexCodec(cricket::VideoCodec(format)))
return factory_->CreateVideoDecoder(format);
const auto& it =
format.parameters.find(cricket::kCodecParamAssociatedCodecName);
if (it == format.parameters.end()) {
RTC_LOG(LS_ERROR) << "No assicated codec for multiplex.";
return nullptr;
}
SdpVideoFormat associated_format = format;
associated_format.name = it->second;
return std::unique_ptr<VideoDecoder>(new MultiplexDecoderAdapter(
factory_.get(), associated_format, supports_augmenting_data_));
}
} // namespace webrtc
| alexsh/Telegram | TMessagesProj/jni/voip/webrtc/media/engine/multiplex_codec_factory.cc | C++ | gpl-2.0 | 4,111 |
<?php
/**
* @file
* Contains \Drupal\locale\Tests\LocaleConfigTranslationImportTest.
*/
namespace Drupal\locale\Tests;
use Drupal\simpletest\WebTestBase;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\Core\Url;
/**
* Tests translation update's effects on configuration translations.
*
* @group locale
*/
class LocaleConfigTranslationImportTest extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('language', 'update', 'locale_test_translate');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$admin_user = $this->drupalCreateUser(array('administer modules', 'administer site configuration', 'administer languages', 'access administration pages', 'administer permissions'));
$this->drupalLogin($admin_user);
// Update module should not go out to d.o to check for updates. We override
// the url to an invalid update source. No update data will be found.
$this->config('update.settings')->set('fetch.url', (string) Url::fromRoute('<front>', array(), array('absolute' => TRUE)))->save();
}
/**
* Test update changes configuration translations if enabled after language.
*/
public function testConfigTranslationImport() {
// Add a language. The Afrikaans translation file of locale_test_translate
// (test.af.po) has been prepared with a configuration translation.
ConfigurableLanguage::createFromLangcode('af')->save();
// Enable locale module.
$this->container->get('module_installer')->install(array('locale'));
$this->resetAll();
// Enable import of translations. By default this is disabled for automated
// tests.
$this->config('locale.settings')
->set('translation.import_enabled', TRUE)
->save();
// Add translation permissions now that the locale module has been enabled.
$edit = array(
'authenticated[translate interface]' => 'translate interface',
);
$this->drupalPostForm('admin/people/permissions', $edit, t('Save permissions'));
// Check and update the translation status. This will import the Afrikaans
// translations of locale_test_translate module.
$this->drupalGet('admin/reports/translations/check');
// Override the Drupal core translation status to be up to date.
// Drupal core should not be a subject in this test.
$status = locale_translation_get_status();
$status['drupal']['af']->type = 'current';
\Drupal::state()->set('locale.translation_status', $status);
$this->drupalPostForm('admin/reports/translations', array(), t('Update translations'));
// Check if configuration translations have been imported.
$override = \Drupal::languageManager()->getLanguageConfigOverride('af', 'system.maintenance');
$this->assertEqual($override->get('message'), 'Ons is tans besig met onderhoud op @site. Wees asseblief geduldig, ons sal binnekort weer terug wees.');
}
}
| webflo/d8-core | modules/locale/src/Tests/LocaleConfigTranslationImportTest.php | PHP | gpl-2.0 | 2,966 |
/*
* Copyright (c) 2004, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#include <stdlib.h>
#include <string.h>
#include "jni_tools.h"
#include "agent_common.h"
#include "jvmti_tools.h"
#define PASSED 0
#define STATUS_FAILED 2
extern "C" {
/* ========================================================================== */
/* scaffold objects */
static jlong timeout = 0;
/* event counts */
static int ExceptionEventsCount = 0;
static int ExceptionCatchEventsCount = 0;
/* ========================================================================== */
/** callback functions **/
static void JNICALL
Exception(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread,
jmethodID method, jlocation location, jobject exception,
jmethodID catch_method, jlocation catch_location) {
jclass klass = NULL;
char *signature = NULL;
if (!isThreadExpected(jvmti_env, thread)) {
return;
}
ExceptionEventsCount++;
if (!NSK_JNI_VERIFY(jni_env, (klass = jni_env->GetObjectClass(exception)) != NULL)) {
nsk_jvmti_setFailStatus();
return;
}
if (!NSK_JVMTI_VERIFY(jvmti_env->GetClassSignature(klass, &signature, NULL))) {
nsk_jvmti_setFailStatus();
return;
}
NSK_DISPLAY1("Exception event: %s\n", signature);
if (signature != NULL)
jvmti_env->Deallocate((unsigned char*)signature);
}
void JNICALL
ExceptionCatch(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread,
jmethodID method, jlocation location, jobject exception) {
jclass klass = NULL;
char *signature = NULL;
if (!isThreadExpected(jvmti_env, thread)) {
return;
}
ExceptionCatchEventsCount++;
if (!NSK_JNI_VERIFY(jni_env, (klass = jni_env->GetObjectClass(exception)) != NULL)) {
nsk_jvmti_setFailStatus();
return;
}
if (!NSK_JVMTI_VERIFY(jvmti_env->GetClassSignature(klass, &signature, NULL))) {
nsk_jvmti_setFailStatus();
return;
}
NSK_DISPLAY1("ExceptionCatch event: %s\n", signature);
if (signature != NULL)
jvmti_env->Deallocate((unsigned char*)signature);
}
/* ========================================================================== */
/** Agent algorithm. */
static void JNICALL
agentProc(jvmtiEnv* jvmti, JNIEnv* jni, void* arg) {
if (!nsk_jvmti_waitForSync(timeout))
return;
if (!NSK_JVMTI_VERIFY(jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_EXCEPTION, NULL)))
nsk_jvmti_setFailStatus();
if (!NSK_JVMTI_VERIFY(jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_EXCEPTION_CATCH, NULL)))
nsk_jvmti_setFailStatus();
/* resume debugee and wait for sync */
if (!nsk_jvmti_resumeSync())
return;
if (!nsk_jvmti_waitForSync(timeout))
return;
if (!NSK_JVMTI_VERIFY(jvmti->SetEventNotificationMode(JVMTI_DISABLE, JVMTI_EVENT_EXCEPTION, NULL)))
nsk_jvmti_setFailStatus();
if (!NSK_JVMTI_VERIFY(jvmti->SetEventNotificationMode(JVMTI_DISABLE, JVMTI_EVENT_EXCEPTION_CATCH, NULL)))
nsk_jvmti_setFailStatus();
NSK_DISPLAY1("Exception events received: %d\n",
ExceptionEventsCount);
if (!NSK_VERIFY(ExceptionEventsCount == 3))
nsk_jvmti_setFailStatus();
NSK_DISPLAY1("ExceptionCatch events received: %d\n",
ExceptionCatchEventsCount);
if (!NSK_VERIFY(ExceptionCatchEventsCount == 3))
nsk_jvmti_setFailStatus();
if (!nsk_jvmti_resumeSync())
return;
}
/* ========================================================================== */
/** Agent library initialization. */
#ifdef STATIC_BUILD
JNIEXPORT jint JNICALL Agent_OnLoad_ma10t001(JavaVM *jvm, char *options, void *reserved) {
return Agent_Initialize(jvm, options, reserved);
}
JNIEXPORT jint JNICALL Agent_OnAttach_ma10t001(JavaVM *jvm, char *options, void *reserved) {
return Agent_Initialize(jvm, options, reserved);
}
JNIEXPORT jint JNI_OnLoad_ma10t001(JavaVM *jvm, char *options, void *reserved) {
return JNI_VERSION_1_8;
}
#endif
jint Agent_Initialize(JavaVM *jvm, char *options, void *reserved) {
jvmtiEnv* jvmti = NULL;
jvmtiCapabilities caps;
jvmtiEventCallbacks callbacks;
NSK_DISPLAY0("Agent_OnLoad\n");
if (!NSK_VERIFY(nsk_jvmti_parseOptions(options)))
return JNI_ERR;
timeout = nsk_jvmti_getWaitTime() * 60 * 1000;
if (!NSK_VERIFY((jvmti =
nsk_jvmti_createJVMTIEnv(jvm, reserved)) != NULL))
return JNI_ERR;
if (!NSK_VERIFY(nsk_jvmti_setAgentProc(agentProc, NULL)))
return JNI_ERR;
memset(&caps, 0, sizeof(caps));
caps.can_generate_exception_events = 1;
if (!NSK_JVMTI_VERIFY(jvmti->AddCapabilities(&caps))) {
return JNI_ERR;
}
memset(&callbacks, 0, sizeof(callbacks));
callbacks.Exception = &Exception;
callbacks.ExceptionCatch = &ExceptionCatch;
if (!NSK_VERIFY(nsk_jvmti_init_MA(&callbacks)))
return JNI_ERR;
return JNI_OK;
}
/* ========================================================================== */
}
| md-5/jdk10 | test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/multienv/MA10/ma10t001/ma10t001.cpp | C++ | gpl-2.0 | 6,032 |
<?php
return [
'actions' => "действия",
'author' => "Автор",
'cancel' => "Отмена",
'create' => "Создать",
'delete' => "Удалить",
'deleted' => "Удаленный",
'description' => "Описание",
'edit' => "Редактировать",
'editing' => "Вы редактируете :item",
'generic_confirm' => "Вы уверены?",
'home_title' => "Форум",
'index' => "Главная",
'invalid_selection' => "Неверный выбор",
'last_updated' => "Последнее обновление",
'mark_read' => "Отметить как прочитаное",
'move' => "Перенести",
'new' => "Новая",
'new_reply' => "Новый ответ",
'none' => "Ни одной",
'perma_delete' => "Удалить навсегда",
'posted' => "Опубликовано",
'private' => "Приватная",
'proceed' => "Продолжить",
'quick_reply' => "Быстрый ответ",
'rename' => "Переименовать",
'reorder' => "Сортировать",
'replies' => "Ответы",
'reply' => "Ответить",
'reply_added' => "Ответ добавлен",
'replying_to' => "Вы публикуете пост в :item",
'response_to' => "в ответ на :item",
'restore' => "восстановить",
'subject' => "Тема",
'title' => "Заголовок",
'weight' => "Вес",
'with_selection' => "С выбранными…",
];
| MontanaBanana/unidescription.com | vendor/riari/laravel-forum/translations/ru/general.php | PHP | gpl-2.0 | 1,886 |
<?php
/**
* This file is part of the Tmdb PHP API created by Michael Roterman.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @package Tmdb
* @author Michael Roterman <michael@wtfz.net>
* @copyright (c) 2013, Michael Roterman
* @version 0.0.1
*/
namespace Tmdb\Model;
/**
* Class Change
* @package Tmdb\Model
*/
class Change extends AbstractModel
{
/**
* @var integer
*/
private $id;
/**
* @var boolean
*/
private $adult;
/**
* @var array
*/
public static $properties = [
'id',
'adult'
];
/**
* @param boolean $adult
* @return $this
*/
public function setAdult($adult)
{
$this->adult = (bool) $adult;
return $this;
}
/**
* @return boolean
*/
public function getAdult()
{
return $this->adult;
}
/**
* @param int $id
* @return $this
*/
public function setId($id)
{
$this->id = (int) $id;
return $this;
}
/**
* @return int
*/
public function getId()
{
return $this->id;
}
}
| yorkulibraries/vufind | web/vendor/php-tmdb/api/lib/Tmdb/Model/Change.php | PHP | gpl-2.0 | 1,217 |
<?php
// # Get Sale sample
// Sale transactions are nothing but completed payments.
// This sample code demonstrates how you can retrieve
// details of completed Sale Transaction.
// API used: /v1/payments/sale/{sale-id}
/** @var Payment $payment */
$payment = require __DIR__ . '/../payments/CreatePayment.php';
use PayPal\Api\Sale;
use PayPal\Api\Payment;
// ### Get Sale From Created Payment
// You can retrieve the sale Id from Related Resources for each transactions.
$transactions = $payment->getTransactions();
$relatedResources = $transactions[0]->getRelatedResources();
$sale = $relatedResources[0]->getSale();
$saleId = $sale->getId();
try {
// ### Retrieve the sale object
// Pass the ID of the sale
// transaction from your payment resource.
$sale = Sale::get($saleId, $apiContext);
} catch (Exception $ex) {
ResultPrinter::printError("Look Up A Sale", "Sale", $sale->getId(), null, $ex);
exit(1);
}
ResultPrinter::printResult("Look Up A Sale", "Sale", $sale->getId(), null, $sale);
return $sale;
| jhonrsalcedo/sitio | wp-content/plugins/realia/libraries/PayPal-PHP-SDK/sample/sale/GetSale.php | PHP | gpl-2.0 | 1,041 |
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2002 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Alan Knowles <alan@akbkhome.com> |
// +----------------------------------------------------------------------+
//
// $Id: Flexy.php 6 2006-12-15 17:27:27Z $
//
// Base Compiler Class
// Standard 'Original Flavour' Flexy compiler
// this does the main conversion, (eg. for {vars and methods})
// it relays into Compiler/Tag & Compiler/Flexy for tags and namespace handling.
require_once 'HTML/Template/Flexy/Tokenizer.php';
require_once 'HTML/Template/Flexy/Token.php';
class HTML_Template_Flexy_Compiler_Flexy extends HTML_Template_Flexy_Compiler {
/**
* The current template (Full path)
*
* @var string
* @access public
*/
var $currentTemplate;
/**
* The compile method.
*
* @params object HTML_Template_Flexy
* @params string|false string to compile of false to use a file.
* @return string filename of template
* @access public
*/
function compile(&$flexy, $string=false)
{
// read the entire file into one variable
// note this should be moved to new HTML_Template_Flexy_Token
// and that can then manage all the tokens in one place..
global $_HTML_TEMPLATE_FLEXY_COMPILER;
$this->currentTemplate = $flexy->currentTemplate;
$gettextStrings = &$_HTML_TEMPLATE_FLEXY_COMPILER['gettextStrings'];
$gettextStrings = array(); // reset it.
if (@$this->options['debug']) {
echo "compiling template $flexy->currentTemplate<BR>";
}
// reset the elements.
$flexy->_elements = array();
// replace this with a singleton??
$GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions'] = $this->options;
$GLOBALS['_HTML_TEMPLATE_FLEXY']['elements'] = array();
$GLOBALS['_HTML_TEMPLATE_FLEXY']['filename'] = $flexy->currentTemplate;
$GLOBALS['_HTML_TEMPLATE_FLEXY']['prefixOutput'] = '';
$GLOBALS['_HTML_TEMPLATE_FLEXY']['compiledTemplate']= $flexy->compiledTemplate;
// initialize Translation 2, and
$this->initializeTranslator();
// load the template!
$data = $string;
$res = false;
if ($string === false) {
$data = file_get_contents($flexy->currentTemplate);
}
// PRE PROCESS {_(.....)} translation markers.
if (strpos($data, '{_(') !== false) {
$data = $this->preProcessTranslation($data);
}
// Tree generation!!!
if (!$this->options['forceCompile'] && isset($_HTML_TEMPLATE_FLEXY_COMPILER['cache'][md5($data)])) {
$res = $_HTML_TEMPLATE_FLEXY_COMPILER['cache'][md5($data)];
} else {
$tokenizer = new HTML_Template_Flexy_Tokenizer($data);
$tokenizer->fileName = $flexy->currentTemplate;
//$tokenizer->debug=1;
$tokenizer->options['ignore_html'] = $this->options['nonHTML'];
require_once 'HTML/Template/Flexy/Token.php';
$res = HTML_Template_Flexy_Token::buildTokens($tokenizer);
if (is_a($res, 'PEAR_Error')) {
return $res;
}
$_HTML_TEMPLATE_FLEXY_COMPILER['cache'][md5($data)] = $res;
}
// technically we shouldnt get here as we dont cache errors..
if (is_a($res, 'PEAR_Error')) {
return $res;
}
// turn tokens into Template..
$data = $res->compile($this);
if (is_a($data, 'PEAR_Error')) {
return $data;
}
$data = $GLOBALS['_HTML_TEMPLATE_FLEXY']['prefixOutput'] . $data;
if ( $flexy->options['debug'] > 1) {
echo "<B>Result: </B><PRE>".htmlspecialchars($data)."</PRE><BR>\n";
}
if ($this->options['nonHTML']) {
$data = str_replace("?>\n", "?>\n\n", $data);
}
// at this point we are into writing stuff...
if ($flexy->options['compileToString']) {
if ( $flexy->options['debug']) {
echo "<B>Returning string:<BR>\n";
}
$flexy->elements = $GLOBALS['_HTML_TEMPLATE_FLEXY']['elements'];
return $data;
}
// error checking?
$file = $flexy->compiledTemplate;
if (isset($flexy->options['output.block'])) {
list($file, $part) = explode('#', $file);
}
if( ($cfp = fopen($file, 'w')) ) {
if ($flexy->options['debug']) {
echo "<B>Writing: </B>$file<BR>\n";
}
fwrite($cfp, $data);
fclose($cfp);
chmod($file, 0775);
// make the timestamp of the two items match.
clearstatcache();
touch($file, filemtime($flexy->currentTemplate));
if ($file != $flexy->compiledTemplate) {
chmod($flexy->compiledTemplate, 0775);
// make the timestamp of the two items match.
clearstatcache();
touch($flexy->compiledTemplate, filemtime($flexy->currentTemplate));
}
} else {
return HTML_Template_Flexy::raiseError('HTML_Template_Flexy::failed to write to '.$flexy->compiledTemplate,
HTML_TEMPLATE_FLEXY_ERROR_FILE, HTML_TEMPLATE_FLEXY_ERROR_RETURN);
}
// gettext strings
if (file_exists($flexy->getTextStringsFile)) {
unlink($flexy->getTextStringsFile);
}
if($gettextStrings && ($cfp = fopen( $flexy->getTextStringsFile, 'w') ) ) {
fwrite($cfp, serialize(array_unique($gettextStrings)));
fclose($cfp);
chmod($flexy->getTextStringsFile, 0664);
}
// elements
if (file_exists($flexy->elementsFile)) {
unlink($flexy->elementsFile);
}
if( $GLOBALS['_HTML_TEMPLATE_FLEXY']['elements'] &&
($cfp = fopen( $flexy->elementsFile, 'w') ) ) {
fwrite($cfp, serialize( $GLOBALS['_HTML_TEMPLATE_FLEXY']['elements']));
fclose($cfp);
chmod($flexy->elementsFile, 0664);
// now clear it.
}
return true;
}
/**
* Initilalize the translation methods.
*
* Loads Translation2 if required.
*
*
* @return none
* @access public
*/
function initializeTranslator() {
if (is_array($this->options['Translation2'])) {
require_once 'Translation2.php';
$this->options['Translation2'] = &Translation2::factory(
$this->options['Translation2']['driver'],
isset($this->options['Translation2']['options']) ? $this->options['Translation2']['options'] : array(),
isset($this->options['Translation2']['params']) ? $this->options['Translation2']['params'] : array()
);
}
if (is_a($this->options['Translation2'], 'Translation2')) {
$this->options['Translation2']->setLang($this->options['locale']);
// fixme - needs to be more specific to which template to use..
foreach ($this->options['templateDir'] as $tt) {
$n = basename($this->currentTemplate);
if (substr($this->currentTemplate, 0, strlen($tt)) == $tt) {
$n = substr($this->currentTemplate, strlen($tt)+1);
}
//echo $n;
}
$this->options['Translation2']->setPageID($n);
} else {
setlocale(LC_ALL, $this->options['locale']);
}
}
/**
* do the early tranlsation of {_(......)_} text
*
*
* @param input string
* @return output string
* @access public
*/
function preProcessTranslation($data) {
global $_HTML_TEMPLATE_FLEXY_COMPILER;
$matches = array();
$lmatches = explode ('{_(', $data);
array_shift($lmatches);
// shift the first..
foreach ($lmatches as $k) {
if (false === strpos($k, ')_}')) {
continue;
}
$x = explode(')_}', $k);
$matches[] = $x[0];
}
//echo '<PRE>';print_r($matches);
// we may need to do some house cleaning here...
$_HTML_TEMPLATE_FLEXY_COMPILER['gettextStrings'] = $matches;
// replace them now..
// ** leaving in the tag (which should be ignored by the parser..
// we then get rid of the tags during the toString method in this class.
foreach($matches as $v) {
$data = str_replace('{_('.$v.')_}', '{_('.$this->translateString($v).')_}', $data);
}
return $data;
}
/**
* Flag indicating compiler is inside {_( .... )_} block, and should not
* add to the gettextstrings array.
*
* @var boolean
* @access public
*/
var $inGetTextBlock = false;
/**
* This is the base toString Method, it relays into toString{TokenName}
*
* @param object HTML_Template_Flexy_Token_*
*
* @return string string to build a template
* @access public
* @see toString*
*/
function toString($element)
{
static $len = 26; // strlen('HTML_Template_Flexy_Token_');
if ($this->options['debug'] > 1) {
$x = $element;
unset($x->children);
//echo htmlspecialchars(print_r($x,true))."<BR>\n";
}
if ($element->token == 'GetTextStart') {
$this->inGetTextBlock = true;
return '';
}
if ($element->token == 'GetTextEnd') {
$this->inGetTextBlock = false;
return '';
}
$class = get_class($element);
if (strlen($class) >= $len) {
$type = substr($class, $len);
return $this->{'toString'.$type}($element);
}
$ret = $element->value;
$add = $element->compileChildren($this);
if (is_a($add, 'PEAR_Error')) {
return $add;
}
$ret .= $add;
if ($element->close) {
$add = $element->close->compile($this);
if (is_a($add, 'PEAR_Error')) {
return $add;
}
$ret .= $add;
}
return $ret;
}
/**
* HTML_Template_Flexy_Token_Else toString
*
* @param object HTML_Template_Flexy_Token_Else
*
* @return string string to build a template
* @access public
* @see toString*
*/
function toStringElse($element)
{
// pushpull states to make sure we are in an area.. - should really check to see
// if the state it is pulling is a if...
if ($element->pullState() === false) {
return $this->appendHTML(
"<font color=\"red\">Unmatched {else:} on line: {$element->line}</font>"
);
}
$element->pushState();
return $this->appendPhp("} else {");
}
/**
* HTML_Template_Flexy_Token_End toString
*
* @param object HTML_Template_Flexy_Token_Else
*
* @return string string to build a template
* @access public
* @see toString*
*/
function toStringEnd($element)
{
// pushpull states to make sure we are in an area.. - should really check to see
// if the state it is pulling is a if...
if ($element->pullState() === false) {
return $this->appendHTML(
"<font color=\"red\">Unmatched {end:} on line: {$element->line}</font>"
);
}
return $this->appendPhp("}");
}
/**
* HTML_Template_Flexy_Token_EndTag toString
*
* @param object HTML_Template_Flexy_Token_EndTag
*
* @return string string to build a template
* @access public
* @see toString*
*/
function toStringEndTag($element)
{
return $this->toStringTag($element);
}
/**
* HTML_Template_Flexy_Token_Foreach toString
*
* @param object HTML_Template_Flexy_Token_Foreach
*
* @return string string to build a template
* @access public
* @see toString*
*/
function toStringForeach($element)
{
$loopon = $element->toVar($element->loopOn);
if (is_a($loopon, 'PEAR_Error')) {
return $loopon;
}
$ret = 'if ($this->options[\'strict\'] || ('.
'is_array('. $loopon. ') || ' .
'is_object(' . $loopon . '))) ' .
'foreach(' . $loopon . " ";
$ret .= "as \${$element->key}";
if ($element->value) {
$ret .= " => \${$element->value}";
}
$ret .= ") {";
$element->pushState();
$element->pushVar($element->key);
$element->pushVar($element->value);
return $this->appendPhp($ret);
}
/**
* HTML_Template_Flexy_Token_If toString
*
* @param object HTML_Template_Flexy_Token_If
*
* @return string string to build a template
* @access public
* @see toString*
*/
function toStringIf($element)
{
$var = $element->toVar($element->condition);
if (is_a($var, 'PEAR_Error')) {
return $var;
}
$ret = "if (".$element->isNegative . $var .") {";
$element->pushState();
return $this->appendPhp($ret);
}
/**
* get Modifier Wrapper
*
* converts :h, :u, :r , .....
* @param object HTML_Template_Flexy_Token_Method|Var
*
* @return array prefix,suffix
* @access public
* @see toString*
*/
function getModifierWrapper($element)
{
$prefix = 'echo ';
$suffix = '';
$modifier = strlen(trim($element->modifier)) ? $element->modifier : ' ';
switch ($modifier) {
case 'h':
break;
case 'u':
$prefix = 'echo urlencode(';
$suffix = ')';
break;
case 'r':
$prefix = 'echo \'<pre>\'; echo htmlspecialchars(print_r(';
$suffix = ',true)); echo \'</pre>\';';
break;
case 'n':
// blank or value..
$numberformat = @$GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions']['numberFormat'];
$prefix = 'echo number_format(';
$suffix = $GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions']['numberFormat'] . ')';
break;
case 'b': // nl2br + htmlspecialchars
$prefix = 'echo nl2br(htmlspecialchars(';
// add language ?
$suffix = '))';
break;
case ' ':
$prefix = 'echo htmlspecialchars(';
// add language ?
$suffix = ')';
break;
default:
$prefix = 'echo $this->plugin("'.trim($element->modifier) .'",';
$suffix = ')';
}
return array($prefix, $suffix);
}
/**
* HTML_Template_Flexy_Token_Var toString
*
* @param object HTML_Template_Flexy_Token_Method
*
* @return string string to build a template
* @access public
* @see toString*
*/
function toStringVar($element)
{
// ignore modifier at present!!
$var = $element->toVar($element->value);
if (is_a($var, 'PEAR_Error')) {
return $var;
}
list($prefix, $suffix) = $this->getModifierWrapper($element);
return $this->appendPhp( $prefix . $var . $suffix .';');
}
/**
* HTML_Template_Flexy_Token_Method toString
*
* @param object HTML_Template_Flexy_Token_Method
*
* @return string string to build a template
* @access public
* @see toString*
*/
function toStringMethod($element)
{
// set up the modifier at present!!
list($prefix, $suffix) = $this->getModifierWrapper($element);
// add the '!' to if
if ($element->isConditional) {
$prefix = 'if ('.$element->isNegative;
$element->pushState();
$suffix = ')';
}
// check that method exists..
// if (method_exists($object,'method');
$bits = explode('.', $element->method);
$method = array_pop($bits);
$object = implode('.', $bits);
$var = $element->toVar($object);
if (is_a($var, 'PEAR_Error')) {
return $var;
}
if (($object == 'GLOBALS') &&
$GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions']['globalfunctions']) {
// we should check if they something weird like: GLOBALS.xxxx[sdf](....)
$var = $method;
} else {
$prefix = 'if ($this->options[\'strict\'] || (isset('.$var.
') && method_exists('.$var .", '{$method}'))) " . $prefix;
$var = $element->toVar($element->method);
}
if (is_a($var, 'PEAR_Error')) {
return $var;
}
$ret = $prefix;
$ret .= $var . "(";
$s =0;
foreach($element->args as $a) {
if ($s) {
$ret .= ",";
}
$s =1;
if ($a{0} == '#') {
if (is_numeric(substr($a, 1, -1))) {
$ret .= substr($a, 1, -1);
} else {
$ret .= '"'. addslashes(substr($a, 1, -1)) . '"';
}
continue;
}
$var = $element->toVar($a);
if (is_a($var, 'PEAR_Error')) {
return $var;
}
$ret .= $var;
}
$ret .= ")" . $suffix;
if ($element->isConditional) {
$ret .= ' { ';
} else {
$ret .= ";";
}
return $this->appendPhp($ret);
}
/**
* HTML_Template_Flexy_Token_Processing toString
*
* @param object HTML_Template_Flexy_Token_Processing
*
* @return string string to build a template
* @access public
* @see toString*
*/
function toStringProcessing($element)
{
// if it's XML then quote it..
if (strtoupper(substr($element->value, 2, 3)) == 'XML') {
return $this->appendPhp("echo '" . str_replace("'", "\\"."'", $element->value) . "';");
}
// otherwise it's PHP code - so echo it..
return $element->value;
}
/**
* HTML_Template_Flexy_Token_Text toString
*
* @param object HTML_Template_Flexy_Token_Text
*
* @return string string to build a template
* @access public
* @see toString*
*/
function toStringText($element)
{
// first get rid of stuff thats not translated etc.
// empty strings => output.
// comments -> just output
// our special tags -> output..
if (!strlen(trim($element->value) )) {
return $this->appendHtml($element->value);
}
// dont add comments to translation lists.
if (substr($element->value, 0, 4) == '<!--') {
return $this->appendHtml($element->value);
}
// ignore anything wrapped with {_( .... )_}
if ($this->inGetTextBlock) {
return $this->appendHtml($element->value);
}
if (!$element->isWord()) {
return $this->appendHtml($element->value);
}
// grab the white space at start and end (and keep it!
$value = ltrim($element->value);
$front = substr($element->value, 0, -strlen($value));
$value = rtrim($element->value);
$rear = substr($element->value, strlen($value));
$value = trim($element->value);
// convert to escaped chars.. (limited..)
//$value = strtr($value,$cleanArray);
$this->addStringToGettext($value);
$value = $this->translateString($value);
// its a simple word!
return $this->appendHtml($front . $value . $rear);
}
/**
* HTML_Template_Flexy_Token_Cdata toString
*
* @param object HTML_Template_Flexy_Token_Cdata ?
*
* @return string string to build a template
* @access public
* @see toString*
*/
function toStringCdata($element)
{
return $this->appendHtml($element->value);
}
/**
* addStringToGettext
*
* Adds a string to the gettext array.
*
* @param mixed preferably.. string to store
*
* @return none
* @access public
*/
function addStringToGettext($string)
{
if (!is_string($string)) {
return;
}
if (!preg_match('/[a-z]+/i', $string)) {
return;
}
$string = trim($string);
if (substr($string, 0, 4) == '<!--') {
return;
}
$GLOBALS['_HTML_TEMPLATE_FLEXY_COMPILER']['gettextStrings'][] = $string;
}
/**
* translateString - a gettextWrapper
*
* tries to do gettext or falls back on File_Gettext
* This has !!!NO!!! error handling - if it fails you just get english..
* no questions asked!!!
*
* @param string string to translate
*
* @return string translated string..
* @access public
*/
function translateString($string)
{
if (is_a($this->options['Translation2'], 'Translation2')) {
$result = $this->options['Translation2']->get($string);
if (!empty($result)) {
return $result;
}
return $string;
}
// note this stuff may have been broken by removing the \n replacement code
// since i dont have a test for it... it may remain broken..
// use Translation2 - it has gettext backend support
// and should sort out the mess that \n etc. entail.
$prefix = basename($GLOBALS['_HTML_TEMPLATE_FLEXY']['filename']).':';
if (@$this->options['debug']) {
echo __CLASS__.":TRANSLATING $string<BR>\n";
}
if (function_exists('gettext') && !$this->options['textdomain']) {
if (@$this->options['debug']) {
echo __CLASS__.":USING GETTEXT?<BR>";
}
$t = gettext($string);
if ($t != $string) {
return $t;
}
$tt = gettext($prefix.$string);
if ($tt != $prefix.$string) {
return $tt;
}
// give up it's not translated anywhere...
return $string;
}
if (!$this->options['textdomain'] || !$this->options['textdomainDir']) {
// text domain is not set..
if (@$this->options['debug']) {
echo __CLASS__.":MISSING textdomain settings<BR>";
}
return $string;
}
$pofile = $this->options['textdomainDir'] .
'/' . $this->options['locale'] .
'/LC_MESSAGES/' . $this->options['textdomain'] . '.po';
// did we try to load it already..
if (@$GLOBALS['_'.__CLASS__]['PO'][$pofile] === false) {
if (@$this->options['debug']) {
echo __CLASS__.":LOAD failed (Cached):<BR>";
}
return $string;
}
if (!@$GLOBALS['_'.__CLASS__]['PO'][$pofile]) {
// default - cant load it..
$GLOBALS['_'.__CLASS__]['PO'][$pofile] = false;
if (!file_exists($pofile)) {
if (@$this->options['debug']) {
echo __CLASS__.":LOAD failed: {$pofile}<BR>";
}
return $string;
}
if (!@include_once 'File/Gettext.php') {
if (@$this->options['debug']) {
echo __CLASS__.":LOAD no File_gettext:<BR>";
}
return $string;
}
$GLOBALS['_'.__CLASS__]['PO'][$pofile] = File_Gettext::factory('PO', $pofile);
$GLOBALS['_'.__CLASS__]['PO'][$pofile]->load();
//echo '<PRE>'.htmlspecialchars(print_r($GLOBALS['_'.__CLASS__]['PO'][$pofile]->strings,true));
}
$po = &$GLOBALS['_'.__CLASS__]['PO'][$pofile];
// we should have it loaded now...
// this is odd - data is a bit messed up with CR's
$string = str_replace('\n', "\n", $string);
if (isset($po->strings[$prefix.$string])) {
return $po->strings[$prefix.$string];
}
if (!isset($po->strings[$string])) {
if (@$this->options['debug']) {
echo __CLASS__.":no match:<BR>";
}
return $string;
}
if (@$this->options['debug']) {
echo __CLASS__.":MATCHED: {$po->strings[$string]}<BR>";
}
// finally we have a match!!!
return $po->strings[$string];
}
/**
* HTML_Template_Flexy_Token_Tag toString
*
* @param object HTML_Template_Flexy_Token_Tag
*
* @return string string to build a template
* @access public
* @see toString*
*/
function toStringTag($element) {
$original = $element->getAttribute('ALT');
if (($element->tag == 'IMG') && is_string($original) && strlen($original)) {
$this->addStringToGettext($original);
$quote = $element->ucAttributes['ALT']{0};
$element->ucAttributes['ALT'] = $quote . $this->translateString($original). $quote;
}
$original = $element->getAttribute('TITLE');
if (($element->tag == 'A') && is_string($original) && strlen($original)) {
$this->addStringToGettext($original);
$quote = $element->ucAttributes['TITLE']{0};
$element->ucAttributes['TITLE'] = $quote . $this->translateString($original). $quote;
}
if (strpos($element->tag, ':') === false) {
$namespace = 'Tag';
} else {
$bits = explode(':', $element->tag);
$namespace = $bits[0];
}
if ($namespace{0} == '/') {
$namespace = substr($namespace, 1);
}
if (empty($this->tagHandlers[$namespace])) {
require_once 'HTML/Template/Flexy/Compiler/Flexy/Tag.php';
$this->tagHandlers[$namespace] = &HTML_Template_Flexy_Compiler_Flexy_Tag::factory($namespace, $this);
if (!$this->tagHandlers[$namespace] ) {
return HTML_Template_Flexy::raiseError('HTML_Template_Flexy::failed to create Namespace Handler '.$namespace .
' in file ' . $GLOBALS['_HTML_TEMPLATE_FLEXY']['filename'],
HTML_TEMPLATE_FLEXY_ERROR_SYNTAX, HTML_TEMPLATE_FLEXY_ERROR_RETURN);
}
}
return $this->tagHandlers[$namespace]->toString($element);
}
}
| wassemgtk/OpenX-using-S3-and-CloudFront | lib/pear/HTML/Template/Flexy/Compiler/Flexy.php | PHP | gpl-2.0 | 29,721 |
/*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.marshal;
import com.caucho.quercus.env.Env;
import com.caucho.quercus.env.NullValue;
import com.caucho.quercus.env.Value;
public class JavaByteObjectArrayMarshal extends JavaArrayMarshal
{
public static final Marshal MARSHAL
= new JavaByteObjectArrayMarshal();
@Override
public Value unmarshal(Env env, Object value)
{
Byte []byteValue = (Byte []) value;
if (byteValue == null)
return NullValue.NULL;
byte []data = new byte[byteValue.length];
for (int i = 0; i < data.length; i++)
data[i] = byteValue[i];
return env.createBinaryBuilder(data);
}
@Override
protected int getMarshalingCostImpl(Value argValue)
{
return Marshal.COST_INCOMPATIBLE;
/*
if (argValue.isString()) {
if (argValue.isUnicode())
return Marshal.UNICODE_BYTE_OBJECT_ARRAY_COST;
else if (argValue.isBinary())
return Marshal.BINARY_BYTE_OBJECT_ARRAY_COST;
else
return Marshal.PHP5_BYTE_OBJECT_ARRAY_COST;
}
else if (argValue.isArray())
return Marshal.THREE;
else
return Marshal.FOUR;
*/
}
@Override
public Class getExpectedClass()
{
return Byte[].class;
}
}
| dwango/quercus | src/main/java/com/caucho/quercus/marshal/JavaByteObjectArrayMarshal.java | Java | gpl-2.0 | 2,241 |
<?php
/**
* Base class that represents a row from the 'cc_smemb' table.
*
*
*
* @package propel.generator.airtime.om
*/
abstract class BaseCcSmemb extends BaseObject implements Persistent
{
/**
* Peer class name
*/
const PEER = 'CcSmembPeer';
/**
* The Peer class.
* Instance provides a convenient way of calling static methods on a class
* that calling code may not be able to identify.
* @var CcSmembPeer
*/
protected static $peer;
/**
* The value for the id field.
* @var int
*/
protected $id;
/**
* The value for the uid field.
* Note: this column has a database default value of: 0
* @var int
*/
protected $uid;
/**
* The value for the gid field.
* Note: this column has a database default value of: 0
* @var int
*/
protected $gid;
/**
* The value for the level field.
* Note: this column has a database default value of: 0
* @var int
*/
protected $level;
/**
* The value for the mid field.
* @var int
*/
protected $mid;
/**
* Flag to prevent endless save loop, if this object is referenced
* by another object which falls in this transaction.
* @var boolean
*/
protected $alreadyInSave = false;
/**
* Flag to prevent endless validation loop, if this object is referenced
* by another object which falls in this transaction.
* @var boolean
*/
protected $alreadyInValidation = false;
/**
* Applies default values to this object.
* This method should be called from the object's constructor (or
* equivalent initialization method).
* @see __construct()
*/
public function applyDefaultValues()
{
$this->uid = 0;
$this->gid = 0;
$this->level = 0;
}
/**
* Initializes internal state of BaseCcSmemb object.
* @see applyDefaults()
*/
public function __construct()
{
parent::__construct();
$this->applyDefaultValues();
}
/**
* Get the [id] column value.
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Get the [uid] column value.
*
* @return int
*/
public function getUid()
{
return $this->uid;
}
/**
* Get the [gid] column value.
*
* @return int
*/
public function getGid()
{
return $this->gid;
}
/**
* Get the [level] column value.
*
* @return int
*/
public function getLevel()
{
return $this->level;
}
/**
* Get the [mid] column value.
*
* @return int
*/
public function getMid()
{
return $this->mid;
}
/**
* Set the value of [id] column.
*
* @param int $v new value
* @return CcSmemb The current object (for fluent API support)
*/
public function setId($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->id !== $v) {
$this->id = $v;
$this->modifiedColumns[] = CcSmembPeer::ID;
}
return $this;
} // setId()
/**
* Set the value of [uid] column.
*
* @param int $v new value
* @return CcSmemb The current object (for fluent API support)
*/
public function setUid($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->uid !== $v || $this->isNew()) {
$this->uid = $v;
$this->modifiedColumns[] = CcSmembPeer::UID;
}
return $this;
} // setUid()
/**
* Set the value of [gid] column.
*
* @param int $v new value
* @return CcSmemb The current object (for fluent API support)
*/
public function setGid($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->gid !== $v || $this->isNew()) {
$this->gid = $v;
$this->modifiedColumns[] = CcSmembPeer::GID;
}
return $this;
} // setGid()
/**
* Set the value of [level] column.
*
* @param int $v new value
* @return CcSmemb The current object (for fluent API support)
*/
public function setLevel($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->level !== $v || $this->isNew()) {
$this->level = $v;
$this->modifiedColumns[] = CcSmembPeer::LEVEL;
}
return $this;
} // setLevel()
/**
* Set the value of [mid] column.
*
* @param int $v new value
* @return CcSmemb The current object (for fluent API support)
*/
public function setMid($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->mid !== $v) {
$this->mid = $v;
$this->modifiedColumns[] = CcSmembPeer::MID;
}
return $this;
} // setMid()
/**
* Indicates whether the columns in this object are only set to default values.
*
* This method can be used in conjunction with isModified() to indicate whether an object is both
* modified _and_ has some values set which are non-default.
*
* @return boolean Whether the columns in this object are only been set with default values.
*/
public function hasOnlyDefaultValues()
{
if ($this->uid !== 0) {
return false;
}
if ($this->gid !== 0) {
return false;
}
if ($this->level !== 0) {
return false;
}
// otherwise, everything was equal, so return TRUE
return true;
} // hasOnlyDefaultValues()
/**
* Hydrates (populates) the object variables with values from the database resultset.
*
* An offset (0-based "start column") is specified so that objects can be hydrated
* with a subset of the columns in the resultset rows. This is needed, for example,
* for results of JOIN queries where the resultset row includes columns from two or
* more tables.
*
* @param array $row The row returned by PDOStatement->fetch(PDO::FETCH_NUM)
* @param int $startcol 0-based offset column which indicates which restultset column to start with.
* @param boolean $rehydrate Whether this object is being re-hydrated from the database.
* @return int next starting column
* @throws PropelException - Any caught Exception will be rewrapped as a PropelException.
*/
public function hydrate($row, $startcol = 0, $rehydrate = false)
{
try {
$this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null;
$this->uid = ($row[$startcol + 1] !== null) ? (int) $row[$startcol + 1] : null;
$this->gid = ($row[$startcol + 2] !== null) ? (int) $row[$startcol + 2] : null;
$this->level = ($row[$startcol + 3] !== null) ? (int) $row[$startcol + 3] : null;
$this->mid = ($row[$startcol + 4] !== null) ? (int) $row[$startcol + 4] : null;
$this->resetModified();
$this->setNew(false);
if ($rehydrate) {
$this->ensureConsistency();
}
return $startcol + 5; // 5 = CcSmembPeer::NUM_COLUMNS - CcSmembPeer::NUM_LAZY_LOAD_COLUMNS).
} catch (Exception $e) {
throw new PropelException("Error populating CcSmemb object", $e);
}
}
/**
* Checks and repairs the internal consistency of the object.
*
* This method is executed after an already-instantiated object is re-hydrated
* from the database. It exists to check any foreign keys to make sure that
* the objects related to the current object are correct based on foreign key.
*
* You can override this method in the stub class, but you should always invoke
* the base method from the overridden method (i.e. parent::ensureConsistency()),
* in case your model changes.
*
* @throws PropelException
*/
public function ensureConsistency()
{
} // ensureConsistency
/**
* Reloads this object from datastore based on primary key and (optionally) resets all associated objects.
*
* This will only work if the object has been saved and has a valid primary key set.
*
* @param boolean $deep (optional) Whether to also de-associated any related objects.
* @param PropelPDO $con (optional) The PropelPDO connection to use.
* @return void
* @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db
*/
public function reload($deep = false, PropelPDO $con = null)
{
if ($this->isDeleted()) {
throw new PropelException("Cannot reload a deleted object.");
}
if ($this->isNew()) {
throw new PropelException("Cannot reload an unsaved object.");
}
if ($con === null) {
$con = Propel::getConnection(CcSmembPeer::DATABASE_NAME, Propel::CONNECTION_READ);
}
// We don't need to alter the object instance pool; we're just modifying this instance
// already in the pool.
$stmt = CcSmembPeer::doSelectStmt($this->buildPkeyCriteria(), $con);
$row = $stmt->fetch(PDO::FETCH_NUM);
$stmt->closeCursor();
if (!$row) {
throw new PropelException('Cannot find matching row in the database to reload object values.');
}
$this->hydrate($row, 0, true); // rehydrate
if ($deep) { // also de-associate any related objects?
} // if (deep)
}
/**
* Removes this object from datastore and sets delete attribute.
*
* @param PropelPDO $con
* @return void
* @throws PropelException
* @see BaseObject::setDeleted()
* @see BaseObject::isDeleted()
*/
public function delete(PropelPDO $con = null)
{
if ($this->isDeleted()) {
throw new PropelException("This object has already been deleted.");
}
if ($con === null) {
$con = Propel::getConnection(CcSmembPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
}
$con->beginTransaction();
try {
$ret = $this->preDelete($con);
if ($ret) {
CcSmembQuery::create()
->filterByPrimaryKey($this->getPrimaryKey())
->delete($con);
$this->postDelete($con);
$con->commit();
$this->setDeleted(true);
} else {
$con->commit();
}
} catch (PropelException $e) {
$con->rollBack();
throw $e;
}
}
/**
* Persists this object to the database.
*
* If the object is new, it inserts it; otherwise an update is performed.
* All modified related objects will also be persisted in the doSave()
* method. This method wraps all precipitate database operations in a
* single transaction.
*
* @param PropelPDO $con
* @return int The number of rows affected by this insert/update and any referring fk objects' save() operations.
* @throws PropelException
* @see doSave()
*/
public function save(PropelPDO $con = null)
{
if ($this->isDeleted()) {
throw new PropelException("You cannot save an object that has been deleted.");
}
if ($con === null) {
$con = Propel::getConnection(CcSmembPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
}
$con->beginTransaction();
$isInsert = $this->isNew();
try {
$ret = $this->preSave($con);
if ($isInsert) {
$ret = $ret && $this->preInsert($con);
} else {
$ret = $ret && $this->preUpdate($con);
}
if ($ret) {
$affectedRows = $this->doSave($con);
if ($isInsert) {
$this->postInsert($con);
} else {
$this->postUpdate($con);
}
$this->postSave($con);
CcSmembPeer::addInstanceToPool($this);
} else {
$affectedRows = 0;
}
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollBack();
throw $e;
}
}
/**
* Performs the work of inserting or updating the row in the database.
*
* If the object is new, it inserts it; otherwise an update is performed.
* All related objects are also updated in this method.
*
* @param PropelPDO $con
* @return int The number of rows affected by this insert/update and any referring fk objects' save() operations.
* @throws PropelException
* @see save()
*/
protected function doSave(PropelPDO $con)
{
$affectedRows = 0; // initialize var to track total num of affected rows
if (!$this->alreadyInSave) {
$this->alreadyInSave = true;
// If this object has been modified, then save it to the database.
if ($this->isModified()) {
if ($this->isNew()) {
$criteria = $this->buildCriteria();
$pk = BasePeer::doInsert($criteria, $con);
$affectedRows = 1;
$this->setNew(false);
} else {
$affectedRows = CcSmembPeer::doUpdate($this, $con);
}
$this->resetModified(); // [HL] After being saved an object is no longer 'modified'
}
$this->alreadyInSave = false;
}
return $affectedRows;
} // doSave()
/**
* Array of ValidationFailed objects.
* @var array ValidationFailed[]
*/
protected $validationFailures = array();
/**
* Gets any ValidationFailed objects that resulted from last call to validate().
*
*
* @return array ValidationFailed[]
* @see validate()
*/
public function getValidationFailures()
{
return $this->validationFailures;
}
/**
* Validates the objects modified field values and all objects related to this table.
*
* If $columns is either a column name or an array of column names
* only those columns are validated.
*
* @param mixed $columns Column name or an array of column names.
* @return boolean Whether all columns pass validation.
* @see doValidate()
* @see getValidationFailures()
*/
public function validate($columns = null)
{
$res = $this->doValidate($columns);
if ($res === true) {
$this->validationFailures = array();
return true;
} else {
$this->validationFailures = $res;
return false;
}
}
/**
* This function performs the validation work for complex object models.
*
* In addition to checking the current object, all related objects will
* also be validated. If all pass then <code>true</code> is returned; otherwise
* an aggreagated array of ValidationFailed objects will be returned.
*
* @param array $columns Array of column names to validate.
* @return mixed <code>true</code> if all validations pass; array of <code>ValidationFailed</code> objets otherwise.
*/
protected function doValidate($columns = null)
{
if (!$this->alreadyInValidation) {
$this->alreadyInValidation = true;
$retval = null;
$failureMap = array();
if (($retval = CcSmembPeer::doValidate($this, $columns)) !== true) {
$failureMap = array_merge($failureMap, $retval);
}
$this->alreadyInValidation = false;
}
return (!empty($failureMap) ? $failureMap : true);
}
/**
* Retrieves a field from the object by name passed in as a string.
*
* @param string $name name
* @param string $type The type of fieldname the $name is of:
* one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
* BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM
* @return mixed Value of field.
*/
public function getByName($name, $type = BasePeer::TYPE_PHPNAME)
{
$pos = CcSmembPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM);
$field = $this->getByPosition($pos);
return $field;
}
/**
* Retrieves a field from the object by Position as specified in the xml schema.
* Zero-based.
*
* @param int $pos position in xml schema
* @return mixed Value of field at $pos
*/
public function getByPosition($pos)
{
switch($pos) {
case 0:
return $this->getId();
break;
case 1:
return $this->getUid();
break;
case 2:
return $this->getGid();
break;
case 3:
return $this->getLevel();
break;
case 4:
return $this->getMid();
break;
default:
return null;
break;
} // switch()
}
/**
* Exports the object as an array.
*
* You can specify the key type of the array by passing one of the class
* type constants.
*
* @param string $keyType (optional) One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME,
* BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM.
* Defaults to BasePeer::TYPE_PHPNAME.
* @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE.
*
* @return array an associative array containing the field names (as keys) and field values
*/
public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true)
{
$keys = CcSmembPeer::getFieldNames($keyType);
$result = array(
$keys[0] => $this->getId(),
$keys[1] => $this->getUid(),
$keys[2] => $this->getGid(),
$keys[3] => $this->getLevel(),
$keys[4] => $this->getMid(),
);
return $result;
}
/**
* Sets a field from the object by name passed in as a string.
*
* @param string $name peer name
* @param mixed $value field value
* @param string $type The type of fieldname the $name is of:
* one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
* BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM
* @return void
*/
public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME)
{
$pos = CcSmembPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM);
return $this->setByPosition($pos, $value);
}
/**
* Sets a field from the object by Position as specified in the xml schema.
* Zero-based.
*
* @param int $pos position in xml schema
* @param mixed $value field value
* @return void
*/
public function setByPosition($pos, $value)
{
switch($pos) {
case 0:
$this->setId($value);
break;
case 1:
$this->setUid($value);
break;
case 2:
$this->setGid($value);
break;
case 3:
$this->setLevel($value);
break;
case 4:
$this->setMid($value);
break;
} // switch()
}
/**
* Populates the object using an array.
*
* This is particularly useful when populating an object from one of the
* request arrays (e.g. $_POST). This method goes through the column
* names, checking to see whether a matching key exists in populated
* array. If so the setByName() method is called for that column.
*
* You can specify the key type of the array by additionally passing one
* of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME,
* BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM.
* The default key type is the column's phpname (e.g. 'AuthorId')
*
* @param array $arr An array to populate the object from.
* @param string $keyType The type of keys the array uses.
* @return void
*/
public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME)
{
$keys = CcSmembPeer::getFieldNames($keyType);
if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]);
if (array_key_exists($keys[1], $arr)) $this->setUid($arr[$keys[1]]);
if (array_key_exists($keys[2], $arr)) $this->setGid($arr[$keys[2]]);
if (array_key_exists($keys[3], $arr)) $this->setLevel($arr[$keys[3]]);
if (array_key_exists($keys[4], $arr)) $this->setMid($arr[$keys[4]]);
}
/**
* Build a Criteria object containing the values of all modified columns in this object.
*
* @return Criteria The Criteria object containing all modified values.
*/
public function buildCriteria()
{
$criteria = new Criteria(CcSmembPeer::DATABASE_NAME);
if ($this->isColumnModified(CcSmembPeer::ID)) $criteria->add(CcSmembPeer::ID, $this->id);
if ($this->isColumnModified(CcSmembPeer::UID)) $criteria->add(CcSmembPeer::UID, $this->uid);
if ($this->isColumnModified(CcSmembPeer::GID)) $criteria->add(CcSmembPeer::GID, $this->gid);
if ($this->isColumnModified(CcSmembPeer::LEVEL)) $criteria->add(CcSmembPeer::LEVEL, $this->level);
if ($this->isColumnModified(CcSmembPeer::MID)) $criteria->add(CcSmembPeer::MID, $this->mid);
return $criteria;
}
/**
* Builds a Criteria object containing the primary key for this object.
*
* Unlike buildCriteria() this method includes the primary key values regardless
* of whether or not they have been modified.
*
* @return Criteria The Criteria object containing value(s) for primary key(s).
*/
public function buildPkeyCriteria()
{
$criteria = new Criteria(CcSmembPeer::DATABASE_NAME);
$criteria->add(CcSmembPeer::ID, $this->id);
return $criteria;
}
/**
* Returns the primary key for this object (row).
* @return int
*/
public function getPrimaryKey()
{
return $this->getId();
}
/**
* Generic method to set the primary key (id column).
*
* @param int $key Primary key.
* @return void
*/
public function setPrimaryKey($key)
{
$this->setId($key);
}
/**
* Returns true if the primary key for this object is null.
* @return boolean
*/
public function isPrimaryKeyNull()
{
return null === $this->getId();
}
/**
* Sets contents of passed object to values from current object.
*
* If desired, this method can also make copies of all associated (fkey referrers)
* objects.
*
* @param object $copyObj An object of CcSmemb (or compatible) type.
* @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
* @throws PropelException
*/
public function copyInto($copyObj, $deepCopy = false)
{
$copyObj->setId($this->id);
$copyObj->setUid($this->uid);
$copyObj->setGid($this->gid);
$copyObj->setLevel($this->level);
$copyObj->setMid($this->mid);
$copyObj->setNew(true);
}
/**
* Makes a copy of this object that will be inserted as a new row in table when saved.
* It creates a new object filling in the simple attributes, but skipping any primary
* keys that are defined for the table.
*
* If desired, this method can also make copies of all associated (fkey referrers)
* objects.
*
* @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
* @return CcSmemb Clone of current object.
* @throws PropelException
*/
public function copy($deepCopy = false)
{
// we use get_class(), because this might be a subclass
$clazz = get_class($this);
$copyObj = new $clazz();
$this->copyInto($copyObj, $deepCopy);
return $copyObj;
}
/**
* Returns a peer instance associated with this om.
*
* Since Peer classes are not to have any instance attributes, this method returns the
* same instance for all member of this class. The method could therefore
* be static, but this would prevent one from overriding the behavior.
*
* @return CcSmembPeer
*/
public function getPeer()
{
if (self::$peer === null) {
self::$peer = new CcSmembPeer();
}
return self::$peer;
}
/**
* Clears the current object and sets all attributes to their default values
*/
public function clear()
{
$this->id = null;
$this->uid = null;
$this->gid = null;
$this->level = null;
$this->mid = null;
$this->alreadyInSave = false;
$this->alreadyInValidation = false;
$this->clearAllReferences();
$this->applyDefaultValues();
$this->resetModified();
$this->setNew(true);
$this->setDeleted(false);
}
/**
* Resets all collections of referencing foreign keys.
*
* This method is a user-space workaround for PHP's inability to garbage collect objects
* with circular references. This is currently necessary when using Propel in certain
* daemon or large-volumne/high-memory operations.
*
* @param boolean $deep Whether to also clear the references on all associated objects.
*/
public function clearAllReferences($deep = false)
{
if ($deep) {
} // if ($deep)
}
/**
* Catches calls to virtual methods
*/
public function __call($name, $params)
{
if (preg_match('/get(\w+)/', $name, $matches)) {
$virtualColumn = $matches[1];
if ($this->hasVirtualColumn($virtualColumn)) {
return $this->getVirtualColumn($virtualColumn);
}
// no lcfirst in php<5.3...
$virtualColumn[0] = strtolower($virtualColumn[0]);
if ($this->hasVirtualColumn($virtualColumn)) {
return $this->getVirtualColumn($virtualColumn);
}
}
throw new PropelException('Call to undefined method: ' . $name);
}
} // BaseCcSmemb
| martin-craig/Airtime | airtime_mvc/application/models/airtime/om/BaseCcSmemb.php | PHP | gpl-3.0 | 23,769 |
L.Polyline.Measure = L.Draw.Polyline.extend({
addHooks: function() {
L.Draw.Polyline.prototype.addHooks.call(this);
if (this._map) {
this._markerGroup = new L.LayerGroup();
this._map.addLayer(this._markerGroup);
this._markers = [];
this._map.on('click', this._onClick, this);
this._startShape();
}
},
removeHooks: function () {
L.Draw.Polyline.prototype.removeHooks.call(this);
this._clearHideErrorTimeout();
//!\ Still useful when control is disabled before any drawing (refactor needed?)
this._map.off('mousemove', this._onMouseMove);
this._clearGuides();
this._container.style.cursor = '';
this._removeShape();
this._map.off('click', this._onClick, this);
},
_startShape: function() {
this._drawing = true;
this._poly = new L.Polyline([], this.options.shapeOptions);
this._container.style.cursor = 'crosshair';
this._updateTooltip();
this._map.on('mousemove', this._onMouseMove, this);
},
_finishShape: function () {
this._drawing = false;
this._cleanUpShape();
this._clearGuides();
this._updateTooltip();
this._map.off('mousemove', this._onMouseMove, this);
this._container.style.cursor = '';
},
_removeShape: function() {
if (!this._poly)
return;
this._map.removeLayer(this._poly);
delete this._poly;
this._markers.splice(0);
this._markerGroup.clearLayers();
},
_onClick: function(e) {
if (!this._drawing && e.originalEvent.target.id !== 'btn-elevation-profile') {
this._removeShape();
this._startShape();
return;
}
else if (!this._drawing && e.originalEvent.target.id === 'btn-elevation-profile') {
this._elevationProfile();
}
},
_getTooltipText: function() {
var labelText = L.Draw.Polyline.prototype._getTooltipText.call(this),
elevLabel,
elevButton;
if (!this._drawing) {
elevLabel = gettext('elevation profile');
labelText.text = '<button class="btn btn-default" id="btn-elevation-profile">' + elevLabel + '</button>';
}
return labelText;
},
_elevationProfile: function () {
Ns.body.currentView.panels.currentView.drawElevation(this._poly.toGeoJSON());
this.disable();
}
});
L.Polyline.Elevation = L.Polyline.Measure.extend({
_getTooltipText: function() {
var labelText = L.Draw.Polyline.prototype._getTooltipText.call(this);
if (!this._drawing) {
labelText.text = '';
}
return labelText;
},
_finishShape: function () {
L.Polyline.Measure.prototype._finishShape.call(this);
this._elevationProfile();
},
});
L.Polygon.Measure = L.Draw.Polygon.extend({
options: { showArea: true },
addHooks: function() {
L.Draw.Polygon.prototype.addHooks.call(this);
if (this._map) {
this._markerGroup = new L.LayerGroup();
this._map.addLayer(this._markerGroup);
this._markers = [];
this._map.on('click', this._onClick, this);
this._startShape();
}
},
removeHooks: function () {
L.Draw.Polygon.prototype.removeHooks.call(this);
this._clearHideErrorTimeout();
//!\ Still useful when control is disabled before any drawing (refactor needed?)
this._map.off('mousemove', this._onMouseMove);
this._clearGuides();
this._container.style.cursor = '';
this._removeShape();
this._map.off('click', this._onClick, this);
},
_startShape: function() {
this._drawing = true;
this._poly = new L.Polygon([], this.options.shapeOptions);
this._container.style.cursor = 'crosshair';
this._updateTooltip();
this._map.on('mousemove', this._onMouseMove, this);
},
_finishShape: function () {
this._drawing = false;
this._cleanUpShape();
this._clearGuides();
this._updateTooltip();
this._map.off('mousemove', this._onMouseMove, this);
this._container.style.cursor = '';
},
_removeShape: function() {
if (!this._poly)
return;
this._map.removeLayer(this._poly);
delete this._poly;
this._markers.splice(0);
this._markerGroup.clearLayers();
},
_onClick: function(e) {
if (!this._drawing) {
this._removeShape();
this._startShape();
return;
}
},
_getTooltipText: function() {
var labelText = L.Draw.Polygon.prototype._getTooltipText.call(this);
if (!this._drawing) {
labelText.text = '';
labelText.subtext = this._getArea();
}
return labelText;
},
_getArea: function() {
var latLng = [],
geodisc;
for(var i=0, len=this._markers.length; i < len; i++) {
latLng.push(this._markers[i]._latlng);
}
geodisc = L.GeometryUtil.geodesicArea(latLng);
return L.GeometryUtil.readableArea(geodisc, true);
}
});
| sephiroth6/nodeshot | nodeshot/ui/default/static/ui/lib/js/leaflet.measurecontrol-customized.js | JavaScript | gpl-3.0 | 5,309 |
/************************************************************************
**
** Copyright (C) 2012 John Schember <john@nachtimwald.com>
** Copyright (C) 2012 Dave Heiland
** Copyright (C) 2012 Grant Drake
** Copyright (C) 2009, 2010, 2011 Strahinja Markovic <strahinja.markovic@gmail.com>
**
** This file is part of Sigil.
**
** Sigil is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** Sigil is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Sigil. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#include <QtCore/QTimer>
#include <QtCore/QUrl>
#include <QtWidgets/QApplication>
#include <QtWidgets/QAction>
#include <QtWidgets/QDialog>
#include <QtWidgets/QLayout>
#include <QtPrintSupport/QPrinter>
#include <QtPrintSupport/QPrintDialog>
#include <QtPrintSupport/QPrintPreviewDialog>
#include <QtWidgets/QStackedWidget>
#include "BookManipulation/CleanSource.h"
#include "MiscEditors/ClipEditorModel.h"
#include "Misc/SettingsStore.h"
#include "Misc/Utility.h"
#include "ResourceObjects/HTMLResource.h"
#include "sigil_constants.h"
#include "Tabs/FlowTab.h"
#include "Tabs/WellFormedCheckComponent.h"
#include "ViewEditors/BookViewEditor.h"
#include "ViewEditors/BookViewPreview.h"
#include "ViewEditors/CodeViewEditor.h"
static const QString SETTINGS_GROUP = "flowtab";
FlowTab::FlowTab(HTMLResource *resource,
const QUrl &fragment,
MainWindow::ViewState view_state,
int line_to_scroll_to,
int position_to_scroll_to,
QString caret_location_to_scroll_to,
bool grab_focus,
QWidget *parent)
:
ContentTab(resource, parent),
m_FragmentToScroll(fragment),
m_LineToScrollTo(line_to_scroll_to),
m_PositionToScrollTo(position_to_scroll_to),
m_CaretLocationToScrollTo(caret_location_to_scroll_to),
m_HTMLResource(resource),
m_views(new QStackedWidget(this)),
m_wBookView(NULL),
m_wCodeView(NULL),
m_ViewState(view_state),
m_previousViewState(view_state),
m_WellFormedCheckComponent(new WellFormedCheckComponent(this, parent)),
m_safeToLoad(false),
m_initialLoad(true),
m_bookViewNeedsReload(false),
m_grabFocus(grab_focus),
m_suspendTabReloading(false),
m_defaultCaretLocationToTop(false)
{
// Loading a flow tab can take a while. We set the wait
// cursor and clear it at the end of the delayed initialization.
QApplication::setOverrideCursor(Qt::WaitCursor);
if (view_state == MainWindow::ViewState_BookView) {
CreateBookViewIfRequired(false);
} else {
CreateCodeViewIfRequired(false);
}
m_Layout->addWidget(m_views);
LoadSettings();
// We need to set this in the constructor too,
// so that the ContentTab focus handlers don't
// get called when the tab is created.
if (view_state == MainWindow::ViewState_BookView) {
setFocusProxy(m_wBookView);
ConnectBookViewSignalsToSlots();
} else {
setFocusProxy(m_wCodeView);
ConnectCodeViewSignalsToSlots();
}
// We perform delayed initialization after the widget is on
// the screen. This way, the user perceives less load time.
QTimer::singleShot(0, this, SLOT(DelayedInitialization()));
}
FlowTab::~FlowTab()
{
// Explicitly disconnect signals because Modified is causing the ResourceModified
// function to be called after we delete BV and PV later in this destructor.
// No idea how that's possible but this prevents a segfault...
disconnect(m_HTMLResource, SIGNAL(Modified()), this, SLOT(ResourceModified()));
disconnect(this, 0, 0, 0);
m_WellFormedCheckComponent->deleteLater();
if (m_wBookView) {
delete m_wBookView;
m_wBookView = 0;
}
if (m_wCodeView) {
delete m_wCodeView;
m_wCodeView = 0;
}
if (m_views) {
delete(m_views);
m_views = 0;
}
}
void FlowTab::CreateBookViewIfRequired(bool is_delayed_load)
{
if (m_wBookView) {
return;
}
QApplication::setOverrideCursor(Qt::WaitCursor);
m_wBookView = new BookViewEditor(this);
m_views->addWidget(m_wBookView);
m_bookViewNeedsReload = true;
if (is_delayed_load) {
ConnectBookViewSignalsToSlots();
}
m_wBookView->Zoom();
QApplication::restoreOverrideCursor();
}
void FlowTab::CreateCodeViewIfRequired(bool is_delayed_load)
{
if (m_wCodeView) {
return;
}
QApplication::setOverrideCursor(Qt::WaitCursor);
m_wCodeView = new CodeViewEditor(CodeViewEditor::Highlight_XHTML, true, this);
m_wCodeView->SetReformatHTMLEnabled(true);
m_views->addWidget(m_wCodeView);
if (is_delayed_load) {
ConnectCodeViewSignalsToSlots();
// CodeView (if already loaded) will be directly hooked into the TextResource and
// will not need reloading. However if the tab was not in Code View at tab opening
// then we must populate it now.
m_wCodeView->CustomSetDocument(m_HTMLResource->GetTextDocumentForWriting());
// Zoom assignment only works after the document has been loaded
m_wCodeView->Zoom();
}
QApplication::restoreOverrideCursor();
}
void FlowTab::DelayedInitialization()
{
if (m_wBookView) {
m_safeToLoad = true;
LoadTabContent();
} else if (m_wCodeView) {
m_wCodeView->CustomSetDocument(m_HTMLResource->GetTextDocumentForWriting());
// Zoom factor for CodeView can only be set when document has been loaded.
m_wCodeView->Zoom();
}
switch (m_ViewState) {
case MainWindow::ViewState_CodeView: {
CodeView();
if (m_PositionToScrollTo > 0) {
m_wCodeView->ScrollToPosition(m_PositionToScrollTo);
} else if (m_LineToScrollTo > 0) {
m_wCodeView->ScrollToLine(m_LineToScrollTo);
} else {
m_wCodeView->ScrollToFragment(m_FragmentToScroll.toString());
}
break;
}
case MainWindow::ViewState_BookView:
default:
BookView();
if (!m_CaretLocationToScrollTo.isEmpty()) {
m_wBookView->ExecuteCaretUpdate(m_CaretLocationToScrollTo);
} else {
m_wBookView->ScrollToFragment(m_FragmentToScroll.toString());
}
break;
}
m_initialLoad = false;
// Only now will we wire up monitoring of ResourceChanged, to prevent
// unnecessary saving and marking of the resource for reloading.
DelayedConnectSignalsToSlots();
// Cursor set in constructor
QApplication::restoreOverrideCursor();
}
MainWindow::ViewState FlowTab::GetViewState()
{
return m_ViewState;
}
bool FlowTab::SetViewState(MainWindow::ViewState new_view_state)
{
// There are only two ways a tab can get routed into a particular viewstate.
// At FlowTab construction time, all initialisation is done via a timer to
// call DelayedInitialization(). So that needs to handle first time tab state.
// The second route is via this function, which is invoked from MainWindow
// any time a tab is switched to.
// Do we really need to do anything? Not if we are already in this state.
if (new_view_state == m_ViewState) {
return false;
}
// Ignore this function if we are in the middle of doing an initial load
// of the content. We don't want it to save over the content with nothing
// if this is called before the delayed initialization function is called.
if (m_initialLoad || !IsLoadingFinished()) {
return false;
}
// Our well formed check will be run if switching to BV. If this check fails,
// that check will set our tab viewstate to be in CV.
if (new_view_state == MainWindow::ViewState_BookView && !IsDataWellFormed()) {
return false;
}
// We do a save (if pending changes) before switching to ensure we don't lose
// any unsaved data in the current view, as cannot rely on lost focus happened.
SaveTabContent();
// Track our previous view state for the purposes of caret syncing
m_previousViewState = m_ViewState;
m_ViewState = new_view_state;
if (new_view_state == MainWindow::ViewState_CodeView) {
// As CV is directly hooked to the QTextDocument, we never have to "Load" content
// except for when creating the CV control for the very first time.
CreateCodeViewIfRequired();
CodeView();
} else {
CreateBookViewIfRequired();
LoadTabContent();
BookView();
}
return true;
}
bool FlowTab::IsLoadingFinished()
{
bool is_finished = true;
if (m_wCodeView) {
is_finished = m_wCodeView->IsLoadingFinished();
}
if (is_finished && m_wBookView) {
is_finished = m_wBookView->IsLoadingFinished();
}
return is_finished;
}
bool FlowTab::IsModified()
{
bool is_modified = false;
if (m_wCodeView) {
is_modified = is_modified || m_wCodeView->document()->isModified();
}
if (!is_modified && m_wBookView) {
is_modified = is_modified || m_wBookView->isModified();
}
return is_modified;
}
void FlowTab::BookView()
{
if (!IsDataWellFormed()) {
return;
}
QApplication::setOverrideCursor(Qt::WaitCursor);
CreateBookViewIfRequired();
m_views->setCurrentIndex(m_views->indexOf(m_wBookView));
setFocusProxy(m_wBookView);
// We will usually want focus in the tab, except when splitting opens this as a preceding tab.
if (m_grabFocus) {
m_wBookView->GrabFocus();
}
m_grabFocus = true;
// Ensure the caret is positioned corresponding to previous view of this tab
if (m_previousViewState == MainWindow::ViewState_CodeView) {
m_wBookView->StoreCaretLocationUpdate(m_wCodeView->GetCaretLocation());
}
m_wBookView->ExecuteCaretUpdate();
QApplication::restoreOverrideCursor();
}
void FlowTab::CodeView()
{
QApplication::setOverrideCursor(Qt::WaitCursor);
m_ViewState = MainWindow::ViewState_CodeView;
CreateCodeViewIfRequired();
m_views->setCurrentIndex(m_views->indexOf(m_wCodeView));
m_wCodeView->SetDelayedCursorScreenCenteringRequired();
setFocusProxy(m_wCodeView);
// We will usually want focus in the tab, except when splitting opens this as a preceding tab.
if (m_grabFocus) {
m_wCodeView->setFocus();
}
m_grabFocus = true;
// Ensure the caret is positioned corresponding to previous view of this tab
if (m_previousViewState == MainWindow::ViewState_BookView) {
m_wCodeView->StoreCaretLocationUpdate(m_wBookView->GetCaretLocation());
}
m_wCodeView->ExecuteCaretUpdate();
QApplication::restoreOverrideCursor();
}
void FlowTab::LoadTabContent()
{
// In CV, this call has nothing to do, as the resource is connected to QTextDocument.
// The only exception is initial load when control is created, done elsewhere.
// In BV, we will only allow loading if the document is well formed, since loading the
// resource into BV and then saving will alter badly formed sections of text.
if (m_ViewState == MainWindow::ViewState_BookView) {
if (m_safeToLoad && m_bookViewNeedsReload) {
m_wBookView->CustomSetDocument(m_HTMLResource->GetFullPath(), m_HTMLResource->GetText());
m_bookViewNeedsReload = false;
}
}
}
void FlowTab::SaveTabContent()
{
// In PV, content is read-only so nothing to do
// In CV, the connection between QPlainTextEdit and the underlying QTextDocument
// means the resource already is "saved". We just need to reset modified state.
// In BV, we only need to save the BV HTML into the resource if user has modified it,
// which will trigger ResourceModified() to set flag to say PV needs reloading.
if (m_ViewState == MainWindow::ViewState_BookView && m_wBookView && m_wBookView->IsModified()) {
SettingsStore ss;
QString html = m_wBookView->GetHtml();
if (ss.cleanOn() & CLEANON_OPEN) {
html = CleanSource::Clean(html);
}
m_HTMLResource->SetText(html);
m_wBookView->ResetModified();
m_safeToLoad = true;
}
// Either from being in CV or saving from BV above we now reset the resource to say no user changes unsaved.
m_HTMLResource->GetTextDocumentForWriting().setModified(false);
}
void FlowTab::ResourceModified()
{
// This slot tells us that the underlying HTML resource has been changed
if (m_ViewState == MainWindow::ViewState_CodeView) {
// It could be the user has done a Replace All on underlying resource, so reset our well formed check.
m_safeToLoad = false;
// When the underlying resource has been modified, it replaces the whole QTextDocument which
// causes cursor position to move to bottom of the document. We will have captured the location
// of the caret prior to replacing in the ResourceTextChanging() slot, so now we can restore it.
m_wCodeView->ExecuteCaretUpdate(m_defaultCaretLocationToTop);
m_defaultCaretLocationToTop = false;
}
m_bookViewNeedsReload = true;
EmitUpdatePreview();
}
void FlowTab::LinkedResourceModified()
{
MainWindow::clearMemoryCaches();
ResourceModified();
ReloadTabIfPending();
}
void FlowTab::ResourceTextChanging()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
// We need to store the caret location so it can be restored later
m_wCodeView->StoreCaretLocationUpdate(m_wCodeView->GetCaretLocation());
// If the caret happened to be at the very top of the document then our location
// will be empty. The problem is that when ResourceModified() fires next
// it will have effectively moved the caret to the bottom of the document.
// At which point we will call the CodeView to restore caret location.
// However the default behaviour of CodeView is to "do nothing" if no location
// is stored. So in this one situation we want to override that to force
// it to place the cursor at the top of the document.
m_defaultCaretLocationToTop = true;
}
}
void FlowTab::ReloadTabIfPending()
{
if (!isVisible()) {
return;
}
if (m_suspendTabReloading) {
return;
}
setFocus();
// Reload BV if the resource was marked as changed outside of the editor.
if ((m_bookViewNeedsReload && m_ViewState == MainWindow::ViewState_BookView)) {
LoadTabContent();
}
}
void FlowTab::LeaveEditor(QWidget *editor)
{
SaveTabContent();
}
void FlowTab::LoadSettings()
{
UpdateDisplay();
// SettingsChanged can fire for wanting the spelling highlighting to be refreshed on the tab.
if (m_wCodeView) {
m_wCodeView->RefreshSpellingHighlighting();
}
}
void FlowTab::UpdateDisplay()
{
if (m_wBookView) {
m_wBookView->UpdateDisplay();
}
if (m_wCodeView) {
m_wCodeView->UpdateDisplay();
}
}
void FlowTab::EmitContentChanged()
{
m_safeToLoad = false;
emit ContentChanged();
}
void FlowTab::EmitUpdatePreview()
{
emit UpdatePreview();
}
void FlowTab::EmitUpdatePreviewImmediately()
{
emit UpdatePreviewImmediately();
}
void FlowTab::EmitUpdateCursorPosition()
{
emit UpdateCursorPosition(GetCursorLine(), GetCursorColumn());
}
void FlowTab::HighlightWord(QString word, int pos)
{
if (m_wCodeView) {
m_wCodeView->HighlightWord(word, pos);
}
}
void FlowTab::RefreshSpellingHighlighting()
{
// We always want this to happen, regardless of what the current view is.
if (m_wCodeView) {
m_wCodeView->RefreshSpellingHighlighting();
}
}
bool FlowTab::CutEnabled()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->pageAction(QWebPage::Cut)->isEnabled();
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->textCursor().hasSelection();
}
return false;
}
bool FlowTab::CopyEnabled()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->pageAction(QWebPage::Copy)->isEnabled();
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->textCursor().hasSelection();
}
return false;
}
bool FlowTab::PasteEnabled()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->pageAction(QWebPage::Paste)->isEnabled();
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->canPaste();
}
return false;
}
bool FlowTab::DeleteLineEnabled()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return !m_wCodeView->document()->isEmpty();
}
return false;
}
bool FlowTab::RemoveFormattingEnabled()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->pageAction(QWebPage::RemoveFormat)->isEnabled();
}
if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->IsCutCodeTagsAllowed();
}
return false;
}
bool FlowTab::InsertClosingTagEnabled()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->IsInsertClosingTagAllowed();
}
return false;
}
bool FlowTab::AddToIndexEnabled()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->IsAddToIndexAllowed();
} else if (m_ViewState == MainWindow::ViewState_BookView) {
return true;
}
return false;
}
bool FlowTab::MarkForIndexEnabled()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return true;
} else if (m_ViewState == MainWindow::ViewState_BookView) {
return true;
}
return false;
}
bool FlowTab::InsertIdEnabled()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->IsInsertIdAllowed();
} else if (m_ViewState == MainWindow::ViewState_BookView) {
return true;
}
return false;
}
bool FlowTab::InsertHyperlinkEnabled()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->IsInsertHyperlinkAllowed();
} else if (m_ViewState == MainWindow::ViewState_BookView) {
return true;
}
return false;
}
bool FlowTab::InsertSpecialCharacterEnabled()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return true;
} else if (m_ViewState == MainWindow::ViewState_BookView) {
return true;
}
return false;
}
bool FlowTab::InsertFileEnabled()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->IsInsertFileAllowed();
} else if (m_ViewState == MainWindow::ViewState_BookView) {
return true;
}
return false;
}
bool FlowTab::ToggleAutoSpellcheckEnabled()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return true;
}
return false;
}
bool FlowTab::ViewStatesEnabled()
{
if (m_ViewState == MainWindow::ViewState_BookView ||
m_ViewState == MainWindow::ViewState_CodeView) {
return true;
}
return false;
}
void FlowTab::GoToCaretLocation(QList<ViewEditor::ElementIndex> location)
{
if (location.isEmpty()) {
return;
}
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->StoreCaretLocationUpdate(location);
m_wBookView->ExecuteCaretUpdate();
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->StoreCaretLocationUpdate(location);
m_wCodeView->ExecuteCaretUpdate();
}
}
QList<ViewEditor::ElementIndex> FlowTab::GetCaretLocation()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->GetCaretLocation();
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->GetCaretLocation();
}
return QList<ViewEditor::ElementIndex>();
}
QString FlowTab::GetCaretLocationUpdate() const
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->GetCaretLocationUpdate();
}
return QString();
}
QString FlowTab::GetDisplayedCharacters()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->GetDisplayedCharacters();
}
return "";
}
QString FlowTab::GetText()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->toPlainText();
} else if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->GetHtml();
}
return "";
}
int FlowTab::GetCursorPosition() const
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->GetCursorPosition();
}
return -1;
}
int FlowTab::GetCursorLine() const
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->GetCursorLine();
}
return -1;
}
int FlowTab::GetCursorColumn() const
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->GetCursorColumn();
}
return -1;
}
float FlowTab::GetZoomFactor() const
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->GetZoomFactor();
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->GetZoomFactor();
}
return 1;
}
void FlowTab::SetZoomFactor(float new_zoom_factor)
{
// We need to set a wait cursor for the Book View
// since zoom operations take some time in it.
if (m_ViewState == MainWindow::ViewState_BookView) {
QApplication::setOverrideCursor(Qt::WaitCursor);
if (m_wBookView) {
m_wBookView->SetZoomFactor(new_zoom_factor);
}
QApplication::restoreOverrideCursor();
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->SetZoomFactor(new_zoom_factor);
}
}
Searchable *FlowTab::GetSearchableContent()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView;
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView;
}
return NULL;
}
void FlowTab::ScrollToFragment(const QString &fragment)
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->ScrollToFragment(fragment);
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->ScrollToFragment(fragment);
}
}
void FlowTab::ScrollToLine(int line)
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->ScrollToLine(line);
}
// Scrolling to top if BV/CV requests a line allows
// view to be reset to top for links
else if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->ScrollToTop();
}
}
void FlowTab::ScrollToPosition(int cursor_position)
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->ScrollToPosition(cursor_position);
}
}
void FlowTab::ScrollToCaretLocation(QString caret_location_update)
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->ExecuteCaretUpdate(caret_location_update);
}
}
void FlowTab::ScrollToTop()
{
if (m_wBookView) {
m_wBookView->ScrollToTop();
}
if (m_wCodeView) {
m_wCodeView->ScrollToTop();
}
}
void FlowTab::AutoFixWellFormedErrors()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
int pos = m_wCodeView->GetCursorPosition();
m_wCodeView->ReplaceDocumentText(CleanSource::ToValidXHTML(m_wCodeView->toPlainText()));
m_wCodeView->ScrollToPosition(pos);
}
}
void FlowTab::TakeControlOfUI()
{
EmitCentralTabRequest();
setFocus();
}
QString FlowTab::GetFilename()
{
return ContentTab::GetFilename();
}
bool FlowTab::IsDataWellFormed()
{
// The content has been changed or was in a not well formed state when last checked.
if (m_ViewState == MainWindow::ViewState_BookView) {
// If we are in BookView, then we know the data must be well formed, as even if edits have
// taken place QWebView will have retained the XHTML integrity.
m_safeToLoad = true;
} else {
// We are in PV or CV. In either situation the xhtml from CV could be invalid as the user may
// have switched to PV to preview it (as they are allowed to do).
// It is also possible that they opened the tab in PV as the initial load and CV is not loaded.
// We are doing a well formed check, but we can only do it on the CV text if CV has been loaded.
// So lets play safe and have a fallback to use the resource text if CV is not loaded yet.
XhtmlDoc::WellFormedError error = (m_wCodeView != NULL)
? XhtmlDoc::WellFormedErrorForSource(m_wCodeView->toPlainText())
: XhtmlDoc::WellFormedErrorForSource(m_HTMLResource->GetText());
m_safeToLoad = error.line == -1;
if (!m_safeToLoad) {
if (m_ViewState != MainWindow::ViewState_CodeView) {
CodeView();
}
m_WellFormedCheckComponent->DemandAttentionIfAllowed(error);
}
}
return m_safeToLoad;
}
void FlowTab::Undo()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->Undo();
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->undo();
}
}
void FlowTab::Redo()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->Redo();
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->redo();
}
}
void FlowTab::Cut()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->page()->triggerAction(QWebPage::Cut);
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->cut();
}
}
void FlowTab::Copy()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->page()->triggerAction(QWebPage::Copy);
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->copy();
}
}
void FlowTab::Paste()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->paste();
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->paste();
}
}
void FlowTab::DeleteLine()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->DeleteLine();
}
}
bool FlowTab::MarkSelection()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->MarkSelection();
}
return false;
}
bool FlowTab::ClearMarkedText()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->ClearMarkedText();
}
return false;
}
void FlowTab::SplitSection()
{
if (!IsDataWellFormed()) {
return;
}
if (m_ViewState == MainWindow::ViewState_BookView) {
QString content = m_wBookView->SplitSection();
// The webview visually has split off the text, but not yet saved to the underlying resource
SaveTabContent();
emit OldTabRequest(content, m_HTMLResource);
} else if (m_ViewState == MainWindow::ViewState_CodeView && m_wCodeView) {
emit OldTabRequest(m_wCodeView->SplitSection(), m_HTMLResource);
}
}
void FlowTab::InsertSGFSectionMarker()
{
if (!IsDataWellFormed()) {
return;
}
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->InsertHtml(BREAK_TAG_INSERT);
} else if (m_ViewState == MainWindow::ViewState_CodeView && m_wCodeView) {
m_wCodeView->InsertSGFSectionMarker();
}
}
void FlowTab::InsertClosingTag()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->InsertClosingTag();
}
}
void FlowTab::AddToIndex()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->AddToIndex();
} else if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->AddToIndex();
}
}
bool FlowTab::MarkForIndex(const QString &title)
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->MarkForIndex(title);
} else if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->MarkForIndex(title);
}
return false;
}
QString FlowTab::GetAttributeId()
{
QString attribute_value;
if (m_ViewState == MainWindow::ViewState_CodeView) {
// We are only interested in ids on <a> anchor elements
attribute_value = m_wCodeView->GetAttributeId();
} else if (m_ViewState == MainWindow::ViewState_BookView) {
attribute_value = m_wBookView->GetAncestorTagAttributeValue("id", ANCHOR_TAGS);
}
return attribute_value;
}
QString FlowTab::GetAttributeHref()
{
QString attribute_value;
if (m_ViewState == MainWindow::ViewState_CodeView) {
attribute_value = m_wCodeView->GetAttribute("href", ANCHOR_TAGS, false, true);
} else if (m_ViewState == MainWindow::ViewState_BookView) {
attribute_value = m_wBookView->GetAncestorTagAttributeValue("href", ANCHOR_TAGS);
}
return attribute_value;
}
QString FlowTab::GetAttributeIndexTitle()
{
QString attribute_value;
if (m_ViewState == MainWindow::ViewState_CodeView) {
attribute_value = m_wCodeView->GetAttribute("title", ANCHOR_TAGS, false, true);
if (attribute_value.isEmpty()) {
attribute_value = m_wCodeView->GetSelectedText();
}
} else if (m_ViewState == MainWindow::ViewState_BookView) {
attribute_value = m_wBookView->GetAncestorTagAttributeValue("title", ANCHOR_TAGS);
if (attribute_value.isEmpty()) {
attribute_value = m_wBookView->GetSelectedText();
}
}
return attribute_value;
}
QString FlowTab::GetSelectedText()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->GetSelectedText();
} else if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->GetSelectedText();
}
return "";
}
bool FlowTab::InsertId(const QString &id)
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->InsertId(id);
} else if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->InsertId(id);
}
return false;
}
bool FlowTab::InsertHyperlink(const QString &href)
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->InsertHyperlink(href);
} else if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->InsertHyperlink(href);
}
return false;
}
void FlowTab::InsertFile(QString html)
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->InsertHtml(html);
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->insertPlainText(html);
}
}
void FlowTab::PrintPreview()
{
QPrintPreviewDialog *print_preview = new QPrintPreviewDialog(this);
if (m_ViewState == MainWindow::ViewState_BookView) {
connect(print_preview, SIGNAL(paintRequested(QPrinter *)), m_wBookView, SLOT(print(QPrinter *)));
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
connect(print_preview, SIGNAL(paintRequested(QPrinter *)), m_wCodeView, SLOT(print(QPrinter *)));
} else {
return;
}
print_preview->exec();
print_preview->deleteLater();
}
void FlowTab::Print()
{
QPrinter printer;
QPrintDialog print_dialog(&printer, this);
print_dialog.setWindowTitle(tr("Print %1").arg(GetFilename()));
if (print_dialog.exec() == QDialog::Accepted) {
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->print(&printer);
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->print(&printer);
}
}
}
void FlowTab::Bold()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->page()->triggerAction(QWebPage::ToggleBold);
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->ToggleFormatSelection("b", "font-weight", "bold");
}
}
void FlowTab::Italic()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->page()->triggerAction(QWebPage::ToggleItalic);
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->ToggleFormatSelection("i", "font-style", "italic");
}
}
void FlowTab::Underline()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->page()->triggerAction(QWebPage::ToggleUnderline);
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->ToggleFormatSelection("u", "text-decoration", "underline");
}
}
// the strike tag has been deprecated, the del tag is still okay
void FlowTab::Strikethrough()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->ExecCommand("strikeThrough");
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->ToggleFormatSelection("del", "text-decoration", "line-through");
}
}
void FlowTab::Subscript()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->page()->triggerAction(QWebPage::ToggleSubscript);
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->ToggleFormatSelection("sub");
}
}
void FlowTab::Superscript()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->page()->triggerAction(QWebPage::ToggleSuperscript);
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->ToggleFormatSelection("sup");
}
}
void FlowTab::AlignLeft()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->ExecCommand("justifyLeft");
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->FormatStyle("text-align", "left");
}
}
void FlowTab::AlignCenter()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->ExecCommand("justifyCenter");
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->FormatStyle("text-align", "center");
}
}
void FlowTab::AlignRight()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->ExecCommand("justifyRight");
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->FormatStyle("text-align", "right");
}
}
void FlowTab::AlignJustify()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->ExecCommand("justifyFull");
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->FormatStyle("text-align", "justify");
}
}
void FlowTab::InsertBulletedList()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->ExecCommand("insertUnorderedList");
}
}
void FlowTab::InsertNumberedList()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->ExecCommand("insertOrderedList");
}
}
void FlowTab::DecreaseIndent()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->page()->triggerAction(QWebPage::Outdent);
}
}
void FlowTab::IncreaseIndent()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->page()->triggerAction(QWebPage::Indent);
}
}
void FlowTab::TextDirectionLeftToRight()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->page()->triggerAction(QWebPage::SetTextDirectionLeftToRight);
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->FormatStyle("direction", "ltr");
}
}
void FlowTab::TextDirectionRightToLeft()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->page()->triggerAction(QWebPage::SetTextDirectionRightToLeft);
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->FormatStyle("direction", "rtl");
}
}
void FlowTab::TextDirectionDefault()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->page()->triggerAction(QWebPage::SetTextDirectionDefault);
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->FormatStyle("direction", "inherit");
}
}
void FlowTab::ShowTag()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->ShowTag();
}
}
void FlowTab::RemoveFormatting()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->page()->triggerAction(QWebPage::RemoveFormat);
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->CutCodeTags();
}
}
void FlowTab::ChangeCasing(const Utility::Casing casing)
{
if (m_ViewState == MainWindow::ViewState_BookView) {
m_wBookView->ApplyCaseChangeToSelection(casing);
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->ApplyCaseChangeToSelection(casing);
}
}
void FlowTab::HeadingStyle(const QString &heading_type, bool preserve_attributes)
{
if (m_ViewState == MainWindow::ViewState_BookView) {
QChar last_char = heading_type[ heading_type.count() - 1 ];
// For heading_type == "Heading #"
if (last_char.isDigit()) {
m_wBookView->FormatBlock("h" % QString(last_char), preserve_attributes);
} else if (heading_type == "Normal") {
m_wBookView->FormatBlock("p", preserve_attributes);
}
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
QChar last_char = heading_type[ heading_type.count() - 1 ];
// For heading_type == "Heading #"
if (last_char.isDigit()) {
m_wCodeView->FormatBlock("h" % QString(last_char), preserve_attributes);
} else if (heading_type == "Normal") {
m_wCodeView->FormatBlock("p", preserve_attributes);
}
}
}
void FlowTab::GoToLinkOrStyle()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->GoToLinkOrStyle();
}
}
void FlowTab::AddMisspelledWord()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->AddMisspelledWord();
}
}
void FlowTab::IgnoreMisspelledWord()
{
if (m_ViewState == MainWindow::ViewState_CodeView) {
m_wCodeView->IgnoreMisspelledWord();
}
}
bool FlowTab::BoldChecked()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->pageAction(QWebPage::ToggleBold)->isChecked();
} else {
return ContentTab::BoldChecked();
}
}
bool FlowTab::ItalicChecked()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->pageAction(QWebPage::ToggleItalic)->isChecked();
} else {
return ContentTab::ItalicChecked();
}
}
bool FlowTab::UnderlineChecked()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->pageAction(QWebPage::ToggleUnderline)->isChecked();
} else {
return ContentTab::UnderlineChecked();
}
}
bool FlowTab::StrikethroughChecked()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->QueryCommandState("strikeThrough");
} else {
return ContentTab::StrikethroughChecked();
}
}
bool FlowTab::SubscriptChecked()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->QueryCommandState("subscript");
} else {
return ContentTab::SubscriptChecked();
}
}
bool FlowTab::SuperscriptChecked()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->QueryCommandState("superscript");
} else {
return ContentTab::SuperscriptChecked();
}
}
bool FlowTab::AlignLeftChecked()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->QueryCommandState("justifyLeft");
} else {
return ContentTab::AlignLeftChecked();
}
}
bool FlowTab::AlignRightChecked()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->QueryCommandState("justifyRight");
} else {
return ContentTab::AlignRightChecked();
}
}
bool FlowTab::AlignCenterChecked()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->QueryCommandState("justifyCenter");
} else {
return ContentTab::AlignCenterChecked();
}
}
bool FlowTab::AlignJustifyChecked()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->QueryCommandState("justifyFull");
} else {
return ContentTab::AlignJustifyChecked();
}
}
bool FlowTab::BulletListChecked()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->QueryCommandState("insertUnorderedList");
} else {
return ContentTab::BulletListChecked();
}
}
bool FlowTab::NumberListChecked()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->QueryCommandState("insertOrderedList");
} else {
return ContentTab::NumberListChecked();
}
}
bool FlowTab::PasteClipNumber(int clip_number)
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->PasteClipNumber(clip_number);
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->PasteClipNumber(clip_number);
}
return false;
}
bool FlowTab::PasteClipEntries(QList<ClipEditorModel::clipEntry *>clips)
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->PasteClipEntries(clips);
} else if (m_ViewState == MainWindow::ViewState_CodeView) {
return m_wCodeView->PasteClipEntries(clips);
}
return false;
}
QString FlowTab::GetCaretElementName()
{
if (m_ViewState == MainWindow::ViewState_BookView) {
return m_wBookView->GetCaretElementName();
} else {
return ContentTab::GetCaretElementName();
}
}
void FlowTab::SuspendTabReloading()
{
// Call this function to prevent the currently displayed BV/PV from being
// reloaded if a linked resource is changed. Automatic reloading can cause
// issues if your code is attempting to manipulate the tab content concurrently.
m_suspendTabReloading = true;
}
void FlowTab::ResumeTabReloading()
{
// Call this function to resume reloading of BV/PV in response to linked
// resources changing. If a reload tab request is pending it is executed now.
m_suspendTabReloading = false;
// Force an immediate reload if there is one pending
if (m_bookViewNeedsReload) {
// Must save tab content first or else reload may not take place.
SaveTabContent();
ReloadTabIfPending();
}
}
void FlowTab::DelayedConnectSignalsToSlots()
{
connect(m_HTMLResource, SIGNAL(TextChanging()), this, SLOT(ResourceTextChanging()));
connect(m_HTMLResource, SIGNAL(LinkedResourceUpdated()), this, SLOT(LinkedResourceModified()));
connect(m_HTMLResource, SIGNAL(Modified()), this, SLOT(ResourceModified()));
connect(m_HTMLResource, SIGNAL(LoadedFromDisk()), this, SLOT(ReloadTabIfPending()));
}
void FlowTab::ConnectBookViewSignalsToSlots()
{
connect(m_wBookView, SIGNAL(ZoomFactorChanged(float)), this, SIGNAL(ZoomFactorChanged(float)));
connect(m_wBookView, SIGNAL(selectionChanged()), this, SIGNAL(SelectionChanged()));
connect(m_wBookView, SIGNAL(FocusLost(QWidget *)), this, SLOT(LeaveEditor(QWidget *)));
connect(m_wBookView, SIGNAL(InsertFile()), this, SIGNAL(InsertFileRequest()));
connect(m_wBookView, SIGNAL(LinkClicked(const QUrl &)), this, SIGNAL(LinkClicked(const QUrl &)));
connect(m_wBookView, SIGNAL(ClipboardSaveRequest()), this, SIGNAL(ClipboardSaveRequest()));
connect(m_wBookView, SIGNAL(ClipboardRestoreRequest()), this, SIGNAL(ClipboardRestoreRequest()));
connect(m_wBookView, SIGNAL(InsertedFileOpenedExternally(const QString &)), this, SIGNAL(InsertedFileOpenedExternally(const QString &)));
connect(m_wBookView, SIGNAL(InsertedFileSaveAs(const QUrl &)), this, SIGNAL(InsertedFileSaveAs(const QUrl &)));
connect(m_wBookView, SIGNAL(ShowStatusMessageRequest(const QString &)), this, SIGNAL(ShowStatusMessageRequest(const QString &)));
connect(m_wBookView, SIGNAL(OpenClipEditorRequest(ClipEditorModel::clipEntry *)), this, SIGNAL(OpenClipEditorRequest(ClipEditorModel::clipEntry *)));
connect(m_wBookView, SIGNAL(OpenIndexEditorRequest(IndexEditorModel::indexEntry *)), this, SIGNAL(OpenIndexEditorRequest(IndexEditorModel::indexEntry *)));
connect(m_wBookView, SIGNAL(textChanged()), this, SLOT(EmitContentChanged()));
connect(m_wBookView, SIGNAL(BVInspectElement()), this, SIGNAL(InspectElement()));
connect(m_wBookView, SIGNAL(PageUpdated()), this, SLOT(EmitUpdatePreview()));
connect(m_wBookView, SIGNAL(PageClicked()), this, SLOT(EmitUpdatePreviewImmediately()));
connect(m_wBookView, SIGNAL(PageOpened()), this, SLOT(EmitUpdatePreviewImmediately()));
connect(m_wBookView, SIGNAL(DocumentLoaded()), this, SLOT(EmitUpdatePreviewImmediately()));
}
void FlowTab::ConnectCodeViewSignalsToSlots()
{
connect(m_wCodeView, SIGNAL(cursorPositionChanged()), this, SLOT(EmitUpdateCursorPosition()));
connect(m_wCodeView, SIGNAL(ZoomFactorChanged(float)), this, SIGNAL(ZoomFactorChanged(float)));
connect(m_wCodeView, SIGNAL(selectionChanged()), this, SIGNAL(SelectionChanged()));
connect(m_wCodeView, SIGNAL(FocusLost(QWidget *)), this, SLOT(LeaveEditor(QWidget *)));
connect(m_wCodeView, SIGNAL(LinkClicked(const QUrl &)), this, SIGNAL(LinkClicked(const QUrl &)));
connect(m_wCodeView, SIGNAL(ViewImage(const QUrl &)), this, SIGNAL(ViewImageRequest(const QUrl &)));
connect(m_wCodeView, SIGNAL(OpenClipEditorRequest(ClipEditorModel::clipEntry *)), this, SIGNAL(OpenClipEditorRequest(ClipEditorModel::clipEntry *)));
connect(m_wCodeView, SIGNAL(OpenIndexEditorRequest(IndexEditorModel::indexEntry *)), this, SIGNAL(OpenIndexEditorRequest(IndexEditorModel::indexEntry *)));
connect(m_wCodeView, SIGNAL(GoToLinkedStyleDefinitionRequest(const QString &, const QString &)), this, SIGNAL(GoToLinkedStyleDefinitionRequest(const QString &, const QString &)));
connect(m_wCodeView, SIGNAL(BookmarkLinkOrStyleLocationRequest()), this, SIGNAL(BookmarkLinkOrStyleLocationRequest()));
connect(m_wCodeView, SIGNAL(SpellingHighlightRefreshRequest()), this, SIGNAL(SpellingHighlightRefreshRequest()));
connect(m_wCodeView, SIGNAL(ShowStatusMessageRequest(const QString &)), this, SIGNAL(ShowStatusMessageRequest(const QString &)));
connect(m_wCodeView, SIGNAL(FilteredTextChanged()), this, SLOT(EmitContentChanged()));
connect(m_wCodeView, SIGNAL(FilteredCursorMoved()), this, SLOT(EmitUpdatePreview()));
connect(m_wCodeView, SIGNAL(PageUpdated()), this, SLOT(EmitUpdatePreview()));
connect(m_wCodeView, SIGNAL(PageClicked()), this, SLOT(EmitUpdatePreviewImmediately()));
connect(m_wCodeView, SIGNAL(DocumentSet()), this, SLOT(EmitUpdatePreviewImmediately()));
connect(m_wCodeView, SIGNAL(MarkSelectionRequest()), this, SIGNAL(MarkSelectionRequest()));
connect(m_wCodeView, SIGNAL(ClearMarkedTextRequest()), this, SIGNAL(ClearMarkedTextRequest()));
}
| uchuugaka/Sigil | src/Tabs/FlowTab.cpp | C++ | gpl-3.0 | 47,948 |
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2014 The Kuali Foundation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.module.tem.batch.service.impl;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ArrayUtils;
import org.kuali.kfs.module.tem.batch.businessobject.PerDiemForLoad;
import org.kuali.kfs.module.tem.batch.service.PerDiemFileParsingService;
import org.kuali.kfs.sys.ObjectUtil;
import au.com.bytecode.opencsv.CSVReader;
public class PerDiemFileParsingServiceImpl implements PerDiemFileParsingService {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(PerDiemFileParsingServiceImpl.class);
/**
* @see org.kuali.kfs.module.tem.batch.service.PerDiemFileParsingService#buildPerDiemsFromFlatFile(java.lang.String,
* java.lang.String)
*/
@Override
public List<PerDiemForLoad> buildPerDiemsFromFlatFile(String fileName, String deliminator, List<String> fieldsToPopulate) {
try {
Reader fileReader = new FileReader(fileName);
return this.buildPerDiemsFromFlatFile(fileReader, deliminator, fieldsToPopulate);
}
catch (FileNotFoundException ex) {
LOG.error("Failed to process data file: " + fileName);
throw new RuntimeException("Failed to process data file: " + fileName, ex);
}
}
/**
* @see org.kuali.kfs.module.tem.batch.service.PerDiemFileParsingService#buildPerDiemsFromFlatFile(java.io.Reader,
* java.lang.String)
*/
@Override
public List<PerDiemForLoad> buildPerDiemsFromFlatFile(Reader reader, String deliminator, List<String> fieldsToPopulate) {
List<PerDiemForLoad> perDiemList = new ArrayList<PerDiemForLoad>();
CSVReader csvReader = null;
try {
char charDeliminator = deliminator.charAt(0);
csvReader = new CSVReader(reader, charDeliminator);
String[] perDiemInString = null;
while ((perDiemInString = csvReader.readNext()) != null) {
if (ArrayUtils.contains(perDiemInString, "FOOTNOTES: ")) {
break;
}
PerDiemForLoad perDiem = new PerDiemForLoad();
ObjectUtil.buildObject(perDiem, perDiemInString, fieldsToPopulate);
perDiemList.add(perDiem);
}
}
catch (Exception ex) {
LOG.error("Failed to process data file. ");
throw new RuntimeException("Failed to process data file. ", ex);
}
finally {
if (csvReader != null) {
try {
csvReader.close();
}
catch (IOException ex) {
LOG.info(ex);
}
}
IOUtils.closeQuietly(reader);
}
return perDiemList;
}
}
| ua-eas/ua-kfs-5.3 | work/src/org/kuali/kfs/module/tem/batch/service/impl/PerDiemFileParsingServiceImpl.java | Java | agpl-3.0 | 3,883 |
/*
* re-quote.js
*
* Copyright (C) 2009-13 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
module.exports = function(str){
// List derived from http://stackoverflow.com/questions/399078/what-special-characters-must-be-escaped-in-regular-expressions
return str.replace(/[.\^$*+?()[{\\|\-\]]/g, '\\$&');
} | rstudio/shiny-server | lib/core/re-quote.js | JavaScript | agpl-3.0 | 656 |
/*
* eXist Open Source Native XML Database
* Copyright (C) 2001-2009 The eXist Project
* http://exist-db.org
*
* 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
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* $Id$
*/
package org.exist.xquery.functions.fn;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.dom.QName;
import org.exist.xquery.Cardinality;
import org.exist.xquery.Dependency;
import org.exist.xquery.Function;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.Profiler;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.DateTimeValue;
import org.exist.xquery.value.FunctionReturnSequenceType;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.Type;
/**
* @author Wolfgang Meier (wolfgang@exist-db.org)
*/
public class FunCurrentDateTime extends Function {
protected static final Logger logger = LogManager.getLogger(FunCurrentDateTime.class);
public final static FunctionSignature fnCurrentDateTime =
new FunctionSignature(
new QName("current-dateTime", Function.BUILTIN_FUNCTION_NS),
"Returns the xs:dateTime (with timezone) that is current at some time " +
"during the evaluation of a query or transformation in which " +
"fn:current-dateTime() is executed.",
null,
new FunctionReturnSequenceType(Type.DATE_TIME,
Cardinality.EXACTLY_ONE, "the date-time current " +
"within query execution time span"));
public final static FunctionSignature fnCurrentTime =
new FunctionSignature(
new QName("current-time", Function.BUILTIN_FUNCTION_NS),
"Returns the xs:time (with timezone) that is current at some time " +
"during the evaluation of a query or transformation in which " +
"fn:current-time() is executed.",
null,
new FunctionReturnSequenceType(Type.TIME,
Cardinality.EXACTLY_ONE, "the time current " +
"within query execution time span"));
public final static FunctionSignature fnCurrentDate =
new FunctionSignature(
new QName("current-date", Function.BUILTIN_FUNCTION_NS),
"Returns the xs:date (with timezone) that is current at some time " +
"during the evaluation of a query or transformation in which " +
"fn:current-date() is executed.",
null,
new FunctionReturnSequenceType(Type.DATE,
Cardinality.EXACTLY_ONE, "the date current " +
"within the query execution time span"));
public FunCurrentDateTime(XQueryContext context, FunctionSignature signature) {
super(context, signature);
}
public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
if (context.getProfiler().isEnabled()) {
context.getProfiler().start(this);
context.getProfiler().message(this, Profiler.DEPENDENCIES,
"DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies()));
if (contextSequence != null)
{context.getProfiler().message(this, Profiler.START_SEQUENCES,
"CONTEXT SEQUENCE", contextSequence);}
if (contextItem != null)
{context.getProfiler().message(this, Profiler.START_SEQUENCES,
"CONTEXT ITEM", contextItem.toSequence());}
}
Sequence result = new DateTimeValue(context.getCalendar());
if (isCalledAs("current-dateTime")) {
// do nothing, result already in right form
} else if (isCalledAs("current-date")) {
result = result.convertTo(Type.DATE);
} else if (isCalledAs("current-time")) {
result = result.convertTo(Type.TIME);
} else {
throw new Error("Can't handle function " + mySignature.getName().getLocalPart());
}
if (context.getProfiler().isEnabled()) {context.getProfiler().end(this, "", result);}
return result;
}
}
| MjAbuz/exist | src/org/exist/xquery/functions/fn/FunCurrentDateTime.java | Java | lgpl-2.1 | 4,868 |
/*
* Copyright 2016 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.test.manual.elytron.seccontext;
import java.security.Principal;
import javax.ejb.Remote;
@Remote
public interface WhoAmI {
/**
* @return the caller principal obtained from the EJBContext.
*/
Principal getCallerPrincipal();
/**
* Throws IllegalStateException.
*/
String throwIllegalStateException();
/**
* Throws Server2Exception.
*/
String throwServer2Exception();
} | xasx/wildfly | testsuite/integration/manualmode/src/test/java/org/wildfly/test/manual/elytron/seccontext/WhoAmI.java | Java | lgpl-2.1 | 1,040 |
<?php
class AddReviewedWordsCountToChunkReviews extends AbstractMatecatMigration
{
public $sql_up = <<<EOF
ALTER TABLE `qa_chunk_reviews` ADD COLUMN `reviewed_words_count` integer NOT NULL DEFAULT 0 ;
EOF;
public $sql_down = <<<EOF
ALTER TABLE `qa_chunk_reviews` DROP COLUMN `reviewed_words_count` ;
EOF;
}
| danizero/MateCat | migrations/20160124101801_add_reviewed_words_count_to_chunk_reviews.php | PHP | lgpl-3.0 | 322 |
#include <private/qmetaobjectbuilder_p.h>
#include <QtOpenGL/QtOpenGL>
#include <QtOpenGL/QGLFunctions>
#include <QtQml/QtQml>
#include <QQmlEngine>
#include <QDebug>
#include "govalue.h"
#include "capi.h"
class GoValueMetaObject : public QAbstractDynamicMetaObject
{
public:
GoValueMetaObject(QObject* value, GoAddr *addr, GoTypeInfo *typeInfo);
void activatePropIndex(int propIndex);
protected:
int metaCall(QMetaObject::Call c, int id, void **a);
private:
QObject *value;
GoAddr *addr;
GoTypeInfo *typeInfo;
};
GoValueMetaObject::GoValueMetaObject(QObject *value, GoAddr *addr, GoTypeInfo *typeInfo)
: value(value), addr(addr), typeInfo(typeInfo)
{
//d->parent = static_cast<QAbstractDynamicMetaObject *>(priv->metaObject);
*static_cast<QMetaObject *>(this) = *metaObjectFor(typeInfo);
QObjectPrivate *objPriv = QObjectPrivate::get(value);
objPriv->metaObject = this;
}
int GoValueMetaObject::metaCall(QMetaObject::Call c, int idx, void **a)
{
//qWarning() << "GoValueMetaObject::metaCall" << c << idx;
switch (c) {
case QMetaObject::ReadProperty:
case QMetaObject::WriteProperty:
{
// TODO Cache propertyOffset, methodOffset (and maybe qmlEngine)
int propOffset = propertyOffset();
if (idx < propOffset) {
return value->qt_metacall(c, idx, a);
}
GoMemberInfo *memberInfo = typeInfo->fields;
for (int i = 0; i < typeInfo->fieldsLen; i++) {
if (memberInfo->metaIndex == idx) {
if (c == QMetaObject::ReadProperty) {
DataValue result;
hookGoValueReadField(qmlEngine(value), addr, memberInfo->reflectIndex, memberInfo->reflectGetIndex, memberInfo->reflectSetIndex, &result);
if (memberInfo->memberType == DTListProperty) {
if (result.dataType != DTListProperty) {
panicf("reading DTListProperty field returned non-DTListProperty result");
}
QQmlListProperty<QObject> *in = *reinterpret_cast<QQmlListProperty<QObject> **>(result.data);
QQmlListProperty<QObject> *out = reinterpret_cast<QQmlListProperty<QObject> *>(a[0]);
*out = *in;
// TODO Could provide a single variable in the stack to ReadField instead.
delete in;
} else {
QVariant *out = reinterpret_cast<QVariant *>(a[0]);
unpackDataValue(&result, out);
}
} else {
DataValue assign;
QVariant *in = reinterpret_cast<QVariant *>(a[0]);
packDataValue(in, &assign);
hookGoValueWriteField(qmlEngine(value), addr, memberInfo->reflectIndex, memberInfo->reflectSetIndex, &assign);
activate(value, methodOffset() + (idx - propOffset), 0);
}
return -1;
}
memberInfo++;
}
QMetaProperty prop = property(idx);
qWarning() << "Property" << prop.name() << "not found!?";
break;
}
case QMetaObject::InvokeMetaMethod:
{
if (idx < methodOffset()) {
return value->qt_metacall(c, idx, a);
}
GoMemberInfo *memberInfo = typeInfo->methods;
for (int i = 0; i < typeInfo->methodsLen; i++) {
if (memberInfo->metaIndex == idx) {
// args[0] is the result if any.
DataValue args[1 + MaxParams];
for (int i = 1; i < memberInfo->numIn+1; i++) {
packDataValue(reinterpret_cast<QVariant *>(a[i]), &args[i]);
}
hookGoValueCallMethod(qmlEngine(value), addr, memberInfo->reflectIndex, args);
if (memberInfo->numOut > 0) {
unpackDataValue(&args[0], reinterpret_cast<QVariant *>(a[0]));
}
return -1;
}
memberInfo++;
}
QMetaMethod m = method(idx);
qWarning() << "Method" << m.name() << "not found!?";
break;
}
default:
break; // Unhandled.
}
return -1;
}
void GoValueMetaObject::activatePropIndex(int propIndex)
{
// Properties are added first, so the first fieldLen methods are in
// fact the signals of the respective properties.
int relativeIndex = propIndex - propertyOffset();
activate(value, methodOffset() + relativeIndex, 0);
}
GoValue::GoValue(GoAddr *addr, GoTypeInfo *typeInfo, QObject *parent)
: addr(addr), typeInfo(typeInfo)
{
valueMeta = new GoValueMetaObject(this, addr, typeInfo);
setParent(parent);
}
GoValue::~GoValue()
{
hookGoValueDestroyed(qmlEngine(this), addr);
}
void GoValue::activate(int propIndex)
{
valueMeta->activatePropIndex(propIndex);
}
GoPaintedValue::GoPaintedValue(GoAddr *addr, GoTypeInfo *typeInfo, QObject *parent)
: addr(addr), typeInfo(typeInfo)
{
valueMeta = new GoValueMetaObject(this, addr, typeInfo);
setParent(parent);
QQuickItem::setFlag(QQuickItem::ItemHasContents, true);
QQuickPaintedItem::setRenderTarget(QQuickPaintedItem::FramebufferObject);
}
GoPaintedValue::~GoPaintedValue()
{
hookGoValueDestroyed(qmlEngine(this), addr);
}
void GoPaintedValue::activate(int propIndex)
{
valueMeta->activatePropIndex(propIndex);
}
void GoPaintedValue::paint(QPainter *painter)
{
painter->beginNativePainting();
hookGoValuePaint(qmlEngine(this), addr, typeInfo->paint->reflectIndex);
painter->endNativePainting();
}
QMetaObject *metaObjectFor(GoTypeInfo *typeInfo)
{
if (typeInfo->metaObject) {
return reinterpret_cast<QMetaObject *>(typeInfo->metaObject);
}
QMetaObjectBuilder mob;
if (typeInfo->paint) {
mob.setSuperClass(&QQuickPaintedItem::staticMetaObject);
} else {
mob.setSuperClass(&QObject::staticMetaObject);
}
mob.setClassName(typeInfo->typeName);
mob.setFlags(QMetaObjectBuilder::DynamicMetaObject);
GoMemberInfo *memberInfo;
memberInfo = typeInfo->fields;
int relativePropIndex = mob.propertyCount();
for (int i = 0; i < typeInfo->fieldsLen; i++) {
mob.addSignal("__" + QByteArray::number(relativePropIndex) + "()");
const char *typeName = "QVariant";
if (memberInfo->memberType == DTListProperty) {
typeName = "QQmlListProperty<QObject>";
}
QMetaPropertyBuilder propb = mob.addProperty(memberInfo->memberName, typeName, relativePropIndex);
propb.setWritable(true);
memberInfo->metaIndex = relativePropIndex;
memberInfo++;
relativePropIndex++;
}
memberInfo = typeInfo->methods;
int relativeMethodIndex = mob.methodCount();
for (int i = 0; i < typeInfo->methodsLen; i++) {
if (*memberInfo->resultSignature) {
mob.addMethod(memberInfo->methodSignature, memberInfo->resultSignature);
} else {
mob.addMethod(memberInfo->methodSignature);
}
memberInfo->metaIndex = relativeMethodIndex;
memberInfo++;
relativeMethodIndex++;
}
// TODO Support default properties.
//mob.addClassInfo("DefaultProperty", "objects");
QMetaObject *mo = mob.toMetaObject();
// Turn the relative indexes into absolute indexes.
memberInfo = typeInfo->fields;
int propOffset = mo->propertyOffset();
for (int i = 0; i < typeInfo->fieldsLen; i++) {
memberInfo->metaIndex += propOffset;
memberInfo++;
}
memberInfo = typeInfo->methods;
int methodOffset = mo->methodOffset();
for (int i = 0; i < typeInfo->methodsLen; i++) {
memberInfo->metaIndex += methodOffset;
memberInfo++;
}
typeInfo->metaObject = mo;
return mo;
}
// vim:ts=4:sw=4:et:ft=cpp
| Ouroboros/goqml | src/cpp/govalue.cpp | C++ | lgpl-3.0 | 8,198 |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
int_or_none,
float_or_none,
qualities,
)
class GfycatIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?gfycat\.com/(?P<id>[^/?#]+)'
_TEST = {
'url': 'http://gfycat.com/DeadlyDecisiveGermanpinscher',
'info_dict': {
'id': 'DeadlyDecisiveGermanpinscher',
'ext': 'mp4',
'title': 'Ghost in the Shell',
'timestamp': 1410656006,
'upload_date': '20140914',
'uploader': 'anonymous',
'duration': 10.4,
'view_count': int,
'like_count': int,
'dislike_count': int,
'categories': list,
'age_limit': 0,
}
}
def _real_extract(self, url):
video_id = self._match_id(url)
gfy = self._download_json(
'http://gfycat.com/cajax/get/%s' % video_id,
video_id, 'Downloading video info')['gfyItem']
title = gfy.get('title') or gfy['gfyName']
description = gfy.get('description')
timestamp = int_or_none(gfy.get('createDate'))
uploader = gfy.get('userName')
view_count = int_or_none(gfy.get('views'))
like_count = int_or_none(gfy.get('likes'))
dislike_count = int_or_none(gfy.get('dislikes'))
age_limit = 18 if gfy.get('nsfw') == '1' else 0
width = int_or_none(gfy.get('width'))
height = int_or_none(gfy.get('height'))
fps = int_or_none(gfy.get('frameRate'))
num_frames = int_or_none(gfy.get('numFrames'))
duration = float_or_none(num_frames, fps) if num_frames and fps else None
categories = gfy.get('tags') or gfy.get('extraLemmas') or []
FORMATS = ('gif', 'webm', 'mp4')
quality = qualities(FORMATS)
formats = []
for format_id in FORMATS:
video_url = gfy.get('%sUrl' % format_id)
if not video_url:
continue
filesize = gfy.get('%sSize' % format_id)
formats.append({
'url': video_url,
'format_id': format_id,
'width': width,
'height': height,
'fps': fps,
'filesize': filesize,
'quality': quality(format_id),
})
self._sort_formats(formats)
return {
'id': video_id,
'title': title,
'description': description,
'timestamp': timestamp,
'uploader': uploader,
'duration': duration,
'view_count': view_count,
'like_count': like_count,
'dislike_count': dislike_count,
'categories': categories,
'age_limit': age_limit,
'formats': formats,
}
| apllicationCOM/youtube-dl-api-server | youtube_dl_server/youtube_dl/extractor/gfycat.py | Python | unlicense | 2,868 |
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* 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.zaproxy.zap.extension.exampleRightClickMsg;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ResourceBundle;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.extension.ExtensionAdaptor;
import org.parosproxy.paros.extension.ExtensionHook;
/*
* An example ZAP extension which adds a right click menu item to all of the main
* tabs which list messages.
*
* This class is defines the extension.
*/
public class ExtensionRightClickMsgMenu extends ExtensionAdaptor {
private RightClickMsgMenu popupMsgMenuExample = null;
private ResourceBundle messages = null;
/**
*
*/
public ExtensionRightClickMsgMenu() {
super();
initialize();
}
/**
* @param name
*/
public ExtensionRightClickMsgMenu(String name) {
super(name);
}
/**
* This method initializes this
*
*/
private void initialize() {
this.setName("ExtensionPopupMsgMenu");
// Load extension specific language files - these are held in the extension jar
messages = ResourceBundle.getBundle(
this.getClass().getPackage().getName() + ".resources.Messages", Constant.getLocale());
}
@Override
public void hook(ExtensionHook extensionHook) {
super.hook(extensionHook);
if (getView() != null) {
// Register our popup menu item, as long as we're not running as a daemon
extensionHook.getHookMenu().addPopupMenuItem(getPopupMsgMenuExample());
}
}
private RightClickMsgMenu getPopupMsgMenuExample() {
if (popupMsgMenuExample == null) {
popupMsgMenuExample = new RightClickMsgMenu(
this.getMessageString("ext.popupmsg.popup.example"));
popupMsgMenuExample.setExtension(this);
}
return popupMsgMenuExample;
}
public String getMessageString (String key) {
return messages.getString(key);
}
@Override
public String getAuthor() {
return Constant.ZAP_TEAM;
}
@Override
public String getDescription() {
return messages.getString("ext.popupmsg.desc");
}
@Override
public URL getURL() {
try {
return new URL(Constant.ZAP_EXTENSIONS_PAGE);
} catch (MalformedURLException e) {
return null;
}
}
} | msrader/zap-extensions | src/org/zaproxy/zap/extension/exampleRightClickMsg/ExtensionRightClickMsgMenu.java | Java | apache-2.0 | 3,011 |
using System;
using System.Data.Entity;
using System.Transactions;
namespace Nop.Data.Initializers
{
/// <summary>
/// An implementation of IDatabaseInitializer that will <b>DELETE</b>, recreate, and optionally re-seed the
/// database only if the model has changed since the database was created. This is achieved by writing a
/// hash of the store model to the database when it is created and then comparing that hash with one
/// generated from the current model.
/// To seed the database, create a derived class and override the Seed method.
/// </summary>
public class DropCreateCeDatabaseIfModelChanges<TContext> : SqlCeInitializer<TContext> where TContext : DbContext
{
#region Strategy implementation
/// <summary>
/// Executes the strategy to initialize the database for the given context.
/// </summary>
/// <param name="context">The context.</param>
public override void InitializeDatabase(TContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var replacedContext = ReplaceSqlCeConnection(context);
bool databaseExists;
using (new TransactionScope(TransactionScopeOption.Suppress))
{
databaseExists = replacedContext.Database.Exists();
}
if (databaseExists)
{
if (context.Database.CompatibleWithModel(throwIfNoMetadata: true))
{
return;
}
replacedContext.Database.Delete();
}
// Database didn't exist or we deleted it, so we now create it again.
context.Database.Create();
Seed(context);
context.SaveChanges();
}
#endregion
#region Seeding methods
/// <summary>
/// A that should be overridden to actually add data to the context for seeding.
/// The default implementation does nothing.
/// </summary>
/// <param name="context">The context to seed.</param>
protected virtual void Seed(TContext context)
{
}
#endregion
}
}
| jornfilho/nopCommerce | source/Libraries/Nop.Data/Initializers/DropCreateCeDatabaseIfModelChanges.cs | C# | apache-2.0 | 2,276 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.action.termvectors;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.IndicesRequest;
import org.elasticsearch.action.RoutingMissingException;
import org.elasticsearch.action.get.TransportMultiGetActionTests;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.ActionTestUtils;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.OperationRouting;
import org.elasticsearch.cluster.routing.ShardIterator;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.AtomicArray;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.indices.EmptySystemIndices;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.tasks.TaskId;
import org.elasticsearch.tasks.TaskManager;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.transport.TransportService;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import static org.elasticsearch.common.UUIDs.randomBase64UUID;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TransportMultiTermVectorsActionTests extends ESTestCase {
private static ThreadPool threadPool;
private static TransportService transportService;
private static ClusterService clusterService;
private static TransportMultiTermVectorsAction transportAction;
private static TransportShardMultiTermsVectorAction shardAction;
@BeforeClass
public static void beforeClass() throws Exception {
threadPool = new TestThreadPool(TransportMultiGetActionTests.class.getSimpleName());
transportService = new TransportService(Settings.EMPTY, mock(Transport.class), threadPool,
TransportService.NOOP_TRANSPORT_INTERCEPTOR,
boundAddress -> DiscoveryNode.createLocal(Settings.builder().put("node.name", "node1").build(),
boundAddress.publishAddress(), randomBase64UUID()), null, emptySet()) {
@Override
public TaskManager getTaskManager() {
return taskManager;
}
};
final Index index1 = new Index("index1", randomBase64UUID());
final Index index2 = new Index("index2", randomBase64UUID());
final ClusterState clusterState = ClusterState.builder(new ClusterName(TransportMultiGetActionTests.class.getSimpleName()))
.metadata(new Metadata.Builder()
.put(new IndexMetadata.Builder(index1.getName())
.settings(Settings.builder().put("index.version.created", Version.CURRENT)
.put("index.number_of_shards", 1)
.put("index.number_of_replicas", 1)
.put(IndexMetadata.SETTING_INDEX_UUID, index1.getUUID()))
.putMapping(
XContentHelper.convertToJson(BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.startObject("_doc")
.startObject("_routing")
.field("required", false)
.endObject()
.endObject()
.endObject()), true, XContentType.JSON)))
.put(new IndexMetadata.Builder(index2.getName())
.settings(Settings.builder().put("index.version.created", Version.CURRENT)
.put("index.number_of_shards", 1)
.put("index.number_of_replicas", 1)
.put(IndexMetadata.SETTING_INDEX_UUID, index1.getUUID()))
.putMapping(
XContentHelper.convertToJson(BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject()
.startObject("_doc")
.startObject("_routing")
.field("required", true)
.endObject()
.endObject()
.endObject()), true, XContentType.JSON)))).build();
final ShardIterator index1ShardIterator = mock(ShardIterator.class);
when(index1ShardIterator.shardId()).thenReturn(new ShardId(index1, randomInt()));
final ShardIterator index2ShardIterator = mock(ShardIterator.class);
when(index2ShardIterator.shardId()).thenReturn(new ShardId(index2, randomInt()));
final OperationRouting operationRouting = mock(OperationRouting.class);
when(operationRouting.getShards(eq(clusterState), eq(index1.getName()), anyString(), anyString(), anyString()))
.thenReturn(index1ShardIterator);
when(operationRouting.shardId(eq(clusterState), eq(index1.getName()), anyString(), anyString()))
.thenReturn(new ShardId(index1, randomInt()));
when(operationRouting.getShards(eq(clusterState), eq(index2.getName()), anyString(), anyString(), anyString()))
.thenReturn(index2ShardIterator);
when(operationRouting.shardId(eq(clusterState), eq(index2.getName()), anyString(), anyString()))
.thenReturn(new ShardId(index2, randomInt()));
clusterService = mock(ClusterService.class);
when(clusterService.localNode()).thenReturn(transportService.getLocalNode());
when(clusterService.state()).thenReturn(clusterState);
when(clusterService.operationRouting()).thenReturn(operationRouting);
shardAction = new TransportShardMultiTermsVectorAction(clusterService, transportService, mock(IndicesService.class), threadPool,
new ActionFilters(emptySet()), new Resolver()) {
@Override
protected void doExecute(Task task, MultiTermVectorsShardRequest request,
ActionListener<MultiTermVectorsShardResponse> listener) {
}
};
}
@AfterClass
public static void afterClass() {
ThreadPool.terminate(threadPool, 30, TimeUnit.SECONDS);
threadPool = null;
transportService = null;
clusterService = null;
transportAction = null;
shardAction = null;
}
public void testTransportMultiGetAction() {
final Task task = createTask();
final NodeClient client = new NodeClient(Settings.EMPTY, threadPool);
final MultiTermVectorsRequestBuilder request = new MultiTermVectorsRequestBuilder(client, MultiTermVectorsAction.INSTANCE);
request.add(new TermVectorsRequest("index1", "1"));
request.add(new TermVectorsRequest("index2", "2"));
final AtomicBoolean shardActionInvoked = new AtomicBoolean(false);
transportAction = new TransportMultiTermVectorsAction(transportService, clusterService, client,
new ActionFilters(emptySet()), new Resolver()) {
@Override
protected void executeShardAction(final ActionListener<MultiTermVectorsResponse> listener,
final AtomicArray<MultiTermVectorsItemResponse> responses,
final Map<ShardId, MultiTermVectorsShardRequest> shardRequests) {
shardActionInvoked.set(true);
assertEquals(2, responses.length());
assertNull(responses.get(0));
assertNull(responses.get(1));
}
};
ActionTestUtils.execute(transportAction, task, request.request(), new ActionListenerAdapter());
assertTrue(shardActionInvoked.get());
}
public void testTransportMultiGetAction_withMissingRouting() {
final Task task = createTask();
final NodeClient client = new NodeClient(Settings.EMPTY, threadPool);
final MultiTermVectorsRequestBuilder request = new MultiTermVectorsRequestBuilder(client, MultiTermVectorsAction.INSTANCE);
request.add(new TermVectorsRequest("index2", "1").routing("1"));
request.add(new TermVectorsRequest("index2", "2"));
final AtomicBoolean shardActionInvoked = new AtomicBoolean(false);
transportAction = new TransportMultiTermVectorsAction(transportService, clusterService, client,
new ActionFilters(emptySet()), new Resolver()) {
@Override
protected void executeShardAction(final ActionListener<MultiTermVectorsResponse> listener,
final AtomicArray<MultiTermVectorsItemResponse> responses,
final Map<ShardId, MultiTermVectorsShardRequest> shardRequests) {
shardActionInvoked.set(true);
assertEquals(2, responses.length());
assertNull(responses.get(0));
assertThat(responses.get(1).getFailure().getCause(), instanceOf(RoutingMissingException.class));
assertThat(responses.get(1).getFailure().getCause().getMessage(),
equalTo("routing is required for [index1]/[type2]/[2]"));
}
};
ActionTestUtils.execute(transportAction, task, request.request(), new ActionListenerAdapter());
assertTrue(shardActionInvoked.get());
}
private static Task createTask() {
return new Task(randomLong(), "transport", MultiTermVectorsAction.NAME, "description",
new TaskId(randomLong() + ":" + randomLong()), emptyMap());
}
static class Resolver extends IndexNameExpressionResolver {
Resolver() {
super(new ThreadContext(Settings.EMPTY), EmptySystemIndices.INSTANCE);
}
@Override
public Index concreteSingleIndex(ClusterState state, IndicesRequest request) {
return new Index("index1", randomBase64UUID());
}
}
static class ActionListenerAdapter implements ActionListener<MultiTermVectorsResponse> {
@Override
public void onResponse(MultiTermVectorsResponse response) {
}
@Override
public void onFailure(Exception e) {
}
}
}
| robin13/elasticsearch | server/src/test/java/org/elasticsearch/action/termvectors/TransportMultiTermVectorsActionTests.java | Java | apache-2.0 | 11,980 |
/*
* 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 datareq
import (
"github.com/apache/incubator-trafficcontrol/traffic_monitor/config"
)
func srvAPIVersion(staticAppData config.StaticAppData) []byte {
s := "traffic_monitor-" + staticAppData.Version + "."
if len(staticAppData.GitRevision) > 6 {
s += staticAppData.GitRevision[:6]
} else {
s += staticAppData.GitRevision
}
return []byte(s)
}
| jeffmart/incubator-trafficcontrol | traffic_monitor/datareq/version.go | GO | apache-2.0 | 1,170 |
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.workbench.common.dmn.client.widgets.grid;
import com.ait.lienzo.client.core.shape.Node;
import com.ait.lienzo.client.core.shape.Viewport;
import com.ait.lienzo.test.LienzoMockitoTestRunner;
import org.jboss.errai.ui.client.local.spi.TranslationService;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.kie.workbench.common.dmn.client.commands.factory.DefaultCanvasCommandFactory;
import org.kie.workbench.common.dmn.client.widgets.grid.controls.container.CellEditorControlsView;
import org.kie.workbench.common.dmn.client.widgets.grid.controls.list.ListSelectorView;
import org.kie.workbench.common.dmn.client.widgets.grid.model.BaseUIModelMapper;
import org.kie.workbench.common.dmn.client.widgets.grid.model.ExpressionEditorChanged;
import org.kie.workbench.common.dmn.client.widgets.grid.model.GridCellTuple;
import org.kie.workbench.common.dmn.client.widgets.layer.DMNGridLayer;
import org.kie.workbench.common.dmn.client.widgets.panel.DMNGridPanel;
import org.kie.workbench.common.stunner.core.client.api.SessionManager;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.canvas.event.selection.DomainObjectSelectionEvent;
import org.kie.workbench.common.stunner.core.client.command.SessionCommandManager;
import org.kie.workbench.common.stunner.core.util.DefinitionUtils;
import org.kie.workbench.common.stunner.forms.client.event.RefreshFormPropertiesEvent;
import org.mockito.Mock;
import org.uberfire.ext.wires.core.grids.client.model.impl.BaseBounds;
import org.uberfire.ext.wires.core.grids.client.widget.grid.renderers.grids.GridRenderer;
import org.uberfire.mocks.EventSourceMock;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
@RunWith(LienzoMockitoTestRunner.class)
public abstract class BaseExpressionGridTest {
@Mock
protected GridRenderer renderer;
@Mock
protected DMNGridPanel gridPanel;
@Mock
protected DMNGridLayer gridLayer;
@Mock
protected DefinitionUtils definitionUtils;
@Mock
protected Viewport viewport;
@Mock
protected SessionManager sessionManager;
@Mock
protected SessionCommandManager<AbstractCanvasHandler> sessionCommandManager;
@Mock
protected DefaultCanvasCommandFactory canvasCommandFactory;
@Mock
protected CellEditorControlsView.Presenter cellEditorControls;
@Mock
protected ListSelectorView.Presenter listSelector;
@Mock
protected TranslationService translationService;
@Mock
protected BaseUIModelMapper mapper;
@Mock
protected Node gridParent;
@Mock
protected GridCellTuple parentCell;
@Mock
protected EventSourceMock<ExpressionEditorChanged> editorSelectedEvent;
@Mock
protected EventSourceMock<RefreshFormPropertiesEvent> refreshFormPropertiesEvent;
@Mock
protected EventSourceMock<DomainObjectSelectionEvent> domainObjectSelectionEvent;
protected BaseExpressionGrid grid;
@Before
@SuppressWarnings("unchecked")
public void setup() {
this.grid = spy(getGrid());
doReturn(gridLayer).when(grid).getLayer();
doReturn(viewport).when(gridLayer).getViewport();
doReturn(new BaseBounds(0, 0, 1000, 1000)).when(gridLayer).getVisibleBounds();
}
protected abstract BaseExpressionGrid getGrid();
}
| jomarko/kie-wb-common | kie-wb-common-dmn/kie-wb-common-dmn-client/src/test/java/org/kie/workbench/common/dmn/client/widgets/grid/BaseExpressionGridTest.java | Java | apache-2.0 | 4,021 |
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.IO;
using System.Xml;
using System.Text;
using System.Linq;
using System.Collections.Generic;
namespace Soomla
{
public class SoomlaManifestTools
{
#if UNITY_EDITOR
public static void GenerateManifest()
{
var outputFile = Path.Combine(Application.dataPath, "Plugins/Android/AndroidManifest.xml");
// only copy over a fresh copy of the AndroidManifest if one does not exist
if (!File.Exists(outputFile))
{
var inputFile = Path.Combine(EditorApplication.applicationContentsPath, "PlaybackEngines/androidplayer/AndroidManifest.xml");
File.Copy(inputFile, outputFile);
}
UpdateManifest(outputFile);
}
private static string _namespace = "";
private static XmlDocument _document = null;
private static XmlNode _manifestNode = null;
private static XmlNode _applicationNode = null;
public static List<ISoomlaManifestTools> ManTools = new List<ISoomlaManifestTools>();
public static void UpdateManifest(string fullPath) {
_document = new XmlDocument();
_document.Load(fullPath);
if (_document == null)
{
Debug.LogError("Couldn't load " + fullPath);
return;
}
_manifestNode = FindChildNode(_document, "manifest");
_namespace = _manifestNode.GetNamespaceOfPrefix("android");
_applicationNode = FindChildNode(_manifestNode, "application");
if (_applicationNode == null) {
Debug.LogError("Error parsing " + fullPath);
return;
}
SetPermission("android.permission.INTERNET");
XmlElement applicationElement = FindChildElement(_manifestNode, "application");
applicationElement.SetAttribute("name", _namespace, "com.soomla.SoomlaApp");
foreach(ISoomlaManifestTools manifestTool in ManTools) {
manifestTool.UpdateManifest();
}
_document.Save(fullPath);
}
public static void AddActivity(string activityName, Dictionary<string, string> attributes) {
AppendApplicationElement("activity", activityName, attributes);
}
public static void RemoveActivity(string activityName) {
RemoveApplicationElement("activity", activityName);
}
public static void SetPermission(string permissionName) {
PrependManifestElement("uses-permission", permissionName);
}
public static void RemovePermission(string permissionName) {
RemoveManifestElement("uses-permission", permissionName);
}
public static XmlElement AppendApplicationElement(string tagName, string name, Dictionary<string, string> attributes) {
return AppendElementIfMissing(tagName, name, attributes, _applicationNode);
}
public static void RemoveApplicationElement(string tagName, string name) {
RemoveElement(tagName, name, _applicationNode);
}
public static XmlElement PrependManifestElement(string tagName, string name) {
return PrependElementIfMissing(tagName, name, null, _manifestNode);
}
public static void RemoveManifestElement(string tagName, string name) {
RemoveElement(tagName, name, _manifestNode);
}
public static XmlElement AddMetaDataTag(string mdName, string mdValue) {
return AppendApplicationElement("meta-data", mdName, new Dictionary<string, string>() {
{ "value", mdValue }
});
}
public static XmlElement AppendElementIfMissing(string tagName, string name, Dictionary<string, string> otherAttributes, XmlNode parent) {
XmlElement e = null;
if (!string.IsNullOrEmpty(name)) {
e = FindElementWithTagAndName(tagName, name, parent);
}
if (e == null)
{
e = _document.CreateElement(tagName);
if (!string.IsNullOrEmpty(name)) {
e.SetAttribute("name", _namespace, name);
}
parent.AppendChild(e);
}
if (otherAttributes != null) {
foreach(string key in otherAttributes.Keys) {
e.SetAttribute(key, _namespace, otherAttributes[key]);
}
}
return e;
}
public static XmlElement PrependElementIfMissing(string tagName, string name, Dictionary<string, string> otherAttributes, XmlNode parent) {
XmlElement e = null;
if (!string.IsNullOrEmpty(name)) {
e = FindElementWithTagAndName(tagName, name, parent);
}
if (e == null)
{
e = _document.CreateElement(tagName);
if (!string.IsNullOrEmpty(name)) {
e.SetAttribute("name", _namespace, name);
}
parent.PrependChild(e);
}
if (otherAttributes != null) {
foreach(string key in otherAttributes.Keys) {
e.SetAttribute(key, _namespace, otherAttributes[key]);
}
}
return e;
}
public static void RemoveElement(string tagName, string name, XmlNode parent) {
XmlElement e = FindElementWithTagAndName(tagName, name, parent);
if (e != null)
{
parent.RemoveChild(e);
}
}
public static XmlNode FindChildNode(XmlNode parent, string tagName)
{
XmlNode curr = parent.FirstChild;
while (curr != null)
{
if (curr.Name.Equals(tagName))
{
return curr;
}
curr = curr.NextSibling;
}
return null;
}
public static XmlElement FindChildElement(XmlNode parent, string tagName)
{
XmlNode curr = parent.FirstChild;
while (curr != null)
{
if (curr.Name.Equals(tagName))
{
return curr as XmlElement;
}
curr = curr.NextSibling;
}
return null;
}
public static XmlElement FindElementWithTagAndName(string tagName, string name, XmlNode parent)
{
var curr = parent.FirstChild;
while (curr != null)
{
if (curr.Name.Equals(tagName) && curr is XmlElement && ((XmlElement)curr).GetAttribute("name", _namespace) == name)
{
return curr as XmlElement;
}
curr = curr.NextSibling;
}
return null;
}
#endif
}
} | john-gu/TuneSoomlaUnity | TuneSoomla/Assets/Plugins/Soomla/Core/Config/android/SoomlaManifestTools.cs | C# | apache-2.0 | 5,762 |
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package sqs
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/query"
)
const opAddPermission = "AddPermission"
// AddPermissionRequest generates a "aws/request.Request" representing the
// client's request for the AddPermission operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See AddPermission for more information on using the AddPermission
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the AddPermissionRequest method.
// req, resp := client.AddPermissionRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/AddPermission
func (c *SQS) AddPermissionRequest(input *AddPermissionInput) (req *request.Request, output *AddPermissionOutput) {
op := &request.Operation{
Name: opAddPermission,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &AddPermissionInput{}
}
output = &AddPermissionOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Remove(query.UnmarshalHandler)
req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
return
}
// AddPermission API operation for Amazon Simple Queue Service.
//
// Adds a permission to a queue for a specific principal (http://docs.aws.amazon.com/general/latest/gr/glos-chap.html#P).
// This allows sharing access to the queue.
//
// When you create a queue, you have full control access rights for the queue.
// Only you, the owner of the queue, can grant or deny permissions to the queue.
// For more information about these permissions, see Shared Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/acp-overview.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// AddPermission writes an Amazon-SQS-generated policy. If you want to write
// your own policy, use SetQueueAttributes to upload your policy. For more information
// about writing your own policy, see Using The Access Policy Language (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AccessPolicyLanguage.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// Some actions take lists of parameters. These lists are specified using the
// param.n notation. Values of n are integers starting from 1. For example,
// a parameter list with two elements looks like this:
//
// &Attribute.1=this
//
// &Attribute.2=that
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation AddPermission for usage and error information.
//
// Returned Error Codes:
// * ErrCodeOverLimit "OverLimit"
// The action that you requested would violate a limit. For example, ReceiveMessage
// returns this error if the maximum number of inflight messages is reached.
// AddPermission returns this error if the maximum number of permissions for
// the queue is reached.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/AddPermission
func (c *SQS) AddPermission(input *AddPermissionInput) (*AddPermissionOutput, error) {
req, out := c.AddPermissionRequest(input)
return out, req.Send()
}
// AddPermissionWithContext is the same as AddPermission with the addition of
// the ability to pass a context and additional request options.
//
// See AddPermission for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) AddPermissionWithContext(ctx aws.Context, input *AddPermissionInput, opts ...request.Option) (*AddPermissionOutput, error) {
req, out := c.AddPermissionRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opChangeMessageVisibility = "ChangeMessageVisibility"
// ChangeMessageVisibilityRequest generates a "aws/request.Request" representing the
// client's request for the ChangeMessageVisibility operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ChangeMessageVisibility for more information on using the ChangeMessageVisibility
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ChangeMessageVisibilityRequest method.
// req, resp := client.ChangeMessageVisibilityRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ChangeMessageVisibility
func (c *SQS) ChangeMessageVisibilityRequest(input *ChangeMessageVisibilityInput) (req *request.Request, output *ChangeMessageVisibilityOutput) {
op := &request.Operation{
Name: opChangeMessageVisibility,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &ChangeMessageVisibilityInput{}
}
output = &ChangeMessageVisibilityOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Remove(query.UnmarshalHandler)
req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
return
}
// ChangeMessageVisibility API operation for Amazon Simple Queue Service.
//
// Changes the visibility timeout of a specified message in a queue to a new
// value. The maximum allowed timeout value is 12 hours. Thus, you can't extend
// the timeout of a message in an existing queue to more than a total visibility
// timeout of 12 hours. For more information, see Visibility Timeout (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// For example, you have a message with a visibility timeout of 5 minutes. After
// 3 minutes, you call ChangeMessageVisiblity with a timeout of 10 minutes.
// At that time, the timeout for the message is extended by 10 minutes beyond
// the time of the ChangeMessageVisibility action. This results in a total visibility
// timeout of 13 minutes. You can continue to call the ChangeMessageVisibility
// to extend the visibility timeout to a maximum of 12 hours. If you try to
// extend the visibility timeout beyond 12 hours, your request is rejected.
//
// A message is considered to be in flight after it's received from a queue
// by a consumer, but not yet deleted from the queue.
//
// For standard queues, there can be a maximum of 120,000 inflight messages
// per queue. If you reach this limit, Amazon SQS returns the OverLimit error
// message. To avoid reaching the limit, you should delete messages from the
// queue after they're processed. You can also increase the number of queues
// you use to process your messages.
//
// For FIFO queues, there can be a maximum of 20,000 inflight messages per queue.
// If you reach this limit, Amazon SQS returns no error messages.
//
// If you attempt to set the VisibilityTimeout to a value greater than the maximum
// time left, Amazon SQS returns an error. Amazon SQS doesn't automatically
// recalculate and increase the timeout to the maximum remaining time.
//
// Unlike with a queue, when you change the visibility timeout for a specific
// message the timeout value is applied immediately but isn't saved in memory
// for that message. If you don't delete a message after it is received, the
// visibility timeout for the message reverts to the original timeout value
// (not to the value you set using the ChangeMessageVisibility action) the next
// time the message is received.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation ChangeMessageVisibility for usage and error information.
//
// Returned Error Codes:
// * ErrCodeMessageNotInflight "AWS.SimpleQueueService.MessageNotInflight"
// The message referred to isn't in flight.
//
// * ErrCodeReceiptHandleIsInvalid "ReceiptHandleIsInvalid"
// The receipt handle provided isn't valid.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ChangeMessageVisibility
func (c *SQS) ChangeMessageVisibility(input *ChangeMessageVisibilityInput) (*ChangeMessageVisibilityOutput, error) {
req, out := c.ChangeMessageVisibilityRequest(input)
return out, req.Send()
}
// ChangeMessageVisibilityWithContext is the same as ChangeMessageVisibility with the addition of
// the ability to pass a context and additional request options.
//
// See ChangeMessageVisibility for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) ChangeMessageVisibilityWithContext(ctx aws.Context, input *ChangeMessageVisibilityInput, opts ...request.Option) (*ChangeMessageVisibilityOutput, error) {
req, out := c.ChangeMessageVisibilityRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opChangeMessageVisibilityBatch = "ChangeMessageVisibilityBatch"
// ChangeMessageVisibilityBatchRequest generates a "aws/request.Request" representing the
// client's request for the ChangeMessageVisibilityBatch operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ChangeMessageVisibilityBatch for more information on using the ChangeMessageVisibilityBatch
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ChangeMessageVisibilityBatchRequest method.
// req, resp := client.ChangeMessageVisibilityBatchRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ChangeMessageVisibilityBatch
func (c *SQS) ChangeMessageVisibilityBatchRequest(input *ChangeMessageVisibilityBatchInput) (req *request.Request, output *ChangeMessageVisibilityBatchOutput) {
op := &request.Operation{
Name: opChangeMessageVisibilityBatch,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &ChangeMessageVisibilityBatchInput{}
}
output = &ChangeMessageVisibilityBatchOutput{}
req = c.newRequest(op, input, output)
return
}
// ChangeMessageVisibilityBatch API operation for Amazon Simple Queue Service.
//
// Changes the visibility timeout of multiple messages. This is a batch version
// of ChangeMessageVisibility. The result of the action on each message is reported
// individually in the response. You can send up to 10 ChangeMessageVisibility
// requests with each ChangeMessageVisibilityBatch action.
//
// Because the batch request can result in a combination of successful and unsuccessful
// actions, you should check for batch errors even when the call returns an
// HTTP status code of 200.
//
// Some actions take lists of parameters. These lists are specified using the
// param.n notation. Values of n are integers starting from 1. For example,
// a parameter list with two elements looks like this:
//
// &Attribute.1=this
//
// &Attribute.2=that
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation ChangeMessageVisibilityBatch for usage and error information.
//
// Returned Error Codes:
// * ErrCodeTooManyEntriesInBatchRequest "AWS.SimpleQueueService.TooManyEntriesInBatchRequest"
// The batch request contains more entries than permissible.
//
// * ErrCodeEmptyBatchRequest "AWS.SimpleQueueService.EmptyBatchRequest"
// The batch request doesn't contain any entries.
//
// * ErrCodeBatchEntryIdsNotDistinct "AWS.SimpleQueueService.BatchEntryIdsNotDistinct"
// Two or more batch entries in the request have the same Id.
//
// * ErrCodeInvalidBatchEntryId "AWS.SimpleQueueService.InvalidBatchEntryId"
// The Id of a batch entry in a batch request doesn't abide by the specification.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ChangeMessageVisibilityBatch
func (c *SQS) ChangeMessageVisibilityBatch(input *ChangeMessageVisibilityBatchInput) (*ChangeMessageVisibilityBatchOutput, error) {
req, out := c.ChangeMessageVisibilityBatchRequest(input)
return out, req.Send()
}
// ChangeMessageVisibilityBatchWithContext is the same as ChangeMessageVisibilityBatch with the addition of
// the ability to pass a context and additional request options.
//
// See ChangeMessageVisibilityBatch for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) ChangeMessageVisibilityBatchWithContext(ctx aws.Context, input *ChangeMessageVisibilityBatchInput, opts ...request.Option) (*ChangeMessageVisibilityBatchOutput, error) {
req, out := c.ChangeMessageVisibilityBatchRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opCreateQueue = "CreateQueue"
// CreateQueueRequest generates a "aws/request.Request" representing the
// client's request for the CreateQueue operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreateQueue for more information on using the CreateQueue
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the CreateQueueRequest method.
// req, resp := client.CreateQueueRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/CreateQueue
func (c *SQS) CreateQueueRequest(input *CreateQueueInput) (req *request.Request, output *CreateQueueOutput) {
op := &request.Operation{
Name: opCreateQueue,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &CreateQueueInput{}
}
output = &CreateQueueOutput{}
req = c.newRequest(op, input, output)
return
}
// CreateQueue API operation for Amazon Simple Queue Service.
//
// Creates a new standard or FIFO queue. You can pass one or more attributes
// in the request. Keep the following caveats in mind:
//
// * If you don't specify the FifoQueue attribute, Amazon SQS creates a standard
// queue.
//
// You can't change the queue type after you create it and you can't convert
// an existing standard queue into a FIFO queue. You must either create a
// new FIFO queue for your application or delete your existing standard queue
// and recreate it as a FIFO queue. For more information, see Moving From
// a Standard Queue to a FIFO Queue (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-moving)
// in the Amazon Simple Queue Service Developer Guide.
//
// * If you don't provide a value for an attribute, the queue is created
// with the default value for the attribute.
//
// * If you delete a queue, you must wait at least 60 seconds before creating
// a queue with the same name.
//
// To successfully create a new queue, you must provide a queue name that adheres
// to the limits related to queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/limits-queues.html)
// and is unique within the scope of your queues.
//
// To get the queue URL, use the GetQueueUrl action. GetQueueUrl requires only
// the QueueName parameter. be aware of existing queue names:
//
// * If you provide the name of an existing queue along with the exact names
// and values of all the queue's attributes, CreateQueue returns the queue
// URL for the existing queue.
//
// * If the queue name, attribute names, or attribute values don't match
// an existing queue, CreateQueue returns an error.
//
// Some actions take lists of parameters. These lists are specified using the
// param.n notation. Values of n are integers starting from 1. For example,
// a parameter list with two elements looks like this:
//
// &Attribute.1=this
//
// &Attribute.2=that
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation CreateQueue for usage and error information.
//
// Returned Error Codes:
// * ErrCodeQueueDeletedRecently "AWS.SimpleQueueService.QueueDeletedRecently"
// You must wait 60 seconds after deleting a queue before you can create another
// one with the same name.
//
// * ErrCodeQueueNameExists "QueueAlreadyExists"
// A queue already exists with this name. Amazon SQS returns this error only
// if the request includes attributes whose values differ from those of the
// existing queue.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/CreateQueue
func (c *SQS) CreateQueue(input *CreateQueueInput) (*CreateQueueOutput, error) {
req, out := c.CreateQueueRequest(input)
return out, req.Send()
}
// CreateQueueWithContext is the same as CreateQueue with the addition of
// the ability to pass a context and additional request options.
//
// See CreateQueue for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) CreateQueueWithContext(ctx aws.Context, input *CreateQueueInput, opts ...request.Option) (*CreateQueueOutput, error) {
req, out := c.CreateQueueRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDeleteMessage = "DeleteMessage"
// DeleteMessageRequest generates a "aws/request.Request" representing the
// client's request for the DeleteMessage operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteMessage for more information on using the DeleteMessage
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DeleteMessageRequest method.
// req, resp := client.DeleteMessageRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/DeleteMessage
func (c *SQS) DeleteMessageRequest(input *DeleteMessageInput) (req *request.Request, output *DeleteMessageOutput) {
op := &request.Operation{
Name: opDeleteMessage,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &DeleteMessageInput{}
}
output = &DeleteMessageOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Remove(query.UnmarshalHandler)
req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
return
}
// DeleteMessage API operation for Amazon Simple Queue Service.
//
// Deletes the specified message from the specified queue. You specify the message
// by using the message's receipt handle and not the MessageId you receive when
// you send the message. Even if the message is locked by another reader due
// to the visibility timeout setting, it is still deleted from the queue. If
// you leave a message in the queue for longer than the queue's configured retention
// period, Amazon SQS automatically deletes the message.
//
// The receipt handle is associated with a specific instance of receiving the
// message. If you receive a message more than once, the receipt handle you
// get each time you receive the message is different. If you don't provide
// the most recently received receipt handle for the message when you use the
// DeleteMessage action, the request succeeds, but the message might not be
// deleted.
//
// For standard queues, it is possible to receive a message even after you delete
// it. This might happen on rare occasions if one of the servers storing a copy
// of the message is unavailable when you send the request to delete the message.
// The copy remains on the server and might be returned to you on a subsequent
// receive request. You should ensure that your application is idempotent, so
// that receiving a message more than once does not cause issues.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation DeleteMessage for usage and error information.
//
// Returned Error Codes:
// * ErrCodeInvalidIdFormat "InvalidIdFormat"
// The receipt handle isn't valid for the current version.
//
// * ErrCodeReceiptHandleIsInvalid "ReceiptHandleIsInvalid"
// The receipt handle provided isn't valid.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/DeleteMessage
func (c *SQS) DeleteMessage(input *DeleteMessageInput) (*DeleteMessageOutput, error) {
req, out := c.DeleteMessageRequest(input)
return out, req.Send()
}
// DeleteMessageWithContext is the same as DeleteMessage with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteMessage for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) DeleteMessageWithContext(ctx aws.Context, input *DeleteMessageInput, opts ...request.Option) (*DeleteMessageOutput, error) {
req, out := c.DeleteMessageRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDeleteMessageBatch = "DeleteMessageBatch"
// DeleteMessageBatchRequest generates a "aws/request.Request" representing the
// client's request for the DeleteMessageBatch operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteMessageBatch for more information on using the DeleteMessageBatch
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DeleteMessageBatchRequest method.
// req, resp := client.DeleteMessageBatchRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/DeleteMessageBatch
func (c *SQS) DeleteMessageBatchRequest(input *DeleteMessageBatchInput) (req *request.Request, output *DeleteMessageBatchOutput) {
op := &request.Operation{
Name: opDeleteMessageBatch,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &DeleteMessageBatchInput{}
}
output = &DeleteMessageBatchOutput{}
req = c.newRequest(op, input, output)
return
}
// DeleteMessageBatch API operation for Amazon Simple Queue Service.
//
// Deletes up to ten messages from the specified queue. This is a batch version
// of DeleteMessage. The result of the action on each message is reported individually
// in the response.
//
// Because the batch request can result in a combination of successful and unsuccessful
// actions, you should check for batch errors even when the call returns an
// HTTP status code of 200.
//
// Some actions take lists of parameters. These lists are specified using the
// param.n notation. Values of n are integers starting from 1. For example,
// a parameter list with two elements looks like this:
//
// &Attribute.1=this
//
// &Attribute.2=that
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation DeleteMessageBatch for usage and error information.
//
// Returned Error Codes:
// * ErrCodeTooManyEntriesInBatchRequest "AWS.SimpleQueueService.TooManyEntriesInBatchRequest"
// The batch request contains more entries than permissible.
//
// * ErrCodeEmptyBatchRequest "AWS.SimpleQueueService.EmptyBatchRequest"
// The batch request doesn't contain any entries.
//
// * ErrCodeBatchEntryIdsNotDistinct "AWS.SimpleQueueService.BatchEntryIdsNotDistinct"
// Two or more batch entries in the request have the same Id.
//
// * ErrCodeInvalidBatchEntryId "AWS.SimpleQueueService.InvalidBatchEntryId"
// The Id of a batch entry in a batch request doesn't abide by the specification.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/DeleteMessageBatch
func (c *SQS) DeleteMessageBatch(input *DeleteMessageBatchInput) (*DeleteMessageBatchOutput, error) {
req, out := c.DeleteMessageBatchRequest(input)
return out, req.Send()
}
// DeleteMessageBatchWithContext is the same as DeleteMessageBatch with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteMessageBatch for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) DeleteMessageBatchWithContext(ctx aws.Context, input *DeleteMessageBatchInput, opts ...request.Option) (*DeleteMessageBatchOutput, error) {
req, out := c.DeleteMessageBatchRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opDeleteQueue = "DeleteQueue"
// DeleteQueueRequest generates a "aws/request.Request" representing the
// client's request for the DeleteQueue operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteQueue for more information on using the DeleteQueue
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the DeleteQueueRequest method.
// req, resp := client.DeleteQueueRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/DeleteQueue
func (c *SQS) DeleteQueueRequest(input *DeleteQueueInput) (req *request.Request, output *DeleteQueueOutput) {
op := &request.Operation{
Name: opDeleteQueue,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &DeleteQueueInput{}
}
output = &DeleteQueueOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Remove(query.UnmarshalHandler)
req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
return
}
// DeleteQueue API operation for Amazon Simple Queue Service.
//
// Deletes the queue specified by the QueueUrl, regardless of the queue's contents.
// If the specified queue doesn't exist, Amazon SQS returns a successful response.
//
// Be careful with the DeleteQueue action: When you delete a queue, any messages
// in the queue are no longer available.
//
// When you delete a queue, the deletion process takes up to 60 seconds. Requests
// you send involving that queue during the 60 seconds might succeed. For example,
// a SendMessage request might succeed, but after 60 seconds the queue and the
// message you sent no longer exist.
//
// When you delete a queue, you must wait at least 60 seconds before creating
// a queue with the same name.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation DeleteQueue for usage and error information.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/DeleteQueue
func (c *SQS) DeleteQueue(input *DeleteQueueInput) (*DeleteQueueOutput, error) {
req, out := c.DeleteQueueRequest(input)
return out, req.Send()
}
// DeleteQueueWithContext is the same as DeleteQueue with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteQueue for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) DeleteQueueWithContext(ctx aws.Context, input *DeleteQueueInput, opts ...request.Option) (*DeleteQueueOutput, error) {
req, out := c.DeleteQueueRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opGetQueueAttributes = "GetQueueAttributes"
// GetQueueAttributesRequest generates a "aws/request.Request" representing the
// client's request for the GetQueueAttributes operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See GetQueueAttributes for more information on using the GetQueueAttributes
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the GetQueueAttributesRequest method.
// req, resp := client.GetQueueAttributesRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/GetQueueAttributes
func (c *SQS) GetQueueAttributesRequest(input *GetQueueAttributesInput) (req *request.Request, output *GetQueueAttributesOutput) {
op := &request.Operation{
Name: opGetQueueAttributes,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &GetQueueAttributesInput{}
}
output = &GetQueueAttributesOutput{}
req = c.newRequest(op, input, output)
return
}
// GetQueueAttributes API operation for Amazon Simple Queue Service.
//
// Gets attributes for the specified queue.
//
// To determine whether a queue is FIFO (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html),
// you can check whether QueueName ends with the .fifo suffix.
//
// Some actions take lists of parameters. These lists are specified using the
// param.n notation. Values of n are integers starting from 1. For example,
// a parameter list with two elements looks like this:
//
// &Attribute.1=this
//
// &Attribute.2=that
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation GetQueueAttributes for usage and error information.
//
// Returned Error Codes:
// * ErrCodeInvalidAttributeName "InvalidAttributeName"
// The attribute referred to doesn't exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/GetQueueAttributes
func (c *SQS) GetQueueAttributes(input *GetQueueAttributesInput) (*GetQueueAttributesOutput, error) {
req, out := c.GetQueueAttributesRequest(input)
return out, req.Send()
}
// GetQueueAttributesWithContext is the same as GetQueueAttributes with the addition of
// the ability to pass a context and additional request options.
//
// See GetQueueAttributes for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) GetQueueAttributesWithContext(ctx aws.Context, input *GetQueueAttributesInput, opts ...request.Option) (*GetQueueAttributesOutput, error) {
req, out := c.GetQueueAttributesRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opGetQueueUrl = "GetQueueUrl"
// GetQueueUrlRequest generates a "aws/request.Request" representing the
// client's request for the GetQueueUrl operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See GetQueueUrl for more information on using the GetQueueUrl
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the GetQueueUrlRequest method.
// req, resp := client.GetQueueUrlRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/GetQueueUrl
func (c *SQS) GetQueueUrlRequest(input *GetQueueUrlInput) (req *request.Request, output *GetQueueUrlOutput) {
op := &request.Operation{
Name: opGetQueueUrl,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &GetQueueUrlInput{}
}
output = &GetQueueUrlOutput{}
req = c.newRequest(op, input, output)
return
}
// GetQueueUrl API operation for Amazon Simple Queue Service.
//
// Returns the URL of an existing queue. This action provides a simple way to
// retrieve the URL of an Amazon SQS queue.
//
// To access a queue that belongs to another AWS account, use the QueueOwnerAWSAccountId
// parameter to specify the account ID of the queue's owner. The queue's owner
// must grant you permission to access the queue. For more information about
// shared queue access, see AddPermission or see Shared Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/acp-overview.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation GetQueueUrl for usage and error information.
//
// Returned Error Codes:
// * ErrCodeQueueDoesNotExist "AWS.SimpleQueueService.NonExistentQueue"
// The queue referred to doesn't exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/GetQueueUrl
func (c *SQS) GetQueueUrl(input *GetQueueUrlInput) (*GetQueueUrlOutput, error) {
req, out := c.GetQueueUrlRequest(input)
return out, req.Send()
}
// GetQueueUrlWithContext is the same as GetQueueUrl with the addition of
// the ability to pass a context and additional request options.
//
// See GetQueueUrl for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) GetQueueUrlWithContext(ctx aws.Context, input *GetQueueUrlInput, opts ...request.Option) (*GetQueueUrlOutput, error) {
req, out := c.GetQueueUrlRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opListDeadLetterSourceQueues = "ListDeadLetterSourceQueues"
// ListDeadLetterSourceQueuesRequest generates a "aws/request.Request" representing the
// client's request for the ListDeadLetterSourceQueues operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListDeadLetterSourceQueues for more information on using the ListDeadLetterSourceQueues
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListDeadLetterSourceQueuesRequest method.
// req, resp := client.ListDeadLetterSourceQueuesRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ListDeadLetterSourceQueues
func (c *SQS) ListDeadLetterSourceQueuesRequest(input *ListDeadLetterSourceQueuesInput) (req *request.Request, output *ListDeadLetterSourceQueuesOutput) {
op := &request.Operation{
Name: opListDeadLetterSourceQueues,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &ListDeadLetterSourceQueuesInput{}
}
output = &ListDeadLetterSourceQueuesOutput{}
req = c.newRequest(op, input, output)
return
}
// ListDeadLetterSourceQueues API operation for Amazon Simple Queue Service.
//
// Returns a list of your queues that have the RedrivePolicy queue attribute
// configured with a dead-letter queue.
//
// For more information about using dead-letter queues, see Using Amazon SQS
// Dead-Letter Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation ListDeadLetterSourceQueues for usage and error information.
//
// Returned Error Codes:
// * ErrCodeQueueDoesNotExist "AWS.SimpleQueueService.NonExistentQueue"
// The queue referred to doesn't exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ListDeadLetterSourceQueues
func (c *SQS) ListDeadLetterSourceQueues(input *ListDeadLetterSourceQueuesInput) (*ListDeadLetterSourceQueuesOutput, error) {
req, out := c.ListDeadLetterSourceQueuesRequest(input)
return out, req.Send()
}
// ListDeadLetterSourceQueuesWithContext is the same as ListDeadLetterSourceQueues with the addition of
// the ability to pass a context and additional request options.
//
// See ListDeadLetterSourceQueues for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) ListDeadLetterSourceQueuesWithContext(ctx aws.Context, input *ListDeadLetterSourceQueuesInput, opts ...request.Option) (*ListDeadLetterSourceQueuesOutput, error) {
req, out := c.ListDeadLetterSourceQueuesRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opListQueueTags = "ListQueueTags"
// ListQueueTagsRequest generates a "aws/request.Request" representing the
// client's request for the ListQueueTags operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListQueueTags for more information on using the ListQueueTags
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListQueueTagsRequest method.
// req, resp := client.ListQueueTagsRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ListQueueTags
func (c *SQS) ListQueueTagsRequest(input *ListQueueTagsInput) (req *request.Request, output *ListQueueTagsOutput) {
op := &request.Operation{
Name: opListQueueTags,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &ListQueueTagsInput{}
}
output = &ListQueueTagsOutput{}
req = c.newRequest(op, input, output)
return
}
// ListQueueTags API operation for Amazon Simple Queue Service.
//
// List all cost allocation tags added to the specified Amazon SQS queue. For
// an overview, see Tagging Amazon SQS Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-tagging-queues.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// When you use queue tags, keep the following guidelines in mind:
//
// * Adding more than 50 tags to a queue isn't recommended.
//
// * Tags don't have any semantic meaning. Amazon SQS interprets tags as
// character strings.
//
// * Tags are case-sensitive.
//
// * A new tag with a key identical to that of an existing tag overwrites
// the existing tag.
//
// * Tagging API actions are limited to 5 TPS per AWS account. If your application
// requires a higher throughput, file a technical support request (https://console.aws.amazon.com/support/home#/case/create?issueType=technical).
//
// For a full list of tag restrictions, see Limits Related to Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/limits-queues.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation ListQueueTags for usage and error information.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ListQueueTags
func (c *SQS) ListQueueTags(input *ListQueueTagsInput) (*ListQueueTagsOutput, error) {
req, out := c.ListQueueTagsRequest(input)
return out, req.Send()
}
// ListQueueTagsWithContext is the same as ListQueueTags with the addition of
// the ability to pass a context and additional request options.
//
// See ListQueueTags for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) ListQueueTagsWithContext(ctx aws.Context, input *ListQueueTagsInput, opts ...request.Option) (*ListQueueTagsOutput, error) {
req, out := c.ListQueueTagsRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opListQueues = "ListQueues"
// ListQueuesRequest generates a "aws/request.Request" representing the
// client's request for the ListQueues operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListQueues for more information on using the ListQueues
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ListQueuesRequest method.
// req, resp := client.ListQueuesRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ListQueues
func (c *SQS) ListQueuesRequest(input *ListQueuesInput) (req *request.Request, output *ListQueuesOutput) {
op := &request.Operation{
Name: opListQueues,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &ListQueuesInput{}
}
output = &ListQueuesOutput{}
req = c.newRequest(op, input, output)
return
}
// ListQueues API operation for Amazon Simple Queue Service.
//
// Returns a list of your queues. The maximum number of queues that can be returned
// is 1,000. If you specify a value for the optional QueueNamePrefix parameter,
// only queues with a name that begins with the specified value are returned.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation ListQueues for usage and error information.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ListQueues
func (c *SQS) ListQueues(input *ListQueuesInput) (*ListQueuesOutput, error) {
req, out := c.ListQueuesRequest(input)
return out, req.Send()
}
// ListQueuesWithContext is the same as ListQueues with the addition of
// the ability to pass a context and additional request options.
//
// See ListQueues for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) ListQueuesWithContext(ctx aws.Context, input *ListQueuesInput, opts ...request.Option) (*ListQueuesOutput, error) {
req, out := c.ListQueuesRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opPurgeQueue = "PurgeQueue"
// PurgeQueueRequest generates a "aws/request.Request" representing the
// client's request for the PurgeQueue operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See PurgeQueue for more information on using the PurgeQueue
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the PurgeQueueRequest method.
// req, resp := client.PurgeQueueRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/PurgeQueue
func (c *SQS) PurgeQueueRequest(input *PurgeQueueInput) (req *request.Request, output *PurgeQueueOutput) {
op := &request.Operation{
Name: opPurgeQueue,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &PurgeQueueInput{}
}
output = &PurgeQueueOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Remove(query.UnmarshalHandler)
req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
return
}
// PurgeQueue API operation for Amazon Simple Queue Service.
//
// Deletes the messages in a queue specified by the QueueURL parameter.
//
// When you use the PurgeQueue action, you can't retrieve a message deleted
// from a queue.
//
// When you purge a queue, the message deletion process takes up to 60 seconds.
// All messages sent to the queue before calling the PurgeQueue action are deleted.
// Messages sent to the queue while it is being purged might be deleted. While
// the queue is being purged, messages sent to the queue before PurgeQueue is
// called might be received, but are deleted within the next minute.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation PurgeQueue for usage and error information.
//
// Returned Error Codes:
// * ErrCodeQueueDoesNotExist "AWS.SimpleQueueService.NonExistentQueue"
// The queue referred to doesn't exist.
//
// * ErrCodePurgeQueueInProgress "AWS.SimpleQueueService.PurgeQueueInProgress"
// Indicates that the specified queue previously received a PurgeQueue request
// within the last 60 seconds (the time it can take to delete the messages in
// the queue).
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/PurgeQueue
func (c *SQS) PurgeQueue(input *PurgeQueueInput) (*PurgeQueueOutput, error) {
req, out := c.PurgeQueueRequest(input)
return out, req.Send()
}
// PurgeQueueWithContext is the same as PurgeQueue with the addition of
// the ability to pass a context and additional request options.
//
// See PurgeQueue for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) PurgeQueueWithContext(ctx aws.Context, input *PurgeQueueInput, opts ...request.Option) (*PurgeQueueOutput, error) {
req, out := c.PurgeQueueRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opReceiveMessage = "ReceiveMessage"
// ReceiveMessageRequest generates a "aws/request.Request" representing the
// client's request for the ReceiveMessage operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ReceiveMessage for more information on using the ReceiveMessage
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the ReceiveMessageRequest method.
// req, resp := client.ReceiveMessageRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ReceiveMessage
func (c *SQS) ReceiveMessageRequest(input *ReceiveMessageInput) (req *request.Request, output *ReceiveMessageOutput) {
op := &request.Operation{
Name: opReceiveMessage,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &ReceiveMessageInput{}
}
output = &ReceiveMessageOutput{}
req = c.newRequest(op, input, output)
return
}
// ReceiveMessage API operation for Amazon Simple Queue Service.
//
// Retrieves one or more messages (up to 10), from the specified queue. Using
// the WaitTimeSeconds parameter enables long-poll support. For more information,
// see Amazon SQS Long Polling (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// Short poll is the default behavior where a weighted random set of machines
// is sampled on a ReceiveMessage call. Thus, only the messages on the sampled
// machines are returned. If the number of messages in the queue is small (fewer
// than 1,000), you most likely get fewer messages than you requested per ReceiveMessage
// call. If the number of messages in the queue is extremely small, you might
// not receive any messages in a particular ReceiveMessage response. If this
// happens, repeat the request.
//
// For each message returned, the response includes the following:
//
// * The message body.
//
// * An MD5 digest of the message body. For information about MD5, see RFC1321
// (https://www.ietf.org/rfc/rfc1321.txt).
//
// * The MessageId you received when you sent the message to the queue.
//
// * The receipt handle.
//
// * The message attributes.
//
// * An MD5 digest of the message attributes.
//
// The receipt handle is the identifier you must provide when deleting the message.
// For more information, see Queue and Message Identifiers (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-queue-message-identifiers.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// You can provide the VisibilityTimeout parameter in your request. The parameter
// is applied to the messages that Amazon SQS returns in the response. If you
// don't include the parameter, the overall visibility timeout for the queue
// is used for the returned messages. For more information, see Visibility Timeout
// (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// A message that isn't deleted or a message whose visibility isn't extended
// before the visibility timeout expires counts as a failed receive. Depending
// on the configuration of the queue, the message might be sent to the dead-letter
// queue.
//
// In the future, new attributes might be added. If you write code that calls
// this action, we recommend that you structure your code so that it can handle
// new attributes gracefully.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation ReceiveMessage for usage and error information.
//
// Returned Error Codes:
// * ErrCodeOverLimit "OverLimit"
// The action that you requested would violate a limit. For example, ReceiveMessage
// returns this error if the maximum number of inflight messages is reached.
// AddPermission returns this error if the maximum number of permissions for
// the queue is reached.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ReceiveMessage
func (c *SQS) ReceiveMessage(input *ReceiveMessageInput) (*ReceiveMessageOutput, error) {
req, out := c.ReceiveMessageRequest(input)
return out, req.Send()
}
// ReceiveMessageWithContext is the same as ReceiveMessage with the addition of
// the ability to pass a context and additional request options.
//
// See ReceiveMessage for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) ReceiveMessageWithContext(ctx aws.Context, input *ReceiveMessageInput, opts ...request.Option) (*ReceiveMessageOutput, error) {
req, out := c.ReceiveMessageRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opRemovePermission = "RemovePermission"
// RemovePermissionRequest generates a "aws/request.Request" representing the
// client's request for the RemovePermission operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See RemovePermission for more information on using the RemovePermission
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the RemovePermissionRequest method.
// req, resp := client.RemovePermissionRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/RemovePermission
func (c *SQS) RemovePermissionRequest(input *RemovePermissionInput) (req *request.Request, output *RemovePermissionOutput) {
op := &request.Operation{
Name: opRemovePermission,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &RemovePermissionInput{}
}
output = &RemovePermissionOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Remove(query.UnmarshalHandler)
req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
return
}
// RemovePermission API operation for Amazon Simple Queue Service.
//
// Revokes any permissions in the queue policy that matches the specified Label
// parameter. Only the owner of the queue can remove permissions.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation RemovePermission for usage and error information.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/RemovePermission
func (c *SQS) RemovePermission(input *RemovePermissionInput) (*RemovePermissionOutput, error) {
req, out := c.RemovePermissionRequest(input)
return out, req.Send()
}
// RemovePermissionWithContext is the same as RemovePermission with the addition of
// the ability to pass a context and additional request options.
//
// See RemovePermission for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) RemovePermissionWithContext(ctx aws.Context, input *RemovePermissionInput, opts ...request.Option) (*RemovePermissionOutput, error) {
req, out := c.RemovePermissionRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opSendMessage = "SendMessage"
// SendMessageRequest generates a "aws/request.Request" representing the
// client's request for the SendMessage operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See SendMessage for more information on using the SendMessage
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the SendMessageRequest method.
// req, resp := client.SendMessageRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SendMessage
func (c *SQS) SendMessageRequest(input *SendMessageInput) (req *request.Request, output *SendMessageOutput) {
op := &request.Operation{
Name: opSendMessage,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &SendMessageInput{}
}
output = &SendMessageOutput{}
req = c.newRequest(op, input, output)
return
}
// SendMessage API operation for Amazon Simple Queue Service.
//
// Delivers a message to the specified queue.
//
// A message can include only XML, JSON, and unformatted text. The following
// Unicode characters are allowed:
//
// #x9 | #xA | #xD | #x20 to #xD7FF | #xE000 to #xFFFD | #x10000 to #x10FFFF
//
// Any characters not included in this list will be rejected. For more information,
// see the W3C specification for characters (http://www.w3.org/TR/REC-xml/#charsets).
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation SendMessage for usage and error information.
//
// Returned Error Codes:
// * ErrCodeInvalidMessageContents "InvalidMessageContents"
// The message contains characters outside the allowed set.
//
// * ErrCodeUnsupportedOperation "AWS.SimpleQueueService.UnsupportedOperation"
// Error code 400. Unsupported operation.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SendMessage
func (c *SQS) SendMessage(input *SendMessageInput) (*SendMessageOutput, error) {
req, out := c.SendMessageRequest(input)
return out, req.Send()
}
// SendMessageWithContext is the same as SendMessage with the addition of
// the ability to pass a context and additional request options.
//
// See SendMessage for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) SendMessageWithContext(ctx aws.Context, input *SendMessageInput, opts ...request.Option) (*SendMessageOutput, error) {
req, out := c.SendMessageRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opSendMessageBatch = "SendMessageBatch"
// SendMessageBatchRequest generates a "aws/request.Request" representing the
// client's request for the SendMessageBatch operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See SendMessageBatch for more information on using the SendMessageBatch
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the SendMessageBatchRequest method.
// req, resp := client.SendMessageBatchRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SendMessageBatch
func (c *SQS) SendMessageBatchRequest(input *SendMessageBatchInput) (req *request.Request, output *SendMessageBatchOutput) {
op := &request.Operation{
Name: opSendMessageBatch,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &SendMessageBatchInput{}
}
output = &SendMessageBatchOutput{}
req = c.newRequest(op, input, output)
return
}
// SendMessageBatch API operation for Amazon Simple Queue Service.
//
// Delivers up to ten messages to the specified queue. This is a batch version
// of SendMessage. For a FIFO queue, multiple messages within a single batch
// are enqueued in the order they are sent.
//
// The result of sending each message is reported individually in the response.
// Because the batch request can result in a combination of successful and unsuccessful
// actions, you should check for batch errors even when the call returns an
// HTTP status code of 200.
//
// The maximum allowed individual message size and the maximum total payload
// size (the sum of the individual lengths of all of the batched messages) are
// both 256 KB (262,144 bytes).
//
// A message can include only XML, JSON, and unformatted text. The following
// Unicode characters are allowed:
//
// #x9 | #xA | #xD | #x20 to #xD7FF | #xE000 to #xFFFD | #x10000 to #x10FFFF
//
// Any characters not included in this list will be rejected. For more information,
// see the W3C specification for characters (http://www.w3.org/TR/REC-xml/#charsets).
//
// If you don't specify the DelaySeconds parameter for an entry, Amazon SQS
// uses the default value for the queue.
//
// Some actions take lists of parameters. These lists are specified using the
// param.n notation. Values of n are integers starting from 1. For example,
// a parameter list with two elements looks like this:
//
// &Attribute.1=this
//
// &Attribute.2=that
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation SendMessageBatch for usage and error information.
//
// Returned Error Codes:
// * ErrCodeTooManyEntriesInBatchRequest "AWS.SimpleQueueService.TooManyEntriesInBatchRequest"
// The batch request contains more entries than permissible.
//
// * ErrCodeEmptyBatchRequest "AWS.SimpleQueueService.EmptyBatchRequest"
// The batch request doesn't contain any entries.
//
// * ErrCodeBatchEntryIdsNotDistinct "AWS.SimpleQueueService.BatchEntryIdsNotDistinct"
// Two or more batch entries in the request have the same Id.
//
// * ErrCodeBatchRequestTooLong "AWS.SimpleQueueService.BatchRequestTooLong"
// The length of all the messages put together is more than the limit.
//
// * ErrCodeInvalidBatchEntryId "AWS.SimpleQueueService.InvalidBatchEntryId"
// The Id of a batch entry in a batch request doesn't abide by the specification.
//
// * ErrCodeUnsupportedOperation "AWS.SimpleQueueService.UnsupportedOperation"
// Error code 400. Unsupported operation.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SendMessageBatch
func (c *SQS) SendMessageBatch(input *SendMessageBatchInput) (*SendMessageBatchOutput, error) {
req, out := c.SendMessageBatchRequest(input)
return out, req.Send()
}
// SendMessageBatchWithContext is the same as SendMessageBatch with the addition of
// the ability to pass a context and additional request options.
//
// See SendMessageBatch for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) SendMessageBatchWithContext(ctx aws.Context, input *SendMessageBatchInput, opts ...request.Option) (*SendMessageBatchOutput, error) {
req, out := c.SendMessageBatchRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opSetQueueAttributes = "SetQueueAttributes"
// SetQueueAttributesRequest generates a "aws/request.Request" representing the
// client's request for the SetQueueAttributes operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See SetQueueAttributes for more information on using the SetQueueAttributes
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the SetQueueAttributesRequest method.
// req, resp := client.SetQueueAttributesRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SetQueueAttributes
func (c *SQS) SetQueueAttributesRequest(input *SetQueueAttributesInput) (req *request.Request, output *SetQueueAttributesOutput) {
op := &request.Operation{
Name: opSetQueueAttributes,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &SetQueueAttributesInput{}
}
output = &SetQueueAttributesOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Remove(query.UnmarshalHandler)
req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
return
}
// SetQueueAttributes API operation for Amazon Simple Queue Service.
//
// Sets the value of one or more queue attributes. When you change a queue's
// attributes, the change can take up to 60 seconds for most of the attributes
// to propagate throughout the Amazon SQS system. Changes made to the MessageRetentionPeriod
// attribute can take up to 15 minutes.
//
// In the future, new attributes might be added. If you write code that calls
// this action, we recommend that you structure your code so that it can handle
// new attributes gracefully.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation SetQueueAttributes for usage and error information.
//
// Returned Error Codes:
// * ErrCodeInvalidAttributeName "InvalidAttributeName"
// The attribute referred to doesn't exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SetQueueAttributes
func (c *SQS) SetQueueAttributes(input *SetQueueAttributesInput) (*SetQueueAttributesOutput, error) {
req, out := c.SetQueueAttributesRequest(input)
return out, req.Send()
}
// SetQueueAttributesWithContext is the same as SetQueueAttributes with the addition of
// the ability to pass a context and additional request options.
//
// See SetQueueAttributes for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) SetQueueAttributesWithContext(ctx aws.Context, input *SetQueueAttributesInput, opts ...request.Option) (*SetQueueAttributesOutput, error) {
req, out := c.SetQueueAttributesRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opTagQueue = "TagQueue"
// TagQueueRequest generates a "aws/request.Request" representing the
// client's request for the TagQueue operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See TagQueue for more information on using the TagQueue
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the TagQueueRequest method.
// req, resp := client.TagQueueRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/TagQueue
func (c *SQS) TagQueueRequest(input *TagQueueInput) (req *request.Request, output *TagQueueOutput) {
op := &request.Operation{
Name: opTagQueue,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &TagQueueInput{}
}
output = &TagQueueOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Remove(query.UnmarshalHandler)
req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
return
}
// TagQueue API operation for Amazon Simple Queue Service.
//
// Add cost allocation tags to the specified Amazon SQS queue. For an overview,
// see Tagging Amazon SQS Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-tagging-queues.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// When you use queue tags, keep the following guidelines in mind:
//
// * Adding more than 50 tags to a queue isn't recommended.
//
// * Tags don't have any semantic meaning. Amazon SQS interprets tags as
// character strings.
//
// * Tags are case-sensitive.
//
// * A new tag with a key identical to that of an existing tag overwrites
// the existing tag.
//
// * Tagging API actions are limited to 5 TPS per AWS account. If your application
// requires a higher throughput, file a technical support request (https://console.aws.amazon.com/support/home#/case/create?issueType=technical).
//
// For a full list of tag restrictions, see Limits Related to Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/limits-queues.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation TagQueue for usage and error information.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/TagQueue
func (c *SQS) TagQueue(input *TagQueueInput) (*TagQueueOutput, error) {
req, out := c.TagQueueRequest(input)
return out, req.Send()
}
// TagQueueWithContext is the same as TagQueue with the addition of
// the ability to pass a context and additional request options.
//
// See TagQueue for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) TagQueueWithContext(ctx aws.Context, input *TagQueueInput, opts ...request.Option) (*TagQueueOutput, error) {
req, out := c.TagQueueRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
const opUntagQueue = "UntagQueue"
// UntagQueueRequest generates a "aws/request.Request" representing the
// client's request for the UntagQueue operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See UntagQueue for more information on using the UntagQueue
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
// // Example sending a request using the UntagQueueRequest method.
// req, resp := client.UntagQueueRequest(params)
//
// err := req.Send()
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/UntagQueue
func (c *SQS) UntagQueueRequest(input *UntagQueueInput) (req *request.Request, output *UntagQueueOutput) {
op := &request.Operation{
Name: opUntagQueue,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &UntagQueueInput{}
}
output = &UntagQueueOutput{}
req = c.newRequest(op, input, output)
req.Handlers.Unmarshal.Remove(query.UnmarshalHandler)
req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
return
}
// UntagQueue API operation for Amazon Simple Queue Service.
//
// Remove cost allocation tags from the specified Amazon SQS queue. For an overview,
// see Tagging Amazon SQS Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-tagging-queues.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// When you use queue tags, keep the following guidelines in mind:
//
// * Adding more than 50 tags to a queue isn't recommended.
//
// * Tags don't have any semantic meaning. Amazon SQS interprets tags as
// character strings.
//
// * Tags are case-sensitive.
//
// * A new tag with a key identical to that of an existing tag overwrites
// the existing tag.
//
// * Tagging API actions are limited to 5 TPS per AWS account. If your application
// requires a higher throughput, file a technical support request (https://console.aws.amazon.com/support/home#/case/create?issueType=technical).
//
// For a full list of tag restrictions, see Limits Related to Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/limits-queues.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Simple Queue Service's
// API operation UntagQueue for usage and error information.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/UntagQueue
func (c *SQS) UntagQueue(input *UntagQueueInput) (*UntagQueueOutput, error) {
req, out := c.UntagQueueRequest(input)
return out, req.Send()
}
// UntagQueueWithContext is the same as UntagQueue with the addition of
// the ability to pass a context and additional request options.
//
// See UntagQueue for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *SQS) UntagQueueWithContext(ctx aws.Context, input *UntagQueueInput, opts ...request.Option) (*UntagQueueOutput, error) {
req, out := c.UntagQueueRequest(input)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return out, req.Send()
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/AddPermissionRequest
type AddPermissionInput struct {
_ struct{} `type:"structure"`
// The AWS account number of the principal (http://docs.aws.amazon.com/general/latest/gr/glos-chap.html#P)
// who is given permission. The principal must have an AWS account, but does
// not need to be signed up for Amazon SQS. For information about locating the
// AWS account identification, see Your AWS Identifiers (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AWSCredentials.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// AWSAccountIds is a required field
AWSAccountIds []*string `locationNameList:"AWSAccountId" type:"list" flattened:"true" required:"true"`
// The action the client wants to allow for the specified principal. The following
// values are valid:
//
// * *
//
// * ChangeMessageVisibility
//
// * DeleteMessage
//
// * GetQueueAttributes
//
// * GetQueueUrl
//
// * ReceiveMessage
//
// * SendMessage
//
// For more information about these actions, see Understanding Permissions (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/acp-overview.html#PermissionTypes)
// in the Amazon Simple Queue Service Developer Guide.
//
// Specifying SendMessage, DeleteMessage, or ChangeMessageVisibility for ActionName.n
// also grants permissions for the corresponding batch versions of those actions:
// SendMessageBatch, DeleteMessageBatch, and ChangeMessageVisibilityBatch.
//
// Actions is a required field
Actions []*string `locationNameList:"ActionName" type:"list" flattened:"true" required:"true"`
// The unique identification of the permission you're setting (for example,
// AliceSendMessage). Maximum 80 characters. Allowed characters include alphanumeric
// characters, hyphens (-), and underscores (_).
//
// Label is a required field
Label *string `type:"string" required:"true"`
// The URL of the Amazon SQS queue to which permissions are added.
//
// Queue URLs are case-sensitive.
//
// QueueUrl is a required field
QueueUrl *string `type:"string" required:"true"`
}
// String returns the string representation
func (s AddPermissionInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s AddPermissionInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *AddPermissionInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "AddPermissionInput"}
if s.AWSAccountIds == nil {
invalidParams.Add(request.NewErrParamRequired("AWSAccountIds"))
}
if s.Actions == nil {
invalidParams.Add(request.NewErrParamRequired("Actions"))
}
if s.Label == nil {
invalidParams.Add(request.NewErrParamRequired("Label"))
}
if s.QueueUrl == nil {
invalidParams.Add(request.NewErrParamRequired("QueueUrl"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAWSAccountIds sets the AWSAccountIds field's value.
func (s *AddPermissionInput) SetAWSAccountIds(v []*string) *AddPermissionInput {
s.AWSAccountIds = v
return s
}
// SetActions sets the Actions field's value.
func (s *AddPermissionInput) SetActions(v []*string) *AddPermissionInput {
s.Actions = v
return s
}
// SetLabel sets the Label field's value.
func (s *AddPermissionInput) SetLabel(v string) *AddPermissionInput {
s.Label = &v
return s
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *AddPermissionInput) SetQueueUrl(v string) *AddPermissionInput {
s.QueueUrl = &v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/AddPermissionOutput
type AddPermissionOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s AddPermissionOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s AddPermissionOutput) GoString() string {
return s.String()
}
// This is used in the responses of batch API to give a detailed description
// of the result of an action on each entry in the request.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/BatchResultErrorEntry
type BatchResultErrorEntry struct {
_ struct{} `type:"structure"`
// An error code representing why the action failed on this entry.
//
// Code is a required field
Code *string `type:"string" required:"true"`
// The Id of an entry in a batch request.
//
// Id is a required field
Id *string `type:"string" required:"true"`
// A message explaining why the action failed on this entry.
Message *string `type:"string"`
// Specifies whether the error happened due to the sender's fault.
//
// SenderFault is a required field
SenderFault *bool `type:"boolean" required:"true"`
}
// String returns the string representation
func (s BatchResultErrorEntry) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s BatchResultErrorEntry) GoString() string {
return s.String()
}
// SetCode sets the Code field's value.
func (s *BatchResultErrorEntry) SetCode(v string) *BatchResultErrorEntry {
s.Code = &v
return s
}
// SetId sets the Id field's value.
func (s *BatchResultErrorEntry) SetId(v string) *BatchResultErrorEntry {
s.Id = &v
return s
}
// SetMessage sets the Message field's value.
func (s *BatchResultErrorEntry) SetMessage(v string) *BatchResultErrorEntry {
s.Message = &v
return s
}
// SetSenderFault sets the SenderFault field's value.
func (s *BatchResultErrorEntry) SetSenderFault(v bool) *BatchResultErrorEntry {
s.SenderFault = &v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ChangeMessageVisibilityBatchRequest
type ChangeMessageVisibilityBatchInput struct {
_ struct{} `type:"structure"`
// A list of receipt handles of the messages for which the visibility timeout
// must be changed.
//
// Entries is a required field
Entries []*ChangeMessageVisibilityBatchRequestEntry `locationNameList:"ChangeMessageVisibilityBatchRequestEntry" type:"list" flattened:"true" required:"true"`
// The URL of the Amazon SQS queue whose messages' visibility is changed.
//
// Queue URLs are case-sensitive.
//
// QueueUrl is a required field
QueueUrl *string `type:"string" required:"true"`
}
// String returns the string representation
func (s ChangeMessageVisibilityBatchInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ChangeMessageVisibilityBatchInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ChangeMessageVisibilityBatchInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ChangeMessageVisibilityBatchInput"}
if s.Entries == nil {
invalidParams.Add(request.NewErrParamRequired("Entries"))
}
if s.QueueUrl == nil {
invalidParams.Add(request.NewErrParamRequired("QueueUrl"))
}
if s.Entries != nil {
for i, v := range s.Entries {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Entries", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetEntries sets the Entries field's value.
func (s *ChangeMessageVisibilityBatchInput) SetEntries(v []*ChangeMessageVisibilityBatchRequestEntry) *ChangeMessageVisibilityBatchInput {
s.Entries = v
return s
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *ChangeMessageVisibilityBatchInput) SetQueueUrl(v string) *ChangeMessageVisibilityBatchInput {
s.QueueUrl = &v
return s
}
// For each message in the batch, the response contains a ChangeMessageVisibilityBatchResultEntry
// tag if the message succeeds or a BatchResultErrorEntry tag if the message
// fails.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ChangeMessageVisibilityBatchResult
type ChangeMessageVisibilityBatchOutput struct {
_ struct{} `type:"structure"`
// A list of BatchResultErrorEntry items.
//
// Failed is a required field
Failed []*BatchResultErrorEntry `locationNameList:"BatchResultErrorEntry" type:"list" flattened:"true" required:"true"`
// A list of ChangeMessageVisibilityBatchResultEntry items.
//
// Successful is a required field
Successful []*ChangeMessageVisibilityBatchResultEntry `locationNameList:"ChangeMessageVisibilityBatchResultEntry" type:"list" flattened:"true" required:"true"`
}
// String returns the string representation
func (s ChangeMessageVisibilityBatchOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ChangeMessageVisibilityBatchOutput) GoString() string {
return s.String()
}
// SetFailed sets the Failed field's value.
func (s *ChangeMessageVisibilityBatchOutput) SetFailed(v []*BatchResultErrorEntry) *ChangeMessageVisibilityBatchOutput {
s.Failed = v
return s
}
// SetSuccessful sets the Successful field's value.
func (s *ChangeMessageVisibilityBatchOutput) SetSuccessful(v []*ChangeMessageVisibilityBatchResultEntry) *ChangeMessageVisibilityBatchOutput {
s.Successful = v
return s
}
// Encloses a receipt handle and an entry id for each message in ChangeMessageVisibilityBatch.
//
// All of the following list parameters must be prefixed with ChangeMessageVisibilityBatchRequestEntry.n,
// where n is an integer value starting with 1. For example, a parameter list
// for this action might look like this:
//
// &ChangeMessageVisibilityBatchRequestEntry.1.Id=change_visibility_msg_2
//
// &ChangeMessageVisibilityBatchRequestEntry.1.ReceiptHandle=<replaceable>Your_Receipt_Handle</replaceable>
//
// &ChangeMessageVisibilityBatchRequestEntry.1.VisibilityTimeout=45
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ChangeMessageVisibilityBatchRequestEntry
type ChangeMessageVisibilityBatchRequestEntry struct {
_ struct{} `type:"structure"`
// An identifier for this particular receipt handle used to communicate the
// result.
//
// The Ids of a batch request need to be unique within a request
//
// Id is a required field
Id *string `type:"string" required:"true"`
// A receipt handle.
//
// ReceiptHandle is a required field
ReceiptHandle *string `type:"string" required:"true"`
// The new value (in seconds) for the message's visibility timeout.
VisibilityTimeout *int64 `type:"integer"`
}
// String returns the string representation
func (s ChangeMessageVisibilityBatchRequestEntry) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ChangeMessageVisibilityBatchRequestEntry) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ChangeMessageVisibilityBatchRequestEntry) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ChangeMessageVisibilityBatchRequestEntry"}
if s.Id == nil {
invalidParams.Add(request.NewErrParamRequired("Id"))
}
if s.ReceiptHandle == nil {
invalidParams.Add(request.NewErrParamRequired("ReceiptHandle"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetId sets the Id field's value.
func (s *ChangeMessageVisibilityBatchRequestEntry) SetId(v string) *ChangeMessageVisibilityBatchRequestEntry {
s.Id = &v
return s
}
// SetReceiptHandle sets the ReceiptHandle field's value.
func (s *ChangeMessageVisibilityBatchRequestEntry) SetReceiptHandle(v string) *ChangeMessageVisibilityBatchRequestEntry {
s.ReceiptHandle = &v
return s
}
// SetVisibilityTimeout sets the VisibilityTimeout field's value.
func (s *ChangeMessageVisibilityBatchRequestEntry) SetVisibilityTimeout(v int64) *ChangeMessageVisibilityBatchRequestEntry {
s.VisibilityTimeout = &v
return s
}
// Encloses the Id of an entry in ChangeMessageVisibilityBatch.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ChangeMessageVisibilityBatchResultEntry
type ChangeMessageVisibilityBatchResultEntry struct {
_ struct{} `type:"structure"`
// Represents a message whose visibility timeout has been changed successfully.
//
// Id is a required field
Id *string `type:"string" required:"true"`
}
// String returns the string representation
func (s ChangeMessageVisibilityBatchResultEntry) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ChangeMessageVisibilityBatchResultEntry) GoString() string {
return s.String()
}
// SetId sets the Id field's value.
func (s *ChangeMessageVisibilityBatchResultEntry) SetId(v string) *ChangeMessageVisibilityBatchResultEntry {
s.Id = &v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ChangeMessageVisibilityRequest
type ChangeMessageVisibilityInput struct {
_ struct{} `type:"structure"`
// The URL of the Amazon SQS queue whose message's visibility is changed.
//
// Queue URLs are case-sensitive.
//
// QueueUrl is a required field
QueueUrl *string `type:"string" required:"true"`
// The receipt handle associated with the message whose visibility timeout is
// changed. This parameter is returned by the ReceiveMessage action.
//
// ReceiptHandle is a required field
ReceiptHandle *string `type:"string" required:"true"`
// The new value for the message's visibility timeout (in seconds). Values values:
// 0 to 43200. Maximum: 12 hours.
//
// VisibilityTimeout is a required field
VisibilityTimeout *int64 `type:"integer" required:"true"`
}
// String returns the string representation
func (s ChangeMessageVisibilityInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ChangeMessageVisibilityInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ChangeMessageVisibilityInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ChangeMessageVisibilityInput"}
if s.QueueUrl == nil {
invalidParams.Add(request.NewErrParamRequired("QueueUrl"))
}
if s.ReceiptHandle == nil {
invalidParams.Add(request.NewErrParamRequired("ReceiptHandle"))
}
if s.VisibilityTimeout == nil {
invalidParams.Add(request.NewErrParamRequired("VisibilityTimeout"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *ChangeMessageVisibilityInput) SetQueueUrl(v string) *ChangeMessageVisibilityInput {
s.QueueUrl = &v
return s
}
// SetReceiptHandle sets the ReceiptHandle field's value.
func (s *ChangeMessageVisibilityInput) SetReceiptHandle(v string) *ChangeMessageVisibilityInput {
s.ReceiptHandle = &v
return s
}
// SetVisibilityTimeout sets the VisibilityTimeout field's value.
func (s *ChangeMessageVisibilityInput) SetVisibilityTimeout(v int64) *ChangeMessageVisibilityInput {
s.VisibilityTimeout = &v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ChangeMessageVisibilityOutput
type ChangeMessageVisibilityOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s ChangeMessageVisibilityOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ChangeMessageVisibilityOutput) GoString() string {
return s.String()
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/CreateQueueRequest
type CreateQueueInput struct {
_ struct{} `type:"structure"`
// A map of attributes with their corresponding values.
//
// The following lists the names, descriptions, and values of the special request
// parameters that the CreateQueue action uses:
//
// * DelaySeconds - The length of time, in seconds, for which the delivery
// of all messages in the queue is delayed. Valid values: An integer from
// 0 to 900 seconds (15 minutes). The default is 0 (zero).
//
// * MaximumMessageSize - The limit of how many bytes a message can contain
// before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes
// (1 KiB) to 262,144 bytes (256 KiB). The default is 262,144 (256 KiB).
//
//
// * MessageRetentionPeriod - The length of time, in seconds, for which Amazon
// SQS retains a message. Valid values: An integer from 60 seconds (1 minute)
// to 1,209,600 seconds (14 days). The default is 345,600 (4 days).
//
// * Policy - The queue's policy. A valid AWS policy. For more information
// about policy structure, see Overview of AWS IAM Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html)
// in the Amazon IAM User Guide.
//
// * ReceiveMessageWaitTimeSeconds - The length of time, in seconds, for
// which a ReceiveMessage action waits for a message to arrive. Valid values:
// An integer from 0 to 20 (seconds). The default is 0 (zero).
//
// * RedrivePolicy - The string that includes the parameters for the dead-letter
// queue functionality of the source queue. For more information about the
// redrive policy and dead-letter queues, see Using Amazon SQS Dead-Letter
// Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// deadLetterTargetArn - The Amazon Resource Name (ARN) of the dead-letter queue
// to which Amazon SQS moves messages after the value of maxReceiveCount
// is exceeded.
//
// maxReceiveCount - The number of times a message is delivered to the source
// queue before being moved to the dead-letter queue.
//
// The dead-letter queue of a FIFO queue must also be a FIFO queue. Similarly,
// the dead-letter queue of a standard queue must also be a standard queue.
//
// * VisibilityTimeout - The visibility timeout for the queue. Valid values:
// An integer from 0 to 43,200 (12 hours). The default is 30. For more information
// about the visibility timeout, see Visibility Timeout (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// The following attributes apply only to server-side-encryption (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html):
//
// * KmsMasterKeyId - The ID of an AWS-managed customer master key (CMK)
// for Amazon SQS or a custom CMK. For more information, see Key Terms (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html#sqs-sse-key-terms).
// While the alias of the AWS-managed CMK for Amazon SQS is always alias/aws/sqs,
// the alias of a custom CMK can, for example, be alias/MyAlias. For more
// examples, see KeyId (http://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html#API_DescribeKey_RequestParameters)
// in the AWS Key Management Service API Reference.
//
// * KmsDataKeyReusePeriodSeconds - The length of time, in seconds, for which
// Amazon SQS can reuse a data key (http://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-keys)
// to encrypt or decrypt messages before calling AWS KMS again. An integer
// representing seconds, between 60 seconds (1 minute) and 86,400 seconds
// (24 hours). The default is 300 (5 minutes). A shorter time period provides
// better security but results in more calls to KMS which might incur charges
// after Free Tier. For more information, see How Does the Data Key Reuse
// Period Work? (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html#sqs-how-does-the-data-key-reuse-period-work).
//
//
// The following attributes apply only to FIFO (first-in-first-out) queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html):
//
// * FifoQueue - Designates a queue as FIFO. Valid values: true, false. You
// can provide this attribute only during queue creation. You can't change
// it for an existing queue. When you set this attribute, you must also provide
// the MessageGroupId for your messages explicitly.
//
// For more information, see FIFO Queue Logic (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-understanding-logic)
// in the Amazon Simple Queue Service Developer Guide.
//
// * ContentBasedDeduplication - Enables content-based deduplication. Valid
// values: true, false. For more information, see Exactly-Once Processing
// (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing)
// in the Amazon Simple Queue Service Developer Guide.
//
// Every message must have a unique MessageDeduplicationId,
//
// You may provide a MessageDeduplicationId explicitly.
//
// If you aren't able to provide a MessageDeduplicationId and you enable ContentBasedDeduplication
// for your queue, Amazon SQS uses a SHA-256 hash to generate the MessageDeduplicationId
// using the body of the message (but not the attributes of the message).
//
//
// If you don't provide a MessageDeduplicationId and the queue doesn't have
// ContentBasedDeduplication set, the action fails with an error.
//
// If the queue has ContentBasedDeduplication set, your MessageDeduplicationId
// overrides the generated one.
//
// When ContentBasedDeduplication is in effect, messages with identical content
// sent within the deduplication interval are treated as duplicates and only
// one copy of the message is delivered.
//
// If you send one message with ContentBasedDeduplication enabled and then another
// message with a MessageDeduplicationId that is the same as the one generated
// for the first MessageDeduplicationId, the two messages are treated as
// duplicates and only one copy of the message is delivered.
//
// Any other valid special request parameters (such as the following) are ignored:
//
// * ApproximateNumberOfMessages
//
// * ApproximateNumberOfMessagesDelayed
//
// * ApproximateNumberOfMessagesNotVisible
//
// * CreatedTimestamp
//
// * LastModifiedTimestamp
//
// * QueueArn
Attributes map[string]*string `locationName:"Attribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"`
// The name of the new queue. The following limits apply to this name:
//
// * A queue name can have up to 80 characters.
//
// * Valid values: alphanumeric characters, hyphens (-), and underscores
// (_).
//
// * A FIFO queue name must end with the .fifo suffix.
//
// Queue names are case-sensitive.
//
// QueueName is a required field
QueueName *string `type:"string" required:"true"`
}
// String returns the string representation
func (s CreateQueueInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s CreateQueueInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *CreateQueueInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "CreateQueueInput"}
if s.QueueName == nil {
invalidParams.Add(request.NewErrParamRequired("QueueName"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAttributes sets the Attributes field's value.
func (s *CreateQueueInput) SetAttributes(v map[string]*string) *CreateQueueInput {
s.Attributes = v
return s
}
// SetQueueName sets the QueueName field's value.
func (s *CreateQueueInput) SetQueueName(v string) *CreateQueueInput {
s.QueueName = &v
return s
}
// Returns the QueueUrl attribute of the created queue.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/CreateQueueResult
type CreateQueueOutput struct {
_ struct{} `type:"structure"`
// The URL of the created Amazon SQS queue.
QueueUrl *string `type:"string"`
}
// String returns the string representation
func (s CreateQueueOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s CreateQueueOutput) GoString() string {
return s.String()
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *CreateQueueOutput) SetQueueUrl(v string) *CreateQueueOutput {
s.QueueUrl = &v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/DeleteMessageBatchRequest
type DeleteMessageBatchInput struct {
_ struct{} `type:"structure"`
// A list of receipt handles for the messages to be deleted.
//
// Entries is a required field
Entries []*DeleteMessageBatchRequestEntry `locationNameList:"DeleteMessageBatchRequestEntry" type:"list" flattened:"true" required:"true"`
// The URL of the Amazon SQS queue from which messages are deleted.
//
// Queue URLs are case-sensitive.
//
// QueueUrl is a required field
QueueUrl *string `type:"string" required:"true"`
}
// String returns the string representation
func (s DeleteMessageBatchInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s DeleteMessageBatchInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteMessageBatchInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DeleteMessageBatchInput"}
if s.Entries == nil {
invalidParams.Add(request.NewErrParamRequired("Entries"))
}
if s.QueueUrl == nil {
invalidParams.Add(request.NewErrParamRequired("QueueUrl"))
}
if s.Entries != nil {
for i, v := range s.Entries {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Entries", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetEntries sets the Entries field's value.
func (s *DeleteMessageBatchInput) SetEntries(v []*DeleteMessageBatchRequestEntry) *DeleteMessageBatchInput {
s.Entries = v
return s
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *DeleteMessageBatchInput) SetQueueUrl(v string) *DeleteMessageBatchInput {
s.QueueUrl = &v
return s
}
// For each message in the batch, the response contains a DeleteMessageBatchResultEntry
// tag if the message is deleted or a BatchResultErrorEntry tag if the message
// can't be deleted.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/DeleteMessageBatchResult
type DeleteMessageBatchOutput struct {
_ struct{} `type:"structure"`
// A list of BatchResultErrorEntry items.
//
// Failed is a required field
Failed []*BatchResultErrorEntry `locationNameList:"BatchResultErrorEntry" type:"list" flattened:"true" required:"true"`
// A list of DeleteMessageBatchResultEntry items.
//
// Successful is a required field
Successful []*DeleteMessageBatchResultEntry `locationNameList:"DeleteMessageBatchResultEntry" type:"list" flattened:"true" required:"true"`
}
// String returns the string representation
func (s DeleteMessageBatchOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s DeleteMessageBatchOutput) GoString() string {
return s.String()
}
// SetFailed sets the Failed field's value.
func (s *DeleteMessageBatchOutput) SetFailed(v []*BatchResultErrorEntry) *DeleteMessageBatchOutput {
s.Failed = v
return s
}
// SetSuccessful sets the Successful field's value.
func (s *DeleteMessageBatchOutput) SetSuccessful(v []*DeleteMessageBatchResultEntry) *DeleteMessageBatchOutput {
s.Successful = v
return s
}
// Encloses a receipt handle and an identifier for it.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/DeleteMessageBatchRequestEntry
type DeleteMessageBatchRequestEntry struct {
_ struct{} `type:"structure"`
// An identifier for this particular receipt handle. This is used to communicate
// the result.
//
// The Ids of a batch request need to be unique within a request
//
// Id is a required field
Id *string `type:"string" required:"true"`
// A receipt handle.
//
// ReceiptHandle is a required field
ReceiptHandle *string `type:"string" required:"true"`
}
// String returns the string representation
func (s DeleteMessageBatchRequestEntry) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s DeleteMessageBatchRequestEntry) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteMessageBatchRequestEntry) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DeleteMessageBatchRequestEntry"}
if s.Id == nil {
invalidParams.Add(request.NewErrParamRequired("Id"))
}
if s.ReceiptHandle == nil {
invalidParams.Add(request.NewErrParamRequired("ReceiptHandle"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetId sets the Id field's value.
func (s *DeleteMessageBatchRequestEntry) SetId(v string) *DeleteMessageBatchRequestEntry {
s.Id = &v
return s
}
// SetReceiptHandle sets the ReceiptHandle field's value.
func (s *DeleteMessageBatchRequestEntry) SetReceiptHandle(v string) *DeleteMessageBatchRequestEntry {
s.ReceiptHandle = &v
return s
}
// Encloses the Id of an entry in DeleteMessageBatch.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/DeleteMessageBatchResultEntry
type DeleteMessageBatchResultEntry struct {
_ struct{} `type:"structure"`
// Represents a successfully deleted message.
//
// Id is a required field
Id *string `type:"string" required:"true"`
}
// String returns the string representation
func (s DeleteMessageBatchResultEntry) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s DeleteMessageBatchResultEntry) GoString() string {
return s.String()
}
// SetId sets the Id field's value.
func (s *DeleteMessageBatchResultEntry) SetId(v string) *DeleteMessageBatchResultEntry {
s.Id = &v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/DeleteMessageRequest
type DeleteMessageInput struct {
_ struct{} `type:"structure"`
// The URL of the Amazon SQS queue from which messages are deleted.
//
// Queue URLs are case-sensitive.
//
// QueueUrl is a required field
QueueUrl *string `type:"string" required:"true"`
// The receipt handle associated with the message to delete.
//
// ReceiptHandle is a required field
ReceiptHandle *string `type:"string" required:"true"`
}
// String returns the string representation
func (s DeleteMessageInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s DeleteMessageInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteMessageInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DeleteMessageInput"}
if s.QueueUrl == nil {
invalidParams.Add(request.NewErrParamRequired("QueueUrl"))
}
if s.ReceiptHandle == nil {
invalidParams.Add(request.NewErrParamRequired("ReceiptHandle"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *DeleteMessageInput) SetQueueUrl(v string) *DeleteMessageInput {
s.QueueUrl = &v
return s
}
// SetReceiptHandle sets the ReceiptHandle field's value.
func (s *DeleteMessageInput) SetReceiptHandle(v string) *DeleteMessageInput {
s.ReceiptHandle = &v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/DeleteMessageOutput
type DeleteMessageOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s DeleteMessageOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s DeleteMessageOutput) GoString() string {
return s.String()
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/DeleteQueueRequest
type DeleteQueueInput struct {
_ struct{} `type:"structure"`
// The URL of the Amazon SQS queue to delete.
//
// Queue URLs are case-sensitive.
//
// QueueUrl is a required field
QueueUrl *string `type:"string" required:"true"`
}
// String returns the string representation
func (s DeleteQueueInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s DeleteQueueInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteQueueInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "DeleteQueueInput"}
if s.QueueUrl == nil {
invalidParams.Add(request.NewErrParamRequired("QueueUrl"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *DeleteQueueInput) SetQueueUrl(v string) *DeleteQueueInput {
s.QueueUrl = &v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/DeleteQueueOutput
type DeleteQueueOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s DeleteQueueOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s DeleteQueueOutput) GoString() string {
return s.String()
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/GetQueueAttributesRequest
type GetQueueAttributesInput struct {
_ struct{} `type:"structure"`
// A list of attributes for which to retrieve information.
//
// In the future, new attributes might be added. If you write code that calls
// this action, we recommend that you structure your code so that it can handle
// new attributes gracefully.
//
// The following attributes are supported:
//
// * All - Returns all values.
//
// * ApproximateNumberOfMessages - Returns the approximate number of visible
// messages in a queue. For more information, see Resources Required to Process
// Messages (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-resources-required-process-messages.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// * ApproximateNumberOfMessagesDelayed - Returns the approximate number
// of messages that are waiting to be added to the queue.
//
// * ApproximateNumberOfMessagesNotVisible - Returns the approximate number
// of messages that have not timed-out and aren't deleted. For more information,
// see Resources Required to Process Messages (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-resources-required-process-messages.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// * CreatedTimestamp - Returns the time when the queue was created in seconds
// (epoch time (http://en.wikipedia.org/wiki/Unix_time)).
//
// * DelaySeconds - Returns the default delay on the queue in seconds.
//
// * LastModifiedTimestamp - Returns the time when the queue was last changed
// in seconds (epoch time (http://en.wikipedia.org/wiki/Unix_time)).
//
// * MaximumMessageSize - Returns the limit of how many bytes a message can
// contain before Amazon SQS rejects it.
//
// * MessageRetentionPeriod - Returns the length of time, in seconds, for
// which Amazon SQS retains a message.
//
// * Policy - Returns the policy of the queue.
//
// * QueueArn - Returns the Amazon resource name (ARN) of the queue.
//
// * ReceiveMessageWaitTimeSeconds - Returns the length of time, in seconds,
// for which the ReceiveMessage action waits for a message to arrive.
//
// * RedrivePolicy - Returns the string that includes the parameters for
// dead-letter queue functionality of the source queue. For more information
// about the redrive policy and dead-letter queues, see Using Amazon SQS
// Dead-Letter Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// deadLetterTargetArn - The Amazon Resource Name (ARN) of the dead-letter queue
// to which Amazon SQS moves messages after the value of maxReceiveCount
// is exceeded.
//
// maxReceiveCount - The number of times a message is delivered to the source
// queue before being moved to the dead-letter queue.
//
// * VisibilityTimeout - Returns the visibility timeout for the queue. For
// more information about the visibility timeout, see Visibility Timeout
// (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// The following attributes apply only to server-side-encryption (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html):
//
// * KmsMasterKeyId - Returns the ID of an AWS-managed customer master key
// (CMK) for Amazon SQS or a custom CMK. For more information, see Key Terms
// (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html#sqs-sse-key-terms).
//
//
// * KmsDataKeyReusePeriodSeconds - Returns the length of time, in seconds,
// for which Amazon SQS can reuse a data key to encrypt or decrypt messages
// before calling AWS KMS again. For more information, see How Does the Data
// Key Reuse Period Work? (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html#sqs-how-does-the-data-key-reuse-period-work).
//
//
// The following attributes apply only to FIFO (first-in-first-out) queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html):
//
// * FifoQueue - Returns whether the queue is FIFO. For more information,
// see FIFO Queue Logic (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-understanding-logic)
// in the Amazon Simple Queue Service Developer Guide.
//
// To determine whether a queue is FIFO (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html),
// you can check whether QueueName ends with the .fifo suffix.
//
// * ContentBasedDeduplication - Returns whether content-based deduplication
// is enabled for the queue. For more information, see Exactly-Once Processing
// (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing)
// in the Amazon Simple Queue Service Developer Guide.
AttributeNames []*string `locationNameList:"AttributeName" type:"list" flattened:"true"`
// The URL of the Amazon SQS queue whose attribute information is retrieved.
//
// Queue URLs are case-sensitive.
//
// QueueUrl is a required field
QueueUrl *string `type:"string" required:"true"`
}
// String returns the string representation
func (s GetQueueAttributesInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s GetQueueAttributesInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GetQueueAttributesInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GetQueueAttributesInput"}
if s.QueueUrl == nil {
invalidParams.Add(request.NewErrParamRequired("QueueUrl"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAttributeNames sets the AttributeNames field's value.
func (s *GetQueueAttributesInput) SetAttributeNames(v []*string) *GetQueueAttributesInput {
s.AttributeNames = v
return s
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *GetQueueAttributesInput) SetQueueUrl(v string) *GetQueueAttributesInput {
s.QueueUrl = &v
return s
}
// A list of returned queue attributes.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/GetQueueAttributesResult
type GetQueueAttributesOutput struct {
_ struct{} `type:"structure"`
// A map of attributes to their respective values.
Attributes map[string]*string `locationName:"Attribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"`
}
// String returns the string representation
func (s GetQueueAttributesOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s GetQueueAttributesOutput) GoString() string {
return s.String()
}
// SetAttributes sets the Attributes field's value.
func (s *GetQueueAttributesOutput) SetAttributes(v map[string]*string) *GetQueueAttributesOutput {
s.Attributes = v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/GetQueueUrlRequest
type GetQueueUrlInput struct {
_ struct{} `type:"structure"`
// The name of the queue whose URL must be fetched. Maximum 80 characters. Valid
// values: alphanumeric characters, hyphens (-), and underscores (_).
//
// Queue names are case-sensitive.
//
// QueueName is a required field
QueueName *string `type:"string" required:"true"`
// The AWS account ID of the account that created the queue.
QueueOwnerAWSAccountId *string `type:"string"`
}
// String returns the string representation
func (s GetQueueUrlInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s GetQueueUrlInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *GetQueueUrlInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "GetQueueUrlInput"}
if s.QueueName == nil {
invalidParams.Add(request.NewErrParamRequired("QueueName"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetQueueName sets the QueueName field's value.
func (s *GetQueueUrlInput) SetQueueName(v string) *GetQueueUrlInput {
s.QueueName = &v
return s
}
// SetQueueOwnerAWSAccountId sets the QueueOwnerAWSAccountId field's value.
func (s *GetQueueUrlInput) SetQueueOwnerAWSAccountId(v string) *GetQueueUrlInput {
s.QueueOwnerAWSAccountId = &v
return s
}
// For more information, see Responses (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/UnderstandingResponses.html)
// in the Amazon Simple Queue Service Developer Guide.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/GetQueueUrlResult
type GetQueueUrlOutput struct {
_ struct{} `type:"structure"`
// The URL of the queue.
QueueUrl *string `type:"string"`
}
// String returns the string representation
func (s GetQueueUrlOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s GetQueueUrlOutput) GoString() string {
return s.String()
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *GetQueueUrlOutput) SetQueueUrl(v string) *GetQueueUrlOutput {
s.QueueUrl = &v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ListDeadLetterSourceQueuesRequest
type ListDeadLetterSourceQueuesInput struct {
_ struct{} `type:"structure"`
// The URL of a dead-letter queue.
//
// Queue URLs are case-sensitive.
//
// QueueUrl is a required field
QueueUrl *string `type:"string" required:"true"`
}
// String returns the string representation
func (s ListDeadLetterSourceQueuesInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ListDeadLetterSourceQueuesInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListDeadLetterSourceQueuesInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListDeadLetterSourceQueuesInput"}
if s.QueueUrl == nil {
invalidParams.Add(request.NewErrParamRequired("QueueUrl"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *ListDeadLetterSourceQueuesInput) SetQueueUrl(v string) *ListDeadLetterSourceQueuesInput {
s.QueueUrl = &v
return s
}
// A list of your dead letter source queues.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ListDeadLetterSourceQueuesResult
type ListDeadLetterSourceQueuesOutput struct {
_ struct{} `type:"structure"`
// A list of source queue URLs that have the RedrivePolicy queue attribute configured
// with a dead-letter queue.
//
// QueueUrls is a required field
QueueUrls []*string `locationName:"queueUrls" locationNameList:"QueueUrl" type:"list" flattened:"true" required:"true"`
}
// String returns the string representation
func (s ListDeadLetterSourceQueuesOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ListDeadLetterSourceQueuesOutput) GoString() string {
return s.String()
}
// SetQueueUrls sets the QueueUrls field's value.
func (s *ListDeadLetterSourceQueuesOutput) SetQueueUrls(v []*string) *ListDeadLetterSourceQueuesOutput {
s.QueueUrls = v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ListQueueTagsRequest
type ListQueueTagsInput struct {
_ struct{} `type:"structure"`
// The URL of the queue.
//
// QueueUrl is a required field
QueueUrl *string `type:"string" required:"true"`
}
// String returns the string representation
func (s ListQueueTagsInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ListQueueTagsInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ListQueueTagsInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ListQueueTagsInput"}
if s.QueueUrl == nil {
invalidParams.Add(request.NewErrParamRequired("QueueUrl"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *ListQueueTagsInput) SetQueueUrl(v string) *ListQueueTagsInput {
s.QueueUrl = &v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ListQueueTagsResult
type ListQueueTagsOutput struct {
_ struct{} `type:"structure"`
// The list of all tags added to the specified queue.
Tags map[string]*string `locationName:"Tag" locationNameKey:"Key" locationNameValue:"Value" type:"map" flattened:"true"`
}
// String returns the string representation
func (s ListQueueTagsOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ListQueueTagsOutput) GoString() string {
return s.String()
}
// SetTags sets the Tags field's value.
func (s *ListQueueTagsOutput) SetTags(v map[string]*string) *ListQueueTagsOutput {
s.Tags = v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ListQueuesRequest
type ListQueuesInput struct {
_ struct{} `type:"structure"`
// A string to use for filtering the list results. Only those queues whose name
// begins with the specified string are returned.
//
// Queue names are case-sensitive.
QueueNamePrefix *string `type:"string"`
}
// String returns the string representation
func (s ListQueuesInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ListQueuesInput) GoString() string {
return s.String()
}
// SetQueueNamePrefix sets the QueueNamePrefix field's value.
func (s *ListQueuesInput) SetQueueNamePrefix(v string) *ListQueuesInput {
s.QueueNamePrefix = &v
return s
}
// A list of your queues.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ListQueuesResult
type ListQueuesOutput struct {
_ struct{} `type:"structure"`
// A list of queue URLs, up to 1,000 entries.
QueueUrls []*string `locationNameList:"QueueUrl" type:"list" flattened:"true"`
}
// String returns the string representation
func (s ListQueuesOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ListQueuesOutput) GoString() string {
return s.String()
}
// SetQueueUrls sets the QueueUrls field's value.
func (s *ListQueuesOutput) SetQueueUrls(v []*string) *ListQueuesOutput {
s.QueueUrls = v
return s
}
// An Amazon SQS message.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/Message
type Message struct {
_ struct{} `type:"structure"`
// SenderId, SentTimestamp, ApproximateReceiveCount, and/or ApproximateFirstReceiveTimestamp.
// SentTimestamp and ApproximateFirstReceiveTimestamp are each returned as an
// integer representing the epoch time (http://en.wikipedia.org/wiki/Unix_time)
// in milliseconds.
Attributes map[string]*string `locationName:"Attribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"`
// The message's contents (not URL-encoded).
Body *string `type:"string"`
// An MD5 digest of the non-URL-encoded message body string.
MD5OfBody *string `type:"string"`
// An MD5 digest of the non-URL-encoded message attribute string. You can use
// this attribute to verify that Amazon SQS received the message correctly.
// Amazon SQS URL-decodes the message before creating the MD5 digest. For information
// about MD5, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt).
MD5OfMessageAttributes *string `type:"string"`
// Each message attribute consists of a Name, Type, and Value. For more information,
// see Message Attribute Items and Validation (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-attributes.html#message-attributes-items-validation)
// in the Amazon Simple Queue Service Developer Guide.
MessageAttributes map[string]*MessageAttributeValue `locationName:"MessageAttribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"`
// A unique identifier for the message. A MessageIdis considered unique across
// all AWS accounts for an extended period of time.
MessageId *string `type:"string"`
// An identifier associated with the act of receiving the message. A new receipt
// handle is returned every time you receive a message. When deleting a message,
// you provide the last received receipt handle to delete the message.
ReceiptHandle *string `type:"string"`
}
// String returns the string representation
func (s Message) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s Message) GoString() string {
return s.String()
}
// SetAttributes sets the Attributes field's value.
func (s *Message) SetAttributes(v map[string]*string) *Message {
s.Attributes = v
return s
}
// SetBody sets the Body field's value.
func (s *Message) SetBody(v string) *Message {
s.Body = &v
return s
}
// SetMD5OfBody sets the MD5OfBody field's value.
func (s *Message) SetMD5OfBody(v string) *Message {
s.MD5OfBody = &v
return s
}
// SetMD5OfMessageAttributes sets the MD5OfMessageAttributes field's value.
func (s *Message) SetMD5OfMessageAttributes(v string) *Message {
s.MD5OfMessageAttributes = &v
return s
}
// SetMessageAttributes sets the MessageAttributes field's value.
func (s *Message) SetMessageAttributes(v map[string]*MessageAttributeValue) *Message {
s.MessageAttributes = v
return s
}
// SetMessageId sets the MessageId field's value.
func (s *Message) SetMessageId(v string) *Message {
s.MessageId = &v
return s
}
// SetReceiptHandle sets the ReceiptHandle field's value.
func (s *Message) SetReceiptHandle(v string) *Message {
s.ReceiptHandle = &v
return s
}
// The user-specified message attribute value. For string data types, the Value
// attribute has the same restrictions on the content as the message body. For
// more information, see SendMessage.
//
// Name, type, value and the message body must not be empty or null. All parts
// of the message attribute, including Name, Type, and Value, are part of the
// message size restriction (256 KB or 262,144 bytes).
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/MessageAttributeValue
type MessageAttributeValue struct {
_ struct{} `type:"structure"`
// Not implemented. Reserved for future use.
BinaryListValues [][]byte `locationName:"BinaryListValue" locationNameList:"BinaryListValue" type:"list" flattened:"true"`
// Binary type attributes can store any binary data, such as compressed data,
// encrypted data, or images.
//
// BinaryValue is automatically base64 encoded/decoded by the SDK.
BinaryValue []byte `type:"blob"`
// Amazon SQS supports the following logical data types: String, Number, and
// Binary. For the Number data type, you must use StringValue.
//
// You can also append custom labels. For more information, see Message Attribute
// Data Types and Validation (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-attributes.html#message-attributes-data-types-validation)
// in the Amazon Simple Queue Service Developer Guide.
//
// DataType is a required field
DataType *string `type:"string" required:"true"`
// Not implemented. Reserved for future use.
StringListValues []*string `locationName:"StringListValue" locationNameList:"StringListValue" type:"list" flattened:"true"`
// Strings are Unicode with UTF-8 binary encoding. For a list of code values,
// see ASCII Printable Characters (http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters).
StringValue *string `type:"string"`
}
// String returns the string representation
func (s MessageAttributeValue) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s MessageAttributeValue) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *MessageAttributeValue) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "MessageAttributeValue"}
if s.DataType == nil {
invalidParams.Add(request.NewErrParamRequired("DataType"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetBinaryListValues sets the BinaryListValues field's value.
func (s *MessageAttributeValue) SetBinaryListValues(v [][]byte) *MessageAttributeValue {
s.BinaryListValues = v
return s
}
// SetBinaryValue sets the BinaryValue field's value.
func (s *MessageAttributeValue) SetBinaryValue(v []byte) *MessageAttributeValue {
s.BinaryValue = v
return s
}
// SetDataType sets the DataType field's value.
func (s *MessageAttributeValue) SetDataType(v string) *MessageAttributeValue {
s.DataType = &v
return s
}
// SetStringListValues sets the StringListValues field's value.
func (s *MessageAttributeValue) SetStringListValues(v []*string) *MessageAttributeValue {
s.StringListValues = v
return s
}
// SetStringValue sets the StringValue field's value.
func (s *MessageAttributeValue) SetStringValue(v string) *MessageAttributeValue {
s.StringValue = &v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/PurgeQueueRequest
type PurgeQueueInput struct {
_ struct{} `type:"structure"`
// The URL of the queue from which the PurgeQueue action deletes messages.
//
// Queue URLs are case-sensitive.
//
// QueueUrl is a required field
QueueUrl *string `type:"string" required:"true"`
}
// String returns the string representation
func (s PurgeQueueInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s PurgeQueueInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *PurgeQueueInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "PurgeQueueInput"}
if s.QueueUrl == nil {
invalidParams.Add(request.NewErrParamRequired("QueueUrl"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *PurgeQueueInput) SetQueueUrl(v string) *PurgeQueueInput {
s.QueueUrl = &v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/PurgeQueueOutput
type PurgeQueueOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s PurgeQueueOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s PurgeQueueOutput) GoString() string {
return s.String()
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ReceiveMessageRequest
type ReceiveMessageInput struct {
_ struct{} `type:"structure"`
// A list of attributes that need to be returned along with each message. These
// attributes include:
//
// * All - Returns all values.
//
// * ApproximateFirstReceiveTimestamp - Returns the time the message was
// first received from the queue (epoch time (http://en.wikipedia.org/wiki/Unix_time)
// in milliseconds).
//
// * ApproximateReceiveCount - Returns the number of times a message has
// been received from the queue but not deleted.
//
// * SenderId
//
// For an IAM user, returns the IAM user ID, for example ABCDEFGHI1JKLMNOPQ23R.
//
// For an IAM role, returns the IAM role ID, for example ABCDE1F2GH3I4JK5LMNOP:i-a123b456.
//
// * SentTimestamp - Returns the time the message was sent to the queue (epoch
// time (http://en.wikipedia.org/wiki/Unix_time) in milliseconds).
//
// * MessageDeduplicationId - Returns the value provided by the sender that
// calls the SendMessage action.
//
// * MessageGroupId - Returns the value provided by the sender that calls
// the SendMessage action. Messages with the same MessageGroupId are returned
// in sequence.
//
// * SequenceNumber - Returns the value provided by Amazon SQS.
//
// Any other valid special request parameters (such as the following) are ignored:
//
// * ApproximateNumberOfMessages
//
// * ApproximateNumberOfMessagesDelayed
//
// * ApproximateNumberOfMessagesNotVisible
//
// * CreatedTimestamp
//
// * ContentBasedDeduplication
//
// * DelaySeconds
//
// * FifoQueue
//
// * LastModifiedTimestamp
//
// * MaximumMessageSize
//
// * MessageRetentionPeriod
//
// * Policy
//
// * QueueArn,
//
// * ReceiveMessageWaitTimeSeconds
//
// * RedrivePolicy
//
// * VisibilityTimeout
AttributeNames []*string `locationNameList:"AttributeName" type:"list" flattened:"true"`
// The maximum number of messages to return. Amazon SQS never returns more messages
// than this value (however, fewer messages might be returned). Valid values
// are 1 to 10. Default is 1.
MaxNumberOfMessages *int64 `type:"integer"`
// The name of the message attribute, where N is the index.
//
// * The name can contain alphanumeric characters and the underscore (_),
// hyphen (-), and period (.).
//
// * The name is case-sensitive and must be unique among all attribute names
// for the message.
//
// * The name must not start with AWS-reserved prefixes such as AWS. or Amazon.
// (or any casing variants).
//
// * The name must not start or end with a period (.), and it should not
// have periods in succession (..).
//
// * The name can be up to 256 characters long.
//
// When using ReceiveMessage, you can send a list of attribute names to receive,
// or you can return all of the attributes by specifying All or .* in your request.
// You can also use all message attributes starting with a prefix, for example
// bar.*.
MessageAttributeNames []*string `locationNameList:"MessageAttributeName" type:"list" flattened:"true"`
// The URL of the Amazon SQS queue from which messages are received.
//
// Queue URLs are case-sensitive.
//
// QueueUrl is a required field
QueueUrl *string `type:"string" required:"true"`
// This parameter applies only to FIFO (first-in-first-out) queues.
//
// The token used for deduplication of ReceiveMessage calls. If a networking
// issue occurs after a ReceiveMessage action, and instead of a response you
// receive a generic error, you can retry the same action with an identical
// ReceiveRequestAttemptId to retrieve the same set of messages, even if their
// visibility timeout has not yet expired.
//
// * You can use ReceiveRequestAttemptId only for 5 minutes after a ReceiveMessage
// action.
//
// * When you set FifoQueue, a caller of the ReceiveMessage action can provide
// a ReceiveRequestAttemptId explicitly.
//
// * If a caller of the ReceiveMessage action doesn't provide a ReceiveRequestAttemptId,
// Amazon SQS generates a ReceiveRequestAttemptId.
//
// * You can retry the ReceiveMessage action with the same ReceiveRequestAttemptId
// if none of the messages have been modified (deleted or had their visibility
// changes).
//
// * During a visibility timeout, subsequent calls with the same ReceiveRequestAttemptId
// return the same messages and receipt handles. If a retry occurs within
// the deduplication interval, it resets the visibility timeout. For more
// information, see Visibility Timeout (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// If a caller of the ReceiveMessage action is still processing messages when
// the visibility timeout expires and messages become visible, another worker
// reading from the same queue can receive the same messages and therefore
// process duplicates. Also, if a reader whose message processing time is
// longer than the visibility timeout tries to delete the processed messages,
// the action fails with an error.
//
// To mitigate this effect, ensure that your application observes a safe threshold
// before the visibility timeout expires and extend the visibility timeout
// as necessary.
//
// * While messages with a particular MessageGroupId are invisible, no more
// messages belonging to the same MessageGroupId are returned until the visibility
// timeout expires. You can still receive messages with another MessageGroupId
// as long as it is also visible.
//
// * If a caller of ReceiveMessage can't track the ReceiveRequestAttemptId,
// no retries work until the original visibility timeout expires. As a result,
// delays might occur but the messages in the queue remain in a strict order.
//
// The length of ReceiveRequestAttemptId is 128 characters. ReceiveRequestAttemptId
// can contain alphanumeric characters (a-z, A-Z, 0-9) and punctuation (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~).
//
// For best practices of using ReceiveRequestAttemptId, see Using the ReceiveRequestAttemptId
// Request Parameter (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queue-recommendations.html#using-receiverequestattemptid-request-parameter)
// in the Amazon Simple Queue Service Developer Guide.
ReceiveRequestAttemptId *string `type:"string"`
// The duration (in seconds) that the received messages are hidden from subsequent
// retrieve requests after being retrieved by a ReceiveMessage request.
VisibilityTimeout *int64 `type:"integer"`
// The duration (in seconds) for which the call waits for a message to arrive
// in the queue before returning. If a message is available, the call returns
// sooner than WaitTimeSeconds. If no messages are available and the wait time
// expires, the call returns successfully with an empty list of messages.
WaitTimeSeconds *int64 `type:"integer"`
}
// String returns the string representation
func (s ReceiveMessageInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ReceiveMessageInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *ReceiveMessageInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "ReceiveMessageInput"}
if s.QueueUrl == nil {
invalidParams.Add(request.NewErrParamRequired("QueueUrl"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAttributeNames sets the AttributeNames field's value.
func (s *ReceiveMessageInput) SetAttributeNames(v []*string) *ReceiveMessageInput {
s.AttributeNames = v
return s
}
// SetMaxNumberOfMessages sets the MaxNumberOfMessages field's value.
func (s *ReceiveMessageInput) SetMaxNumberOfMessages(v int64) *ReceiveMessageInput {
s.MaxNumberOfMessages = &v
return s
}
// SetMessageAttributeNames sets the MessageAttributeNames field's value.
func (s *ReceiveMessageInput) SetMessageAttributeNames(v []*string) *ReceiveMessageInput {
s.MessageAttributeNames = v
return s
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *ReceiveMessageInput) SetQueueUrl(v string) *ReceiveMessageInput {
s.QueueUrl = &v
return s
}
// SetReceiveRequestAttemptId sets the ReceiveRequestAttemptId field's value.
func (s *ReceiveMessageInput) SetReceiveRequestAttemptId(v string) *ReceiveMessageInput {
s.ReceiveRequestAttemptId = &v
return s
}
// SetVisibilityTimeout sets the VisibilityTimeout field's value.
func (s *ReceiveMessageInput) SetVisibilityTimeout(v int64) *ReceiveMessageInput {
s.VisibilityTimeout = &v
return s
}
// SetWaitTimeSeconds sets the WaitTimeSeconds field's value.
func (s *ReceiveMessageInput) SetWaitTimeSeconds(v int64) *ReceiveMessageInput {
s.WaitTimeSeconds = &v
return s
}
// A list of received messages.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ReceiveMessageResult
type ReceiveMessageOutput struct {
_ struct{} `type:"structure"`
// A list of messages.
Messages []*Message `locationNameList:"Message" type:"list" flattened:"true"`
}
// String returns the string representation
func (s ReceiveMessageOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s ReceiveMessageOutput) GoString() string {
return s.String()
}
// SetMessages sets the Messages field's value.
func (s *ReceiveMessageOutput) SetMessages(v []*Message) *ReceiveMessageOutput {
s.Messages = v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/RemovePermissionRequest
type RemovePermissionInput struct {
_ struct{} `type:"structure"`
// The identification of the permission to remove. This is the label added using
// the AddPermission action.
//
// Label is a required field
Label *string `type:"string" required:"true"`
// The URL of the Amazon SQS queue from which permissions are removed.
//
// Queue URLs are case-sensitive.
//
// QueueUrl is a required field
QueueUrl *string `type:"string" required:"true"`
}
// String returns the string representation
func (s RemovePermissionInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s RemovePermissionInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *RemovePermissionInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "RemovePermissionInput"}
if s.Label == nil {
invalidParams.Add(request.NewErrParamRequired("Label"))
}
if s.QueueUrl == nil {
invalidParams.Add(request.NewErrParamRequired("QueueUrl"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetLabel sets the Label field's value.
func (s *RemovePermissionInput) SetLabel(v string) *RemovePermissionInput {
s.Label = &v
return s
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *RemovePermissionInput) SetQueueUrl(v string) *RemovePermissionInput {
s.QueueUrl = &v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/RemovePermissionOutput
type RemovePermissionOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s RemovePermissionOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s RemovePermissionOutput) GoString() string {
return s.String()
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SendMessageBatchRequest
type SendMessageBatchInput struct {
_ struct{} `type:"structure"`
// A list of SendMessageBatchRequestEntry items.
//
// Entries is a required field
Entries []*SendMessageBatchRequestEntry `locationNameList:"SendMessageBatchRequestEntry" type:"list" flattened:"true" required:"true"`
// The URL of the Amazon SQS queue to which batched messages are sent.
//
// Queue URLs are case-sensitive.
//
// QueueUrl is a required field
QueueUrl *string `type:"string" required:"true"`
}
// String returns the string representation
func (s SendMessageBatchInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s SendMessageBatchInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *SendMessageBatchInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "SendMessageBatchInput"}
if s.Entries == nil {
invalidParams.Add(request.NewErrParamRequired("Entries"))
}
if s.QueueUrl == nil {
invalidParams.Add(request.NewErrParamRequired("QueueUrl"))
}
if s.Entries != nil {
for i, v := range s.Entries {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Entries", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetEntries sets the Entries field's value.
func (s *SendMessageBatchInput) SetEntries(v []*SendMessageBatchRequestEntry) *SendMessageBatchInput {
s.Entries = v
return s
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *SendMessageBatchInput) SetQueueUrl(v string) *SendMessageBatchInput {
s.QueueUrl = &v
return s
}
// For each message in the batch, the response contains a SendMessageBatchResultEntry
// tag if the message succeeds or a BatchResultErrorEntry tag if the message
// fails.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SendMessageBatchResult
type SendMessageBatchOutput struct {
_ struct{} `type:"structure"`
// A list of BatchResultErrorEntry items with error details about each message
// that can't be enqueued.
//
// Failed is a required field
Failed []*BatchResultErrorEntry `locationNameList:"BatchResultErrorEntry" type:"list" flattened:"true" required:"true"`
// A list of SendMessageBatchResultEntry items.
//
// Successful is a required field
Successful []*SendMessageBatchResultEntry `locationNameList:"SendMessageBatchResultEntry" type:"list" flattened:"true" required:"true"`
}
// String returns the string representation
func (s SendMessageBatchOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s SendMessageBatchOutput) GoString() string {
return s.String()
}
// SetFailed sets the Failed field's value.
func (s *SendMessageBatchOutput) SetFailed(v []*BatchResultErrorEntry) *SendMessageBatchOutput {
s.Failed = v
return s
}
// SetSuccessful sets the Successful field's value.
func (s *SendMessageBatchOutput) SetSuccessful(v []*SendMessageBatchResultEntry) *SendMessageBatchOutput {
s.Successful = v
return s
}
// Contains the details of a single Amazon SQS message along with an Id.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SendMessageBatchRequestEntry
type SendMessageBatchRequestEntry struct {
_ struct{} `type:"structure"`
// The length of time, in seconds, for which a specific message is delayed.
// Valid values: 0 to 900. Maximum: 15 minutes. Messages with a positive DelaySeconds
// value become available for processing after the delay period is finished.
// If you don't specify a value, the default value for the queue is applied.
//
// When you set FifoQueue, you can't set DelaySeconds per message. You can set
// this parameter only on a queue level.
DelaySeconds *int64 `type:"integer"`
// An identifier for a message in this batch used to communicate the result.
//
// The Ids of a batch request need to be unique within a request
//
// Id is a required field
Id *string `type:"string" required:"true"`
// Each message attribute consists of a Name, Type, and Value. For more information,
// see Message Attribute Items and Validation (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-attributes.html#message-attributes-items-validation)
// in the Amazon Simple Queue Service Developer Guide.
MessageAttributes map[string]*MessageAttributeValue `locationName:"MessageAttribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"`
// The body of the message.
//
// MessageBody is a required field
MessageBody *string `type:"string" required:"true"`
// This parameter applies only to FIFO (first-in-first-out) queues.
//
// The token used for deduplication of messages within a 5-minute minimum deduplication
// interval. If a message with a particular MessageDeduplicationId is sent successfully,
// subsequent messages with the same MessageDeduplicationId are accepted successfully
// but aren't delivered. For more information, see Exactly-Once Processing
// (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing)
// in the Amazon Simple Queue Service Developer Guide.
//
// * Every message must have a unique MessageDeduplicationId,
//
// You may provide a MessageDeduplicationId explicitly.
//
// If you aren't able to provide a MessageDeduplicationId and you enable ContentBasedDeduplication
// for your queue, Amazon SQS uses a SHA-256 hash to generate the MessageDeduplicationId
// using the body of the message (but not the attributes of the message).
//
//
// If you don't provide a MessageDeduplicationId and the queue doesn't have
// ContentBasedDeduplication set, the action fails with an error.
//
// If the queue has ContentBasedDeduplication set, your MessageDeduplicationId
// overrides the generated one.
//
// * When ContentBasedDeduplication is in effect, messages with identical
// content sent within the deduplication interval are treated as duplicates
// and only one copy of the message is delivered.
//
// * If you send one message with ContentBasedDeduplication enabled and then
// another message with a MessageDeduplicationId that is the same as the
// one generated for the first MessageDeduplicationId, the two messages are
// treated as duplicates and only one copy of the message is delivered.
//
// The MessageDeduplicationId is available to the recipient of the message (this
// can be useful for troubleshooting delivery issues).
//
// If a message is sent successfully but the acknowledgement is lost and the
// message is resent with the same MessageDeduplicationId after the deduplication
// interval, Amazon SQS can't detect duplicate messages.
//
// The length of MessageDeduplicationId is 128 characters. MessageDeduplicationId
// can contain alphanumeric characters (a-z, A-Z, 0-9) and punctuation (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~).
//
// For best practices of using MessageDeduplicationId, see Using the MessageDeduplicationId
// Property (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queue-recommendations.html#using-messagededuplicationid-property)
// in the Amazon Simple Queue Service Developer Guide.
MessageDeduplicationId *string `type:"string"`
// This parameter applies only to FIFO (first-in-first-out) queues.
//
// The tag that specifies that a message belongs to a specific message group.
// Messages that belong to the same message group are processed in a FIFO manner
// (however, messages in different message groups might be processed out of
// order). To interleave multiple ordered streams within a single queue, use
// MessageGroupId values (for example, session data for multiple users). In
// this scenario, multiple readers can process the queue, but the session data
// of each user is processed in a FIFO fashion.
//
// * You must associate a non-empty MessageGroupId with a message. If you
// don't provide a MessageGroupId, the action fails.
//
// * ReceiveMessage might return messages with multiple MessageGroupId values.
// For each MessageGroupId, the messages are sorted by time sent. The caller
// can't specify a MessageGroupId.
//
// The length of MessageGroupId is 128 characters. Valid values are alphanumeric
// characters and punctuation (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~).
//
// For best practices of using MessageGroupId, see Using the MessageGroupId
// Property (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queue-recommendations.html#using-messagegroupid-property)
// in the Amazon Simple Queue Service Developer Guide.
//
// MessageGroupId is required for FIFO queues. You can't use it for Standard
// queues.
MessageGroupId *string `type:"string"`
}
// String returns the string representation
func (s SendMessageBatchRequestEntry) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s SendMessageBatchRequestEntry) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *SendMessageBatchRequestEntry) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "SendMessageBatchRequestEntry"}
if s.Id == nil {
invalidParams.Add(request.NewErrParamRequired("Id"))
}
if s.MessageBody == nil {
invalidParams.Add(request.NewErrParamRequired("MessageBody"))
}
if s.MessageAttributes != nil {
for i, v := range s.MessageAttributes {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "MessageAttributes", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetDelaySeconds sets the DelaySeconds field's value.
func (s *SendMessageBatchRequestEntry) SetDelaySeconds(v int64) *SendMessageBatchRequestEntry {
s.DelaySeconds = &v
return s
}
// SetId sets the Id field's value.
func (s *SendMessageBatchRequestEntry) SetId(v string) *SendMessageBatchRequestEntry {
s.Id = &v
return s
}
// SetMessageAttributes sets the MessageAttributes field's value.
func (s *SendMessageBatchRequestEntry) SetMessageAttributes(v map[string]*MessageAttributeValue) *SendMessageBatchRequestEntry {
s.MessageAttributes = v
return s
}
// SetMessageBody sets the MessageBody field's value.
func (s *SendMessageBatchRequestEntry) SetMessageBody(v string) *SendMessageBatchRequestEntry {
s.MessageBody = &v
return s
}
// SetMessageDeduplicationId sets the MessageDeduplicationId field's value.
func (s *SendMessageBatchRequestEntry) SetMessageDeduplicationId(v string) *SendMessageBatchRequestEntry {
s.MessageDeduplicationId = &v
return s
}
// SetMessageGroupId sets the MessageGroupId field's value.
func (s *SendMessageBatchRequestEntry) SetMessageGroupId(v string) *SendMessageBatchRequestEntry {
s.MessageGroupId = &v
return s
}
// Encloses a MessageId for a successfully-enqueued message in a SendMessageBatch.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SendMessageBatchResultEntry
type SendMessageBatchResultEntry struct {
_ struct{} `type:"structure"`
// An identifier for the message in this batch.
//
// Id is a required field
Id *string `type:"string" required:"true"`
// An MD5 digest of the non-URL-encoded message attribute string. You can use
// this attribute to verify that Amazon SQS received the message correctly.
// Amazon SQS URL-decodes the message before creating the MD5 digest. For information
// about MD5, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt).
MD5OfMessageAttributes *string `type:"string"`
// An MD5 digest of the non-URL-encoded message attribute string. You can use
// this attribute to verify that Amazon SQS received the message correctly.
// Amazon SQS URL-decodes the message before creating the MD5 digest. For information
// about MD5, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt).
//
// MD5OfMessageBody is a required field
MD5OfMessageBody *string `type:"string" required:"true"`
// An identifier for the message.
//
// MessageId is a required field
MessageId *string `type:"string" required:"true"`
// This parameter applies only to FIFO (first-in-first-out) queues.
//
// The large, non-consecutive number that Amazon SQS assigns to each message.
//
// The length of SequenceNumber is 128 bits. As SequenceNumber continues to
// increase for a particular MessageGroupId.
SequenceNumber *string `type:"string"`
}
// String returns the string representation
func (s SendMessageBatchResultEntry) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s SendMessageBatchResultEntry) GoString() string {
return s.String()
}
// SetId sets the Id field's value.
func (s *SendMessageBatchResultEntry) SetId(v string) *SendMessageBatchResultEntry {
s.Id = &v
return s
}
// SetMD5OfMessageAttributes sets the MD5OfMessageAttributes field's value.
func (s *SendMessageBatchResultEntry) SetMD5OfMessageAttributes(v string) *SendMessageBatchResultEntry {
s.MD5OfMessageAttributes = &v
return s
}
// SetMD5OfMessageBody sets the MD5OfMessageBody field's value.
func (s *SendMessageBatchResultEntry) SetMD5OfMessageBody(v string) *SendMessageBatchResultEntry {
s.MD5OfMessageBody = &v
return s
}
// SetMessageId sets the MessageId field's value.
func (s *SendMessageBatchResultEntry) SetMessageId(v string) *SendMessageBatchResultEntry {
s.MessageId = &v
return s
}
// SetSequenceNumber sets the SequenceNumber field's value.
func (s *SendMessageBatchResultEntry) SetSequenceNumber(v string) *SendMessageBatchResultEntry {
s.SequenceNumber = &v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SendMessageRequest
type SendMessageInput struct {
_ struct{} `type:"structure"`
// The length of time, in seconds, for which to delay a specific message. Valid
// values: 0 to 900. Maximum: 15 minutes. Messages with a positive DelaySeconds
// value become available for processing after the delay period is finished.
// If you don't specify a value, the default value for the queue applies.
//
// When you set FifoQueue, you can't set DelaySeconds per message. You can set
// this parameter only on a queue level.
DelaySeconds *int64 `type:"integer"`
// Each message attribute consists of a Name, Type, and Value. For more information,
// see Message Attribute Items and Validation (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-attributes.html#message-attributes-items-validation)
// in the Amazon Simple Queue Service Developer Guide.
MessageAttributes map[string]*MessageAttributeValue `locationName:"MessageAttribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"`
// The message to send. The maximum string size is 256 KB.
//
// A message can include only XML, JSON, and unformatted text. The following
// Unicode characters are allowed:
//
// #x9 | #xA | #xD | #x20 to #xD7FF | #xE000 to #xFFFD | #x10000 to #x10FFFF
//
// Any characters not included in this list will be rejected. For more information,
// see the W3C specification for characters (http://www.w3.org/TR/REC-xml/#charsets).
//
// MessageBody is a required field
MessageBody *string `type:"string" required:"true"`
// This parameter applies only to FIFO (first-in-first-out) queues.
//
// The token used for deduplication of sent messages. If a message with a particular
// MessageDeduplicationId is sent successfully, any messages sent with the same
// MessageDeduplicationId are accepted successfully but aren't delivered during
// the 5-minute deduplication interval. For more information, see Exactly-Once
// Processing (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing)
// in the Amazon Simple Queue Service Developer Guide.
//
// * Every message must have a unique MessageDeduplicationId,
//
// You may provide a MessageDeduplicationId explicitly.
//
// If you aren't able to provide a MessageDeduplicationId and you enable ContentBasedDeduplication
// for your queue, Amazon SQS uses a SHA-256 hash to generate the MessageDeduplicationId
// using the body of the message (but not the attributes of the message).
//
//
// If you don't provide a MessageDeduplicationId and the queue doesn't have
// ContentBasedDeduplication set, the action fails with an error.
//
// If the queue has ContentBasedDeduplication set, your MessageDeduplicationId
// overrides the generated one.
//
// * When ContentBasedDeduplication is in effect, messages with identical
// content sent within the deduplication interval are treated as duplicates
// and only one copy of the message is delivered.
//
// * If you send one message with ContentBasedDeduplication enabled and then
// another message with a MessageDeduplicationId that is the same as the
// one generated for the first MessageDeduplicationId, the two messages are
// treated as duplicates and only one copy of the message is delivered.
//
// The MessageDeduplicationId is available to the recipient of the message (this
// can be useful for troubleshooting delivery issues).
//
// If a message is sent successfully but the acknowledgement is lost and the
// message is resent with the same MessageDeduplicationId after the deduplication
// interval, Amazon SQS can't detect duplicate messages.
//
// The length of MessageDeduplicationId is 128 characters. MessageDeduplicationId
// can contain alphanumeric characters (a-z, A-Z, 0-9) and punctuation (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~).
//
// For best practices of using MessageDeduplicationId, see Using the MessageDeduplicationId
// Property (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queue-recommendations.html#using-messagededuplicationid-property)
// in the Amazon Simple Queue Service Developer Guide.
MessageDeduplicationId *string `type:"string"`
// This parameter applies only to FIFO (first-in-first-out) queues.
//
// The tag that specifies that a message belongs to a specific message group.
// Messages that belong to the same message group are processed in a FIFO manner
// (however, messages in different message groups might be processed out of
// order). To interleave multiple ordered streams within a single queue, use
// MessageGroupId values (for example, session data for multiple users). In
// this scenario, multiple readers can process the queue, but the session data
// of each user is processed in a FIFO fashion.
//
// * You must associate a non-empty MessageGroupId with a message. If you
// don't provide a MessageGroupId, the action fails.
//
// * ReceiveMessage might return messages with multiple MessageGroupId values.
// For each MessageGroupId, the messages are sorted by time sent. The caller
// can't specify a MessageGroupId.
//
// The length of MessageGroupId is 128 characters. Valid values are alphanumeric
// characters and punctuation (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~).
//
// For best practices of using MessageGroupId, see Using the MessageGroupId
// Property (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queue-recommendations.html#using-messagegroupid-property)
// in the Amazon Simple Queue Service Developer Guide.
//
// MessageGroupId is required for FIFO queues. You can't use it for Standard
// queues.
MessageGroupId *string `type:"string"`
// The URL of the Amazon SQS queue to which a message is sent.
//
// Queue URLs are case-sensitive.
//
// QueueUrl is a required field
QueueUrl *string `type:"string" required:"true"`
}
// String returns the string representation
func (s SendMessageInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s SendMessageInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *SendMessageInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "SendMessageInput"}
if s.MessageBody == nil {
invalidParams.Add(request.NewErrParamRequired("MessageBody"))
}
if s.QueueUrl == nil {
invalidParams.Add(request.NewErrParamRequired("QueueUrl"))
}
if s.MessageAttributes != nil {
for i, v := range s.MessageAttributes {
if v == nil {
continue
}
if err := v.Validate(); err != nil {
invalidParams.AddNested(fmt.Sprintf("%s[%v]", "MessageAttributes", i), err.(request.ErrInvalidParams))
}
}
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetDelaySeconds sets the DelaySeconds field's value.
func (s *SendMessageInput) SetDelaySeconds(v int64) *SendMessageInput {
s.DelaySeconds = &v
return s
}
// SetMessageAttributes sets the MessageAttributes field's value.
func (s *SendMessageInput) SetMessageAttributes(v map[string]*MessageAttributeValue) *SendMessageInput {
s.MessageAttributes = v
return s
}
// SetMessageBody sets the MessageBody field's value.
func (s *SendMessageInput) SetMessageBody(v string) *SendMessageInput {
s.MessageBody = &v
return s
}
// SetMessageDeduplicationId sets the MessageDeduplicationId field's value.
func (s *SendMessageInput) SetMessageDeduplicationId(v string) *SendMessageInput {
s.MessageDeduplicationId = &v
return s
}
// SetMessageGroupId sets the MessageGroupId field's value.
func (s *SendMessageInput) SetMessageGroupId(v string) *SendMessageInput {
s.MessageGroupId = &v
return s
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *SendMessageInput) SetQueueUrl(v string) *SendMessageInput {
s.QueueUrl = &v
return s
}
// The MD5OfMessageBody and MessageId elements.
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SendMessageResult
type SendMessageOutput struct {
_ struct{} `type:"structure"`
// An MD5 digest of the non-URL-encoded message attribute string. You can use
// this attribute to verify that Amazon SQS received the message correctly.
// Amazon SQS URL-decodes the message before creating the MD5 digest. For information
// about MD5, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt).
MD5OfMessageAttributes *string `type:"string"`
// An MD5 digest of the non-URL-encoded message attribute string. You can use
// this attribute to verify that Amazon SQS received the message correctly.
// Amazon SQS URL-decodes the message before creating the MD5 digest. For information
// about MD5, see RFC1321 (https://www.ietf.org/rfc/rfc1321.txt).
MD5OfMessageBody *string `type:"string"`
// An attribute containing the MessageId of the message sent to the queue. For
// more information, see Queue and Message Identifiers (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-queue-message-identifiers.html)
// in the Amazon Simple Queue Service Developer Guide.
MessageId *string `type:"string"`
// This parameter applies only to FIFO (first-in-first-out) queues.
//
// The large, non-consecutive number that Amazon SQS assigns to each message.
//
// The length of SequenceNumber is 128 bits. SequenceNumber continues to increase
// for a particular MessageGroupId.
SequenceNumber *string `type:"string"`
}
// String returns the string representation
func (s SendMessageOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s SendMessageOutput) GoString() string {
return s.String()
}
// SetMD5OfMessageAttributes sets the MD5OfMessageAttributes field's value.
func (s *SendMessageOutput) SetMD5OfMessageAttributes(v string) *SendMessageOutput {
s.MD5OfMessageAttributes = &v
return s
}
// SetMD5OfMessageBody sets the MD5OfMessageBody field's value.
func (s *SendMessageOutput) SetMD5OfMessageBody(v string) *SendMessageOutput {
s.MD5OfMessageBody = &v
return s
}
// SetMessageId sets the MessageId field's value.
func (s *SendMessageOutput) SetMessageId(v string) *SendMessageOutput {
s.MessageId = &v
return s
}
// SetSequenceNumber sets the SequenceNumber field's value.
func (s *SendMessageOutput) SetSequenceNumber(v string) *SendMessageOutput {
s.SequenceNumber = &v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SetQueueAttributesRequest
type SetQueueAttributesInput struct {
_ struct{} `type:"structure"`
// A map of attributes to set.
//
// The following lists the names, descriptions, and values of the special request
// parameters that the SetQueueAttributes action uses:
//
// * DelaySeconds - The length of time, in seconds, for which the delivery
// of all messages in the queue is delayed. Valid values: An integer from
// 0 to 900 (15 minutes). The default is 0 (zero).
//
// * MaximumMessageSize - The limit of how many bytes a message can contain
// before Amazon SQS rejects it. Valid values: An integer from 1,024 bytes
// (1 KiB) up to 262,144 bytes (256 KiB). The default is 262,144 (256 KiB).
//
//
// * MessageRetentionPeriod - The length of time, in seconds, for which Amazon
// SQS retains a message. Valid values: An integer representing seconds,
// from 60 (1 minute) to 1,209,600 (14 days). The default is 345,600 (4 days).
//
//
// * Policy - The queue's policy. A valid AWS policy. For more information
// about policy structure, see Overview of AWS IAM Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html)
// in the Amazon IAM User Guide.
//
// * ReceiveMessageWaitTimeSeconds - The length of time, in seconds, for
// which a ReceiveMessage action waits for a message to arrive. Valid values:
// an integer from 0 to 20 (seconds). The default is 0.
//
// * RedrivePolicy - The string that includes the parameters for the dead-letter
// queue functionality of the source queue. For more information about the
// redrive policy and dead-letter queues, see Using Amazon SQS Dead-Letter
// Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// deadLetterTargetArn - The Amazon Resource Name (ARN) of the dead-letter queue
// to which Amazon SQS moves messages after the value of maxReceiveCount
// is exceeded.
//
// maxReceiveCount - The number of times a message is delivered to the source
// queue before being moved to the dead-letter queue.
//
// The dead-letter queue of a FIFO queue must also be a FIFO queue. Similarly,
// the dead-letter queue of a standard queue must also be a standard queue.
//
// * VisibilityTimeout - The visibility timeout for the queue. Valid values:
// an integer from 0 to 43,200 (12 hours). The default is 30. For more information
// about the visibility timeout, see Visibility Timeout (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html)
// in the Amazon Simple Queue Service Developer Guide.
//
// The following attributes apply only to server-side-encryption (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html):
//
// * KmsMasterKeyId - The ID of an AWS-managed customer master key (CMK)
// for Amazon SQS or a custom CMK. For more information, see Key Terms (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html#sqs-sse-key-terms).
// While the alias of the AWS-managed CMK for Amazon SQS is always alias/aws/sqs,
// the alias of a custom CMK can, for example, be alias/MyAlias. For more
// examples, see KeyId (http://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html#API_DescribeKey_RequestParameters)
// in the AWS Key Management Service API Reference.
//
// * KmsDataKeyReusePeriodSeconds - The length of time, in seconds, for which
// Amazon SQS can reuse a data key (http://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-keys)
// to encrypt or decrypt messages before calling AWS KMS again. An integer
// representing seconds, between 60 seconds (1 minute) and 86,400 seconds
// (24 hours). The default is 300 (5 minutes). A shorter time period provides
// better security but results in more calls to KMS which might incur charges
// after Free Tier. For more information, see How Does the Data Key Reuse
// Period Work? (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html#sqs-how-does-the-data-key-reuse-period-work).
//
//
// The following attribute applies only to FIFO (first-in-first-out) queues
// (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html):
//
// * ContentBasedDeduplication - Enables content-based deduplication. For
// more information, see Exactly-Once Processing (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing)
// in the Amazon Simple Queue Service Developer Guide.
//
// Every message must have a unique MessageDeduplicationId,
//
// You may provide a MessageDeduplicationId explicitly.
//
// If you aren't able to provide a MessageDeduplicationId and you enable ContentBasedDeduplication
// for your queue, Amazon SQS uses a SHA-256 hash to generate the MessageDeduplicationId
// using the body of the message (but not the attributes of the message).
//
//
// If you don't provide a MessageDeduplicationId and the queue doesn't have
// ContentBasedDeduplication set, the action fails with an error.
//
// If the queue has ContentBasedDeduplication set, your MessageDeduplicationId
// overrides the generated one.
//
// When ContentBasedDeduplication is in effect, messages with identical content
// sent within the deduplication interval are treated as duplicates and only
// one copy of the message is delivered.
//
// If you send one message with ContentBasedDeduplication enabled and then another
// message with a MessageDeduplicationId that is the same as the one generated
// for the first MessageDeduplicationId, the two messages are treated as
// duplicates and only one copy of the message is delivered.
//
// Any other valid special request parameters (such as the following) are ignored:
//
// * ApproximateNumberOfMessages
//
// * ApproximateNumberOfMessagesDelayed
//
// * ApproximateNumberOfMessagesNotVisible
//
// * CreatedTimestamp
//
// * LastModifiedTimestamp
//
// * QueueArn
//
// Attributes is a required field
Attributes map[string]*string `locationName:"Attribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true" required:"true"`
// The URL of the Amazon SQS queue whose attributes are set.
//
// Queue URLs are case-sensitive.
//
// QueueUrl is a required field
QueueUrl *string `type:"string" required:"true"`
}
// String returns the string representation
func (s SetQueueAttributesInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s SetQueueAttributesInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *SetQueueAttributesInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "SetQueueAttributesInput"}
if s.Attributes == nil {
invalidParams.Add(request.NewErrParamRequired("Attributes"))
}
if s.QueueUrl == nil {
invalidParams.Add(request.NewErrParamRequired("QueueUrl"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetAttributes sets the Attributes field's value.
func (s *SetQueueAttributesInput) SetAttributes(v map[string]*string) *SetQueueAttributesInput {
s.Attributes = v
return s
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *SetQueueAttributesInput) SetQueueUrl(v string) *SetQueueAttributesInput {
s.QueueUrl = &v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/SetQueueAttributesOutput
type SetQueueAttributesOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s SetQueueAttributesOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s SetQueueAttributesOutput) GoString() string {
return s.String()
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/TagQueueRequest
type TagQueueInput struct {
_ struct{} `type:"structure"`
// The URL of the queue.
//
// QueueUrl is a required field
QueueUrl *string `type:"string" required:"true"`
// The list of tags to be added to the specified queue.
//
// Tags is a required field
Tags map[string]*string `locationName:"Tag" locationNameKey:"Key" locationNameValue:"Value" type:"map" flattened:"true" required:"true"`
}
// String returns the string representation
func (s TagQueueInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s TagQueueInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *TagQueueInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "TagQueueInput"}
if s.QueueUrl == nil {
invalidParams.Add(request.NewErrParamRequired("QueueUrl"))
}
if s.Tags == nil {
invalidParams.Add(request.NewErrParamRequired("Tags"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *TagQueueInput) SetQueueUrl(v string) *TagQueueInput {
s.QueueUrl = &v
return s
}
// SetTags sets the Tags field's value.
func (s *TagQueueInput) SetTags(v map[string]*string) *TagQueueInput {
s.Tags = v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/TagQueueOutput
type TagQueueOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s TagQueueOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s TagQueueOutput) GoString() string {
return s.String()
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/UntagQueueRequest
type UntagQueueInput struct {
_ struct{} `type:"structure"`
// The URL of the queue.
//
// QueueUrl is a required field
QueueUrl *string `type:"string" required:"true"`
// The list of tags to be removed from the specified queue.
//
// TagKeys is a required field
TagKeys []*string `locationNameList:"TagKey" type:"list" flattened:"true" required:"true"`
}
// String returns the string representation
func (s UntagQueueInput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s UntagQueueInput) GoString() string {
return s.String()
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *UntagQueueInput) Validate() error {
invalidParams := request.ErrInvalidParams{Context: "UntagQueueInput"}
if s.QueueUrl == nil {
invalidParams.Add(request.NewErrParamRequired("QueueUrl"))
}
if s.TagKeys == nil {
invalidParams.Add(request.NewErrParamRequired("TagKeys"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// SetQueueUrl sets the QueueUrl field's value.
func (s *UntagQueueInput) SetQueueUrl(v string) *UntagQueueInput {
s.QueueUrl = &v
return s
}
// SetTagKeys sets the TagKeys field's value.
func (s *UntagQueueInput) SetTagKeys(v []*string) *UntagQueueInput {
s.TagKeys = v
return s
}
// See also, https://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/UntagQueueOutput
type UntagQueueOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s UntagQueueOutput) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s UntagQueueOutput) GoString() string {
return s.String()
}
const (
// MessageSystemAttributeNameSenderId is a MessageSystemAttributeName enum value
MessageSystemAttributeNameSenderId = "SenderId"
// MessageSystemAttributeNameSentTimestamp is a MessageSystemAttributeName enum value
MessageSystemAttributeNameSentTimestamp = "SentTimestamp"
// MessageSystemAttributeNameApproximateReceiveCount is a MessageSystemAttributeName enum value
MessageSystemAttributeNameApproximateReceiveCount = "ApproximateReceiveCount"
// MessageSystemAttributeNameApproximateFirstReceiveTimestamp is a MessageSystemAttributeName enum value
MessageSystemAttributeNameApproximateFirstReceiveTimestamp = "ApproximateFirstReceiveTimestamp"
// MessageSystemAttributeNameSequenceNumber is a MessageSystemAttributeName enum value
MessageSystemAttributeNameSequenceNumber = "SequenceNumber"
// MessageSystemAttributeNameMessageDeduplicationId is a MessageSystemAttributeName enum value
MessageSystemAttributeNameMessageDeduplicationId = "MessageDeduplicationId"
// MessageSystemAttributeNameMessageGroupId is a MessageSystemAttributeName enum value
MessageSystemAttributeNameMessageGroupId = "MessageGroupId"
)
const (
// QueueAttributeNameAll is a QueueAttributeName enum value
QueueAttributeNameAll = "All"
// QueueAttributeNamePolicy is a QueueAttributeName enum value
QueueAttributeNamePolicy = "Policy"
// QueueAttributeNameVisibilityTimeout is a QueueAttributeName enum value
QueueAttributeNameVisibilityTimeout = "VisibilityTimeout"
// QueueAttributeNameMaximumMessageSize is a QueueAttributeName enum value
QueueAttributeNameMaximumMessageSize = "MaximumMessageSize"
// QueueAttributeNameMessageRetentionPeriod is a QueueAttributeName enum value
QueueAttributeNameMessageRetentionPeriod = "MessageRetentionPeriod"
// QueueAttributeNameApproximateNumberOfMessages is a QueueAttributeName enum value
QueueAttributeNameApproximateNumberOfMessages = "ApproximateNumberOfMessages"
// QueueAttributeNameApproximateNumberOfMessagesNotVisible is a QueueAttributeName enum value
QueueAttributeNameApproximateNumberOfMessagesNotVisible = "ApproximateNumberOfMessagesNotVisible"
// QueueAttributeNameCreatedTimestamp is a QueueAttributeName enum value
QueueAttributeNameCreatedTimestamp = "CreatedTimestamp"
// QueueAttributeNameLastModifiedTimestamp is a QueueAttributeName enum value
QueueAttributeNameLastModifiedTimestamp = "LastModifiedTimestamp"
// QueueAttributeNameQueueArn is a QueueAttributeName enum value
QueueAttributeNameQueueArn = "QueueArn"
// QueueAttributeNameApproximateNumberOfMessagesDelayed is a QueueAttributeName enum value
QueueAttributeNameApproximateNumberOfMessagesDelayed = "ApproximateNumberOfMessagesDelayed"
// QueueAttributeNameDelaySeconds is a QueueAttributeName enum value
QueueAttributeNameDelaySeconds = "DelaySeconds"
// QueueAttributeNameReceiveMessageWaitTimeSeconds is a QueueAttributeName enum value
QueueAttributeNameReceiveMessageWaitTimeSeconds = "ReceiveMessageWaitTimeSeconds"
// QueueAttributeNameRedrivePolicy is a QueueAttributeName enum value
QueueAttributeNameRedrivePolicy = "RedrivePolicy"
// QueueAttributeNameFifoQueue is a QueueAttributeName enum value
QueueAttributeNameFifoQueue = "FifoQueue"
// QueueAttributeNameContentBasedDeduplication is a QueueAttributeName enum value
QueueAttributeNameContentBasedDeduplication = "ContentBasedDeduplication"
// QueueAttributeNameKmsMasterKeyId is a QueueAttributeName enum value
QueueAttributeNameKmsMasterKeyId = "KmsMasterKeyId"
// QueueAttributeNameKmsDataKeyReusePeriodSeconds is a QueueAttributeName enum value
QueueAttributeNameKmsDataKeyReusePeriodSeconds = "KmsDataKeyReusePeriodSeconds"
)
| xiaozhu36/terraform-provider | vendor/github.com/hashicorp/terraform/vendor/github.com/aws/aws-sdk-go/service/sqs/api.go | GO | apache-2.0 | 191,506 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.plugin.raptor.legacy.storage.organization;
import io.prestosql.plugin.raptor.legacy.metadata.ForMetadata;
import io.prestosql.plugin.raptor.legacy.metadata.MetadataDao;
import io.prestosql.plugin.raptor.legacy.metadata.ShardManager;
import org.skife.jdbi.v2.IDBI;
import javax.inject.Inject;
import static io.prestosql.plugin.raptor.legacy.util.DatabaseUtil.onDemandDao;
import static java.util.Objects.requireNonNull;
public class OrganizationJobFactory
implements JobFactory
{
private final MetadataDao metadataDao;
private final ShardManager shardManager;
private final ShardCompactor compactor;
@Inject
public OrganizationJobFactory(@ForMetadata IDBI dbi, ShardManager shardManager, ShardCompactor compactor)
{
requireNonNull(dbi, "dbi is null");
this.metadataDao = onDemandDao(dbi, MetadataDao.class);
this.shardManager = requireNonNull(shardManager, "shardManager is null");
this.compactor = requireNonNull(compactor, "compactor is null");
}
@Override
public Runnable create(OrganizationSet organizationSet)
{
return new OrganizationJob(organizationSet, metadataDao, shardManager, compactor);
}
}
| miniway/presto | presto-raptor-legacy/src/main/java/io/prestosql/plugin/raptor/legacy/storage/organization/OrganizationJobFactory.java | Java | apache-2.0 | 1,784 |
/*
* Copyright 2012-2017 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.boot.devtools.restart;
import java.net.URL;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Default {@link RestartInitializer} that only enable initial restart when running a
* standard "main" method. Skips initialization when running "fat" jars (included
* exploded) or when running from a test.
*
* @author Phillip Webb
* @author Andy Wilkinson
* @since 1.3.0
*/
public class DefaultRestartInitializer implements RestartInitializer {
private static final Set<String> SKIPPED_STACK_ELEMENTS;
static {
Set<String> skipped = new LinkedHashSet<>();
skipped.add("org.junit.runners.");
skipped.add("org.springframework.boot.test.");
skipped.add("cucumber.runtime.");
SKIPPED_STACK_ELEMENTS = Collections.unmodifiableSet(skipped);
}
@Override
public URL[] getInitialUrls(Thread thread) {
if (!isMain(thread)) {
return null;
}
for (StackTraceElement element : thread.getStackTrace()) {
if (isSkippedStackElement(element)) {
return null;
}
}
return getUrls(thread);
}
/**
* Returns if the thread is for a main invocation. By default checks the name of the
* thread and the context classloader.
* @param thread the thread to check
* @return {@code true} if the thread is a main invocation
*/
protected boolean isMain(Thread thread) {
return thread.getName().equals("main") && thread.getContextClassLoader()
.getClass().getName().contains("AppClassLoader");
}
/**
* Checks if a specific {@link StackTraceElement} should cause the initializer to be
* skipped.
* @param element the stack element to check
* @return {@code true} if the stack element means that the initializer should be
* skipped
*/
protected boolean isSkippedStackElement(StackTraceElement element) {
for (String skipped : SKIPPED_STACK_ELEMENTS) {
if (element.getClassName().startsWith(skipped)) {
return true;
}
}
return false;
}
/**
* Return the URLs that should be used with initialization.
* @param thread the source thread
* @return the URLs
*/
protected URL[] getUrls(Thread thread) {
return ChangeableUrls.fromClassLoader(thread.getContextClassLoader()).toArray();
}
}
| bclozel/spring-boot | spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/DefaultRestartInitializer.java | Java | apache-2.0 | 2,844 |
package network
// Copyright (c) Microsoft and contributors. 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// RouteFilterRulesClient is the network Client
type RouteFilterRulesClient struct {
BaseClient
}
// NewRouteFilterRulesClient creates an instance of the RouteFilterRulesClient client.
func NewRouteFilterRulesClient(subscriptionID string) RouteFilterRulesClient {
return NewRouteFilterRulesClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewRouteFilterRulesClientWithBaseURI creates an instance of the RouteFilterRulesClient client.
func NewRouteFilterRulesClientWithBaseURI(baseURI string, subscriptionID string) RouteFilterRulesClient {
return RouteFilterRulesClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CreateOrUpdate creates or updates a route in the specified route filter.
// Parameters:
// resourceGroupName - the name of the resource group.
// routeFilterName - the name of the route filter.
// ruleName - the name of the route filter rule.
// routeFilterRuleParameters - parameters supplied to the create or update route filter rule operation.
func (client RouteFilterRulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, routeFilterRuleParameters RouteFilterRule) (result RouteFilterRulesCreateOrUpdateFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRulesClient.CreateOrUpdate")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: routeFilterRuleParameters,
Constraints: []validation.Constraint{{Target: "routeFilterRuleParameters.RouteFilterRulePropertiesFormat", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "routeFilterRuleParameters.RouteFilterRulePropertiesFormat.RouteFilterRuleType", Name: validation.Null, Rule: true, Chain: nil},
{Target: "routeFilterRuleParameters.RouteFilterRulePropertiesFormat.Communities", Name: validation.Null, Rule: true, Chain: nil},
}}}}}); err != nil {
return result, validation.NewError("network.RouteFilterRulesClient", "CreateOrUpdate", err.Error())
}
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
result, err = client.CreateOrUpdateSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "CreateOrUpdate", result.Response(), "Failure sending request")
return
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client RouteFilterRulesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, routeFilterRuleParameters RouteFilterRule) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"routeFilterName": autorest.Encode("path", routeFilterName),
"ruleName": autorest.Encode("path", ruleName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-11-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
routeFilterRuleParameters.Etag = nil
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}", pathParameters),
autorest.WithJSON(routeFilterRuleParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client RouteFilterRulesClient) CreateOrUpdateSender(req *http.Request) (future RouteFilterRulesCreateOrUpdateFuture, err error) {
sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client))
var resp *http.Response
resp, err = autorest.SendWithSender(client, req, sd...)
if err != nil {
return
}
future.Future, err = azure.NewFutureFromResponse(resp)
return
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client RouteFilterRulesClient) CreateOrUpdateResponder(resp *http.Response) (result RouteFilterRule, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes the specified rule from a route filter.
// Parameters:
// resourceGroupName - the name of the resource group.
// routeFilterName - the name of the route filter.
// ruleName - the name of the rule.
func (client RouteFilterRulesClient) Delete(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string) (result RouteFilterRulesDeleteFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRulesClient.Delete")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.DeletePreparer(ctx, resourceGroupName, routeFilterName, ruleName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Delete", nil, "Failure preparing request")
return
}
result, err = client.DeleteSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Delete", result.Response(), "Failure sending request")
return
}
return
}
// DeletePreparer prepares the Delete request.
func (client RouteFilterRulesClient) DeletePreparer(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"routeFilterName": autorest.Encode("path", routeFilterName),
"ruleName": autorest.Encode("path", ruleName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-11-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client RouteFilterRulesClient) DeleteSender(req *http.Request) (future RouteFilterRulesDeleteFuture, err error) {
sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client))
var resp *http.Response
resp, err = autorest.SendWithSender(client, req, sd...)
if err != nil {
return
}
future.Future, err = azure.NewFutureFromResponse(resp)
return
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client RouteFilterRulesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get gets the specified rule from a route filter.
// Parameters:
// resourceGroupName - the name of the resource group.
// routeFilterName - the name of the route filter.
// ruleName - the name of the rule.
func (client RouteFilterRulesClient) Get(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string) (result RouteFilterRule, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRulesClient.Get")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.GetPreparer(ctx, resourceGroupName, routeFilterName, ruleName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client RouteFilterRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"routeFilterName": autorest.Encode("path", routeFilterName),
"ruleName": autorest.Encode("path", ruleName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-11-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client RouteFilterRulesClient) GetSender(req *http.Request) (*http.Response, error) {
sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client))
return autorest.SendWithSender(client, req, sd...)
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client RouteFilterRulesClient) GetResponder(resp *http.Response) (result RouteFilterRule, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListByRouteFilter gets all RouteFilterRules in a route filter.
// Parameters:
// resourceGroupName - the name of the resource group.
// routeFilterName - the name of the route filter.
func (client RouteFilterRulesClient) ListByRouteFilter(ctx context.Context, resourceGroupName string, routeFilterName string) (result RouteFilterRuleListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRulesClient.ListByRouteFilter")
defer func() {
sc := -1
if result.rfrlr.Response.Response != nil {
sc = result.rfrlr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.fn = client.listByRouteFilterNextResults
req, err := client.ListByRouteFilterPreparer(ctx, resourceGroupName, routeFilterName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "ListByRouteFilter", nil, "Failure preparing request")
return
}
resp, err := client.ListByRouteFilterSender(req)
if err != nil {
result.rfrlr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "ListByRouteFilter", resp, "Failure sending request")
return
}
result.rfrlr, err = client.ListByRouteFilterResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "ListByRouteFilter", resp, "Failure responding to request")
}
return
}
// ListByRouteFilterPreparer prepares the ListByRouteFilter request.
func (client RouteFilterRulesClient) ListByRouteFilterPreparer(ctx context.Context, resourceGroupName string, routeFilterName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"routeFilterName": autorest.Encode("path", routeFilterName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-11-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByRouteFilterSender sends the ListByRouteFilter request. The method will close the
// http.Response Body if it receives an error.
func (client RouteFilterRulesClient) ListByRouteFilterSender(req *http.Request) (*http.Response, error) {
sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client))
return autorest.SendWithSender(client, req, sd...)
}
// ListByRouteFilterResponder handles the response to the ListByRouteFilter request. The method always
// closes the http.Response Body.
func (client RouteFilterRulesClient) ListByRouteFilterResponder(resp *http.Response) (result RouteFilterRuleListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByRouteFilterNextResults retrieves the next set of results, if any.
func (client RouteFilterRulesClient) listByRouteFilterNextResults(ctx context.Context, lastResults RouteFilterRuleListResult) (result RouteFilterRuleListResult, err error) {
req, err := lastResults.routeFilterRuleListResultPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "listByRouteFilterNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByRouteFilterSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "listByRouteFilterNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByRouteFilterResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "listByRouteFilterNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByRouteFilterComplete enumerates all values, automatically crossing page boundaries as required.
func (client RouteFilterRulesClient) ListByRouteFilterComplete(ctx context.Context, resourceGroupName string, routeFilterName string) (result RouteFilterRuleListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRulesClient.ListByRouteFilter")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.ListByRouteFilter(ctx, resourceGroupName, routeFilterName)
return
}
// Update updates a route in the specified route filter.
// Parameters:
// resourceGroupName - the name of the resource group.
// routeFilterName - the name of the route filter.
// ruleName - the name of the route filter rule.
// routeFilterRuleParameters - parameters supplied to the update route filter rule operation.
func (client RouteFilterRulesClient) Update(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, routeFilterRuleParameters PatchRouteFilterRule) (result RouteFilterRulesUpdateFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRulesClient.Update")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.UpdatePreparer(ctx, resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Update", nil, "Failure preparing request")
return
}
result, err = client.UpdateSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Update", result.Response(), "Failure sending request")
return
}
return
}
// UpdatePreparer prepares the Update request.
func (client RouteFilterRulesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, routeFilterRuleParameters PatchRouteFilterRule) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"routeFilterName": autorest.Encode("path", routeFilterName),
"ruleName": autorest.Encode("path", ruleName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-11-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
routeFilterRuleParameters.Name = nil
routeFilterRuleParameters.Etag = nil
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPatch(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}", pathParameters),
autorest.WithJSON(routeFilterRuleParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client RouteFilterRulesClient) UpdateSender(req *http.Request) (future RouteFilterRulesUpdateFuture, err error) {
sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client))
var resp *http.Response
resp, err = autorest.SendWithSender(client, req, sd...)
if err != nil {
return
}
future.Future, err = azure.NewFutureFromResponse(resp)
return
}
// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client RouteFilterRulesClient) UpdateResponder(resp *http.Response) (result RouteFilterRule, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
| Miciah/origin | vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2017-11-01/network/routefilterrules.go | GO | apache-2.0 | 20,757 |
/*
* Copyright 2000-2013 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 org.jetbrains.jps.appengine.model.impl;
import com.intellij.util.xmlb.annotations.AbstractCollection;
import com.intellij.util.xmlb.annotations.Tag;
import org.jetbrains.jps.appengine.model.PersistenceApi;
import java.util.ArrayList;
import java.util.List;
/**
* @author nik
*/
public class AppEngineModuleExtensionProperties {
@Tag("sdk-home-path")
public String mySdkHomePath = "";
@Tag("run-enhancer-on-make")
public boolean myRunEnhancerOnMake = false;
@Tag("files-to-enhance")
@AbstractCollection(surroundWithTag = false, elementTag = "file", elementValueAttribute = "path")
public List<String> myFilesToEnhance = new ArrayList<>();
@Tag("persistence-api")
public PersistenceApi myPersistenceApi = PersistenceApi.JDO;
}
| asedunov/intellij-community | plugins/google-app-engine/jps-plugin/src/org/jetbrains/jps/appengine/model/impl/AppEngineModuleExtensionProperties.java | Java | apache-2.0 | 1,360 |
define(
//begin v1.x content
{
"months-format-narrow": [
"E",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
"field-weekday": "día de la semana",
"dateFormatItem-yyQQQQ": "QQQQ 'de' yy",
"dateFormatItem-yQQQ": "QQQ y",
"dateFormatItem-yMEd": "EEE d/M/y",
"dateFormatItem-MMMEd": "E d MMM",
"eraNarrow": [
"a.C.",
"d.C."
],
"dateFormatItem-MMMdd": "dd-MMM",
"dateFormat-long": "d 'de' MMMM 'de' y",
"months-format-wide": [
"enero",
"febrero",
"marzo",
"abril",
"mayo",
"junio",
"julio",
"agosto",
"septiembre",
"octubre",
"noviembre",
"diciembre"
],
"dateFormatItem-EEEd": "EEE d",
"dayPeriods-format-wide-pm": "p.m.",
"dateFormat-full": "EEEE d 'de' MMMM 'de' y",
"dateFormatItem-Md": "d/M",
"field-era": "era",
"dateFormatItem-yM": "M/y",
"months-standAlone-wide": [
"enero",
"febrero",
"marzo",
"abril",
"mayo",
"junio",
"julio",
"agosto",
"septiembre",
"octubre",
"noviembre",
"diciembre"
],
"timeFormat-short": "HH:mm",
"quarters-format-wide": [
"1er trimestre",
"2º trimestre",
"3er trimestre",
"4º trimestre"
],
"timeFormat-long": "HH:mm:ss z",
"field-year": "año",
"dateFormatItem-yMMM": "MMM y",
"dateFormatItem-yQ": "Q y",
"field-hour": "hora",
"months-format-abbr": [
"ene",
"feb",
"mar",
"abr",
"may",
"jun",
"jul",
"ago",
"sep",
"oct",
"nov",
"dic"
],
"dateFormatItem-yyQ": "Q yy",
"timeFormat-full": "HH:mm:ss zzzz",
"field-day-relative+0": "hoy",
"field-day-relative+1": "mañana",
"field-day-relative+2": "pasado mañana",
"field-day-relative+3": "Dentro de tres días",
"months-standAlone-abbr": [
"ene",
"feb",
"mar",
"abr",
"may",
"jun",
"jul",
"ago",
"sep",
"oct",
"nov",
"dic"
],
"quarters-format-abbr": [
"T1",
"T2",
"T3",
"T4"
],
"quarters-standAlone-wide": [
"1er trimestre",
"2º trimestre",
"3er trimestre",
"4º trimestre"
],
"dateFormatItem-M": "L",
"days-standAlone-wide": [
"domingo",
"lunes",
"martes",
"miércoles",
"jueves",
"viernes",
"sábado"
],
"dateFormatItem-MMMMd": "d 'de' MMMM",
"dateFormatItem-yyMMM": "MMM-yy",
"timeFormat-medium": "HH:mm:ss",
"dateFormatItem-Hm": "HH:mm",
"quarters-standAlone-abbr": [
"T1",
"T2",
"T3",
"T4"
],
"eraAbbr": [
"a.C.",
"d.C."
],
"field-minute": "minuto",
"field-dayperiod": "periodo del día",
"days-standAlone-abbr": [
"dom",
"lun",
"mar",
"mié",
"jue",
"vie",
"sáb"
],
"dateFormatItem-d": "d",
"dateFormatItem-ms": "mm:ss",
"field-day-relative+-1": "ayer",
"dateFormatItem-h": "hh a",
"field-day-relative+-2": "antes de ayer",
"field-day-relative+-3": "Hace tres días",
"dateFormatItem-MMMd": "d MMM",
"dateFormatItem-MEd": "E, d/M",
"dateFormatItem-yMMMM": "MMMM 'de' y",
"field-day": "día",
"days-format-wide": [
"domingo",
"lunes",
"martes",
"miércoles",
"jueves",
"viernes",
"sábado"
],
"field-zone": "zona",
"dateFormatItem-yyyyMM": "MM/yyyy",
"dateFormatItem-y": "y",
"months-standAlone-narrow": [
"E",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
"dateFormatItem-yyMM": "MM/yy",
"dateFormatItem-hm": "hh:mm a",
"days-format-abbr": [
"dom",
"lun",
"mar",
"mié",
"jue",
"vie",
"sáb"
],
"eraNames": [
"antes de Cristo",
"anno Dómini"
],
"days-format-narrow": [
"D",
"L",
"M",
"M",
"J",
"V",
"S"
],
"field-month": "mes",
"days-standAlone-narrow": [
"D",
"L",
"M",
"M",
"J",
"V",
"S"
],
"dateFormatItem-MMM": "LLL",
"dayPeriods-format-wide-am": "a.m.",
"dateFormat-short": "dd/MM/yy",
"dateFormatItem-MMd": "d/MM",
"field-second": "segundo",
"dateFormatItem-yMMMEd": "EEE, d MMM y",
"field-week": "semana",
"dateFormat-medium": "dd/MM/yyyy",
"dateFormatItem-Hms": "HH:mm:ss",
"dateFormatItem-hms": "hh:mm:ss a"
}
//end v1.x content
); | sulistionoadi/belajar-springmvc-dojo | training-web/src/main/webapp/js/dojotoolkit/dojo/cldr/nls/es/gregorian.js | JavaScript | apache-2.0 | 3,916 |
/*
Copyright 2016 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 images
import (
"fmt"
"runtime"
kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util"
)
const (
KubeEtcdImage = "etcd"
KubeAPIServerImage = "apiserver"
KubeControllerManagerImage = "controller-manager"
KubeSchedulerImage = "scheduler"
etcdVersion = "3.0.17"
)
func GetCoreImage(image string, cfg *kubeadmapi.MasterConfiguration, overrideImage string) string {
if overrideImage != "" {
return overrideImage
}
repoPrefix := cfg.ImageRepository
kubernetesImageTag := kubeadmutil.KubernetesVersionToImageTag(cfg.KubernetesVersion)
return map[string]string{
KubeEtcdImage: fmt.Sprintf("%s/%s-%s:%s", repoPrefix, "etcd", runtime.GOARCH, etcdVersion),
KubeAPIServerImage: fmt.Sprintf("%s/%s-%s:%s", repoPrefix, "kube-apiserver", runtime.GOARCH, kubernetesImageTag),
KubeControllerManagerImage: fmt.Sprintf("%s/%s-%s:%s", repoPrefix, "kube-controller-manager", runtime.GOARCH, kubernetesImageTag),
KubeSchedulerImage: fmt.Sprintf("%s/%s-%s:%s", repoPrefix, "kube-scheduler", runtime.GOARCH, kubernetesImageTag),
}[image]
}
| yaxinlx/apiserver-builder | cmd/vendor/k8s.io/kubernetes/cmd/kubeadm/app/images/images.go | GO | apache-2.0 | 1,741 |
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.javascript;
import java.io.Serializable;
import org.mozilla.javascript.xml.XMLLib;
import static org.mozilla.javascript.ScriptableObject.DONTENUM;
import static org.mozilla.javascript.ScriptableObject.READONLY;
import static org.mozilla.javascript.ScriptableObject.PERMANENT;
/**
* This class implements the global native object (function and value
* properties only).
*
* See ECMA 15.1.[12].
*
*/
public class NativeGlobal implements Serializable, IdFunctionCall
{
static final long serialVersionUID = 6080442165748707530L;
public static void init(Context cx, Scriptable scope, boolean sealed) {
NativeGlobal obj = new NativeGlobal();
for (int id = 1; id <= LAST_SCOPE_FUNCTION_ID; ++id) {
String name;
int arity = 1;
switch (id) {
case Id_decodeURI:
name = "decodeURI";
break;
case Id_decodeURIComponent:
name = "decodeURIComponent";
break;
case Id_encodeURI:
name = "encodeURI";
break;
case Id_encodeURIComponent:
name = "encodeURIComponent";
break;
case Id_escape:
name = "escape";
break;
case Id_eval:
name = "eval";
break;
case Id_isFinite:
name = "isFinite";
break;
case Id_isNaN:
name = "isNaN";
break;
case Id_isXMLName:
name = "isXMLName";
break;
case Id_parseFloat:
name = "parseFloat";
break;
case Id_parseInt:
name = "parseInt";
arity = 2;
break;
case Id_unescape:
name = "unescape";
break;
case Id_uneval:
name = "uneval";
break;
default:
throw Kit.codeBug();
}
IdFunctionObject f = new IdFunctionObject(obj, FTAG, id, name,
arity, scope);
if (sealed) {
f.sealObject();
}
f.exportAsScopeProperty();
}
ScriptableObject.defineProperty(
scope, "NaN", ScriptRuntime.NaNobj,
READONLY|DONTENUM|PERMANENT);
ScriptableObject.defineProperty(
scope, "Infinity",
ScriptRuntime.wrapNumber(Double.POSITIVE_INFINITY),
READONLY|DONTENUM|PERMANENT);
ScriptableObject.defineProperty(
scope, "undefined", Undefined.instance,
READONLY|DONTENUM|PERMANENT);
String[] errorMethods = {
"ConversionError",
"EvalError",
"RangeError",
"ReferenceError",
"SyntaxError",
"TypeError",
"URIError",
"InternalError",
"JavaException"
};
/*
Each error constructor gets its own Error object as a prototype,
with the 'name' property set to the name of the error.
*/
for (int i = 0; i < errorMethods.length; i++) {
String name = errorMethods[i];
ScriptableObject errorProto =
(ScriptableObject) ScriptRuntime.newObject(cx, scope, "Error",
ScriptRuntime.emptyArgs);
errorProto.put("name", errorProto, name);
errorProto.put("message", errorProto, "");
IdFunctionObject ctor = new IdFunctionObject(obj, FTAG,
Id_new_CommonError,
name, 1, scope);
ctor.markAsConstructor(errorProto);
errorProto.put("constructor", errorProto, ctor);
errorProto.setAttributes("constructor", ScriptableObject.DONTENUM);
if (sealed) {
errorProto.sealObject();
ctor.sealObject();
}
ctor.exportAsScopeProperty();
}
}
public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
if (f.hasTag(FTAG)) {
int methodId = f.methodId();
switch (methodId) {
case Id_decodeURI:
case Id_decodeURIComponent: {
String str = ScriptRuntime.toString(args, 0);
return decode(str, methodId == Id_decodeURI);
}
case Id_encodeURI:
case Id_encodeURIComponent: {
String str = ScriptRuntime.toString(args, 0);
return encode(str, methodId == Id_encodeURI);
}
case Id_escape:
return js_escape(args);
case Id_eval:
return js_eval(cx, scope, args);
case Id_isFinite: {
boolean result;
if (args.length < 1) {
result = false;
} else {
double d = ScriptRuntime.toNumber(args[0]);
result = (d == d
&& d != Double.POSITIVE_INFINITY
&& d != Double.NEGATIVE_INFINITY);
}
return ScriptRuntime.wrapBoolean(result);
}
case Id_isNaN: {
// The global method isNaN, as per ECMA-262 15.1.2.6.
boolean result;
if (args.length < 1) {
result = true;
} else {
double d = ScriptRuntime.toNumber(args[0]);
result = (d != d);
}
return ScriptRuntime.wrapBoolean(result);
}
case Id_isXMLName: {
Object name = (args.length == 0)
? Undefined.instance : args[0];
XMLLib xmlLib = XMLLib.extractFromScope(scope);
return ScriptRuntime.wrapBoolean(
xmlLib.isXMLName(cx, name));
}
case Id_parseFloat:
return js_parseFloat(args);
case Id_parseInt:
return js_parseInt(args);
case Id_unescape:
return js_unescape(args);
case Id_uneval: {
Object value = (args.length != 0)
? args[0] : Undefined.instance;
return ScriptRuntime.uneval(cx, scope, value);
}
case Id_new_CommonError:
// The implementation of all the ECMA error constructors
// (SyntaxError, TypeError, etc.)
return NativeError.make(cx, scope, f, args);
}
}
throw f.unknown();
}
/**
* The global method parseInt, as per ECMA-262 15.1.2.2.
*/
private Object js_parseInt(Object[] args) {
String s = ScriptRuntime.toString(args, 0);
int radix = ScriptRuntime.toInt32(args, 1);
int len = s.length();
if (len == 0)
return ScriptRuntime.NaNobj;
boolean negative = false;
int start = 0;
char c;
do {
c = s.charAt(start);
if (!ScriptRuntime.isStrWhiteSpaceChar(c))
break;
start++;
} while (start < len);
if (c == '+' || (negative = (c == '-')))
start++;
final int NO_RADIX = -1;
if (radix == 0) {
radix = NO_RADIX;
} else if (radix < 2 || radix > 36) {
return ScriptRuntime.NaNobj;
} else if (radix == 16 && len - start > 1 && s.charAt(start) == '0') {
c = s.charAt(start+1);
if (c == 'x' || c == 'X')
start += 2;
}
if (radix == NO_RADIX) {
radix = 10;
if (len - start > 1 && s.charAt(start) == '0') {
c = s.charAt(start+1);
if (c == 'x' || c == 'X') {
radix = 16;
start += 2;
} else if ('0' <= c && c <= '9') {
radix = 8;
start++;
}
}
}
double d = ScriptRuntime.stringToNumber(s, start, radix);
return ScriptRuntime.wrapNumber(negative ? -d : d);
}
/**
* The global method parseFloat, as per ECMA-262 15.1.2.3.
*
* @param args the arguments to parseFloat, ignoring args[>=1]
*/
private Object js_parseFloat(Object[] args)
{
if (args.length < 1)
return ScriptRuntime.NaNobj;
String s = ScriptRuntime.toString(args[0]);
int len = s.length();
int start = 0;
// Scan forward to skip whitespace
char c;
for (;;) {
if (start == len) {
return ScriptRuntime.NaNobj;
}
c = s.charAt(start);
if (!ScriptRuntime.isStrWhiteSpaceChar(c)) {
break;
}
++start;
}
int i = start;
if (c == '+' || c == '-') {
++i;
if (i == len) {
return ScriptRuntime.NaNobj;
}
c = s.charAt(i);
}
if (c == 'I') {
// check for "Infinity"
if (i+8 <= len && s.regionMatches(i, "Infinity", 0, 8)) {
double d;
if (s.charAt(start) == '-') {
d = Double.NEGATIVE_INFINITY;
} else {
d = Double.POSITIVE_INFINITY;
}
return ScriptRuntime.wrapNumber(d);
}
return ScriptRuntime.NaNobj;
}
// Find the end of the legal bit
int decimal = -1;
int exponent = -1;
boolean exponentValid = false;
for (; i < len; i++) {
switch (s.charAt(i)) {
case '.':
if (decimal != -1) // Only allow a single decimal point.
break;
decimal = i;
continue;
case 'e':
case 'E':
if (exponent != -1) {
break;
} else if (i == len - 1) {
break;
}
exponent = i;
continue;
case '+':
case '-':
// Only allow '+' or '-' after 'e' or 'E'
if (exponent != i-1) {
break;
} else if (i == len - 1) {
--i;
break;
}
continue;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
if (exponent != -1) {
exponentValid = true;
}
continue;
default:
break;
}
break;
}
if (exponent != -1 && !exponentValid) {
i = exponent;
}
s = s.substring(start, i);
try {
return Double.valueOf(s);
}
catch (NumberFormatException ex) {
return ScriptRuntime.NaNobj;
}
}
/**
* The global method escape, as per ECMA-262 15.1.2.4.
* Includes code for the 'mask' argument supported by the C escape
* method, which used to be part of the browser imbedding. Blame
* for the strange constant names should be directed there.
*/
private Object js_escape(Object[] args) {
final int
URL_XALPHAS = 1,
URL_XPALPHAS = 2,
URL_PATH = 4;
String s = ScriptRuntime.toString(args, 0);
int mask = URL_XALPHAS | URL_XPALPHAS | URL_PATH;
if (args.length > 1) { // the 'mask' argument. Non-ECMA.
double d = ScriptRuntime.toNumber(args[1]);
if (d != d || ((mask = (int) d) != d) ||
0 != (mask & ~(URL_XALPHAS | URL_XPALPHAS | URL_PATH)))
{
throw Context.reportRuntimeError0("msg.bad.esc.mask");
}
}
StringBuffer sb = null;
for (int k = 0, L = s.length(); k != L; ++k) {
int c = s.charAt(k);
if (mask != 0
&& ((c >= '0' && c <= '9')
|| (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
|| c == '@' || c == '*' || c == '_' || c == '-' || c == '.'
|| (0 != (mask & URL_PATH) && (c == '/' || c == '+'))))
{
if (sb != null) {
sb.append((char)c);
}
} else {
if (sb == null) {
sb = new StringBuffer(L + 3);
sb.append(s);
sb.setLength(k);
}
int hexSize;
if (c < 256) {
if (c == ' ' && mask == URL_XPALPHAS) {
sb.append('+');
continue;
}
sb.append('%');
hexSize = 2;
} else {
sb.append('%');
sb.append('u');
hexSize = 4;
}
// append hexadecimal form of c left-padded with 0
for (int shift = (hexSize - 1) * 4; shift >= 0; shift -= 4) {
int digit = 0xf & (c >> shift);
int hc = (digit < 10) ? '0' + digit : 'A' - 10 + digit;
sb.append((char)hc);
}
}
}
return (sb == null) ? s : sb.toString();
}
/**
* The global unescape method, as per ECMA-262 15.1.2.5.
*/
private Object js_unescape(Object[] args)
{
String s = ScriptRuntime.toString(args, 0);
int firstEscapePos = s.indexOf('%');
if (firstEscapePos >= 0) {
int L = s.length();
char[] buf = s.toCharArray();
int destination = firstEscapePos;
for (int k = firstEscapePos; k != L;) {
char c = buf[k];
++k;
if (c == '%' && k != L) {
int end, start;
if (buf[k] == 'u') {
start = k + 1;
end = k + 5;
} else {
start = k;
end = k + 2;
}
if (end <= L) {
int x = 0;
for (int i = start; i != end; ++i) {
x = Kit.xDigitToInt(buf[i], x);
}
if (x >= 0) {
c = (char)x;
k = end;
}
}
}
buf[destination] = c;
++destination;
}
s = new String(buf, 0, destination);
}
return s;
}
/**
* This is an indirect call to eval, and thus uses the global environment.
* Direct calls are executed via ScriptRuntime.callSpecial().
*/
private Object js_eval(Context cx, Scriptable scope, Object[] args)
{
Scriptable global = ScriptableObject.getTopLevelScope(scope);
return ScriptRuntime.evalSpecial(cx, global, global, args, "eval code", 1);
}
static boolean isEvalFunction(Object functionObj)
{
if (functionObj instanceof IdFunctionObject) {
IdFunctionObject function = (IdFunctionObject)functionObj;
if (function.hasTag(FTAG) && function.methodId() == Id_eval) {
return true;
}
}
return false;
}
/**
* @deprecated Use {@link ScriptRuntime#constructError(String,String)}
* instead.
*/
public static EcmaError constructError(Context cx,
String error,
String message,
Scriptable scope)
{
return ScriptRuntime.constructError(error, message);
}
/**
* @deprecated Use
* {@link ScriptRuntime#constructError(String,String,String,int,String,int)}
* instead.
*/
public static EcmaError constructError(Context cx,
String error,
String message,
Scriptable scope,
String sourceName,
int lineNumber,
int columnNumber,
String lineSource)
{
return ScriptRuntime.constructError(error, message,
sourceName, lineNumber,
lineSource, columnNumber);
}
/*
* ECMA 3, 15.1.3 URI Handling Function Properties
*
* The following are implementations of the algorithms
* given in the ECMA specification for the hidden functions
* 'Encode' and 'Decode'.
*/
private static String encode(String str, boolean fullUri) {
byte[] utf8buf = null;
StringBuffer sb = null;
for (int k = 0, length = str.length(); k != length; ++k) {
char C = str.charAt(k);
if (encodeUnescaped(C, fullUri)) {
if (sb != null) {
sb.append(C);
}
} else {
if (sb == null) {
sb = new StringBuffer(length + 3);
sb.append(str);
sb.setLength(k);
utf8buf = new byte[6];
}
if (0xDC00 <= C && C <= 0xDFFF) {
throw uriError();
}
int V;
if (C < 0xD800 || 0xDBFF < C) {
V = C;
} else {
k++;
if (k == length) {
throw uriError();
}
char C2 = str.charAt(k);
if (!(0xDC00 <= C2 && C2 <= 0xDFFF)) {
throw uriError();
}
V = ((C - 0xD800) << 10) + (C2 - 0xDC00) + 0x10000;
}
int L = oneUcs4ToUtf8Char(utf8buf, V);
for (int j = 0; j < L; j++) {
int d = 0xff & utf8buf[j];
sb.append('%');
sb.append(toHexChar(d >>> 4));
sb.append(toHexChar(d & 0xf));
}
}
}
return (sb == null) ? str : sb.toString();
}
private static char toHexChar(int i) {
if (i >> 4 != 0) Kit.codeBug();
return (char)((i < 10) ? i + '0' : i - 10 + 'A');
}
private static int unHex(char c) {
if ('A' <= c && c <= 'F') {
return c - 'A' + 10;
} else if ('a' <= c && c <= 'f') {
return c - 'a' + 10;
} else if ('0' <= c && c <= '9') {
return c - '0';
} else {
return -1;
}
}
private static int unHex(char c1, char c2) {
int i1 = unHex(c1);
int i2 = unHex(c2);
if (i1 >= 0 && i2 >= 0) {
return (i1 << 4) | i2;
}
return -1;
}
private static String decode(String str, boolean fullUri) {
char[] buf = null;
int bufTop = 0;
for (int k = 0, length = str.length(); k != length;) {
char C = str.charAt(k);
if (C != '%') {
if (buf != null) {
buf[bufTop++] = C;
}
++k;
} else {
if (buf == null) {
// decode always compress so result can not be bigger then
// str.length()
buf = new char[length];
str.getChars(0, k, buf, 0);
bufTop = k;
}
int start = k;
if (k + 3 > length)
throw uriError();
int B = unHex(str.charAt(k + 1), str.charAt(k + 2));
if (B < 0) throw uriError();
k += 3;
if ((B & 0x80) == 0) {
C = (char)B;
} else {
// Decode UTF-8 sequence into ucs4Char and encode it into
// UTF-16
int utf8Tail, ucs4Char, minUcs4Char;
if ((B & 0xC0) == 0x80) {
// First UTF-8 should be ouside 0x80..0xBF
throw uriError();
} else if ((B & 0x20) == 0) {
utf8Tail = 1; ucs4Char = B & 0x1F;
minUcs4Char = 0x80;
} else if ((B & 0x10) == 0) {
utf8Tail = 2; ucs4Char = B & 0x0F;
minUcs4Char = 0x800;
} else if ((B & 0x08) == 0) {
utf8Tail = 3; ucs4Char = B & 0x07;
minUcs4Char = 0x10000;
} else if ((B & 0x04) == 0) {
utf8Tail = 4; ucs4Char = B & 0x03;
minUcs4Char = 0x200000;
} else if ((B & 0x02) == 0) {
utf8Tail = 5; ucs4Char = B & 0x01;
minUcs4Char = 0x4000000;
} else {
// First UTF-8 can not be 0xFF or 0xFE
throw uriError();
}
if (k + 3 * utf8Tail > length)
throw uriError();
for (int j = 0; j != utf8Tail; j++) {
if (str.charAt(k) != '%')
throw uriError();
B = unHex(str.charAt(k + 1), str.charAt(k + 2));
if (B < 0 || (B & 0xC0) != 0x80)
throw uriError();
ucs4Char = (ucs4Char << 6) | (B & 0x3F);
k += 3;
}
// Check for overlongs and other should-not-present codes
if (ucs4Char < minUcs4Char
|| (ucs4Char >= 0xD800 && ucs4Char <= 0xDFFF)) {
ucs4Char = INVALID_UTF8;
} else if (ucs4Char == 0xFFFE || ucs4Char == 0xFFFF) {
ucs4Char = 0xFFFD;
}
if (ucs4Char >= 0x10000) {
ucs4Char -= 0x10000;
if (ucs4Char > 0xFFFFF) {
throw uriError();
}
char H = (char)((ucs4Char >>> 10) + 0xD800);
C = (char)((ucs4Char & 0x3FF) + 0xDC00);
buf[bufTop++] = H;
} else {
C = (char)ucs4Char;
}
}
if (fullUri && URI_DECODE_RESERVED.indexOf(C) >= 0) {
for (int x = start; x != k; x++) {
buf[bufTop++] = str.charAt(x);
}
} else {
buf[bufTop++] = C;
}
}
}
return (buf == null) ? str : new String(buf, 0, bufTop);
}
private static boolean encodeUnescaped(char c, boolean fullUri) {
if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z')
|| ('0' <= c && c <= '9')) {
return true;
}
if ("-_.!~*'()".indexOf(c) >= 0) {
return true;
}
if (fullUri) {
return URI_DECODE_RESERVED.indexOf(c) >= 0;
}
return false;
}
private static EcmaError uriError() {
return ScriptRuntime.constructError("URIError",
ScriptRuntime.getMessage0("msg.bad.uri"));
}
private static final String URI_DECODE_RESERVED = ";/?:@&=+$,#";
private static final int INVALID_UTF8 = Integer.MAX_VALUE;
/* Convert one UCS-4 char and write it into a UTF-8 buffer, which must be
* at least 6 bytes long. Return the number of UTF-8 bytes of data written.
*/
private static int oneUcs4ToUtf8Char(byte[] utf8Buffer, int ucs4Char) {
int utf8Length = 1;
//JS_ASSERT(ucs4Char <= 0x7FFFFFFF);
if ((ucs4Char & ~0x7F) == 0)
utf8Buffer[0] = (byte)ucs4Char;
else {
int i;
int a = ucs4Char >>> 11;
utf8Length = 2;
while (a != 0) {
a >>>= 5;
utf8Length++;
}
i = utf8Length;
while (--i > 0) {
utf8Buffer[i] = (byte)((ucs4Char & 0x3F) | 0x80);
ucs4Char >>>= 6;
}
utf8Buffer[0] = (byte)(0x100 - (1 << (8-utf8Length)) + ucs4Char);
}
return utf8Length;
}
private static final Object FTAG = "Global";
private static final int
Id_decodeURI = 1,
Id_decodeURIComponent = 2,
Id_encodeURI = 3,
Id_encodeURIComponent = 4,
Id_escape = 5,
Id_eval = 6,
Id_isFinite = 7,
Id_isNaN = 8,
Id_isXMLName = 9,
Id_parseFloat = 10,
Id_parseInt = 11,
Id_unescape = 12,
Id_uneval = 13,
LAST_SCOPE_FUNCTION_ID = 13,
Id_new_CommonError = 14;
}
| abdullah38rcc/closure-compiler | lib/rhino/src/org/mozilla/javascript/NativeGlobal.java | Java | apache-2.0 | 26,767 |
/**
* 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.zookeeper.operations;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <code>ZooKeeperOperation</code> is the base class for wrapping various
* ZooKeeper API instructions and callbacks into callable and composable operation
* objects.
*/
public abstract class ZooKeeperOperation<ResultType> {
protected static final Logger LOG = LoggerFactory.getLogger(ZooKeeperOperation.class);
protected static final Class<?>[] CONSTRUCTOR_ARGS = {ZooKeeper.class, String.class};
protected String node;
protected ZooKeeper connection;
protected Set<Thread> waitingThreads = new CopyOnWriteArraySet<>();
protected OperationResult<ResultType> result;
private boolean producesExchange;
private boolean cancelled;
public ZooKeeperOperation(ZooKeeper connection, String node) {
this(connection, node, true);
}
public ZooKeeperOperation(ZooKeeper connection, String node, boolean producesExchange) {
this.connection = connection;
this.node = node;
this.producesExchange = producesExchange;
}
/**
* Gets the result of this zookeeper operation, i.e. some data and the
* associated node stats
*/
public abstract OperationResult<ResultType> getResult();
public OperationResult<ResultType> get() throws InterruptedException, ExecutionException {
waitingThreads.add(Thread.currentThread());
result = getResult();
return result;
}
public OperationResult<ResultType> get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
// TODO perhaps set a timer here
return get();
}
public boolean cancel(boolean mayInterruptIfRunning) {
if (mayInterruptIfRunning) {
for (Thread waiting : waitingThreads) {
waiting.interrupt();
}
cancelled = true;
}
return mayInterruptIfRunning;
}
public boolean isCancelled() {
return cancelled;
}
public boolean isDone() {
return result != null;
}
public String getNode() {
return node;
}
public boolean shouldProduceExchange() {
return producesExchange;
}
// TODO slightly different to a clone as it uses the constructor
public ZooKeeperOperation<?> createCopy() throws Exception {
return getClass().getConstructor(CONSTRUCTOR_ARGS).newInstance(new Object[] {connection, node});
}
}
| kevinearls/camel | components/camel-zookeeper/src/main/java/org/apache/camel/component/zookeeper/operations/ZooKeeperOperation.java | Java | apache-2.0 | 3,582 |
/*
* Copyright 2019 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* 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.
*/
package io.netty.handler.codec.dns;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.util.internal.UnstableApi;
import java.net.SocketAddress;
@UnstableApi
public final class TcpDnsResponseDecoder extends LengthFieldBasedFrameDecoder {
private final DnsResponseDecoder<SocketAddress> responseDecoder;
/**
* Creates a new decoder with {@linkplain DnsRecordDecoder#DEFAULT the default record decoder}.
*/
public TcpDnsResponseDecoder() {
this(DnsRecordDecoder.DEFAULT, 64 * 1024);
}
/**
* Creates a new decoder with the specified {@code recordDecoder} and {@code maxFrameLength}
*/
public TcpDnsResponseDecoder(DnsRecordDecoder recordDecoder, int maxFrameLength) {
// Length is two octets as defined by RFC-7766
// See https://tools.ietf.org/html/rfc7766#section-8
super(maxFrameLength, 0, 2, 0, 2);
this.responseDecoder = new DnsResponseDecoder<SocketAddress>(recordDecoder) {
@Override
protected DnsResponse newResponse(SocketAddress sender, SocketAddress recipient,
int id, DnsOpCode opCode, DnsResponseCode responseCode) {
return new DefaultDnsResponse(id, opCode, responseCode);
}
};
}
@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
ByteBuf frame = (ByteBuf) super.decode(ctx, in);
if (frame == null) {
return null;
}
try {
return responseDecoder.decode(ctx.channel().remoteAddress(), ctx.channel().localAddress(), frame.slice());
} finally {
frame.release();
}
}
@Override
protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
return buffer.copy(index, length);
}
}
| doom369/netty | codec-dns/src/main/java/io/netty/handler/codec/dns/TcpDnsResponseDecoder.java | Java | apache-2.0 | 2,622 |
/*
* Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.is.migration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.is.migration.client.internal.ISMigrationServiceDataHolder;
import org.wso2.carbon.is.migration.util.Constants;
import org.wso2.carbon.is.migration.util.ResourceUtil;
import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.StringTokenizer;
public class MigrationDatabaseCreator {
private static Log log = LogFactory.getLog(MigrationDatabaseCreator.class);
private DataSource dataSource;
private DataSource umDataSource;
private Connection conn = null;
private Statement statement;
private String delimiter = ";";
public MigrationDatabaseCreator(DataSource dataSource, DataSource umDataSource) {
// super(dataSource);
this.dataSource = dataSource;
this.umDataSource = umDataSource;
}
/**
* Execute Migration Script
*
* @throws Exception
*/
public void executeIdentityMigrationScript() throws Exception {
try {
conn = dataSource.getConnection();
conn.setAutoCommit(false);
String databaseType = DatabaseCreator.getDatabaseType(this.conn);
if ("mysql".equals(databaseType)){
ResourceUtil.setMySQLDBName(conn);
}
statement = conn.createStatement();
DatabaseMetaData meta = conn.getMetaData();
String schema = null;
if ("oracle".equals(databaseType)){
schema = ISMigrationServiceDataHolder.getIdentityOracleUser();
}
ResultSet res = meta.getTables(null, schema, "IDN_AUTH_SESSION_STORE", new String[] {"TABLE"});
if (!res.next()) {
String dbscriptName = getIdentityDbScriptLocation(databaseType, Constants.VERSION_5_0_0, Constants
.VERSION_5_0_0_SP1);
executeSQLScript(dbscriptName);
}
String dbscriptName = getIdentityDbScriptLocation(databaseType, Constants.VERSION_5_0_0_SP1, Constants
.VERSION_5_1_0);
executeSQLScript(dbscriptName);
conn.commit();
if (log.isTraceEnabled()) {
log.trace("Migration script executed successfully.");
}
} catch (SQLException e) {
String msg = "Failed to execute the migration script. " + e.getMessage();
log.fatal(msg, e);
throw new Exception(msg, e);
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
log.error("Failed to close database connection.", e);
}
}
}
public void executeUmMigrationScript() throws Exception {
try {
conn = umDataSource.getConnection();
conn.setAutoCommit(false);
String databaseType = DatabaseCreator.getDatabaseType(this.conn);
if ("mysql".equals(databaseType)){
ResourceUtil.setMySQLDBName(conn);
}
statement = conn.createStatement();
String dbscriptName = getUmDbScriptLocation(databaseType, Constants.VERSION_5_0_0, Constants.VERSION_5_1_0);
executeSQLScript(dbscriptName);
conn.commit();
if (log.isTraceEnabled()) {
log.trace("Migration script executed successfully.");
}
} catch (SQLException e) {
String msg = "Failed to execute the migration script. " + e.getMessage();
log.fatal(msg, e);
throw new Exception(msg, e);
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
log.error("Failed to close database connection.", e);
}
}
}
protected String getIdentityDbScriptLocation(String databaseType, String from, String to) {
String scriptName = databaseType + ".sql";
String carbonHome = System.getProperty("carbon.home");
if (Constants.VERSION_5_0_0.equals(from) && Constants.VERSION_5_0_0_SP1.equals(to)) {
return carbonHome + File.separator + "dbscripts" + File.separator + "identity" + File.separator +
"migration-5.0.0_to_5.0.0SP1" + File.separator + scriptName;
} else if (Constants.VERSION_5_0_0_SP1.equals(from) && Constants.VERSION_5_1_0.equals(to)) {
return carbonHome + File.separator + "dbscripts" + File.separator + "identity" + File.separator +
"migration-5.0.0SP1_to_5.1.0" + File.separator + scriptName;
} else {
throw new IllegalArgumentException("Invalid migration versions provided");
}
}
protected String getUmDbScriptLocation(String databaseType, String from, String to) {
String scriptName = databaseType + ".sql";
String carbonHome = System.getProperty("carbon.home");
if (Constants.VERSION_5_0_0.equals(from) && Constants.VERSION_5_1_0.equals(to)) {
return carbonHome + File.separator + "dbscripts" + File.separator + "migration-5.0.0_to_5.1.0" + File
.separator + scriptName;
} else {
throw new IllegalArgumentException("Invalid migration versions provided");
}
}
/**
* executes content in SQL script
*
* @return StringBuffer
* @throws Exception
*/
private void executeSQLScript(String dbscriptName) throws Exception {
String databaseType = DatabaseCreator.getDatabaseType(this.conn);
boolean oracleUserChanged = true;
boolean keepFormat = false;
if ("oracle".equals(databaseType)) {
delimiter = "/";
oracleUserChanged = false;
} else if ("db2".equals(databaseType)) {
delimiter = "/";
} else if ("openedge".equals(databaseType)) {
delimiter = "/";
keepFormat = true;
}
StringBuffer sql = new StringBuffer();
BufferedReader reader = null;
try {
InputStream is = new FileInputStream(dbscriptName);
reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!keepFormat) {
if (line.startsWith("//")) {
continue;
}
if (line.startsWith("--")) {
continue;
}
StringTokenizer st = new StringTokenizer(line);
if (st.hasMoreTokens()) {
String token = st.nextToken();
if ("REM".equalsIgnoreCase(token)) {
continue;
}
}
}
//add the oracle database owner
if (!oracleUserChanged && "oracle".equals(databaseType) && line.contains("databasename :=")){
line = "databasename := '"+ISMigrationServiceDataHolder.getIdentityOracleUser()+"';";
oracleUserChanged = true;
}
sql.append(keepFormat ? "\n" : " ").append(line);
// SQL defines "--" as a comment to EOL
// and in Oracle it may contain a hint
// so we cannot just remove it, instead we must end it
if (!keepFormat && line.indexOf("--") >= 0) {
sql.append("\n");
}
if ((DatabaseCreator.checkStringBufferEndsWith(sql, delimiter))) {
executeSQL(sql.substring(0, sql.length() - delimiter.length()));
sql.replace(0, sql.length(), "");
}
}
// Catch any statements not followed by ;
if (sql.length() > 0) {
executeSQL(sql.toString());
}
} catch (Exception e) {
log.error("Error occurred while executing SQL script for migrating database", e);
throw new Exception("Error occurred while executing SQL script for migrating database", e);
} finally {
if(reader != null){
reader.close();
}
}
}
/**
* executes given sql
*
* @param sql
* @throws Exception
*/
private void executeSQL(String sql) throws Exception {
// Check and ignore empty statements
if ("".equals(sql.trim())) {
return;
}
ResultSet resultSet = null;
try {
if (log.isDebugEnabled()) {
log.debug("SQL : " + sql);
}
boolean ret;
int updateCount = 0, updateCountTotal = 0;
ret = statement.execute(sql);
updateCount = statement.getUpdateCount();
resultSet = statement.getResultSet();
do {
if (!ret && updateCount != -1) {
updateCountTotal += updateCount;
}
ret = statement.getMoreResults();
if (ret) {
updateCount = statement.getUpdateCount();
resultSet = statement.getResultSet();
}
} while (ret);
if (log.isDebugEnabled()) {
log.debug(sql + " : " + updateCountTotal + " rows affected");
}
SQLWarning warning = conn.getWarnings();
while (warning != null) {
log.debug(warning + " sql warning");
warning = warning.getNextWarning();
}
conn.clearWarnings();
} catch (SQLException e) {
if (e.getSQLState().equals("X0Y32") || e.getSQLState().equals("42710")) {
// eliminating the table already exception for the derby and DB2 database types
if (log.isDebugEnabled()) {
log.info("Table Already Exists. Hence, skipping table creation");
}
} else {
throw new Exception("Error occurred while executing : " + sql, e);
}
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
log.error("Error occurred while closing result set.", e);
}
}
}
}
}
| thariyarox/product-is | modules/migration/migration-5.0.0_to_5.1.0/wso2-is-migration-client/src/main/java/org/wso2/carbon/is/migration/MigrationDatabaseCreator.java | Java | apache-2.0 | 11,693 |
// Copyright 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/trees/layer_sorter.h"
#include <algorithm>
#include <deque>
#include <limits>
#include <vector>
#include "base/logging.h"
#include "cc/base/math_util.h"
#include "cc/layers/render_surface_impl.h"
#include "ui/gfx/transform.h"
namespace cc {
// This epsilon is used to determine if two layers are too close to each other
// to be able to tell which is in front of the other. It's a relative epsilon
// so it is robust to changes in scene scale. This value was chosen by picking
// a value near machine epsilon and then increasing it until the flickering on
// the test scene went away.
const float k_layer_epsilon = 1e-4f;
inline static float PerpProduct(gfx::Vector2dF u, gfx::Vector2dF v) {
return u.x() * v.y() - u.y() * v.x();
}
// Tests if two edges defined by their endpoints (a,b) and (c,d) intersect.
// Returns true and the point of intersection if they do and false otherwise.
static bool EdgeEdgeTest(gfx::PointF a,
gfx::PointF b,
gfx::PointF c,
gfx::PointF d,
gfx::PointF* r) {
gfx::Vector2dF u = b - a;
gfx::Vector2dF v = d - c;
gfx::Vector2dF w = a - c;
float denom = PerpProduct(u, v);
// If denom == 0 then the edges are parallel. While they could be overlapping
// we don't bother to check here as the we'll find their intersections from
// the corner to quad tests.
if (!denom)
return false;
float s = PerpProduct(v, w) / denom;
if (s < 0.f || s > 1.f)
return false;
float t = PerpProduct(u, w) / denom;
if (t < 0.f || t > 1.f)
return false;
u.Scale(s);
*r = a + u;
return true;
}
GraphNode::GraphNode(LayerImpl* layer_impl)
: layer(layer_impl),
incoming_edge_weight(0.f) {}
GraphNode::~GraphNode() {}
LayerSorter::LayerSorter()
: z_range_(0.f) {}
LayerSorter::~LayerSorter() {}
static float CheckFloatingPointNumericAccuracy(float a, float b) {
float abs_dif = std::abs(b - a);
float abs_max = std::max(std::abs(b), std::abs(a));
// Check to see if we've got a result with a reasonable amount of error.
return abs_dif / abs_max;
}
// Checks whether layer "a" draws on top of layer "b". The weight value returned
// is an indication of the maximum z-depth difference between the layers or zero
// if the layers are found to be intesecting (some features are in front and
// some are behind).
LayerSorter::ABCompareResult LayerSorter::CheckOverlap(LayerShape* a,
LayerShape* b,
float z_threshold,
float* weight) {
*weight = 0.f;
// Early out if the projected bounds don't overlap.
if (!a->projected_bounds.Intersects(b->projected_bounds))
return None;
gfx::PointF aPoints[4] = { a->projected_quad.p1(),
a->projected_quad.p2(),
a->projected_quad.p3(),
a->projected_quad.p4() };
gfx::PointF bPoints[4] = { b->projected_quad.p1(),
b->projected_quad.p2(),
b->projected_quad.p3(),
b->projected_quad.p4() };
// Make a list of points that inside both layer quad projections.
std::vector<gfx::PointF> overlap_points;
// Check all four corners of one layer against the other layer's quad.
for (int i = 0; i < 4; ++i) {
if (a->projected_quad.Contains(bPoints[i]))
overlap_points.push_back(bPoints[i]);
if (b->projected_quad.Contains(aPoints[i]))
overlap_points.push_back(aPoints[i]);
}
// Check all the edges of one layer for intersection with the other layer's
// edges.
gfx::PointF r;
for (int ea = 0; ea < 4; ++ea)
for (int eb = 0; eb < 4; ++eb)
if (EdgeEdgeTest(aPoints[ea], aPoints[(ea + 1) % 4],
bPoints[eb], bPoints[(eb + 1) % 4],
&r))
overlap_points.push_back(r);
if (overlap_points.empty())
return None;
// Check the corresponding layer depth value for all overlap points to
// determine which layer is in front.
float max_positive = 0.f;
float max_negative = 0.f;
// This flag tracks the existance of a numerically accurate seperation
// between two layers. If there is no accurate seperation, the layers
// cannot be effectively sorted.
bool accurate = false;
for (size_t o = 0; o < overlap_points.size(); o++) {
float za = a->LayerZFromProjectedPoint(overlap_points[o]);
float zb = b->LayerZFromProjectedPoint(overlap_points[o]);
// Here we attempt to avoid numeric issues with layers that are too
// close together. If we have 2-sided quads that are very close
// together then we will draw them in document order to avoid
// flickering. The correct solution is for the content maker to turn
// on back-face culling or move the quads apart (if they're not two
// sides of one object).
if (CheckFloatingPointNumericAccuracy(za, zb) > k_layer_epsilon)
accurate = true;
float diff = za - zb;
if (diff > max_positive)
max_positive = diff;
if (diff < max_negative)
max_negative = diff;
}
// If we can't tell which should come first, we use document order.
if (!accurate)
return ABeforeB;
float max_diff =
fabsf(max_positive) > fabsf(max_negative) ? max_positive : max_negative;
// If the results are inconsistent (and the z difference substantial to rule
// out numerical errors) then the layers are intersecting. We will still
// return an order based on the maximum depth difference but with an edge
// weight of zero these layers will get priority if a graph cycle is present
// and needs to be broken.
if (max_positive > z_threshold && max_negative < -z_threshold)
*weight = 0.f;
else
*weight = fabsf(max_diff);
// Maintain relative order if the layers have the same depth at all
// intersection points.
if (max_diff <= 0.f)
return ABeforeB;
return BBeforeA;
}
LayerShape::LayerShape() {}
LayerShape::LayerShape(float width,
float height,
const gfx::Transform& draw_transform) {
gfx::QuadF layer_quad(gfx::RectF(0.f, 0.f, width, height));
// Compute the projection of the layer quad onto the z = 0 plane.
gfx::PointF clipped_quad[8];
int num_vertices_in_clipped_quad;
MathUtil::MapClippedQuad(draw_transform,
layer_quad,
clipped_quad,
&num_vertices_in_clipped_quad);
if (num_vertices_in_clipped_quad < 3) {
projected_bounds = gfx::RectF();
return;
}
projected_bounds =
MathUtil::ComputeEnclosingRectOfVertices(clipped_quad,
num_vertices_in_clipped_quad);
// NOTE: it will require very significant refactoring and overhead to deal
// with generalized polygons or multiple quads per layer here. For the sake of
// layer sorting it is equally correct to take a subsection of the polygon
// that can be made into a quad. This will only be incorrect in the case of
// intersecting layers, which are not supported yet anyway.
projected_quad.set_p1(clipped_quad[0]);
projected_quad.set_p2(clipped_quad[1]);
projected_quad.set_p3(clipped_quad[2]);
if (num_vertices_in_clipped_quad >= 4) {
projected_quad.set_p4(clipped_quad[3]);
} else {
// This will be a degenerate quad that is actually a triangle.
projected_quad.set_p4(clipped_quad[2]);
}
// Compute the normal of the layer's plane.
bool clipped = false;
gfx::Point3F c1 =
MathUtil::MapPoint(draw_transform, gfx::Point3F(0.f, 0.f, 0.f), &clipped);
gfx::Point3F c2 =
MathUtil::MapPoint(draw_transform, gfx::Point3F(0.f, 1.f, 0.f), &clipped);
gfx::Point3F c3 =
MathUtil::MapPoint(draw_transform, gfx::Point3F(1.f, 0.f, 0.f), &clipped);
// FIXME: Deal with clipping.
gfx::Vector3dF c12 = c2 - c1;
gfx::Vector3dF c13 = c3 - c1;
layer_normal = gfx::CrossProduct(c13, c12);
transform_origin = c1;
}
LayerShape::~LayerShape() {}
// Returns the Z coordinate of a point on the layer that projects
// to point p which lies on the z = 0 plane. It does it by computing the
// intersection of a line starting from p along the Z axis and the plane
// of the layer.
float LayerShape::LayerZFromProjectedPoint(gfx::PointF p) const {
gfx::Vector3dF z_axis(0.f, 0.f, 1.f);
gfx::Vector3dF w = gfx::Point3F(p) - transform_origin;
float d = gfx::DotProduct(layer_normal, z_axis);
float n = -gfx::DotProduct(layer_normal, w);
// Check if layer is parallel to the z = 0 axis which will make it
// invisible and hence returning zero is fine.
if (!d)
return 0.f;
// The intersection point would be given by:
// p + (n / d) * u but since we are only interested in the
// z coordinate and p's z coord is zero, all we need is the value of n/d.
return n / d;
}
void LayerSorter::CreateGraphNodes(LayerImplList::iterator first,
LayerImplList::iterator last) {
DVLOG(2) << "Creating graph nodes:";
float min_z = FLT_MAX;
float max_z = -FLT_MAX;
for (LayerImplList::const_iterator it = first; it < last; it++) {
nodes_.push_back(GraphNode(*it));
GraphNode& node = nodes_.at(nodes_.size() - 1);
RenderSurfaceImpl* render_surface = node.layer->render_surface();
if (!node.layer->DrawsContent() && !render_surface)
continue;
DVLOG(2) << "Layer " << node.layer->id() <<
" (" << node.layer->bounds().width() <<
" x " << node.layer->bounds().height() << ")";
gfx::Transform draw_transform;
float layer_width, layer_height;
if (render_surface) {
draw_transform = render_surface->draw_transform();
layer_width = render_surface->content_rect().width();
layer_height = render_surface->content_rect().height();
} else {
draw_transform = node.layer->draw_transform();
layer_width = node.layer->content_bounds().width();
layer_height = node.layer->content_bounds().height();
}
node.shape = LayerShape(layer_width, layer_height, draw_transform);
max_z = std::max(max_z, node.shape.transform_origin.z());
min_z = std::min(min_z, node.shape.transform_origin.z());
}
z_range_ = fabsf(max_z - min_z);
}
void LayerSorter::CreateGraphEdges() {
DVLOG(2) << "Edges:";
// Fraction of the total z_range below which z differences
// are not considered reliable.
const float z_threshold_factor = 0.01f;
float z_threshold = z_range_ * z_threshold_factor;
for (size_t na = 0; na < nodes_.size(); na++) {
GraphNode& node_a = nodes_[na];
if (!node_a.layer->DrawsContent() && !node_a.layer->render_surface())
continue;
for (size_t nb = na + 1; nb < nodes_.size(); nb++) {
GraphNode& node_b = nodes_[nb];
if (!node_b.layer->DrawsContent() && !node_b.layer->render_surface())
continue;
float weight = 0.f;
ABCompareResult overlap_result = CheckOverlap(&node_a.shape,
&node_b.shape,
z_threshold,
&weight);
GraphNode* start_node = NULL;
GraphNode* end_node = NULL;
if (overlap_result == ABeforeB) {
start_node = &node_a;
end_node = &node_b;
} else if (overlap_result == BBeforeA) {
start_node = &node_b;
end_node = &node_a;
}
if (start_node) {
DVLOG(2) << start_node->layer->id() << " -> " << end_node->layer->id();
edges_.push_back(GraphEdge(start_node, end_node, weight));
}
}
}
for (size_t i = 0; i < edges_.size(); i++) {
GraphEdge& edge = edges_[i];
active_edges_[&edge] = &edge;
edge.from->outgoing.push_back(&edge);
edge.to->incoming.push_back(&edge);
edge.to->incoming_edge_weight += edge.weight;
}
}
// Finds and removes an edge from the list by doing a swap with the
// last element of the list.
void LayerSorter::RemoveEdgeFromList(GraphEdge* edge,
std::vector<GraphEdge*>* list) {
std::vector<GraphEdge*>::iterator iter =
std::find(list->begin(), list->end(), edge);
DCHECK(iter != list->end());
list->erase(iter);
}
// Sorts the given list of layers such that they can be painted in a
// back-to-front order. Sorting produces correct results for non-intersecting
// layers that don't have cyclical order dependencies. Cycles and intersections
// are broken (somewhat) aribtrarily. Sorting of layers is done via a
// topological sort of a directed graph whose nodes are the layers themselves.
// An edge from node A to node B signifies that layer A needs to be drawn before
// layer B. If A and B have no dependency between each other, then we preserve
// the ordering of those layers as they were in the original list.
//
// The draw order between two layers is determined by projecting the two
// triangles making up each layer quad to the Z = 0 plane, finding points of
// intersection between the triangles and backprojecting those points to the
// plane of the layer to determine the corresponding Z coordinate. The layer
// with the lower Z coordinate (farther from the eye) needs to be rendered
// first.
//
// If the layer projections don't intersect, then no edges (dependencies) are
// created between them in the graph. HOWEVER, in this case we still need to
// preserve the ordering of the original list of layers, since that list should
// already have proper z-index ordering of layers.
//
void LayerSorter::Sort(LayerImplList::iterator first,
LayerImplList::iterator last) {
DVLOG(2) << "Sorting start ----";
CreateGraphNodes(first, last);
CreateGraphEdges();
std::vector<GraphNode*> sorted_list;
std::deque<GraphNode*> no_incoming_edge_node_list;
// Find all the nodes that don't have incoming edges.
for (NodeList::iterator la = nodes_.begin(); la < nodes_.end(); la++) {
if (!la->incoming.size())
no_incoming_edge_node_list.push_back(&(*la));
}
DVLOG(2) << "Sorted list: ";
while (active_edges_.size() || no_incoming_edge_node_list.size()) {
while (no_incoming_edge_node_list.size()) {
// It is necessary to preserve the existing ordering of layers, when there
// are no explicit dependencies (because this existing ordering has
// correct z-index/layout ordering). To preserve this ordering, we process
// Nodes in the same order that they were added to the list.
GraphNode* from_node = no_incoming_edge_node_list.front();
no_incoming_edge_node_list.pop_front();
// Add it to the final list.
sorted_list.push_back(from_node);
DVLOG(2) << from_node->layer->id() << ", ";
// Remove all its outgoing edges from the graph.
for (size_t i = 0; i < from_node->outgoing.size(); i++) {
GraphEdge* outgoing_edge = from_node->outgoing[i];
active_edges_.erase(outgoing_edge);
RemoveEdgeFromList(outgoing_edge, &outgoing_edge->to->incoming);
outgoing_edge->to->incoming_edge_weight -= outgoing_edge->weight;
if (!outgoing_edge->to->incoming.size())
no_incoming_edge_node_list.push_back(outgoing_edge->to);
}
from_node->outgoing.clear();
}
if (!active_edges_.size())
break;
// If there are still active edges but the list of nodes without incoming
// edges is empty then we have run into a cycle. Break the cycle by finding
// the node with the smallest overall incoming edge weight and use it. This
// will favor nodes that have zero-weight incoming edges i.e. layers that
// are being occluded by a layer that intersects them.
float min_incoming_edge_weight = FLT_MAX;
GraphNode* next_node = NULL;
for (size_t i = 0; i < nodes_.size(); i++) {
if (nodes_[i].incoming.size() &&
nodes_[i].incoming_edge_weight < min_incoming_edge_weight) {
min_incoming_edge_weight = nodes_[i].incoming_edge_weight;
next_node = &nodes_[i];
}
}
DCHECK(next_node);
// Remove all its incoming edges.
for (size_t e = 0; e < next_node->incoming.size(); e++) {
GraphEdge* incoming_edge = next_node->incoming[e];
active_edges_.erase(incoming_edge);
RemoveEdgeFromList(incoming_edge, &incoming_edge->from->outgoing);
}
next_node->incoming.clear();
next_node->incoming_edge_weight = 0.f;
no_incoming_edge_node_list.push_back(next_node);
DVLOG(2) << "Breaking cycle by cleaning up incoming edges from " <<
next_node->layer->id() <<
" (weight = " << min_incoming_edge_weight << ")";
}
// Note: The original elements of the list are in no danger of having their
// ref count go to zero here as they are all nodes of the layer hierarchy and
// are kept alive by their parent nodes.
int count = 0;
for (LayerImplList::iterator it = first; it < last; it++)
*it = sorted_list[count++]->layer;
DVLOG(2) << "Sorting end ----";
nodes_.clear();
edges_.clear();
active_edges_.clear();
}
} // namespace cc
| plxaye/chromium | src/cc/trees/layer_sorter.cc | C++ | apache-2.0 | 17,413 |
/*
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 testing
import (
"context"
"fmt"
"io/ioutil"
"net"
"os"
"path"
"path/filepath"
"runtime"
"time"
"github.com/spf13/pflag"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apiserver/pkg/registry/generic/registry"
"k8s.io/apiserver/pkg/storage/storagebackend"
"k8s.io/client-go/kubernetes"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/util/cert"
"k8s.io/kubernetes/cmd/kube-apiserver/app"
"k8s.io/kubernetes/cmd/kube-apiserver/app/options"
testutil "k8s.io/kubernetes/test/utils"
)
// TearDownFunc is to be called to tear down a test server.
type TearDownFunc func()
// TestServerInstanceOptions Instance options the TestServer
type TestServerInstanceOptions struct {
// DisableStorageCleanup Disable the automatic storage cleanup
DisableStorageCleanup bool
// Enable cert-auth for the kube-apiserver
EnableCertAuth bool
}
// TestServer return values supplied by kube-test-ApiServer
type TestServer struct {
ClientConfig *restclient.Config // Rest client config
ServerOpts *options.ServerRunOptions // ServerOpts
TearDownFn TearDownFunc // TearDown function
TmpDir string // Temp Dir used, by the apiserver
}
// Logger allows t.Testing and b.Testing to be passed to StartTestServer and StartTestServerOrDie
type Logger interface {
Errorf(format string, args ...interface{})
Fatalf(format string, args ...interface{})
Logf(format string, args ...interface{})
}
// NewDefaultTestServerOptions Default options for TestServer instances
func NewDefaultTestServerOptions() *TestServerInstanceOptions {
return &TestServerInstanceOptions{
DisableStorageCleanup: false,
EnableCertAuth: true,
}
}
// StartTestServer starts a etcd server and kube-apiserver. A rest client config and a tear-down func,
// and location of the tmpdir are returned.
//
// Note: we return a tear-down func instead of a stop channel because the later will leak temporary
// files that because Golang testing's call to os.Exit will not give a stop channel go routine
// enough time to remove temporary files.
func StartTestServer(t Logger, instanceOptions *TestServerInstanceOptions, customFlags []string, storageConfig *storagebackend.Config) (result TestServer, err error) {
if instanceOptions == nil {
instanceOptions = NewDefaultTestServerOptions()
}
// TODO : Remove TrackStorageCleanup below when PR
// https://github.com/kubernetes/kubernetes/pull/50690
// merges as that shuts down storage properly
if !instanceOptions.DisableStorageCleanup {
registry.TrackStorageCleanup()
}
stopCh := make(chan struct{})
tearDown := func() {
if !instanceOptions.DisableStorageCleanup {
registry.CleanupStorage()
}
close(stopCh)
if len(result.TmpDir) != 0 {
os.RemoveAll(result.TmpDir)
}
}
defer func() {
if result.TearDownFn == nil {
tearDown()
}
}()
result.TmpDir, err = ioutil.TempDir("", "kubernetes-kube-apiserver")
if err != nil {
return result, fmt.Errorf("failed to create temp dir: %v", err)
}
fs := pflag.NewFlagSet("test", pflag.PanicOnError)
s := options.NewServerRunOptions()
for _, f := range s.Flags().FlagSets {
fs.AddFlagSet(f)
}
s.InsecureServing.BindPort = 0
s.SecureServing.Listener, s.SecureServing.BindPort, err = createLocalhostListenerOnFreePort()
if err != nil {
return result, fmt.Errorf("failed to create listener: %v", err)
}
s.SecureServing.ServerCert.CertDirectory = result.TmpDir
if instanceOptions.EnableCertAuth {
// create certificates for aggregation and client-cert auth
proxySigningKey, err := testutil.NewPrivateKey()
if err != nil {
return result, err
}
proxySigningCert, err := cert.NewSelfSignedCACert(cert.Config{CommonName: "front-proxy-ca"}, proxySigningKey)
if err != nil {
return result, err
}
proxyCACertFile := path.Join(s.SecureServing.ServerCert.CertDirectory, "proxy-ca.crt")
if err := ioutil.WriteFile(proxyCACertFile, testutil.EncodeCertPEM(proxySigningCert), 0644); err != nil {
return result, err
}
s.Authentication.RequestHeader.ClientCAFile = proxyCACertFile
clientSigningKey, err := testutil.NewPrivateKey()
if err != nil {
return result, err
}
clientSigningCert, err := cert.NewSelfSignedCACert(cert.Config{CommonName: "client-ca"}, clientSigningKey)
if err != nil {
return result, err
}
clientCACertFile := path.Join(s.SecureServing.ServerCert.CertDirectory, "client-ca.crt")
if err := ioutil.WriteFile(clientCACertFile, testutil.EncodeCertPEM(clientSigningCert), 0644); err != nil {
return result, err
}
s.Authentication.ClientCert.ClientCA = clientCACertFile
}
s.SecureServing.ExternalAddress = s.SecureServing.Listener.Addr().(*net.TCPAddr).IP // use listener addr although it is a loopback device
pkgPath, err := pkgPath(t)
if err != nil {
return result, err
}
s.SecureServing.ServerCert.FixtureDirectory = filepath.Join(pkgPath, "testdata")
s.ServiceClusterIPRanges = "10.0.0.0/16"
s.Etcd.StorageConfig = *storageConfig
s.APIEnablement.RuntimeConfig.Set("api/all=true")
if err := fs.Parse(customFlags); err != nil {
return result, err
}
completedOptions, err := app.Complete(s)
if err != nil {
return result, fmt.Errorf("failed to set default ServerRunOptions: %v", err)
}
t.Logf("runtime-config=%v", completedOptions.APIEnablement.RuntimeConfig)
t.Logf("Starting kube-apiserver on port %d...", s.SecureServing.BindPort)
server, err := app.CreateServerChain(completedOptions, stopCh)
if err != nil {
return result, fmt.Errorf("failed to create server chain: %v", err)
}
errCh := make(chan error)
go func(stopCh <-chan struct{}) {
prepared, err := server.PrepareRun()
if err != nil {
errCh <- err
} else if err := prepared.Run(stopCh); err != nil {
errCh <- err
}
}(stopCh)
t.Logf("Waiting for /healthz to be ok...")
client, err := kubernetes.NewForConfig(server.GenericAPIServer.LoopbackClientConfig)
if err != nil {
return result, fmt.Errorf("failed to create a client: %v", err)
}
// wait until healthz endpoint returns ok
err = wait.Poll(100*time.Millisecond, time.Minute, func() (bool, error) {
select {
case err := <-errCh:
return false, err
default:
}
result := client.CoreV1().RESTClient().Get().AbsPath("/healthz").Do(context.TODO())
status := 0
result.StatusCode(&status)
if status == 200 {
return true, nil
}
return false, nil
})
if err != nil {
return result, fmt.Errorf("failed to wait for /healthz to return ok: %v", err)
}
// wait until default namespace is created
err = wait.Poll(100*time.Millisecond, 30*time.Second, func() (bool, error) {
select {
case err := <-errCh:
return false, err
default:
}
if _, err := client.CoreV1().Namespaces().Get(context.TODO(), "default", metav1.GetOptions{}); err != nil {
if !errors.IsNotFound(err) {
t.Logf("Unable to get default namespace: %v", err)
}
return false, nil
}
return true, nil
})
if err != nil {
return result, fmt.Errorf("failed to wait for default namespace to be created: %v", err)
}
// from here the caller must call tearDown
result.ClientConfig = restclient.CopyConfig(server.GenericAPIServer.LoopbackClientConfig)
result.ClientConfig.QPS = 1000
result.ClientConfig.Burst = 10000
result.ServerOpts = s
result.TearDownFn = tearDown
return result, nil
}
// StartTestServerOrDie calls StartTestServer t.Fatal if it does not succeed.
func StartTestServerOrDie(t Logger, instanceOptions *TestServerInstanceOptions, flags []string, storageConfig *storagebackend.Config) *TestServer {
result, err := StartTestServer(t, instanceOptions, flags, storageConfig)
if err == nil {
return &result
}
t.Fatalf("failed to launch server: %v", err)
return nil
}
func createLocalhostListenerOnFreePort() (net.Listener, int, error) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, 0, err
}
// get port
tcpAddr, ok := ln.Addr().(*net.TCPAddr)
if !ok {
ln.Close()
return nil, 0, fmt.Errorf("invalid listen address: %q", ln.Addr().String())
}
return ln, tcpAddr.Port, nil
}
// pkgPath returns the absolute file path to this package's directory. With go
// test, we can just look at the runtime call stack. However, bazel compiles go
// binaries with the -trimpath option so the simple approach fails however we
// can consult environment variables to derive the path.
//
// The approach taken here works for both go test and bazel on the assumption
// that if and only if trimpath is passed, we are running under bazel.
func pkgPath(t Logger) (string, error) {
_, thisFile, _, ok := runtime.Caller(0)
if !ok {
return "", fmt.Errorf("failed to get current file")
}
pkgPath := filepath.Dir(thisFile)
// If we find bazel env variables, then -trimpath was passed so we need to
// construct the path from the environment.
if testSrcdir, testWorkspace := os.Getenv("TEST_SRCDIR"), os.Getenv("TEST_WORKSPACE"); testSrcdir != "" && testWorkspace != "" {
t.Logf("Detected bazel env varaiables: TEST_SRCDIR=%q TEST_WORKSPACE=%q", testSrcdir, testWorkspace)
pkgPath = filepath.Join(testSrcdir, testWorkspace, pkgPath)
}
// If the path is still not absolute, something other than bazel compiled
// with -trimpath.
if !filepath.IsAbs(pkgPath) {
return "", fmt.Errorf("can't construct an absolute path from %q", pkgPath)
}
t.Logf("Resolved testserver package path to: %q", pkgPath)
return pkgPath, nil
}
| tallclair/kubernetes | cmd/kube-apiserver/app/testing/testserver.go | GO | apache-2.0 | 10,075 |
/**
* 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.cxf.jaxrs;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.Response;
import org.apache.camel.CamelExchangeException;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.component.cxf.CxfEndpointUtils;
import org.apache.camel.component.cxf.CxfOperationException;
import org.apache.camel.component.cxf.common.message.CxfConstants;
import org.apache.camel.impl.DefaultProducer;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.LRUSoftCache;
import org.apache.camel.util.ObjectHelper;
import org.apache.cxf.Bus;
import org.apache.cxf.jaxrs.JAXRSServiceFactoryBean;
import org.apache.cxf.jaxrs.client.Client;
import org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean;
import org.apache.cxf.jaxrs.client.WebClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* CxfRsProducer binds a Camel exchange to a CXF exchange, acts as a CXF
* JAXRS client, it will turn the normal Object invocation to a RESTful request
* according to resource annotation. Any response will be bound to Camel exchange.
*/
public class CxfRsProducer extends DefaultProducer {
private static final Logger LOG = LoggerFactory.getLogger(CxfRsProducer.class);
private boolean throwException;
// using a cache of factory beans instead of setting the address of a single cfb
// to avoid concurrent issues
private ClientFactoryBeanCache clientFactoryBeanCache;
public CxfRsProducer(CxfRsEndpoint endpoint) {
super(endpoint);
this.throwException = endpoint.isThrowExceptionOnFailure();
clientFactoryBeanCache = new ClientFactoryBeanCache(endpoint.getMaxClientCacheSize());
}
protected void doStart() throws Exception {
clientFactoryBeanCache.start();
super.doStart();
}
protected void doStop() throws Exception {
super.doStop();
clientFactoryBeanCache.stop();
}
public void process(Exchange exchange) throws Exception {
Message inMessage = exchange.getIn();
Boolean httpClientAPI = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.class);
// set the value with endpoint's option
if (httpClientAPI == null) {
httpClientAPI = ((CxfRsEndpoint) getEndpoint()).isHttpClientAPI();
}
if (httpClientAPI.booleanValue()) {
invokeHttpClient(exchange);
} else {
invokeProxyClient(exchange);
}
}
@SuppressWarnings("unchecked")
protected void setupClientQueryAndHeaders(WebClient client, Exchange exchange) throws Exception {
Message inMessage = exchange.getIn();
CxfRsEndpoint cxfRsEndpoint = (CxfRsEndpoint) getEndpoint();
// check if there is a query map in the message header
Map<String, String> maps = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_QUERY_MAP, Map.class);
if (maps == null) {
// Get the map from HTTP_QUERY header
String queryString = inMessage.getHeader(Exchange.HTTP_QUERY, String.class);
if (queryString != null) {
maps = getQueryParametersFromQueryString(queryString,
IOHelper.getCharsetName(exchange));
}
}
if (maps == null) {
maps = cxfRsEndpoint.getParameters();
}
if (maps != null) {
for (Map.Entry<String, String> entry : maps.entrySet()) {
client.query(entry.getKey(), entry.getValue());
}
}
setupClientHeaders(client, exchange);
}
protected void setupClientMatrix(WebClient client, Exchange exchange) throws Exception {
org.apache.cxf.message.Message cxfMessage = (org.apache.cxf.message.Message) exchange.getIn().getHeader("CamelCxfMessage");
if (cxfMessage != null) {
String requestURL = (String)cxfMessage.get("org.apache.cxf.request.uri");
String matrixParam = null;
int matrixStart = requestURL.indexOf(";");
int matrixEnd = requestURL.indexOf("?") > -1 ? requestURL.indexOf("?") : requestURL.length();
Map<String, String> maps = null;
if (requestURL != null && matrixStart > 0) {
matrixParam = requestURL.substring(matrixStart + 1, matrixEnd);
if (matrixParam != null) {
maps = getMatrixParametersFromMatrixString(matrixParam, IOHelper.getCharsetName(exchange));
}
}
if (maps != null) {
for (Map.Entry<String, String> entry : maps.entrySet()) {
client.matrix(entry.getKey(), entry.getValue());
LOG.debug("Matrix param " + entry.getKey() + " :: " + entry.getValue());
}
}
}
}
protected void setupClientHeaders(Client client, Exchange exchange) throws Exception {
Message inMessage = exchange.getIn();
CxfRsEndpoint cxfRsEndpoint = (CxfRsEndpoint) getEndpoint();
CxfRsBinding binding = cxfRsEndpoint.getBinding();
// set headers
client.headers(binding.bindCamelHeadersToRequestHeaders(inMessage.getHeaders(), exchange));
}
protected void invokeHttpClient(Exchange exchange) throws Exception {
Message inMessage = exchange.getIn();
JAXRSClientFactoryBean cfb = clientFactoryBeanCache.get(CxfEndpointUtils
.getEffectiveAddress(exchange, ((CxfRsEndpoint)getEndpoint()).getAddress()));
Bus bus = ((CxfRsEndpoint)getEndpoint()).getBus();
// We need to apply the bus setting from the CxfRsEndpoint which is not use the default bus
if (bus != null) {
cfb.setBus(bus);
}
WebClient client = cfb.createWebClient();
((CxfRsEndpoint) getEndpoint()).getChainedCxfRsEndpointConfigurer().configureClient(client);
String httpMethod = inMessage.getHeader(Exchange.HTTP_METHOD, String.class);
Class<?> responseClass = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, Class.class);
Type genericType = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_GENERIC_TYPE, Type.class);
Object[] pathValues = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_VAR_VALUES, Object[].class);
String path = inMessage.getHeader(Exchange.HTTP_PATH, String.class);
if (LOG.isTraceEnabled()) {
LOG.trace("HTTP method = {}", httpMethod);
LOG.trace("path = {}", path);
LOG.trace("responseClass = {}", responseClass);
}
// set the path
if (path != null) {
if (ObjectHelper.isNotEmpty(pathValues) && pathValues.length > 0) {
client.path(path, pathValues);
} else {
client.path(path);
}
}
CxfRsEndpoint cxfRsEndpoint = (CxfRsEndpoint) getEndpoint();
CxfRsBinding binding = cxfRsEndpoint.getBinding();
// set the body
Object body = null;
if (!"GET".equals(httpMethod)) {
// need to check the request object if the http Method is not GET
if ("DELETE".equals(httpMethod) && cxfRsEndpoint.isIgnoreDeleteMethodMessageBody()) {
// just ignore the message body if the ignoreDeleteMethodMessageBody is true
} else {
body = binding.bindCamelMessageBodyToRequestBody(inMessage, exchange);
if (LOG.isTraceEnabled()) {
LOG.trace("Request body = " + body);
}
}
}
setupClientMatrix(client, exchange);
setupClientQueryAndHeaders(client, exchange);
// invoke the client
Object response = null;
if (responseClass == null || Response.class.equals(responseClass)) {
response = client.invoke(httpMethod, body);
} else {
if (Collection.class.isAssignableFrom(responseClass)) {
if (genericType instanceof ParameterizedType) {
// Get the collection member type first
Type[] actualTypeArguments = ((ParameterizedType) genericType).getActualTypeArguments();
response = client.invokeAndGetCollection(httpMethod, body, (Class<?>) actualTypeArguments[0]);
} else {
throw new CamelExchangeException("Header " + CxfConstants.CAMEL_CXF_RS_RESPONSE_GENERIC_TYPE + " not found in message", exchange);
}
} else {
response = client.invoke(httpMethod, body, responseClass);
}
}
int statesCode = client.getResponse().getStatus();
//Throw exception on a response > 207
//http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
if (throwException) {
if (response instanceof Response) {
Integer respCode = ((Response) response).getStatus();
if (respCode > 207) {
throw populateCxfRsProducerException(exchange, (Response) response, respCode);
}
}
}
// set response
if (exchange.getPattern().isOutCapable()) {
LOG.trace("Response body = {}", response);
exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders());
exchange.getOut().setBody(binding.bindResponseToCamelBody(response, exchange));
exchange.getOut().getHeaders().putAll(binding.bindResponseHeadersToCamelHeaders(response, exchange));
exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, statesCode);
} else {
// just close the input stream of the response object
if (response instanceof Response) {
((Response)response).close();
}
}
}
protected void invokeProxyClient(Exchange exchange) throws Exception {
Message inMessage = exchange.getIn();
Object[] varValues = inMessage.getHeader(CxfConstants.CAMEL_CXF_RS_VAR_VALUES, Object[].class);
String methodName = inMessage.getHeader(CxfConstants.OPERATION_NAME, String.class);
Client target = null;
JAXRSClientFactoryBean cfb = clientFactoryBeanCache.get(CxfEndpointUtils
.getEffectiveAddress(exchange, ((CxfRsEndpoint)getEndpoint()).getAddress()));
Bus bus = ((CxfRsEndpoint)getEndpoint()).getBus();
// We need to apply the bus setting from the CxfRsEndpoint which is not use the default bus
if (bus != null) {
cfb.setBus(bus);
}
if (varValues == null) {
target = cfb.create();
} else {
target = cfb.createWithValues(varValues);
}
setupClientHeaders(target, exchange);
// find out the method which we want to invoke
JAXRSServiceFactoryBean sfb = cfb.getServiceFactory();
sfb.getResourceClasses();
// check the null body first
Object[] parameters = null;
if (inMessage.getBody() != null) {
parameters = inMessage.getBody(Object[].class);
}
// get the method
Method method = findRightMethod(sfb.getResourceClasses(), methodName, getParameterTypes(parameters));
// Will send out the message to
// Need to deal with the sub resource class
Object response = method.invoke(target, parameters);
int statesCode = target.getResponse().getStatus();
if (throwException) {
if (response instanceof Response) {
Integer respCode = ((Response) response).getStatus();
if (respCode > 207) {
throw populateCxfRsProducerException(exchange, (Response) response, respCode);
}
}
}
CxfRsEndpoint cxfRsEndpoint = (CxfRsEndpoint) getEndpoint();
CxfRsBinding binding = cxfRsEndpoint.getBinding();
if (exchange.getPattern().isOutCapable()) {
LOG.trace("Response body = {}", response);
exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders());
exchange.getOut().setBody(binding.bindResponseToCamelBody(response, exchange));
exchange.getOut().getHeaders().putAll(binding.bindResponseHeadersToCamelHeaders(response, exchange));
exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, statesCode);
} else {
// just close the input stream of the response object
if (response instanceof Response) {
((Response)response).close();
}
}
}
protected ClientFactoryBeanCache getClientFactoryBeanCache() {
return clientFactoryBeanCache;
}
private Map<String, String> getQueryParametersFromQueryString(String queryString, String charset) throws UnsupportedEncodingException {
Map<String, String> answer = new LinkedHashMap<String, String>();
for (String param : queryString.split("&")) {
String[] pair = param.split("=", 2);
if (pair.length == 2) {
String name = URLDecoder.decode(pair[0], charset);
String value = URLDecoder.decode(pair[1], charset);
answer.put(name, value);
} else {
throw new IllegalArgumentException("Invalid parameter, expected to be a pair but was " + param);
}
}
return answer;
}
private Method findRightMethod(List<Class<?>> resourceClasses, String methodName,
Class<?>[] parameterTypes) throws NoSuchMethodException {
for (Class<?> clazz : resourceClasses) {
try {
Method[] m = clazz.getMethods();
iterate_on_methods:
for (Method method : m) {
if (!method.getName().equals(methodName)) {
continue;
}
Class<?>[] params = method.getParameterTypes();
if (params.length != parameterTypes.length) {
continue;
}
for (int i = 0; i < parameterTypes.length; i++) {
if (!params[i].isAssignableFrom(parameterTypes[i])) {
continue iterate_on_methods;
}
}
return method;
}
} catch (SecurityException ex) {
// keep looking
}
}
throw new NoSuchMethodException("Cannot find method with name: " + methodName
+ " having parameters assignable from: "
+ arrayToString(parameterTypes));
}
private Class<?>[] getParameterTypes(Object[] objects) {
// We need to handle the void parameter situation.
if (objects == null) {
return new Class[]{};
}
Class<?>[] answer = new Class[objects.length];
int i = 0;
for (Object obj : objects) {
answer[i] = obj.getClass();
i++;
}
return answer;
}
private Map<String, String> getMatrixParametersFromMatrixString(String matrixString, String charset) throws UnsupportedEncodingException {
Map<String, String> answer = new LinkedHashMap<String, String>();
for (String param : matrixString.split(";")) {
String[] pair = param.split("=", 2);
if (pair.length == 2) {
String name = URLDecoder.decode(pair[0], charset);
String value = URLDecoder.decode(pair[1], charset);
answer.put(name, value);
} else {
throw new IllegalArgumentException("Invalid parameter, expected to be a pair but was " + param);
}
}
return answer;
}
private String arrayToString(Object[] array) {
StringBuilder buffer = new StringBuilder("[");
for (Object obj : array) {
if (buffer.length() > 2) {
buffer.append(",");
}
buffer.append(obj.toString());
}
buffer.append("]");
return buffer.toString();
}
protected CxfOperationException populateCxfRsProducerException(Exchange exchange, Response response, int responseCode) {
CxfOperationException exception;
String uri = exchange.getFromEndpoint().getEndpointUri();
String statusText = statusTextFromResponseCode(responseCode);
Map<String, String> headers = parseResponseHeaders(response, exchange);
//Get the response detail string
String copy = exchange.getContext().getTypeConverter().convertTo(String.class, response.getEntity());
if (responseCode >= 300 && responseCode < 400) {
String redirectLocation;
if (response.getMetadata().getFirst("Location") != null) {
redirectLocation = response.getMetadata().getFirst("location").toString();
exception = new CxfOperationException(uri, responseCode, statusText, redirectLocation, headers, copy);
} else {
//no redirect location
exception = new CxfOperationException(uri, responseCode, statusText, null, headers, copy);
}
} else {
//internal server error(error code 500)
exception = new CxfOperationException(uri, responseCode, statusText, null, headers, copy);
}
return exception;
}
/**
* Convert the given HTTP response code to its corresponding status text or
* response category. This is useful to avoid creating NPEs if this producer
* is presented with an HTTP response code that the JAX-RS API doesn't know.
*
* @param responseCode the HTTP response code to be converted to status text
* @return the status text for the code, or, if JAX-RS doesn't know the code,
* the status category as text
*/
String statusTextFromResponseCode(int responseCode) {
Response.Status status = Response.Status.fromStatusCode(responseCode);
return status != null ? status.toString() : responseCategoryFromCode(responseCode);
}
/**
* Return the category of the given HTTP response code, as text. Invalid
* codes will result in appropriate text; this method never returns null.
*
* @param responseCode HTTP response code whose category is to be returned
* @return the category of the give response code; never {@code null}.
*/
private String responseCategoryFromCode(int responseCode) {
return Response.Status.Family.familyOf(responseCode).name();
}
protected Map<String, String> parseResponseHeaders(Object response, Exchange camelExchange) {
Map<String, String> answer = new HashMap<String, String>();
if (response instanceof Response) {
for (Map.Entry<String, List<Object>> entry : ((Response) response).getMetadata().entrySet()) {
LOG.trace("Parse external header {}={}", entry.getKey(), entry.getValue());
answer.put(entry.getKey(), entry.getValue().get(0).toString());
}
}
return answer;
}
/**
* Cache contains {@link org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean}
*/
class ClientFactoryBeanCache {
private LRUSoftCache<String, JAXRSClientFactoryBean> cache;
ClientFactoryBeanCache(final int maxCacheSize) {
this.cache = new LRUSoftCache<String, JAXRSClientFactoryBean>(maxCacheSize);
}
public void start() throws Exception {
cache.resetStatistics();
}
public void stop() throws Exception {
cache.clear();
}
public JAXRSClientFactoryBean get(String address) throws Exception {
JAXRSClientFactoryBean retVal = null;
synchronized (cache) {
retVal = cache.get(address);
if (retVal == null) {
retVal = ((CxfRsEndpoint)getEndpoint()).createJAXRSClientFactoryBean(address);
cache.put(address, retVal);
LOG.trace("Created client factory bean and add to cache for address '{}'", address);
} else {
LOG.trace("Retrieved client factory bean from cache for address '{}'", address);
}
}
return retVal;
}
}
}
| jmandawg/camel | components/camel-cxf/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducer.java | Java | apache-2.0 | 21,922 |
/*
* Copyright 2000-2015 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.codeInspection.htmlInspections;
import com.intellij.codeInsight.daemon.XmlErrorMessages;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiErrorElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.templateLanguages.OuterLanguageElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlChildRole;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlToken;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.Objects;
/**
* @author spleaner
*/
public class RemoveExtraClosingTagIntentionAction implements LocalQuickFix, IntentionAction {
@Override
@NotNull
public String getFamilyName() {
return XmlErrorMessages.message("remove.extra.closing.tag.quickfix");
}
@Override
@NotNull
public String getText() {
return getName();
}
@Override
public boolean isAvailable(@NotNull final Project project, final Editor editor, final PsiFile file) {
PsiElement psiElement = file.findElementAt(editor.getCaretModel().getOffset());
return psiElement instanceof XmlToken &&
(psiElement.getParent() instanceof XmlTag || psiElement.getParent() instanceof PsiErrorElement);
}
@Override
public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException {
doFix(Objects.requireNonNull(file.findElementAt(editor.getCaretModel().getOffset())).getParent());
}
@Override
public boolean startInWriteAction() {
return true;
}
private static void doFix(@NotNull PsiElement tagElement) throws IncorrectOperationException {
if (tagElement instanceof PsiErrorElement) {
Collection<OuterLanguageElement> outers = PsiTreeUtil.findChildrenOfType(tagElement, OuterLanguageElement.class);
String replacement = StringUtil.join(outers, PsiElement::getText, "");
Document document = getDocument(tagElement);
if (document != null && !replacement.isEmpty()) {
TextRange range = tagElement.getTextRange();
document.replaceString(range.getStartOffset(), range.getEndOffset(), replacement);
} else {
tagElement.delete();
}
}
else {
final ASTNode astNode = tagElement.getNode();
if (astNode != null) {
final ASTNode endTagStart = XmlChildRole.CLOSING_TAG_START_FINDER.findChild(astNode);
if (endTagStart != null) {
Document document = getDocument(tagElement);
if (document != null) {
document.deleteString(endTagStart.getStartOffset(), tagElement.getLastChild().getTextRange().getEndOffset());
}
}
}
}
}
private static Document getDocument(@NotNull PsiElement tagElement) {
return PsiDocumentManager.getInstance(tagElement.getProject()).getDocument(tagElement.getContainingFile());
}
@Override
public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
final PsiElement element = descriptor.getPsiElement();
if (!(element instanceof XmlToken)) return;
doFix(element.getParent());
}
}
| goodwinnk/intellij-community | xml/xml-analysis-impl/src/com/intellij/codeInspection/htmlInspections/RemoveExtraClosingTagIntentionAction.java | Java | apache-2.0 | 4,261 |
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.externalSystem.service;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.externalSystem.ExternalSystemManager;
import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder;
import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys;
import com.intellij.openapi.externalSystem.service.project.ProjectRenameAware;
import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManagerImpl;
import com.intellij.openapi.externalSystem.service.ui.ExternalToolWindowManager;
import com.intellij.openapi.externalSystem.service.vcs.ExternalSystemVcsRegistrar;
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupActivity;
import com.intellij.util.DisposeAwareRunnable;
import org.jetbrains.annotations.NotNull;
/**
* @author Denis Zhdanov
* @since 5/2/13 9:23 PM
*/
public class ExternalSystemStartupActivity implements StartupActivity {
@Override
public void runActivity(@NotNull final Project project) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
return;
}
Runnable task = () -> {
for (ExternalSystemManager<?, ?, ?, ?, ?> manager : ExternalSystemApiUtil.getAllManagers()) {
if (manager instanceof StartupActivity) {
((StartupActivity)manager).runActivity(project);
}
}
if (project.getUserData(ExternalSystemDataKeys.NEWLY_IMPORTED_PROJECT) != Boolean.TRUE) {
for (ExternalSystemManager manager : ExternalSystemManager.EP_NAME.getExtensions()) {
final boolean isNewProject = project.getUserData(ExternalSystemDataKeys.NEWLY_CREATED_PROJECT) == Boolean.TRUE;
if (isNewProject) {
ExternalSystemUtil.refreshProjects(new ImportSpecBuilder(project, manager.getSystemId())
.createDirectoriesForEmptyContentRoots());
}
}
}
ExternalToolWindowManager.handle(project);
ExternalSystemVcsRegistrar.handle(project);
ProjectRenameAware.beAware(project);
};
ExternalProjectsManagerImpl.getInstance(project).init();
DumbService.getInstance(project).runWhenSmart(DisposeAwareRunnable.create(task, project));
}
}
| apixandru/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemStartupActivity.java | Java | apache-2.0 | 3,059 |
"""Support Wink alarm control panels."""
import pywink
import homeassistant.components.alarm_control_panel as alarm
from homeassistant.components.alarm_control_panel.const import (
SUPPORT_ALARM_ARM_AWAY,
SUPPORT_ALARM_ARM_HOME,
)
from homeassistant.const import (
STATE_ALARM_ARMED_AWAY,
STATE_ALARM_ARMED_HOME,
STATE_ALARM_DISARMED,
)
from . import DOMAIN, WinkDevice
STATE_ALARM_PRIVACY = "Private"
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Wink platform."""
for camera in pywink.get_cameras():
# get_cameras returns multiple device types.
# Only add those that aren't sensors.
try:
camera.capability()
except AttributeError:
_id = camera.object_id() + camera.name()
if _id not in hass.data[DOMAIN]["unique_ids"]:
add_entities([WinkCameraDevice(camera, hass)])
class WinkCameraDevice(WinkDevice, alarm.AlarmControlPanelEntity):
"""Representation a Wink camera alarm."""
async def async_added_to_hass(self):
"""Call when entity is added to hass."""
self.hass.data[DOMAIN]["entities"]["alarm_control_panel"].append(self)
@property
def state(self):
"""Return the state of the device."""
wink_state = self.wink.state()
if wink_state == "away":
state = STATE_ALARM_ARMED_AWAY
elif wink_state == "home":
state = STATE_ALARM_DISARMED
elif wink_state == "night":
state = STATE_ALARM_ARMED_HOME
else:
state = None
return state
@property
def supported_features(self) -> int:
"""Return the list of supported features."""
return SUPPORT_ALARM_ARM_HOME | SUPPORT_ALARM_ARM_AWAY
def alarm_disarm(self, code=None):
"""Send disarm command."""
self.wink.set_mode("home")
def alarm_arm_home(self, code=None):
"""Send arm home command."""
self.wink.set_mode("night")
def alarm_arm_away(self, code=None):
"""Send arm away command."""
self.wink.set_mode("away")
@property
def device_state_attributes(self):
"""Return the state attributes."""
return {"private": self.wink.private()}
| sdague/home-assistant | homeassistant/components/wink/alarm_control_panel.py | Python | apache-2.0 | 2,276 |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace OpacityBindingXaml.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
}
| YOTOV-LIMITED/xamarin-forms-book-preview-2 | Chapter16/OpacityBindingXaml/OpacityBindingXaml/OpacityBindingXaml.iOS/AppDelegate.cs | C# | apache-2.0 | 1,111 |
steal("jquerypp/event/hover", 'funcunit/syn', 'funcunit/qunit', function ($, Syn) {
module("jquerypp/dom/hover")
test("hovering", function () {
$("#qunit-test-area").append("<div id='hover'>Content<div>")
var hoverenters = 0,
hoverinits = 0,
hoverleaves = 0,
delay = 15;
$("#hover").bind("hoverinit", function (ev, hover) {
hover.delay(delay);
hoverinits++;
})
.bind('hoverenter', function () {
hoverenters++;
})
.bind('hoverleave', function () {
hoverleaves++;
})
var hover = $("#hover")
var off = hover.offset();
//add a mouseenter, and 2 mouse moves
Syn("mouseover", {pageX : off.top, pageY : off.left}, hover[0])
ok(hoverinits, 'hoverinit');
ok(hoverenters === 0, "hoverinit hasn't been called");
stop();
setTimeout(function () {
ok(hoverenters === 1, "hoverenter has been called");
ok(hoverleaves === 0, "hoverleave hasn't been called");
Syn("mouseout", {pageX : off.top, pageY : off.left}, hover[0]);
ok(hoverleaves === 1, "hoverleave has been called");
delay = 30;
Syn("mouseover", {pageX : off.top, pageY : off.left}, hover[0]);
ok(hoverinits === 2, 'hoverinit');
setTimeout(function () {
Syn("mouseout", {pageX : off.top, pageY : off.left}, hover[0]);
setTimeout(function () {
ok(hoverenters === 1, "hoverenter was not called");
ok(hoverleaves === 1, "hoverleave was not called");
start();
}, 30)
}, 10)
}, 30)
});
test("hoverInit delay 0 triggers hoverenter (issue #57)", function () {
$("#qunit-test-area").append("<div id='hoverzero'>Content<div>");
var hoverenters = 0,
hoverinits = 0,
hoverleaves = 0,
delay = 0;
$("#hoverzero").on({
hoverinit : function (ev, hover) {
hover.delay(delay);
hoverinits++;
},
hoverenter : function () {
hoverenters++;
},
'hoverleave' : function () {
hoverleaves++;
}
});
var hover = $("#hoverzero")
var off = hover.offset();
//add a mouseenter, and 2 mouse moves
Syn("mouseover", { pageX : off.top, pageY : off.left }, hover[0])
ok(hoverinits, 'hoverinit');
ok(hoverenters === 1, "hoverenter has been called");
});
});
| willametteuniversity/webcirc2 | static/jquerypp/event/hover/hover_test.js | JavaScript | apache-2.0 | 2,166 |
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.support.ui;
/**
* A simple encapsulation to allowing timing
*/
public interface Clock {
/**
* @return The current time in milliseconds since epoch time.
* @see System#currentTimeMillis()
*/
long now();
/**
* Computes a point of time in the future.
*
* @param durationInMillis The point in the future, in milliseconds relative to the {@link #now()
* current time}.
* @return A timestamp representing a point in the future.
*/
long laterBy(long durationInMillis);
/**
* Tests if a point in time occurs before the {@link #now() current time}.
*
* @param endInMillis The timestamp to check.
* @return Whether the given timestamp represents a point in time before the current time.
*/
boolean isNowBefore(long endInMillis);
}
| jabbrwcky/selenium | java/client/src/org/openqa/selenium/support/ui/Clock.java | Java | apache-2.0 | 1,621 |
/*
Copyright 2015 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 v1beta1
import (
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/runtime"
"k8s.io/client-go/pkg/util/intstr"
)
func addDefaultingFuncs(scheme *runtime.Scheme) error {
return scheme.AddDefaultingFuncs(
SetDefaults_DaemonSet,
SetDefaults_Deployment,
SetDefaults_Job,
SetDefaults_HorizontalPodAutoscaler,
SetDefaults_ReplicaSet,
SetDefaults_NetworkPolicy,
)
}
func SetDefaults_DaemonSet(obj *DaemonSet) {
labels := obj.Spec.Template.Labels
// TODO: support templates defined elsewhere when we support them in the API
if labels != nil {
if obj.Spec.Selector == nil {
obj.Spec.Selector = &LabelSelector{
MatchLabels: labels,
}
}
if len(obj.Labels) == 0 {
obj.Labels = labels
}
}
}
func SetDefaults_Deployment(obj *Deployment) {
// Default labels and selector to labels from pod template spec.
labels := obj.Spec.Template.Labels
if labels != nil {
if obj.Spec.Selector == nil {
obj.Spec.Selector = &LabelSelector{MatchLabels: labels}
}
if len(obj.Labels) == 0 {
obj.Labels = labels
}
}
// Set DeploymentSpec.Replicas to 1 if it is not set.
if obj.Spec.Replicas == nil {
obj.Spec.Replicas = new(int32)
*obj.Spec.Replicas = 1
}
strategy := &obj.Spec.Strategy
// Set default DeploymentStrategyType as RollingUpdate.
if strategy.Type == "" {
strategy.Type = RollingUpdateDeploymentStrategyType
}
if strategy.Type == RollingUpdateDeploymentStrategyType {
if strategy.RollingUpdate == nil {
rollingUpdate := RollingUpdateDeployment{}
strategy.RollingUpdate = &rollingUpdate
}
if strategy.RollingUpdate.MaxUnavailable == nil {
// Set default MaxUnavailable as 1 by default.
maxUnavailable := intstr.FromInt(1)
strategy.RollingUpdate.MaxUnavailable = &maxUnavailable
}
if strategy.RollingUpdate.MaxSurge == nil {
// Set default MaxSurge as 1 by default.
maxSurge := intstr.FromInt(1)
strategy.RollingUpdate.MaxSurge = &maxSurge
}
}
}
func SetDefaults_Job(obj *Job) {
labels := obj.Spec.Template.Labels
// TODO: support templates defined elsewhere when we support them in the API
if labels != nil {
// if an autoselector is requested, we'll build the selector later with controller-uid and job-name
autoSelector := bool(obj.Spec.AutoSelector != nil && *obj.Spec.AutoSelector)
// otherwise, we are using a manual selector
manualSelector := !autoSelector
// and default behavior for an unspecified manual selector is to use the pod template labels
if manualSelector && obj.Spec.Selector == nil {
obj.Spec.Selector = &LabelSelector{
MatchLabels: labels,
}
}
if len(obj.Labels) == 0 {
obj.Labels = labels
}
}
// For a non-parallel job, you can leave both `.spec.completions` and
// `.spec.parallelism` unset. When both are unset, both are defaulted to 1.
if obj.Spec.Completions == nil && obj.Spec.Parallelism == nil {
obj.Spec.Completions = new(int32)
*obj.Spec.Completions = 1
obj.Spec.Parallelism = new(int32)
*obj.Spec.Parallelism = 1
}
if obj.Spec.Parallelism == nil {
obj.Spec.Parallelism = new(int32)
*obj.Spec.Parallelism = 1
}
}
func SetDefaults_HorizontalPodAutoscaler(obj *HorizontalPodAutoscaler) {
if obj.Spec.MinReplicas == nil {
minReplicas := int32(1)
obj.Spec.MinReplicas = &minReplicas
}
if obj.Spec.CPUUtilization == nil {
obj.Spec.CPUUtilization = &CPUTargetUtilization{TargetPercentage: 80}
}
}
func SetDefaults_ReplicaSet(obj *ReplicaSet) {
labels := obj.Spec.Template.Labels
// TODO: support templates defined elsewhere when we support them in the API
if labels != nil {
if obj.Spec.Selector == nil {
obj.Spec.Selector = &LabelSelector{
MatchLabels: labels,
}
}
if len(obj.Labels) == 0 {
obj.Labels = labels
}
}
if obj.Spec.Replicas == nil {
obj.Spec.Replicas = new(int32)
*obj.Spec.Replicas = 1
}
}
func SetDefaults_NetworkPolicy(obj *NetworkPolicy) {
// Default any undefined Protocol fields to TCP.
for _, i := range obj.Spec.Ingress {
// TODO: Update Ports to be a pointer to slice as soon as auto-generation supports it.
for _, p := range i.Ports {
if p.Protocol == nil {
proto := v1.ProtocolTCP
p.Protocol = &proto
}
}
}
}
| djosborne/kubernetes | staging/src/k8s.io/client-go/pkg/apis/extensions/v1beta1/defaults.go | GO | apache-2.0 | 4,758 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
namespace MandelbrotProgress.WinPhone
{
public partial class MainPage : global::Xamarin.Forms.Platform.WinPhone.FormsApplicationPage
{
public MainPage()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;
global::Xamarin.Forms.Forms.Init();
LoadApplication(new MandelbrotProgress.App());
}
}
}
| YOTOV-LIMITED/xamarin-forms-book-preview-2 | Chapter20/MandelbrotProgress/MandelbrotProgress/MandelbrotProgress.WinPhone/MainPage.xaml.cs | C# | apache-2.0 | 658 |
// 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.
using Org.Apache.REEF.Common.Tasks;
using Org.Apache.REEF.Common.Tasks.Events;
using Org.Apache.REEF.Tang.Annotations;
using Org.Apache.REEF.Utilities;
using Org.Apache.REEF.Utilities.Logging;
using System;
using System.Threading;
namespace Org.Apache.REEF.Bridge.Core.Tests.Fail.Driver
{
internal sealed class NoopTask :
ITask,
ITaskMessageSource,
IDriverMessageHandler,
IObserver<ISuspendEvent>,
IObserver<ITaskStop>,
IObserver<ICloseEvent>
{
private static readonly Logger Log = Logger.GetLogger(typeof(NoopTask));
private static readonly TaskMessage InitMessage =
TaskMessage.From("nooptask", ByteUtilities.StringToByteArrays("MESSAGE::INIT"));
private bool _isRunning = true;
private Optional<TaskMessage> _message = Utilities.Optional<TaskMessage>.Empty();
[Inject]
private NoopTask()
{
Log.Log(Level.Info, "NoopTask created.");
}
public byte[] Call(byte[] memento)
{
_isRunning = true;
while (_isRunning)
{
try
{
Log.Log(Level.Info, "NoopTask.call(): Waiting for the message.");
lock (this)
{
Monitor.Wait(this);
}
}
catch (System.Threading.ThreadInterruptedException ex)
{
Log.Log(Level.Warning, "NoopTask.wait() interrupted.", ex);
}
}
Log.Log(Level.Info,
"NoopTask.call(): Exiting with message {0}",
ByteUtilities.ByteArraysToString(_message.OrElse(InitMessage).Message));
return _message.OrElse(InitMessage).Message;
}
public Optional<TaskMessage> Message
{
get
{
Log.Log(Level.Info,
"NoopTask.getMessage() invoked: {0}",
ByteUtilities.ByteArraysToString(_message.OrElse(InitMessage).Message));
return _message;
}
}
public void Dispose()
{
Log.Log(Level.Info, "NoopTask.stopTask() invoked.");
_isRunning = false;
lock (this)
{
Monitor.Pulse(this);
}
}
public void OnError(System.Exception error)
{
throw new NotImplementedException();
}
public void OnCompleted()
{
throw new NotImplementedException();
}
/// <summary>
/// Handler for SuspendEvent.
/// </summary>
/// <param name="suspendEvent"></param>
public void OnNext(ISuspendEvent suspendEvent)
{
Log.Log(Level.Info, "NoopTask.TaskSuspendHandler.OnNext() invoked.");
Dispose();
}
/// <summary>
/// Handler for TaskStop.
/// </summary>
/// <param name="value"></param>
public void OnNext(ITaskStop value)
{
Log.Log(Level.Info, "NoopTask.TaskStopHandler.OnNext() invoked.");
}
/// <summary>
/// Handler for CloseEvent.
/// </summary>
/// <param name="closeEvent"></param>
public void OnNext(ICloseEvent closeEvent)
{
Log.Log(Level.Info, "NoopTask.TaskCloseHandler.OnNext() invoked.");
Dispose();
}
/// <summary>
/// Handler for DriverMessage.
/// </summary>
/// <param name="driverMessage"></param>
public void Handle(IDriverMessage driverMessage)
{
byte[] msg = driverMessage.Message.Value;
Log.Log(Level.Info,
"NoopTask.DriverMessageHandler.Handle() invoked: {0}",
ByteUtilities.ByteArraysToString(msg));
lock (this)
{
_message = Utilities.Optional<TaskMessage>.Of(TaskMessage.From("nooptask", msg));
}
}
}
} | apache/reef | lang/cs/Org.Apache.REEF.Bridge.Core.Tests/Fail/Driver/NoopTask.cs | C# | apache-2.0 | 4,885 |
package com.crawljax.browser;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.crawljax.core.CrawljaxException;
import com.crawljax.core.configuration.AcceptAllFramesChecker;
import com.crawljax.core.configuration.IgnoreFrameChecker;
import com.crawljax.core.exception.BrowserConnectionException;
import com.crawljax.core.state.Eventable;
import com.crawljax.core.state.Identification;
import com.crawljax.forms.FormHandler;
import com.crawljax.forms.FormInput;
import com.crawljax.forms.InputValue;
import com.crawljax.forms.RandomInputValueGenerator;
import com.crawljax.util.DomUtils;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.io.Files;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.NoSuchFrameException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Platform;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.UnhandledAlertException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.internal.WrapsDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.ErrorHandler.UnknownServerException;
import org.openqa.selenium.remote.HttpCommandExecutor;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.Select;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public final class WebDriverBackedEmbeddedBrowser implements EmbeddedBrowser {
private static final Logger LOGGER = LoggerFactory
.getLogger(WebDriverBackedEmbeddedBrowser.class);
/**
* Create a RemoteWebDriver backed EmbeddedBrowser.
*
* @param hubUrl
* Url of the server.
* @param filterAttributes
* the attributes to be filtered from DOM.
* @param crawlWaitReload
* the period to wait after a reload.
* @param crawlWaitEvent
* the period to wait after an event is fired.
* @return The EmbeddedBrowser.
*/
public static WebDriverBackedEmbeddedBrowser withRemoteDriver(String hubUrl,
ImmutableSortedSet<String> filterAttributes, long crawlWaitEvent, long crawlWaitReload) {
return WebDriverBackedEmbeddedBrowser.withDriver(buildRemoteWebDriver(hubUrl),
filterAttributes, crawlWaitEvent, crawlWaitReload);
}
/**
* Create a RemoteWebDriver backed EmbeddedBrowser.
*
* @param hubUrl
* Url of the server.
* @param filterAttributes
* the attributes to be filtered from DOM.
* @param crawlWaitReload
* the period to wait after a reload.
* @param crawlWaitEvent
* the period to wait after an event is fired.
* @param ignoreFrameChecker
* the checker used to determine if a certain frame must be ignored.
* @return The EmbeddedBrowser.
*/
public static WebDriverBackedEmbeddedBrowser withRemoteDriver(String hubUrl,
ImmutableSortedSet<String> filterAttributes, long crawlWaitEvent,
long crawlWaitReload, IgnoreFrameChecker ignoreFrameChecker) {
return WebDriverBackedEmbeddedBrowser.withDriver(buildRemoteWebDriver(hubUrl),
filterAttributes, crawlWaitEvent, crawlWaitReload, ignoreFrameChecker);
}
/**
* Create a WebDriver backed EmbeddedBrowser.
*
* @param driver
* The WebDriver to use.
* @param filterAttributes
* the attributes to be filtered from DOM.
* @param crawlWaitReload
* the period to wait after a reload.
* @param crawlWaitEvent
* the period to wait after an event is fired.
* @return The EmbeddedBrowser.
*/
public static WebDriverBackedEmbeddedBrowser withDriver(WebDriver driver,
ImmutableSortedSet<String> filterAttributes, long crawlWaitEvent, long crawlWaitReload) {
return new WebDriverBackedEmbeddedBrowser(driver, filterAttributes, crawlWaitEvent,
crawlWaitReload);
}
/**
* Create a WebDriver backed EmbeddedBrowser.
*
* @param driver
* The WebDriver to use.
* @param filterAttributes
* the attributes to be filtered from DOM.
* @param crawlWaitReload
* the period to wait after a reload.
* @param crawlWaitEvent
* the period to wait after an event is fired.
* @param ignoreFrameChecker
* the checker used to determine if a certain frame must be ignored.
* @return The EmbeddedBrowser.
*/
public static WebDriverBackedEmbeddedBrowser withDriver(WebDriver driver,
ImmutableSortedSet<String> filterAttributes, long crawlWaitEvent,
long crawlWaitReload, IgnoreFrameChecker ignoreFrameChecker) {
return new WebDriverBackedEmbeddedBrowser(driver, filterAttributes, crawlWaitEvent,
crawlWaitReload, ignoreFrameChecker);
}
/**
* Create a RemoteWebDriver backed EmbeddedBrowser.
*
* @param hubUrl
* Url of the server.
* @return The EmbeddedBrowser.
*/
public static WebDriverBackedEmbeddedBrowser withRemoteDriver(String hubUrl) {
return WebDriverBackedEmbeddedBrowser.withDriver(buildRemoteWebDriver(hubUrl));
}
/**
* Private used static method for creation of a RemoteWebDriver. Taking care of the default
* Capabilities and using the HttpCommandExecutor.
*
* @param hubUrl
* the url of the hub to use.
* @return the RemoteWebDriver instance.
*/
private static RemoteWebDriver buildRemoteWebDriver(String hubUrl) {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setPlatform(Platform.ANY);
URL url;
try {
url = new URL(hubUrl);
} catch (MalformedURLException e) {
LOGGER.error("The given hub url of the remote server is malformed can not continue!",
e);
return null;
}
HttpCommandExecutor executor = null;
try {
executor = new HttpCommandExecutor(url);
} catch (Exception e) {
// TODO Stefan; refactor this catch, this will definitely result in
// NullPointers, why
// not throw RuntimeExcption direct?
LOGGER.error("Received unknown exception while creating the "
+ "HttpCommandExecutor, can not continue!", e);
return null;
}
return new RemoteWebDriver(executor, capabilities);
}
private final ImmutableSortedSet<String> filterAttributes;
private final WebDriver browser;
private long crawlWaitEvent;
private long crawlWaitReload;
private IgnoreFrameChecker ignoreFrameChecker = new AcceptAllFramesChecker();
/**
* Constructor without configuration values.
*
* @param driver
* The WebDriver to use.
*/
private WebDriverBackedEmbeddedBrowser(WebDriver driver) {
this.browser = driver;
filterAttributes = ImmutableSortedSet.of();
}
/**
* Constructor.
*
* @param driver
* The WebDriver to use.
* @param filterAttributes
* the attributes to be filtered from DOM.
* @param crawlWaitReload
* the period to wait after a reload.
* @param crawlWaitEvent
* the period to wait after an event is fired.
*/
private WebDriverBackedEmbeddedBrowser(WebDriver driver,
ImmutableSortedSet<String> filterAttributes, long crawlWaitReload, long crawlWaitEvent) {
this.browser = driver;
this.filterAttributes = Preconditions.checkNotNull(filterAttributes);
this.crawlWaitEvent = crawlWaitEvent;
this.crawlWaitReload = crawlWaitReload;
}
/**
* Constructor.
*
* @param driver
* The WebDriver to use.
* @param filterAttributes
* the attributes to be filtered from DOM.
* @param crawlWaitReload
* the period to wait after a reload.
* @param crawlWaitEvent
* the period to wait after an event is fired.
* @param ignoreFrameChecker
* the checker used to determine if a certain frame must be ignored.
*/
private WebDriverBackedEmbeddedBrowser(WebDriver driver,
ImmutableSortedSet<String> filterAttributes, long crawlWaitReload,
long crawlWaitEvent, IgnoreFrameChecker ignoreFrameChecker) {
this(driver, filterAttributes, crawlWaitReload, crawlWaitEvent);
this.ignoreFrameChecker = ignoreFrameChecker;
}
/**
* Create a WebDriver backed EmbeddedBrowser.
*
* @param driver
* The WebDriver to use.
* @return The EmbeddedBrowser.
*/
public static WebDriverBackedEmbeddedBrowser withDriver(WebDriver driver) {
return new WebDriverBackedEmbeddedBrowser(driver);
}
/**
* @param url
* The URL.
*/
@Override
public void goToUrl(URI url) {
try {
browser.navigate().to(url.toString());
Thread.sleep(this.crawlWaitReload);
handlePopups();
} catch (WebDriverException e) {
throwIfConnectionException(e);
return;
} catch (InterruptedException e) {
LOGGER.debug("goToUrl got interrupted while waiting for the page to be loaded", e);
Thread.currentThread().interrupt();
return;
}
}
/**
* alert, prompt, and confirm behave as if the OK button is always clicked.
*/
private void handlePopups() {
try {
executeJavaScript("window.alert = function(msg){return true;};"
+ "window.confirm = function(msg){return true;};"
+ "window.prompt = function(msg){return true;};");
} catch (CrawljaxException e) {
LOGGER.error("Handling of PopUp windows failed", e);
}
}
/**
* Fires the event and waits for a specified time.
*
* @param webElement
* the element to fire event on.
* @param eventable
* The HTML event type (onclick, onmouseover, ...).
* @return true if firing event is successful.
* @throws InterruptedException
* when interrupted during the wait.
*/
private boolean fireEventWait(WebElement webElement, Eventable eventable)
throws ElementNotVisibleException, InterruptedException {
switch (eventable.getEventType()) {
case click:
try {
webElement.click();
} catch (ElementNotVisibleException e) {
throw e;
} catch (WebDriverException e) {
throwIfConnectionException(e);
return false;
}
break;
case hover:
LOGGER.info("Eventype hover called but this isnt implemented yet");
break;
default:
LOGGER.info("EventType {} not supported in WebDriver.", eventable.getEventType());
return false;
}
Thread.sleep(this.crawlWaitEvent);
return true;
}
@Override
public void close() {
LOGGER.info("Closing the browser...");
try {
// close browser and close every associated window.
browser.quit();
} catch (WebDriverException e) {
if (e.getCause() instanceof InterruptedException || e.getCause().getCause() instanceof InterruptedException) {
LOGGER.info("Interrupted while waiting for the browser to close. It might not close correctly");
Thread.currentThread().interrupt();
return;
}
throw wrapWebDriverExceptionIfConnectionException(e);
}
LOGGER.debug("Browser closed...");
}
@Override
@Deprecated
public String getDom() {
return getStrippedDom();
}
@Override
public String getStrippedDom() {
try {
String dom = toUniformDOM(DomUtils.getDocumentToString(getDomTreeWithFrames()));
LOGGER.trace(dom);
return dom;
} catch (WebDriverException | CrawljaxException e) {
LOGGER.warn("Could not get the dom", e);
return "";
}
}
@Override
public String getUnStrippedDom() {
return browser.getPageSource();
}
/**
* @param html
* The html string.
* @return uniform version of dom with predefined attributes stripped
*/
private String toUniformDOM(String html) {
Pattern p =
Pattern.compile("<SCRIPT(.*?)</SCRIPT>", Pattern.DOTALL
| Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(html);
String htmlFormatted = m.replaceAll("");
p = Pattern.compile("<\\?xml:(.*?)>");
m = p.matcher(htmlFormatted);
htmlFormatted = m.replaceAll("");
htmlFormatted = filterAttributes(htmlFormatted);
return htmlFormatted;
}
/**
* Filters attributes from the HTML string.
*
* @param html
* The HTML to filter.
* @return The filtered HTML string.
*/
private String filterAttributes(String html) {
String filteredHtml = html;
for (String attribute : this.filterAttributes) {
String regex = "\\s" + attribute + "=\"[^\"]*\"";
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(html);
filteredHtml = m.replaceAll("");
}
return filteredHtml;
}
@Override
public void goBack() {
try {
browser.navigate().back();
} catch (WebDriverException e) {
throw wrapWebDriverExceptionIfConnectionException(e);
}
}
/**
* @param identification
* The identification object.
* @param text
* The input.
* @return true if succeeds.
*/
@Override
public boolean input(Identification identification, String text) {
try {
WebElement field = browser.findElement(identification.getWebDriverBy());
if (field != null) {
field.clear();
field.sendKeys(text);
return true;
}
return false;
} catch (WebDriverException e) {
throwIfConnectionException(e);
return false;
}
}
/**
* Fires an event on an element using its identification.
*
* @param eventable
* The eventable.
* @return true if it is able to fire the event successfully on the element.
* @throws InterruptedException
* when interrupted during the wait.
*/
@Override
public synchronized boolean fireEventAndWait(Eventable eventable)
throws ElementNotVisibleException,
NoSuchElementException, InterruptedException {
try {
boolean handleChanged = false;
boolean result = false;
if (eventable.getRelatedFrame() != null && !eventable.getRelatedFrame().equals("")) {
LOGGER.debug("switching to frame: " + eventable.getRelatedFrame());
try {
switchToFrame(eventable.getRelatedFrame());
} catch (NoSuchFrameException e) {
LOGGER.debug("Frame not found, possibily while back-tracking..", e);
// TODO Stefan, This exception is catched to prevent stopping
// from working
// This was the case on the Gmail case; find out if not switching
// (catching)
// Results in good performance...
}
handleChanged = true;
}
WebElement webElement =
browser.findElement(eventable.getIdentification().getWebDriverBy());
if (webElement != null) {
result = fireEventWait(webElement, eventable);
}
if (handleChanged) {
browser.switchTo().defaultContent();
}
return result;
} catch (ElementNotVisibleException | NoSuchElementException e) {
throw e;
} catch (WebDriverException e) {
throwIfConnectionException(e);
return false;
}
}
/**
* Execute JavaScript in the browser.
*
* @param code
* The code to execute.
* @return The return value of the JavaScript.
* @throws CrawljaxException
* when javascript execution failed.
*/
@Override
public Object executeJavaScript(String code) throws CrawljaxException {
try {
JavascriptExecutor js = (JavascriptExecutor) browser;
return js.executeScript(code);
} catch (WebDriverException e) {
throwIfConnectionException(e);
throw new CrawljaxException(e);
}
}
/**
* Determines whether the corresponding element is visible.
*
* @param identification
* The element to search for.
* @return true if the element is visible
*/
@Override
public boolean isVisible(Identification identification) {
try {
WebElement el = browser.findElement(identification.getWebDriverBy());
if (el != null) {
return el.isDisplayed();
}
return false;
} catch (WebDriverException e) {
throwIfConnectionException(e);
return false;
}
}
/**
* @return The current browser url.
*/
@Override
public String getCurrentUrl() {
try {
return browser.getCurrentUrl();
} catch (WebDriverException e) {
throw wrapWebDriverExceptionIfConnectionException(e);
}
}
@Override
public void closeOtherWindows() {
try {
String current = browser.getWindowHandle();
for (String handle : browser.getWindowHandles()) {
if (!handle.equals(browser.getWindowHandle())) {
browser.switchTo().window(handle);
LOGGER.debug("Closing other window with title \"{}\"", browser.getTitle());
browser.close();
browser.switchTo().window(current);
}
}
} catch (UnhandledAlertException e) {
LOGGER.warn("While closing the window, an alert got ignored: {}", e.getMessage());
} catch (WebDriverException e) {
throw wrapWebDriverExceptionIfConnectionException(e);
}
}
/**
* @return a Document object containing the contents of iframes as well.
* @throws CrawljaxException
* if an exception is thrown.
*/
private Document getDomTreeWithFrames() throws CrawljaxException {
try {
Document document = DomUtils.asDocument(browser.getPageSource());
appendFrameContent(document.getDocumentElement(), document, "");
return document;
} catch (IOException e) {
throw new CrawljaxException(e.getMessage(), e);
}
}
private void appendFrameContent(Element orig, Document document, String topFrame) {
NodeList frameNodes = orig.getElementsByTagName("IFRAME");
List<Element> nodeList = new ArrayList<Element>();
for (int i = 0; i < frameNodes.getLength(); i++) {
Element frameElement = (Element) frameNodes.item(i);
nodeList.add(frameElement);
}
// Added support for FRAMES
frameNodes = orig.getElementsByTagName("FRAME");
for (int i = 0; i < frameNodes.getLength(); i++) {
Element frameElement = (Element) frameNodes.item(i);
nodeList.add(frameElement);
}
for (int i = 0; i < nodeList.size(); i++) {
try {
locateFrameAndgetSource(document, topFrame, nodeList.get(i));
} catch (UnknownServerException | NoSuchFrameException e) {
LOGGER.warn("Could not add frame contents for element {}", nodeList.get(i));
LOGGER.debug("Could not load frame because of {}", e.getMessage(), e);
}
}
}
private void locateFrameAndgetSource(Document document, String topFrame, Element frameElement)
throws NoSuchFrameException {
String frameIdentification = "";
if (topFrame != null && !topFrame.equals("")) {
frameIdentification += topFrame + ".";
}
String nameId = DomUtils.getFrameIdentification(frameElement);
if (nameId != null
&& !ignoreFrameChecker.isFrameIgnored(frameIdentification + nameId)) {
frameIdentification += nameId;
String handle = browser.getWindowHandle();
LOGGER.debug("The current H: " + handle);
switchToFrame(frameIdentification);
String toAppend = browser.getPageSource();
LOGGER.debug("frame dom: " + toAppend);
browser.switchTo().defaultContent();
try {
Element toAppendElement = DomUtils.asDocument(toAppend).getDocumentElement();
Element importedElement =
(Element) document.importNode(toAppendElement, true);
frameElement.appendChild(importedElement);
appendFrameContent(importedElement, document, frameIdentification);
} catch (DOMException | IOException e) {
LOGGER.info("Got exception while inspecting a frame:" + frameIdentification
+ " continuing...", e);
}
}
}
private void switchToFrame(String frameIdentification) throws NoSuchFrameException {
LOGGER.debug("frame identification: " + frameIdentification);
if (frameIdentification.contains(".")) {
String[] frames = frameIdentification.split("\\.");
for (String frameId : frames) {
LOGGER.debug("switching to frame: " + frameId);
browser.switchTo().frame(frameId);
}
} else {
browser.switchTo().frame(frameIdentification);
}
}
/**
* @return the dom without the iframe contents.
* @see com.crawljax.browser.EmbeddedBrowser#getStrippedDomWithoutIframeContent()
*/
@Override
public String getStrippedDomWithoutIframeContent() {
try {
String dom = browser.getPageSource();
String result = toUniformDOM(dom);
return result;
} catch (WebDriverException e) {
throwIfConnectionException(e);
return "";
}
}
/**
* @param input
* the input to be filled.
* @return FormInput with random value assigned if possible. If no values were set it returns
* <code>null</code>
*/
@Override
public FormInput getInputWithRandomValue(FormInput input) {
WebElement webElement;
try {
webElement = browser.findElement(input.getIdentification().getWebDriverBy());
if (!webElement.isDisplayed()) {
return null;
}
} catch (WebDriverException e) {
throwIfConnectionException(e);
return null;
}
Set<InputValue> values = new HashSet<>();
try {
setRandomValues(input, webElement, values);
} catch (WebDriverException e) {
throwIfConnectionException(e);
return null;
}
if (values.isEmpty()) {
return null;
}
input.setInputValues(values);
return input;
}
private void setRandomValues(FormInput input, WebElement webElement, Set<InputValue> values) {
String inputString = input.getType().toLowerCase();
if (inputString.startsWith("text")) {
values.add(new InputValue(new RandomInputValueGenerator()
.getRandomString(FormHandler.RANDOM_STRING_LENGTH), true));
} else if (inputString.equals("checkbox") || inputString.equals("radio")
&& !webElement.isSelected()) {
if (new RandomInputValueGenerator().getCheck()) {
values.add(new InputValue("1", true));
} else {
values.add(new InputValue("0", false));
}
} else if (inputString.equals("select")) {
Select select = new Select(webElement);
if (!select.getOptions().isEmpty()) {
WebElement option =
new RandomInputValueGenerator().getRandomItem(select.getOptions());
values.add(new InputValue(option.getText(), true));
}
}
}
@Override
public String getFrameDom(String iframeIdentification) {
try {
switchToFrame(iframeIdentification);
// make a copy of the dom before changing into the top page
String frameDom = browser.getPageSource();
browser.switchTo().defaultContent();
return frameDom;
} catch (WebDriverException e) {
throwIfConnectionException(e);
return "";
}
}
/**
* @param identification
* the identification of the element.
* @return true if the element can be found in the DOM tree.
*/
@Override
public boolean elementExists(Identification identification) {
try {
WebElement el = browser.findElement(identification.getWebDriverBy());
// TODO Stefan; I think el will never be null as a
// NoSuchElementExcpetion will be
// thrown, catched below.
return el != null;
} catch (WebDriverException e) {
throwIfConnectionException(e);
return false;
}
}
/**
* @param identification
* the identification of the element.
* @return the found element.
*/
@Override
public WebElement getWebElement(Identification identification) {
try {
return browser.findElement(identification.getWebDriverBy());
} catch (WebDriverException e) {
throw wrapWebDriverExceptionIfConnectionException(e);
}
}
/**
* @return the period to wait after an event.
*/
protected long getCrawlWaitEvent() {
return crawlWaitEvent;
}
/**
* @return the list of attributes to be filtered from DOM.
*/
protected ImmutableSortedSet<String> getFilterAttributes() {
return filterAttributes;
}
/**
* @return the period to waint after a reload.
*/
protected long getCrawlWaitReload() {
return crawlWaitReload;
}
@Override
public void saveScreenShot(File file) throws CrawljaxException {
try {
File tmpfile = takeScreenShotOnBrowser(browser, OutputType.FILE);
try {
Files.copy(tmpfile, file);
} catch (IOException e) {
throw new CrawljaxException(e);
}
} catch (WebDriverException e) {
throw wrapWebDriverExceptionIfConnectionException(e);
}
}
private <T> T takeScreenShotOnBrowser(WebDriver driver, OutputType<T> outType)
throws CrawljaxException {
if (driver instanceof TakesScreenshot) {
T screenshot = ((TakesScreenshot) driver).getScreenshotAs(outType);
removeCanvasGeneratedByFirefoxDriverForScreenshots();
return screenshot;
} else if (driver instanceof RemoteWebDriver) {
WebDriver augmentedWebdriver = new Augmenter().augment(driver);
return takeScreenShotOnBrowser(augmentedWebdriver, outType);
} else if (driver instanceof WrapsDriver) {
return takeScreenShotOnBrowser(((WrapsDriver) driver).getWrappedDriver(), outType);
} else {
throw new CrawljaxException("Your current WebDriver doesn't support screenshots.");
}
}
@Override
public byte[] getScreenShot() throws CrawljaxException {
try {
return takeScreenShotOnBrowser(browser, OutputType.BYTES);
} catch (WebDriverException e) {
throw wrapWebDriverExceptionIfConnectionException(e);
}
}
private void removeCanvasGeneratedByFirefoxDriverForScreenshots() {
String js = "";
js += "var canvas = document.getElementById('fxdriver-screenshot-canvas');";
js += "if(canvas != null){";
js += "canvas.parentNode.removeChild(canvas);";
js += "}";
try {
executeJavaScript(js);
} catch (CrawljaxException e) {
LOGGER.error("Removing of Canvas Generated By FirefoxDriver failed,"
+ " most likely leaving it in the browser", e);
}
}
/**
* @return the WebDriver used as an EmbeddedBrowser.
*/
public WebDriver getBrowser() {
return browser;
}
private boolean exceptionIsConnectionException(WebDriverException exception) {
return exception != null && exception.getCause() != null
&& exception.getCause() instanceof IOException;
}
private RuntimeException wrapWebDriverExceptionIfConnectionException(
WebDriverException exception) {
if (exceptionIsConnectionException(exception)) {
return new BrowserConnectionException(exception);
}
return exception;
}
private void throwIfConnectionException(WebDriverException exception) {
if (exceptionIsConnectionException(exception)) {
throw wrapWebDriverExceptionIfConnectionException(exception);
}
}
}
| mmayorivera/crawljax | core/src/main/java/com/crawljax/browser/WebDriverBackedEmbeddedBrowser.java | Java | apache-2.0 | 26,622 |
package com.wangjie.recyclerview.example;
import com.wangjie.androidinject.annotation.present.AIAppCompatActivity;
/**
* Author: wangjie
* Email: tiantian.china.2@gmail.com
* Date: 7/10/15.
*/
public class BaseActivity extends AIAppCompatActivity{
}
| jackyglony/RecyclerViewSample | example/src/main/java/com/wangjie/recyclerview/example/BaseActivity.java | Java | apache-2.0 | 256 |
package com.linkedin.databus2.producers.ds;
import org.apache.avro.Schema;
/*
*
* Copyright 2013 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. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
public class KeyPair
{
Object key;
Schema.Type keyType;
public Schema.Type getKeyType()
{
return keyType;
}
public Object getKey()
{
return key;
}
public KeyPair(Object key, Schema.Type keyType)
{
this.key = key;
this.keyType = keyType;
}
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
KeyPair keyPair = (KeyPair) o;
if (!key.equals(keyPair.key)) return false;
if (keyType != keyPair.keyType) return false;
return true;
}
@Override
public int hashCode()
{
int result = key.hashCode();
result = 31 * result + keyType.hashCode();
return result;
}
}
| rahuljoshi123/databus | databus2-relay/databus2-event-producer-common/src/main/java/com/linkedin/databus2/producers/ds/KeyPair.java | Java | apache-2.0 | 1,479 |
// 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 __PROCESS_METRICS_METRIC_HPP__
#define __PROCESS_METRICS_METRIC_HPP__
#include <atomic>
#include <memory>
#include <string>
#include <process/future.hpp>
#include <process/owned.hpp>
#include <process/statistics.hpp>
#include <process/timeseries.hpp>
#include <stout/duration.hpp>
#include <stout/option.hpp>
#include <stout/synchronized.hpp>
namespace process {
namespace metrics {
// The base class for Metrics such as Counter and Gauge.
class Metric {
public:
virtual ~Metric() {}
virtual Future<double> value() const = 0;
const std::string& name() const
{
return data->name;
}
Option<Statistics<double>> statistics() const
{
Option<Statistics<double>> statistics = None();
if (data->history.isSome()) {
synchronized (data->lock) {
statistics = Statistics<double>::from(*data->history.get());
}
}
return statistics;
}
protected:
// Only derived classes can construct.
Metric(const std::string& name, const Option<Duration>& window)
: data(new Data(name, window)) {}
// Inserts 'value' into the history for this metric.
void push(double value) {
if (data->history.isSome()) {
Time now = Clock::now();
synchronized (data->lock) {
data->history.get()->set(value, now);
}
}
}
private:
struct Data {
Data(const std::string& _name, const Option<Duration>& window)
: name(_name),
history(None())
{
if (window.isSome()) {
history =
Owned<TimeSeries<double>>(new TimeSeries<double>(window.get()));
}
}
const std::string name;
std::atomic_flag lock = ATOMIC_FLAG_INIT;
Option<Owned<TimeSeries<double>>> history;
};
std::shared_ptr<Data> data;
};
} // namespace metrics {
} // namespace process {
#endif // __PROCESS_METRICS_METRIC_HPP__
| ruhip/mesos1.0.1_20170518 | 3rdparty/libprocess/include/process/metrics/metric.hpp | C++ | apache-2.0 | 2,391 |
<?php
/**
* Directory utilities.
*
* Copyright: © 2009-2011
* {@link http://www.websharks-inc.com/ WebSharks, Inc.}
* (coded in the USA)
*
* Released under the terms of the GNU General Public License.
* You should have received a copy of the GNU General Public License,
* along with this software. In the main directory, see: /licensing/
* If not, see: {@link http://www.gnu.org/licenses/}.
*
* @package s2Member\Utilities
* @since 3.5
*/
if(!defined('WPINC')) // MUST have WordPress.
exit ("Do not access this file directly.");
if (!class_exists ("c_ws_plugin__s2member_utils_dirs"))
{
/**
* Directory utilities.
*
* @package s2Member\Utilities
* @since 3.5
*/
class c_ws_plugin__s2member_utils_dirs
{
/**
* Normalizes directory separators in dir/file paths.
*
* @package s2Member\Utilities
* @since 111017
*
* @param string $path Directory or file path.
* @return string Directory or file path, after having been normalized by this routine.
*/
public static function n_dir_seps ($path = FALSE)
{
return rtrim (preg_replace ("/\/+/", "/", str_replace (array(DIRECTORY_SEPARATOR, "\\", "/"), "/", (string)$path)), "/");
}
/**
* Strips a trailing `/app_data/` sub-directory.
*
* @package s2Member\Utilities
* @since 3.5
*
* @param string $path Directory or file path.
* @return string Directory or file path without `/app_data/`.
*/
public static function strip_dir_app_data ($path = FALSE)
{
return preg_replace ("/\/app_data$/", "", c_ws_plugin__s2member_utils_dirs::n_dir_seps ((string)$path));
}
/**
* Basename from a full directory or file path.
*
* @package s2Member\Utilities
* @since 110815
*
* @param string $path Directory or file path.
* @return string Basename; including a possible `/app_data/` directory.
*/
public static function basename_dir_app_data ($path = FALSE)
{
$path = preg_replace ("/\/app_data$/", "", c_ws_plugin__s2member_utils_dirs::n_dir_seps ((string)$path), 1, $app_data);
return basename ($path) . (($app_data) ? "/app_data" : "");
}
/**
* Shortens to a directory or file path, from document root.
*
* @package s2Member\Utilities
* @since 110815
*
* @param string $path Directory or file path.
* @return string Shorther path, from document root.
*/
public static function doc_root_path ($path = FALSE)
{
$doc_root = c_ws_plugin__s2member_utils_dirs::n_dir_seps ($_SERVER["DOCUMENT_ROOT"]);
return preg_replace ("/^" . preg_quote ($doc_root, "/") . "/", "", c_ws_plugin__s2member_utils_dirs::n_dir_seps ((string)$path));
}
/**
* Finds the relative path, from one location to another.
*
* @package s2Member\Utilities
* @since 110815
*
* @param string $from The full directory path to calculate a relative path `from`.
* @param string $to The full directory or file path, which this routine will build a relative path `to`.
* @param bool $try_realpaths Defaults to true. When true, try to acquire ``realpath()``, thereby resolving all relative paths and/or symlinks in ``$from`` and ``$to`` args.
* @param bool $use_win_diff_drive_jctn Defaults to true. When true, we'll work around issues with different drives on Windows by trying to create a directory junction.
* @return string String with the relative path to: ``$to``.
*/
public static function rel_path ($from = FALSE, $to = FALSE, $try_realpaths = TRUE, $use_win_diff_drive_jctn = TRUE)
{
if ( /* Initialize/validate. */!($rel_path = array()) && is_string ($from) && strlen ($from) && is_string ($to) && strlen ($to))
{
$from = ($try_realpaths && ($_real_from = realpath ($from))) ? $_real_from : $from; // Try this?
$to = ($try_realpaths && ($_real_to = realpath ($to))) ? $_real_to : $to; // Try to find realpath?
$from = (is_file ($from)) ? dirname ($from) . "/" : $from . "/"; // A (directory) with trailing `/`.
$from = c_ws_plugin__s2member_utils_dirs::n_dir_seps ($from); // Normalize directory separators now.
$to = c_ws_plugin__s2member_utils_dirs::n_dir_seps ($to); // Normalize directory separators here too.
$from = preg_split ("/\//", $from); // Convert ``$from``, to an array. Split on each directory separator.
$to = preg_split ("/\//", $to); // Also convert ``$to``, to an array. Split this on each directory separator.
if ($use_win_diff_drive_jctn && stripos (PHP_OS, "win") === 0 /* Test for different drives on Windows servers? */)
if (/*Drive? */preg_match ("/^([A-Z])\:$/i", $from[0], $_m) && ($_from_drive = $_m[1]) && preg_match ("/^([A-Z])\:$/i", $to[0], $_m) && ($_to_drive = $_m[1]))
if ( /* Are these locations on completely different drives? */$_from_drive !== $_to_drive)
{
$_from_drive_jctn = $_from_drive . ":/s2-" . $_to_drive . "-jctn";
$_sys_temp_dir_jctn = c_ws_plugin__s2member_utils_dirs::get_temp_dir (false) . "/s2-" . $_to_drive . "-jctn";
$_jctn = ($_sys_temp_dir_jctn && strpos ($_sys_temp_dir_jctn, $_from_drive) === 0) ? $_sys_temp_dir_jctn : $_from_drive_jctn;
if (($_from_drive_jctn_exists = (is_dir ($_from_drive_jctn)) ? true : false) || c_ws_plugin__s2member_utils_dirs::create_win_jctn ($_jctn, $_to_drive . ":/"))
{
array_shift /* Shift drive off and use junction now. */ ($to);
foreach (array_reverse (preg_split ("/\//", (($_from_drive_jctn_exists) ? $_from_drive_jctn : $_jctn))) as $_jctn_dir)
array_unshift ($to, $_jctn_dir);
}
else // Else, we should trigger an error in this case. It's NOT possible to generate this.
{
trigger_error ("Unable to generate a relative path across different Windows drives." .
" Please create a Directory Junction here: " . $_from_drive_jctn . ", pointing to: " . $_to_drive . ":/", E_USER_ERROR);
}
}
unset($_real_from, $_real_to, $_from_drive, $_to_drive, $_from_drive_jctn, $_sys_temp_dir_jctn, $_jctn, $_from_drive_jctn_exists, $_jctn_dir, $_m);
$rel_path = $to; // Re-initialize. Start ``$rel_path`` as the value of the ``$to`` array.
foreach (array_keys ($from) as $_depth) // Each ``$from`` directory ``$_depth``.
{
if (isset ($from[$_depth], $to[$_depth]) && $from[$_depth] === $to[$_depth])
array_shift ($rel_path);
else if (($_remaining = count ($from) - $_depth) > 1)
{
$_left_p = -1 * (count ($rel_path) + ($_remaining - 1));
$rel_path = array_pad ($rel_path, $_left_p, "..");
break; // Stop now, no need to go any further.
}
else // Else, set as the same directory `./[0]`.
{
$rel_path[0] = "./" . $rel_path[0];
break; // Stop now.
}
}
}
return implode ("/", $rel_path);
}
/**
* Creates a directory Junction in Windows.
*
* @package s2Member\Utilities
* @since 111013
*
* @param string $jctn Directory location of the Junction (i.e., the link).
* @param string $target Target directory that this Junction will connect to.
* @return bool True if created successfully, or already exists, else false.
*/
public static function create_win_jctn ($jctn = FALSE, $target = FALSE)
{
if ($jctn && is_string ($jctn) && $target && is_string ($target) && stripos (PHP_OS, "win") === 0)
{
if (is_dir ($jctn)) // Does it already exist? If so return now.
return true; // Return now to save extra processing time below.
else if ( /* Possible? */function_exists ("shell_exec") && ($esa = "escapeshellarg"))
{
@shell_exec ("mklink /J " . $esa ($jctn) . " " . $esa ($target));
clearstatcache (); // Clear ``stat()`` cache now.
if (is_dir ($jctn)) // Created successfully?
return true;
}
}
return false; // Else return false.
}
/**
* Get the system's temporary directory.
*
* @package s2Member\Utilities
* @since 111017
*
* @param string $fallback Defaults to true. If true, fallback on WordPress routine if not available, or if not writable.
* @return str|bool Full string path to a writable temp directory, else false on failure.
*/
public static function get_temp_dir ($fallback = TRUE)
{
$temp_dir = (($temp_dir = realpath (sys_get_temp_dir ())) && is_writable ($temp_dir)) ? $temp_dir : false;
$temp_dir = (!$temp_dir && $fallback && ($wp_temp_dir = realpath (get_temp_dir ())) && is_writable ($wp_temp_dir)) ? $wp_temp_dir : $temp_dir;
return ($temp_dir) ? c_ws_plugin__s2member_utils_dirs::n_dir_seps ($temp_dir) : false;
}
}
}
| Juni4567/meritscholarship | wp-content/plugins3/s2member/includes/classes/utils-dirs.inc.php | PHP | apache-2.0 | 8,976 |
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* 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.
*/
package io.netty.example.udt.echo.rendezvousBytes;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.udt.nio.NioUdtProvider;
/**
* Handler implementation for the echo client. It initiates the ping-pong
* traffic between the echo client and server by sending the first message to
* the server on activation.
*/
public class ByteEchoPeerHandler extends SimpleChannelInboundHandler<ByteBuf> {
private final ByteBuf message;
public ByteEchoPeerHandler(final int messageSize) {
super(false);
message = Unpooled.buffer(messageSize);
for (int i = 0; i < message.capacity(); i++) {
message.writeByte((byte) i);
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
System.err.println("ECHO active " + NioUdtProvider.socketUDT(ctx.channel()).toStringOptions());
ctx.writeAndFlush(message);
}
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) {
ctx.write(buf);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
| NiteshKant/netty | example/src/main/java/io/netty/example/udt/echo/rendezvousBytes/ByteEchoPeerHandler.java | Java | apache-2.0 | 2,044 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/data_reduction_proxy/content/browser/content_lofi_decider.h"
#include <string>
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_headers.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h"
#include "content/public/browser/resource_request_info.h"
#include "net/base/load_flags.h"
#include "net/http/http_request_headers.h"
namespace data_reduction_proxy {
ContentLoFiDecider::ContentLoFiDecider() {}
ContentLoFiDecider::~ContentLoFiDecider() {}
bool ContentLoFiDecider::IsUsingLoFiMode(const net::URLRequest& request) const {
const content::ResourceRequestInfo* request_info =
content::ResourceRequestInfo::ForRequest(&request);
// The Lo-Fi directive should not be added for users in the Lo-Fi field
// trial "Control" group. Check that the user is in a group that can get
// "q=low".
bool lofi_enabled_via_flag_or_field_trial =
params::IsLoFiOnViaFlags() || params::IsIncludedInLoFiEnabledFieldTrial();
// Return if the user is using Lo-Fi and not part of the "Control" group.
if (request_info)
return request_info->IsUsingLoFi() && lofi_enabled_via_flag_or_field_trial;
return false;
}
bool ContentLoFiDecider::MaybeAddLoFiDirectiveToHeaders(
const net::URLRequest& request,
net::HttpRequestHeaders* headers) const {
const content::ResourceRequestInfo* request_info =
content::ResourceRequestInfo::ForRequest(&request);
if (!request_info)
return false;
// The Lo-Fi directive should not be added for users in the Lo-Fi field
// trial "Control" group. Check that the user is in a group that should
// get "q=low".
bool lofi_enabled_via_flag_or_field_trial =
params::IsLoFiOnViaFlags() || params::IsIncludedInLoFiEnabledFieldTrial();
bool lofi_preview_via_flag_or_field_trial =
params::AreLoFiPreviewsEnabledViaFlags() ||
params::IsIncludedInLoFiPreviewFieldTrial();
std::string header_value;
// User is using Lo-Fi and not part of the "Control" group.
if (request_info->IsUsingLoFi() && lofi_enabled_via_flag_or_field_trial) {
if (headers->HasHeader(chrome_proxy_header())) {
headers->GetHeader(chrome_proxy_header(), &header_value);
headers->RemoveHeader(chrome_proxy_header());
header_value += ", ";
}
// If in the preview field trial or the preview flag is enabled, only add
// the "q=preview" directive on main frame requests. Do not add Lo-Fi
// directives to other requests when previews are enabled. If previews are
// not enabled, add "q=low".
if (lofi_preview_via_flag_or_field_trial) {
if (request.load_flags() & net::LOAD_MAIN_FRAME)
header_value += chrome_proxy_lo_fi_preview_directive();
} else {
header_value += chrome_proxy_lo_fi_directive();
}
headers->SetHeader(chrome_proxy_header(), header_value);
return true;
}
// User is part of Lo-Fi active control experiment.
if (request_info->IsUsingLoFi() &&
params::IsIncludedInLoFiControlFieldTrial()) {
if (headers->HasHeader(chrome_proxy_header())) {
headers->GetHeader(chrome_proxy_header(), &header_value);
headers->RemoveHeader(chrome_proxy_header());
header_value += ", ";
}
header_value += chrome_proxy_lo_fi_experiment_directive();
headers->SetHeader(chrome_proxy_header(), header_value);
}
return false;
}
} // namespace data_reduction_proxy
| js0701/chromium-crosswalk | components/data_reduction_proxy/content/browser/content_lofi_decider.cc | C++ | bsd-3-clause | 3,602 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/search_engines/search_provider_install_state_message_filter.h"
#include "base/bind.h"
#include "base/logging.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/render_messages.h"
#include "content/public/browser/render_process_host.h"
#include "url/gurl.h"
using content::BrowserThread;
SearchProviderInstallStateMessageFilter::
SearchProviderInstallStateMessageFilter(
int render_process_id,
Profile* profile)
: BrowserMessageFilter(ChromeMsgStart),
provider_data_(profile,
content::RenderProcessHost::FromID(render_process_id)),
is_off_the_record_(profile->IsOffTheRecord()),
weak_factory_(this) {
// This is initialized by RenderProcessHostImpl. Do not add any non-trivial
// initialization here. Instead do it lazily when required.
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
bool SearchProviderInstallStateMessageFilter::OnMessageReceived(
const IPC::Message& message) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(SearchProviderInstallStateMessageFilter, message)
IPC_MESSAGE_HANDLER_DELAY_REPLY(
ChromeViewHostMsg_GetSearchProviderInstallState,
OnGetSearchProviderInstallState)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
SearchProviderInstallStateMessageFilter::
~SearchProviderInstallStateMessageFilter() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
}
search_provider::InstallState
SearchProviderInstallStateMessageFilter::GetSearchProviderInstallState(
const GURL& page_location,
const GURL& requested_host) {
GURL requested_origin = requested_host.GetOrigin();
// Do the security check before any others to avoid information leaks.
if (page_location.GetOrigin() != requested_origin)
return search_provider::DENIED;
// In incognito mode, no search information is exposed. (This check must be
// done after the security check or else a web site can detect that the
// user is in incognito mode just by doing a cross origin request.)
if (is_off_the_record_)
return search_provider::NOT_INSTALLED;
switch (provider_data_.GetInstallState(requested_origin)) {
case SearchProviderInstallData::NOT_INSTALLED:
return search_provider::NOT_INSTALLED;
case SearchProviderInstallData::INSTALLED_BUT_NOT_DEFAULT:
return search_provider::INSTALLED_BUT_NOT_DEFAULT;
case SearchProviderInstallData::INSTALLED_AS_DEFAULT:
return search_provider::INSTALLED_AS_DEFAULT;
}
NOTREACHED();
return search_provider::NOT_INSTALLED;
}
void
SearchProviderInstallStateMessageFilter::OnGetSearchProviderInstallState(
const GURL& page_location,
const GURL& requested_host,
IPC::Message* reply_msg) {
provider_data_.CallWhenLoaded(
base::Bind(
&SearchProviderInstallStateMessageFilter::
ReplyWithProviderInstallState,
weak_factory_.GetWeakPtr(),
page_location,
requested_host,
reply_msg));
}
void SearchProviderInstallStateMessageFilter::ReplyWithProviderInstallState(
const GURL& page_location,
const GURL& requested_host,
IPC::Message* reply_msg) {
DCHECK(reply_msg);
search_provider::InstallState install_state =
GetSearchProviderInstallState(page_location, requested_host);
ChromeViewHostMsg_GetSearchProviderInstallState::WriteReplyParams(
reply_msg,
install_state);
Send(reply_msg);
}
| boundarydevices/android_external_chromium_org | chrome/browser/search_engines/search_provider_install_state_message_filter.cc | C++ | bsd-3-clause | 3,699 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/policy/core/browser/browser_policy_connector_base.h"
#include <stddef.h>
#include <utility>
#include <vector>
#include "base/check.h"
#include "components/policy/core/common/chrome_schema.h"
#include "components/policy/core/common/configuration_policy_provider.h"
#include "components/policy/core/common/policy_namespace.h"
#include "components/policy/core/common/policy_service.h"
#include "components/policy/core/common/policy_service_impl.h"
#include "ui/base/resource/resource_bundle.h"
namespace policy {
namespace {
// Used in BrowserPolicyConnectorBase::SetPolicyProviderForTesting.
bool g_created_policy_service = false;
ConfigurationPolicyProvider* g_testing_provider = nullptr;
PolicyService* g_testing_policy_service = nullptr;
} // namespace
BrowserPolicyConnectorBase::BrowserPolicyConnectorBase(
const HandlerListFactory& handler_list_factory) {
// GetPolicyService() must be ready after the constructor is done.
// The connector is created very early during startup, when the browser
// threads aren't running yet; initialize components that need local_state,
// the system request context or other threads (e.g. FILE) at
// SetPolicyProviders().
// Initialize the SchemaRegistry with the Chrome schema before creating any
// of the policy providers in subclasses.
const Schema& chrome_schema = policy::GetChromeSchema();
handler_list_ = handler_list_factory.Run(chrome_schema);
schema_registry_.RegisterComponent(PolicyNamespace(POLICY_DOMAIN_CHROME, ""),
chrome_schema);
}
BrowserPolicyConnectorBase::~BrowserPolicyConnectorBase() {
if (is_initialized()) {
// Shutdown() wasn't invoked by our owner after having called
// SetPolicyProviders(). This usually means it's an early shutdown and
// BrowserProcessImpl::StartTearDown() wasn't invoked.
// Cleanup properly in those cases and avoid crashing the ToastCrasher test.
Shutdown();
}
}
void BrowserPolicyConnectorBase::Shutdown() {
is_initialized_ = false;
if (g_testing_provider)
g_testing_provider->Shutdown();
for (const auto& provider : policy_providers_)
provider->Shutdown();
// Drop g_testing_provider so that tests executed with --single-process-tests
// can call SetPolicyProviderForTesting() again. It is still owned by the
// test.
g_testing_provider = nullptr;
g_created_policy_service = false;
}
const Schema& BrowserPolicyConnectorBase::GetChromeSchema() const {
return policy::GetChromeSchema();
}
CombinedSchemaRegistry* BrowserPolicyConnectorBase::GetSchemaRegistry() {
return &schema_registry_;
}
PolicyService* BrowserPolicyConnectorBase::GetPolicyService() {
if (g_testing_policy_service)
return g_testing_policy_service;
if (policy_service_)
return policy_service_.get();
DCHECK(!is_initialized_);
is_initialized_ = true;
policy_providers_ = CreatePolicyProviders();
if (g_testing_provider)
g_testing_provider->Init(GetSchemaRegistry());
for (const auto& provider : policy_providers_)
provider->Init(GetSchemaRegistry());
g_created_policy_service = true;
policy_service_ =
std::make_unique<PolicyServiceImpl>(GetProvidersForPolicyService());
return policy_service_.get();
}
bool BrowserPolicyConnectorBase::HasPolicyService() {
return g_testing_policy_service || policy_service_;
}
const ConfigurationPolicyHandlerList*
BrowserPolicyConnectorBase::GetHandlerList() const {
return handler_list_.get();
}
std::vector<ConfigurationPolicyProvider*>
BrowserPolicyConnectorBase::GetPolicyProviders() const {
std::vector<ConfigurationPolicyProvider*> providers;
for (const auto& provider : policy_providers_)
providers.push_back(provider.get());
return providers;
}
// static
void BrowserPolicyConnectorBase::SetPolicyProviderForTesting(
ConfigurationPolicyProvider* provider) {
// If this function is used by a test then it must be called before the
// browser is created, and GetPolicyService() gets called.
CHECK(!g_created_policy_service);
g_testing_provider = provider;
}
// static
void BrowserPolicyConnectorBase::SetPolicyServiceForTesting(
PolicyService* policy_service) {
g_testing_policy_service = policy_service;
}
void BrowserPolicyConnectorBase::NotifyWhenResourceBundleReady(
base::OnceClosure closure) {
DCHECK(!ui::ResourceBundle::HasSharedInstance());
resource_bundle_callbacks_.push_back(std::move(closure));
}
// static
ConfigurationPolicyProvider*
BrowserPolicyConnectorBase::GetPolicyProviderForTesting() {
return g_testing_provider;
}
std::vector<ConfigurationPolicyProvider*>
BrowserPolicyConnectorBase::GetProvidersForPolicyService() {
std::vector<ConfigurationPolicyProvider*> providers;
if (g_testing_provider) {
providers.push_back(g_testing_provider);
return providers;
}
providers.reserve(policy_providers_.size());
for (const auto& policy : policy_providers_)
providers.push_back(policy.get());
return providers;
}
std::vector<std::unique_ptr<ConfigurationPolicyProvider>>
BrowserPolicyConnectorBase::CreatePolicyProviders() {
return {};
}
void BrowserPolicyConnectorBase::OnResourceBundleCreated() {
std::vector<base::OnceClosure> resource_bundle_callbacks;
std::swap(resource_bundle_callbacks, resource_bundle_callbacks_);
for (auto& closure : resource_bundle_callbacks)
std::move(closure).Run();
}
} // namespace policy
| chromium/chromium | components/policy/core/browser/browser_policy_connector_base.cc | C++ | bsd-3-clause | 5,589 |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import collections
import logging
import os
import tempfile
import types
from pylib import cmd_helper
from pylib import constants
from pylib.utils import device_temp_file
HashAndPath = collections.namedtuple('HashAndPath', ['hash', 'path'])
MD5SUM_DEVICE_LIB_PATH = '/data/local/tmp/md5sum/'
MD5SUM_DEVICE_BIN_PATH = MD5SUM_DEVICE_LIB_PATH + 'md5sum_bin'
MD5SUM_DEVICE_SCRIPT_FORMAT = (
'test -f {path} -o -d {path} '
'&& LD_LIBRARY_PATH={md5sum_lib} {md5sum_bin} {path}')
def CalculateHostMd5Sums(paths):
"""Calculates the MD5 sum value for all items in |paths|.
Args:
paths: A list of host paths to md5sum.
Returns:
A list of named tuples with 'hash' and 'path' attributes.
"""
if isinstance(paths, basestring):
paths = [paths]
out = cmd_helper.GetCmdOutput(
[os.path.join(constants.GetOutDirectory(), 'md5sum_bin_host')] +
[p for p in paths])
return [HashAndPath(*l.split(None, 1)) for l in out.splitlines()]
def CalculateDeviceMd5Sums(paths, device):
"""Calculates the MD5 sum value for all items in |paths|.
Args:
paths: A list of device paths to md5sum.
Returns:
A list of named tuples with 'hash' and 'path' attributes.
"""
if isinstance(paths, basestring):
paths = [paths]
if not device.FileExists(MD5SUM_DEVICE_BIN_PATH):
device.adb.Push(
os.path.join(constants.GetOutDirectory(), 'md5sum_dist'),
MD5SUM_DEVICE_LIB_PATH)
out = []
with tempfile.NamedTemporaryFile() as md5sum_script_file:
with device_temp_file.DeviceTempFile(
device.adb) as md5sum_device_script_file:
md5sum_script = (
MD5SUM_DEVICE_SCRIPT_FORMAT.format(
path=p, md5sum_lib=MD5SUM_DEVICE_LIB_PATH,
md5sum_bin=MD5SUM_DEVICE_BIN_PATH)
for p in paths)
md5sum_script_file.write('; '.join(md5sum_script))
md5sum_script_file.flush()
device.adb.Push(md5sum_script_file.name, md5sum_device_script_file.name)
out = device.RunShellCommand(['sh', md5sum_device_script_file.name])
return [HashAndPath(*l.split(None, 1)) for l in out]
| mxOBS/deb-pkg_trusty_chromium-browser | build/android/pylib/utils/md5sum.py | Python | bsd-3-clause | 2,266 |
/**
* Copyright (C) 2015 Dato, Inc.
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
#ifndef GRAPHLAB_SFRAME_QUERY_ENGINE_INFER_OPERATOR_FIELD_H_
#define GRAPHLAB_SFRAME_QUERY_ENGINE_INFER_OPERATOR_FIELD_H_
#include <logger/assertions.hpp>
#include <memory>
#include <vector>
#include <string>
#include <flexible_type/flexible_type.hpp>
namespace graphlab { namespace query_eval {
struct planner_node;
class query_operator;
struct query_operator_attributes;
/**
* An enumeration of all operator types.
*/
enum class planner_node_type : int {
CONSTANT_NODE,
APPEND_NODE,
BINARY_TRANSFORM_NODE,
LOGICAL_FILTER_NODE,
PROJECT_NODE,
RANGE_NODE,
SARRAY_SOURCE_NODE,
SFRAME_SOURCE_NODE,
TRANSFORM_NODE,
LAMBDA_TRANSFORM_NODE,
GENERALIZED_TRANSFORM_NODE,
UNION_NODE,
GENERALIZED_UNION_PROJECT_NODE,
REDUCE_NODE,
// These are used as logical-node-only types. Do not actually become an operator.
IDENTITY_NODE,
// used to denote an invalid node type. Must always be last.
INVALID
};
/**
* Infers the type schema of a planner node by backtracking its
* dependencies.
*/
std::vector<flex_type_enum> infer_planner_node_type(std::shared_ptr<planner_node> pnode);
/**
* Infers the length of the output of a planner node by backtracking its
* dependencies.
*
* Returns -1 if the length cannot be computed without an actual execution.
*/
int64_t infer_planner_node_length(std::shared_ptr<planner_node> pnode);
/**
* Infers the number of columns present in the output.
*/
size_t infer_planner_node_num_output_columns(std::shared_ptr<planner_node> pnode);
/** Returns the number of nodes in this planning graph, including pnode.
*/
size_t infer_planner_node_num_dependency_nodes(std::shared_ptr<planner_node> pnode);
/**
* Transforms a planner node into the operator.
*/
std::shared_ptr<query_operator> planner_node_to_operator(std::shared_ptr<planner_node> pnode);
/** Get the name of the node from the type.
*/
std::string planner_node_type_to_name(planner_node_type type);
/** Get the type of the node from the name.
*/
planner_node_type planner_node_name_to_type(const std::string& name);
/** Get the attribute struct from the type.
*/
query_operator_attributes planner_node_type_to_attributes(planner_node_type type);
////////////////////////////////////////////////////////////////////////////////
/** This operator consumes all inputs at the same rate, and there
* is exactly one row for every input row.
*/
bool consumes_inputs_at_same_rates(const query_operator_attributes& attr);
bool consumes_inputs_at_same_rates(const std::shared_ptr<planner_node>& n);
////////////////////////////////////////////////////////////////////////////////
/** A collection of flags used in actually doing the query
* optimization.
*/
bool is_linear_transform(const query_operator_attributes& attr);
bool is_linear_transform(const std::shared_ptr<planner_node>& n);
////////////////////////////////////////////////////////////////////////////////
/** This operator consumes all inputs at the same rate, but reduces
* the rows in the output.
*/
bool is_sublinear_transform(const query_operator_attributes& attr);
bool is_sublinear_transform(const std::shared_ptr<planner_node>& n);
////////////////////////////////////////////////////////////////////////////////
/**
* This operator is a source node.
*/
bool is_source_node(const query_operator_attributes& attr);
bool is_source_node(const std::shared_ptr<planner_node>& n);
/** Returns true if the output of this node can be parallel sliceable
* by the sources on this block, and false otherwise.
*/
bool is_parallel_slicable(const std::shared_ptr<planner_node>& n);
/** Returns a set of integers giving the different parallel slicable
* units for the inputs of a particular node. If
*/
std::vector<size_t> get_parallel_slicable_codes(const std::shared_ptr<planner_node>& n);
typedef std::function<std::string(std::shared_ptr<planner_node>)> pnode_tagger;
/** Representation of the node as a string.
*/
std::string planner_node_repr(const std::shared_ptr<planner_node>& node);
std::ostream& operator<<(std::ostream&,
const std::shared_ptr<planner_node>& node);
}}
#endif /* _INFER_OPERATOR_FIELD_H_ */
| jasonyaw/SFrame | oss_src/sframe_query_engine/operators/operator_properties.hpp | C++ | bsd-3-clause | 4,422 |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from urllib.parse import parse_qs
from urllib.request import urlopen
from astropy.utils.data import get_pkg_data_contents
from .standard_profile import (SAMPSimpleXMLRPCRequestHandler,
ThreadingXMLRPCServer)
__all__ = []
CROSS_DOMAIN = get_pkg_data_contents('data/crossdomain.xml')
CLIENT_ACCESS_POLICY = get_pkg_data_contents('data/clientaccesspolicy.xml')
class WebProfileRequestHandler(SAMPSimpleXMLRPCRequestHandler):
"""
Handler of XMLRPC requests performed through the Web Profile.
"""
def _send_CORS_header(self):
if self.headers.get('Origin') is not None:
method = self.headers.get('Access-Control-Request-Method')
if method and self.command == "OPTIONS":
# Preflight method
self.send_header('Content-Length', '0')
self.send_header('Access-Control-Allow-Origin',
self.headers.get('Origin'))
self.send_header('Access-Control-Allow-Methods', method)
self.send_header('Access-Control-Allow-Headers', 'Content-Type')
self.send_header('Access-Control-Allow-Credentials', 'true')
else:
# Simple method
self.send_header('Access-Control-Allow-Origin',
self.headers.get('Origin'))
self.send_header('Access-Control-Allow-Headers', 'Content-Type')
self.send_header('Access-Control-Allow-Credentials', 'true')
def end_headers(self):
self._send_CORS_header()
SAMPSimpleXMLRPCRequestHandler.end_headers(self)
def _serve_cross_domain_xml(self):
cross_domain = False
if self.path == "/crossdomain.xml":
# Adobe standard
response = CROSS_DOMAIN
self.send_response(200, 'OK')
self.send_header('Content-Type', 'text/x-cross-domain-policy')
self.send_header("Content-Length", f"{len(response)}")
self.end_headers()
self.wfile.write(response.encode('utf-8'))
self.wfile.flush()
cross_domain = True
elif self.path == "/clientaccesspolicy.xml":
# Microsoft standard
response = CLIENT_ACCESS_POLICY
self.send_response(200, 'OK')
self.send_header('Content-Type', 'text/xml')
self.send_header("Content-Length", f"{len(response)}")
self.end_headers()
self.wfile.write(response.encode('utf-8'))
self.wfile.flush()
cross_domain = True
return cross_domain
def do_POST(self):
if self._serve_cross_domain_xml():
return
return SAMPSimpleXMLRPCRequestHandler.do_POST(self)
def do_HEAD(self):
if not self.is_http_path_valid():
self.report_404()
return
if self._serve_cross_domain_xml():
return
def do_OPTIONS(self):
self.send_response(200, 'OK')
self.end_headers()
def do_GET(self):
if not self.is_http_path_valid():
self.report_404()
return
split_path = self.path.split('?')
if split_path[0] in [f'/translator/{clid}' for clid in self.server.clients]:
# Request of a file proxying
urlpath = parse_qs(split_path[1])
try:
proxyfile = urlopen(urlpath["ref"][0])
self.send_response(200, 'OK')
self.end_headers()
self.wfile.write(proxyfile.read())
proxyfile.close()
except OSError:
self.report_404()
return
if self._serve_cross_domain_xml():
return
def is_http_path_valid(self):
valid_paths = (["/clientaccesspolicy.xml", "/crossdomain.xml"] +
[f'/translator/{clid}' for clid in self.server.clients])
return self.path.split('?')[0] in valid_paths
class WebProfileXMLRPCServer(ThreadingXMLRPCServer):
"""
XMLRPC server supporting the SAMP Web Profile.
"""
def __init__(self, addr, log=None, requestHandler=WebProfileRequestHandler,
logRequests=True, allow_none=True, encoding=None):
self.clients = []
ThreadingXMLRPCServer.__init__(self, addr, log, requestHandler,
logRequests, allow_none, encoding)
def add_client(self, client_id):
self.clients.append(client_id)
def remove_client(self, client_id):
try:
self.clients.remove(client_id)
except ValueError:
# No warning here because this method gets called for all clients,
# not just web clients, and we expect it to fail for non-web
# clients.
pass
def web_profile_text_dialog(request, queue):
samp_name = "unknown"
if isinstance(request[0], str):
# To support the old protocol version
samp_name = request[0]
else:
samp_name = request[0]["samp.name"]
text = \
f"""A Web application which declares to be
Name: {samp_name}
Origin: {request[2]}
is requesting to be registered with the SAMP Hub.
Pay attention that if you permit its registration, such
application will acquire all current user privileges, like
file read/write.
Do you give your consent? [yes|no]"""
print(text)
answer = input(">>> ")
queue.put(answer.lower() in ["yes", "y"])
| pllim/astropy | astropy/samp/web_profile.py | Python | bsd-3-clause | 5,583 |
/* CertificatePolicies.java -- certificate policy extension.
Copyright (C) 2004 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.java.security.x509.ext;
import gnu.java.security.OID;
import gnu.java.security.der.DER;
import gnu.java.security.der.DERReader;
import gnu.java.security.der.DERValue;
import java.io.IOException;
import java.security.cert.PolicyQualifierInfo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class CertificatePolicies extends Extension.Value
{
// Constants and fields.
// -------------------------------------------------------------------------
public static final OID ID = new OID("2.5.29.32");
private final List policies;
private final Map policyQualifierInfos;
// Constructor.
// -------------------------------------------------------------------------
public CertificatePolicies(final byte[] encoded) throws IOException
{
super(encoded);
DERReader der = new DERReader(encoded);
DERValue pol = der.read();
if (!pol.isConstructed())
throw new IOException("malformed CertificatePolicies");
int len = 0;
LinkedList policyList = new LinkedList();
HashMap qualifierMap = new HashMap();
while (len < pol.getLength())
{
DERValue policyInfo = der.read();
if (!policyInfo.isConstructed())
throw new IOException("malformed PolicyInformation");
DERValue val = der.read();
if (val.getTag() != DER.OBJECT_IDENTIFIER)
throw new IOException("malformed CertPolicyId");
OID policyId = (OID) val.getValue();
policyList.add(policyId);
if (val.getEncodedLength() < policyInfo.getLength())
{
DERValue qual = der.read();
int len2 = 0;
LinkedList quals = new LinkedList();
while (len2 < qual.getLength())
{
val = der.read();
quals.add(new PolicyQualifierInfo(val.getEncoded()));
der.skip(val.getLength());
len2 += val.getEncodedLength();
}
qualifierMap.put(policyId, quals);
}
len += policyInfo.getEncodedLength();
}
policies = Collections.unmodifiableList(policyList);
policyQualifierInfos = Collections.unmodifiableMap(qualifierMap);
}
public CertificatePolicies (final List policies,
final Map policyQualifierInfos)
{
for (Iterator it = policies.iterator(); it.hasNext(); )
if (!(it.next() instanceof OID))
throw new IllegalArgumentException ("policies must be OIDs");
for (Iterator it = policyQualifierInfos.entrySet().iterator(); it.hasNext();)
{
Map.Entry e = (Map.Entry) it.next();
if (!(e.getKey() instanceof OID) || !policies.contains (e.getKey()))
throw new IllegalArgumentException
("policyQualifierInfos keys must be OIDs");
if (!(e.getValue() instanceof List))
throw new IllegalArgumentException
("policyQualifierInfos values must be Lists of PolicyQualifierInfos");
for (Iterator it2 = ((List) e.getValue()).iterator(); it.hasNext(); )
if (!(it2.next() instanceof PolicyQualifierInfo))
throw new IllegalArgumentException
("policyQualifierInfos values must be Lists of PolicyQualifierInfos");
}
this.policies = Collections.unmodifiableList (new ArrayList (policies));
this.policyQualifierInfos = Collections.unmodifiableMap
(new HashMap (policyQualifierInfos));
}
// Instance methods.
// -------------------------------------------------------------------------
public List getPolicies()
{
return policies;
}
public List getPolicyQualifierInfos(OID oid)
{
return (List) policyQualifierInfos.get(oid);
}
public byte[] getEncoded()
{
if (encoded == null)
{
List pol = new ArrayList (policies.size());
for (Iterator it = policies.iterator(); it.hasNext(); )
{
OID policy = (OID) it.next();
List qualifiers = getPolicyQualifierInfos (policy);
List l = new ArrayList (qualifiers == null ? 1 : 2);
l.add (new DERValue (DER.OBJECT_IDENTIFIER, policy));
if (qualifiers != null)
{
List ll = new ArrayList (qualifiers.size());
for (Iterator it2 = qualifiers.iterator(); it.hasNext(); )
{
PolicyQualifierInfo info = (PolicyQualifierInfo) it2.next();
try
{
ll.add (DERReader.read (info.getEncoded()));
}
catch (IOException ioe)
{
}
}
l.add (new DERValue (DER.CONSTRUCTED|DER.SEQUENCE, ll));
}
pol.add (new DERValue (DER.CONSTRUCTED|DER.SEQUENCE, l));
}
encoded = new DERValue (DER.CONSTRUCTED|DER.SEQUENCE, pol).getEncoded();
}
return (byte[]) encoded.clone();
}
public String toString()
{
return CertificatePolicies.class.getName() + " [ policies=" + policies +
" policyQualifierInfos=" + policyQualifierInfos + " ]";
}
}
| shaotuanchen/sunflower_exp | tools/source/gcc-4.2.4/libjava/classpath/gnu/java/security/x509/ext/CertificatePolicies.java | Java | bsd-3-clause | 7,046 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/themes/theme_service_aurax11.h"
#include "base/bind.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/themes/custom_theme_supplier.h"
#include "chrome/common/pref_names.h"
#include "ui/gfx/image/image.h"
#include "ui/native_theme/native_theme_aura.h"
#include "ui/views/linux_ui/linux_ui.h"
namespace {
class SystemThemeX11 : public CustomThemeSupplier {
public:
explicit SystemThemeX11(PrefService* pref_service);
// Overridden from CustomThemeSupplier:
virtual void StartUsingTheme() OVERRIDE;
virtual void StopUsingTheme() OVERRIDE;
virtual bool GetColor(int id, SkColor* color) const OVERRIDE;
virtual gfx::Image GetImageNamed(int id) OVERRIDE;
virtual bool HasCustomImage(int id) const OVERRIDE;
private:
virtual ~SystemThemeX11();
// These pointers are not owned by us.
views::LinuxUI* const linux_ui_;
PrefService* const pref_service_;
DISALLOW_COPY_AND_ASSIGN(SystemThemeX11);
};
SystemThemeX11::SystemThemeX11(PrefService* pref_service)
: CustomThemeSupplier(NATIVE_X11),
linux_ui_(views::LinuxUI::instance()),
pref_service_(pref_service) {}
void SystemThemeX11::StartUsingTheme() {
pref_service_->SetBoolean(prefs::kUsesSystemTheme, true);
// Have the former theme notify its observers of change.
ui::NativeThemeAura::instance()->NotifyObservers();
}
void SystemThemeX11::StopUsingTheme() {
pref_service_->SetBoolean(prefs::kUsesSystemTheme, false);
// Have the former theme notify its observers of change.
if (linux_ui_)
linux_ui_->GetNativeTheme(NULL)->NotifyObservers();
}
bool SystemThemeX11::GetColor(int id, SkColor* color) const {
return linux_ui_ && linux_ui_->GetColor(id, color);
}
gfx::Image SystemThemeX11::GetImageNamed(int id) {
return linux_ui_ ? linux_ui_->GetThemeImageNamed(id) : gfx::Image();
}
bool SystemThemeX11::HasCustomImage(int id) const {
return linux_ui_ && linux_ui_->HasCustomImage(id);
}
SystemThemeX11::~SystemThemeX11() {}
} // namespace
ThemeServiceAuraX11::ThemeServiceAuraX11() {}
ThemeServiceAuraX11::~ThemeServiceAuraX11() {}
bool ThemeServiceAuraX11::ShouldInitWithSystemTheme() const {
return profile()->GetPrefs()->GetBoolean(prefs::kUsesSystemTheme);
}
void ThemeServiceAuraX11::UseSystemTheme() {
SetCustomDefaultTheme(new SystemThemeX11(profile()->GetPrefs()));
}
bool ThemeServiceAuraX11::UsingDefaultTheme() const {
return ThemeService::UsingDefaultTheme() && !UsingSystemTheme();
}
bool ThemeServiceAuraX11::UsingSystemTheme() const {
const CustomThemeSupplier* theme_supplier = get_theme_supplier();
return theme_supplier &&
theme_supplier->get_theme_type() == CustomThemeSupplier::NATIVE_X11;
}
| TeamEOS/external_chromium_org | chrome/browser/themes/theme_service_aurax11.cc | C++ | bsd-3-clause | 2,910 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/extensions/event_filtering_info.h"
#include "base/values.h"
#include "base/json/json_writer.h"
namespace extensions {
EventFilteringInfo::EventFilteringInfo()
: has_url_(false) {
}
EventFilteringInfo::~EventFilteringInfo() {
}
void EventFilteringInfo::SetURL(const GURL& url) {
url_ = url;
has_url_ = true;
}
std::string EventFilteringInfo::AsJSONString() const {
std::string result;
base::DictionaryValue value;
if (has_url_)
value.SetString("url", url_.spec());
base::JSONWriter::Write(&value, &result);
return result;
}
scoped_ptr<base::Value> EventFilteringInfo::AsValue() const {
if (IsEmpty())
return scoped_ptr<base::Value>(base::Value::CreateNullValue());
scoped_ptr<base::DictionaryValue> result(new base::DictionaryValue);
if (has_url_)
result->SetString("url", url_.spec());
return result.PassAs<base::Value>();
}
bool EventFilteringInfo::IsEmpty() const {
return !has_url_;
}
} // namespace extensions
| leiferikb/bitpop-private | chrome/common/extensions/event_filtering_info.cc | C++ | bsd-3-clause | 1,160 |
# encoding: utf-8
module Mongoid #:nodoc
module Hierarchy #:nodoc
extend ActiveSupport::Concern
included do
attr_accessor :_parent
end
# Get all child +Documents+ to this +Document+, going n levels deep if
# necessary. This is used when calling update persistence operations from
# the root document, where changes in the entire tree need to be
# determined. Note that persistence from the embedded documents will
# always be preferred, since they are optimized calls... This operation
# can get expensive in domains with large hierarchies.
#
# @example Get all the document's children.
# person._children
#
# @return [ Array<Document> ] All child documents in the hierarchy.
def _children
@_children ||=
[].tap do |children|
relations.each_pair do |name, metadata|
if metadata.embedded?
without_autobuild do
child = send(name)
Array.wrap(child).each do |doc|
children.push(doc)
children.concat(doc._children) unless metadata.versioned?
end if child
end
end
end
end
end
# Determines if the document is a subclass of another document.
#
# @example Check if the document is a subclass
# Square.new.hereditary?
#
# @return [ true, false ] True if hereditary, false if not.
def hereditary?
self.class.hereditary?
end
# Sets up a child/parent association. This is used for newly created
# objects so they can be properly added to the graph.
#
# @example Set the parent document.
# document.parentize(parent)
#
# @param [ Document ] document The parent document.
#
# @return [ Document ] The parent document.
def parentize(document)
self._parent = document
end
# Remove a child document from this parent. If an embeds one then set to
# nil, otherwise remove from the embeds many.
#
# This is called from the +RemoveEmbedded+ persistence command.
#
# @example Remove the child.
# document.remove_child(child)
#
# @param [ Document ] child The child (embedded) document to remove.
#
# @since 2.0.0.beta.1
def remove_child(child)
name = child.metadata.name
child.embedded_one? ? remove_ivar(name) : send(name).delete_one(child)
end
# After children are persisted we can call this to move all their changes
# and flag them as persisted in one call.
#
# @example Reset the children.
# document.reset_persisted_children
#
# @return [ Array<Document> ] The children.
#
# @since 2.1.0
def reset_persisted_children
_children.each do |child|
child.move_changes
child.new_record = false
end
end
# Return the root document in the object graph. If the current document
# is the root object in the graph it will return self.
#
# @example Get the root document in the hierarchy.
# document._root
#
# @return [ Document ] The root document in the hierarchy.
def _root
object = self
while (object._parent) do object = object._parent; end
object || self
end
module ClassMethods #:nodoc:
# Determines if the document is a subclass of another document.
#
# @example Check if the document is a subclass.
# Square.hereditary?
#
# @return [ true, false ] True if hereditary, false if not.
def hereditary?
Mongoid::Document > superclass
end
end
end
end
| alexmreis/mongoid | lib/mongoid/hierarchy.rb | Ruby | mit | 3,640 |
require 'spec_helper'
describe 'homebrew::formula' do
let(:facts) do
{
:boxen_home => '/opt/boxen',
:boxen_user => 'testuser',
}
end
let(:title) { 'clojure' }
context 'with source provided' do
let(:params) do
{
:source => 'puppet:///modules/whatever/my_special_formula.rb'
}
end
it do
should contain_file('/opt/boxen/homebrew/Library/Taps/boxen-brews/clojure.rb').with({
:source => 'puppet:///modules/whatever/my_special_formula.rb'
})
end
end
context 'without source provided' do
it do
should contain_file('/opt/boxen/homebrew/Library/Taps/boxen-brews/clojure.rb').with({
:source => 'puppet:///modules/main/brews/clojure.rb'
})
end
end
end | joebadmo/puppet-reattachtousernamespace | spec/fixtures/modules/homebrew/spec/defines/homebrew__formula_spec.rb | Ruby | mit | 764 |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Core;
using Umbraco.Core.PropertyEditors;
using umbraco;
using ClientDependency.Core;
using Constants = Umbraco.Core.Constants;
namespace Umbraco.Web.PropertyEditors
{
/// <summary>
/// A property editor to allow the individual selection of pre-defined items.
/// </summary>
/// <remarks>
/// Due to remaining backwards compatible, this stores the id of the drop down item in the database which is why it is marked
/// as INT and we have logic in here to ensure it is formatted correctly including ensuring that the string value is published
/// in cache and not the int ID.
/// </remarks>
[PropertyEditor(Constants.PropertyEditors.DropDownListAlias, "Dropdown list", "dropdown", ValueType = PropertyEditorValueTypes.String, Group = "lists", Icon = "icon-indent", IsDeprecated = true)]
public class DropDownPropertyEditor : DropDownWithKeysPropertyEditor
{
/// <summary>
/// We need to override the value editor so that we can ensure the string value is published in cache and not the integer ID value.
/// </summary>
/// <returns></returns>
protected override PropertyValueEditor CreateValueEditor()
{
return new PublishValueValueEditor(base.CreateValueEditor());
}
}
}
| abryukhov/Umbraco-CMS | src/Umbraco.Web/PropertyEditors/DropDownPropertyEditor.cs | C# | mit | 1,386 |
//---------------------------------------------------------------------
// <copyright file="IEdmIntegerConstantExpression.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
using Microsoft.OData.Edm.Values;
namespace Microsoft.OData.Edm.Expressions
{
/// <summary>
/// Represents an EDM integer constant expression.
/// </summary>
public interface IEdmIntegerConstantExpression : IEdmExpression, IEdmIntegerValue
{
}
}
| hotchandanisagar/odata.net | src/Microsoft.OData.Edm/Interfaces/Expressions/IEdmIntegerConstantExpression.cs | C# | mit | 651 |
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <arith_uint256.h>
#include <clientversion.h>
#include <coins.h>
#include <consensus/consensus.h>
#include <core_io.h>
#include <key_io.h>
#include <policy/rbf.h>
#include <primitives/transaction.h>
#include <script/script.h>
#include <script/sign.h>
#include <script/signingprovider.h>
#include <univalue.h>
#include <util/moneystr.h>
#include <util/rbf.h>
#include <util/strencodings.h>
#include <util/string.h>
#include <util/system.h>
#include <util/translation.h>
#include <atomic>
#include <functional>
#include <memory>
#include <stdio.h>
#include <thread>
#include <boost/algorithm/string.hpp>
static const int CONTINUE_EXECUTION=-1;
const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
static void SetupBitcoinUtilArgs(ArgsManager &argsman)
{
SetupHelpOptions(argsman);
argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
SetupChainParamsBaseOptions(argsman);
}
// This function returns either one of EXIT_ codes when it's expected to stop the process or
// CONTINUE_EXECUTION when it's expected to continue further.
static int AppInitUtil(int argc, char* argv[])
{
SetupBitcoinUtilArgs(gArgs);
std::string error;
if (!gArgs.ParseParameters(argc, argv, error)) {
tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error);
return EXIT_FAILURE;
}
// Check for chain settings (Params() calls are only valid after this clause)
try {
SelectParams(gArgs.GetChainName());
} catch (const std::exception& e) {
tfm::format(std::cerr, "Error: %s\n", e.what());
return EXIT_FAILURE;
}
if (argc < 2 || HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
// First part of help message is specific to this utility
std::string strUsage = PACKAGE_NAME " bitcoin-util utility version " + FormatFullVersion() + "\n";
if (!gArgs.IsArgSet("-version")) {
strUsage += "\n"
"Usage: bitcoin-util [options] [commands] Do stuff\n";
strUsage += "\n" + gArgs.GetHelpMessage();
}
tfm::format(std::cout, "%s", strUsage);
if (argc < 2) {
tfm::format(std::cerr, "Error: too few parameters\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
return CONTINUE_EXECUTION;
}
static void grind_task(uint32_t nBits, CBlockHeader& header_orig, uint32_t offset, uint32_t step, std::atomic<bool>& found)
{
arith_uint256 target;
bool neg, over;
target.SetCompact(nBits, &neg, &over);
if (target == 0 || neg || over) return;
CBlockHeader header = header_orig; // working copy
header.nNonce = offset;
uint32_t finish = std::numeric_limits<uint32_t>::max() - step;
finish = finish - (finish % step) + offset;
while (!found && header.nNonce < finish) {
const uint32_t next = (finish - header.nNonce < 5000*step) ? finish : header.nNonce + 5000*step;
do {
if (UintToArith256(header.GetHash()) <= target) {
if (!found.exchange(true)) {
header_orig.nNonce = header.nNonce;
}
return;
}
header.nNonce += step;
} while(header.nNonce != next);
}
}
static int Grind(int argc, char* argv[], std::string& strPrint)
{
if (argc != 1) {
strPrint = "Must specify block header to grind";
return 1;
}
CBlockHeader header;
if (!DecodeHexBlockHeader(header, argv[0])) {
strPrint = "Could not decode block header";
return 1;
}
uint32_t nBits = header.nBits;
std::atomic<bool> found{false};
std::vector<std::thread> threads;
int n_tasks = std::max(1u, std::thread::hardware_concurrency());
for (int i = 0; i < n_tasks; ++i) {
threads.emplace_back( grind_task, nBits, std::ref(header), i, n_tasks, std::ref(found) );
}
for (auto& t : threads) {
t.join();
}
if (!found) {
strPrint = "Could not satisfy difficulty target";
return 1;
}
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << header;
strPrint = HexStr(ss);
return 0;
}
static int CommandLineUtil(int argc, char* argv[])
{
if (argc <= 1) return 1;
std::string strPrint;
int nRet = 0;
try {
while (argc > 1 && IsSwitchChar(argv[1][0]) && (argv[1][1] != 0)) {
--argc;
++argv;
}
char* command = argv[1];
if (strcmp(command, "grind") == 0) {
nRet = Grind(argc-2, argv+2, strPrint);
} else {
strPrint = strprintf("Unknown command %s", command);
nRet = 1;
}
}
catch (const std::exception& e) {
strPrint = std::string("error: ") + e.what();
nRet = EXIT_FAILURE;
}
catch (...) {
PrintExceptionContinue(nullptr, "CommandLineUtil()");
throw;
}
if (strPrint != "") {
tfm::format(nRet == 0 ? std::cout : std::cerr, "%s\n", strPrint);
}
return nRet;
}
#ifdef WIN32
// Export main() and ensure working ASLR on Windows.
// Exporting a symbol will prevent the linker from stripping
// the .reloc section from the binary, which is a requirement
// for ASLR. This is a temporary workaround until a fixed
// version of binutils is used for releases.
__declspec(dllexport) int main(int argc, char* argv[])
#else
int main(int argc, char* argv[])
#endif
{
SetupEnvironment();
try {
int ret = AppInitUtil(argc, argv);
if (ret != CONTINUE_EXECUTION)
return ret;
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInitUtil()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(nullptr, "AppInitUtil()");
return EXIT_FAILURE;
}
int ret = EXIT_FAILURE;
try {
ret = CommandLineUtil(argc, argv);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "CommandLineUtil()");
} catch (...) {
PrintExceptionContinue(nullptr, "CommandLineUtil()");
}
return ret;
}
| pstratem/bitcoin | src/bitcoin-util.cpp | C++ | mit | 6,424 |
<?php
// Start of uploadprogress v.1.0.3.1
function uploadprogress_get_info () {}
function uploadprogress_get_contents () {}
// End of uploadprogress v.1.0.3.1
?>
| AsaiKen/phpscan | tools/language/php5.4/uploadprogress.php | PHP | mit | 167 |
require 'action_controller'
require 'action_controller/test_process'
require 'will_paginate'
WillPaginate.enable_actionpack
ActionController::Routing::Routes.draw do |map|
map.connect 'dummy/page/:page', :controller => 'dummy'
map.connect ':controller/:action/:id'
end
ActionController::Base.perform_caching = false
class DummyRequest
attr_accessor :symbolized_path_parameters
def initialize
@get = true
@params = {}
@symbolized_path_parameters = { :controller => 'foo', :action => 'bar' }
end
def get?
@get
end
def post
@get = false
end
def relative_url_root
''
end
def params(more = nil)
@params.update(more) if more
@params
end
end
class DummyController
attr_reader :request
attr_accessor :controller_name
def initialize
@request = DummyRequest.new
@url = ActionController::UrlRewriter.new(@request, @request.params)
end
def url_for(params)
@url.rewrite(params)
end
end
module HTML
Node.class_eval do
def inner_text
children.map(&:inner_text).join('')
end
end
Text.class_eval do
def inner_text
self.to_s
end
end
Tag.class_eval do
def inner_text
childless?? '' : super
end
end
end
| technoweenie/mephisto | vendor/gems/will_paginate-2.2.2/test/lib/view_test_process.rb | Ruby | mit | 1,244 |
package com.googlecode.goclipse.ui.navigator;
import java.net.URI;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.ide.FileStoreEditorInput;
import org.eclipse.ui.ide.ResourceUtil;
import org.eclipse.ui.navigator.ILinkHelper;
import org.eclipse.ui.part.FileEditorInput;
/**
* Link IFileStore objects in editors to the selection in the Project Explorer.
*
* @author devoncarew
*/
public class NavigatorLinkHelper implements ILinkHelper {
public NavigatorLinkHelper() {
}
@Override
public void activateEditor(IWorkbenchPage page, IStructuredSelection selection) {
if (selection == null || selection.isEmpty()) {
return;
}
Object element = selection.getFirstElement();
IEditorInput input = null;
if (element instanceof IEditorInput) {
input = (IEditorInput)element;
} else if (element instanceof IFile) {
input = new FileEditorInput((IFile)element);
} else if (element instanceof IFileStore) {
input = new FileStoreEditorInput((IFileStore)element);
}
if (input != null) {
IEditorPart part = page.findEditor(input);
if (part != null) {
page.bringToTop(part);
}
}
}
@Override
public IStructuredSelection findSelection(IEditorInput input) {
IFile file = ResourceUtil.getFile(input);
if (file != null) {
return new StructuredSelection(file);
}
IFileStore fileStore = (IFileStore) input.getAdapter(IFileStore.class);
if (fileStore == null && input instanceof FileStoreEditorInput) {
URI uri = ((FileStoreEditorInput)input).getURI();
try {
fileStore = EFS.getStore(uri);
} catch (CoreException e) {
}
}
if (fileStore != null) {
return new StructuredSelection(fileStore);
}
return StructuredSelection.EMPTY;
}
}
| fredyw/goclipse | plugin_ide.ui/src/com/googlecode/goclipse/ui/navigator/NavigatorLinkHelper.java | Java | epl-1.0 | 2,207 |
/**
* Copyright (c) 2010-2018 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.nibeheatpump.internal.protocol;
/**
* The {@link NibeHeatPumpProtocolState} define interface for Nibe protocol state machine.
*
*
* @author Pauli Anttila - Initial contribution
*/
public interface NibeHeatPumpProtocolState {
/**
* @return true to keep processing, false to read more data.
*/
boolean process(NibeHeatPumpProtocolContext context);
}
| johannrichard/openhab2-addons | addons/binding/org.openhab.binding.nibeheatpump/src/main/java/org/openhab/binding/nibeheatpump/internal/protocol/NibeHeatPumpProtocolState.java | Java | epl-1.0 | 721 |
<?php
/**
* File containing the TextLine Value class
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
* @version //autogentag//
*/
namespace eZ\Publish\Core\FieldType\TextLine;
use eZ\Publish\Core\FieldType\Value as BaseValue;
/**
* Value for TextLine field type
*/
class Value extends BaseValue
{
/**
* Text content
*
* @var string
*/
public $text;
/**
* Construct a new Value object and initialize it $text
*
* @param string $text
*/
public function __construct( $text = '' )
{
$this->text = $text;
}
/**
* @see \eZ\Publish\Core\FieldType\Value
*/
public function __toString()
{
return (string)$this->text;
}
}
| vidarl/ezpublish-kernel | eZ/Publish/Core/FieldType/TextLine/Value.php | PHP | gpl-2.0 | 855 |
<?php
/*
+---------------------------------------------------------------------------+
| Revive Adserver |
| http://www.revive-adserver.com |
| |
| Copyright: See the COPYRIGHT.txt file. |
| License: GPLv2 or later, see the LICENSE.txt file. |
+---------------------------------------------------------------------------+
*/
require_once 'demoUI-common.php';
if (isset($_REQUEST['action']) && in_array($_REQUEST['action'],array('1','2','3','4','4-1', '4-2')))
{
$i = $_REQUEST['action'];
$message = $GLOBALS['_MAX']['CONF']['demoUserInterface']['message'.$i];
$menu = 'demo-menu-'.$i;
switch ($i)
{
case '4':
OA_Permission::enforceAccount(OA_ACCOUNT_ADMIN);
break;
case '3':
OA_Permission::enforceAccount(OA_ACCOUNT_MANAGER);
break;
case '2':
OA_Permission::enforceAccount(OA_ACCOUNT_MANAGER, OA_ACCOUNT_ADMIN);
break;
case '4-1':
OA_Permission::enforceAccount(OA_ACCOUNT_ADMIN);
$message = 'Dynamic submenu 4-1';
$menu = 'demo-menu-4'; // PageHeader function needs to know the *parent* menu
setCurrentLeftMenuSubItem('demo-menu-4-1');
break;
case '4-2':
OA_Permission::enforceAccount(OA_ACCOUNT_ADMIN);
$message = 'Dynamic submenu 4-2';
$menu = 'demo-menu-4'; // PageHeader function needs to know the *parent* menu
setCurrentLeftMenuSubItem('demo-menu-4-2');
break;
}
$colour = $GLOBALS['_MAX']['PREF']['demoUserInterface_demopref_'.OA_Permission::getAccountType(true)];
//$image = 'demoUI'.$i.'.jpg';
$message = $message;
addLeftMenuSubItem('demo-menu-4-1', 'demo submenu 4-1', 'plugins/demoUserInterface/demoUI-page.php?action=4-1');
addLeftMenuSubItem('demo-menu-4-2', 'demo submenu 4-2', 'plugins/demoUserInterface/demoUI-page.php?action=4-2');
phpAds_PageHeader($menu,'','../../');
$oTpl = new OA_Plugin_Template('demoUI.html','demoUserInterface');
//$oTpl->assign('image',$image);
$oTpl->assign('message',$message);
$oTpl->assign('colour',$colour);
$oTpl->display();
phpAds_PageFooter();
}
else
{
require_once LIB_PATH . '/Admin/Redirect.php';
OX_Admin_Redirect::redirect('plugins/demoUserInterface/demoUI-index.php');
}
?> | Tate-ad/revive-adserver | plugins_repo/demoExtension/www/admin/plugins/demoUserInterface/demoUI-page.php | PHP | gpl-2.0 | 2,592 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Adminhtml
* @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
class Mage_Adminhtml_Model_System_Config_Source_Language
{
protected $_options;
public function toOptionArray($isMultiselect)
{
if (!$this->_options) {
$this->_options = Mage::getResourceModel('core/language_collection')->loadData()->toOptionArray();
}
$options = $this->_options;
if(!$isMultiselect){
array_unshift($options, array('value'=>'', 'label'=>''));
}
return $options;
}
}
| keegan2149/magento | sites/default/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Language.php | PHP | gpl-2.0 | 1,443 |
<?php
/**
* Provides a plugin for the '@type' meta tag.
*/
class SchemaImageObjectType extends SchemaTypeBase {
/**
* {@inheritdoc}
*/
public static function labels() {
return [
'ImageObject',
];
}
}
| charlie59/non-texas-2 | sites/all/modules/schema_metatag/schema_image_object/src/SchemaImageObjectType.php | PHP | gpl-2.0 | 231 |
/*
* Copyright (C) 2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "DirectoryProvider.h"
#include "filesystem/Directory.h"
#include "filesystem/FavouritesDirectory.h"
#include "guilib/GUIWindowManager.h"
#include "utils/JobManager.h"
#include "utils/XMLUtils.h"
#include "utils/URIUtils.h"
#include "threads/SingleLock.h"
#include "FileItem.h"
#include "video/VideoThumbLoader.h"
#include "music/MusicThumbLoader.h"
#include "pictures/PictureThumbLoader.h"
#include "interfaces/AnnouncementManager.h"
#include <memory>
using namespace std;
using namespace XFILE;
using namespace ANNOUNCEMENT;
class CDirectoryJob : public CJob
{
public:
CDirectoryJob(const std::string &url, int limit, int parentID)
: m_url(url), m_limit(limit), m_parentID(parentID) {};
virtual ~CDirectoryJob() {};
virtual const char* GetType() const { return "directory"; };
virtual bool operator==(const CJob *job) const
{
if (strcmp(job->GetType(),GetType()) == 0)
{
const CDirectoryJob* dirJob = dynamic_cast<const CDirectoryJob*>(job);
if (dirJob && dirJob->m_url == m_url)
return true;
}
return false;
}
virtual bool DoWork()
{
CFileItemList items;
if (CDirectory::GetDirectory(m_url, items, ""))
{
// limit must not exceed the number of items
int limit = (m_limit == 0) ? items.Size() : min((int) m_limit, items.Size());
// convert to CGUIStaticItem's and set visibility and targets
m_items.reserve(limit);
for (int i = 0; i < limit; i++)
{
CGUIStaticItemPtr item(new CGUIStaticItem(*items[i]));
if (item->HasProperty("node.visible"))
item->SetVisibleCondition(item->GetProperty("node.visible").asString(), m_parentID);
getThumbLoader(item)->LoadItem(item.get());
m_items.push_back(item);
}
m_target = items.GetProperty("node.target").asString();
}
return true;
}
std::shared_ptr<CThumbLoader> getThumbLoader(CGUIStaticItemPtr &item)
{
if (item->IsVideo())
{
initThumbLoader<CVideoThumbLoader>(VIDEO);
return m_thumbloaders[VIDEO];
}
if (item->IsAudio())
{
initThumbLoader<CMusicThumbLoader>(AUDIO);
return m_thumbloaders[AUDIO];
}
if (item->IsPicture())
{
initThumbLoader<CPictureThumbLoader>(PICTURE);
return m_thumbloaders[PICTURE];
}
initThumbLoader<CProgramThumbLoader>(PROGRAM);
return m_thumbloaders[PROGRAM];
}
template<class CThumbLoaderClass>
void initThumbLoader(InfoTagType type)
{
if (!m_thumbloaders.count(type))
{
std::shared_ptr<CThumbLoader> thumbLoader = std::make_shared<CThumbLoaderClass>();
thumbLoader->OnLoaderStart();
m_thumbloaders.insert(make_pair(type, thumbLoader));
}
}
const std::vector<CGUIStaticItemPtr> &GetItems() const { return m_items; }
const std::string &GetTarget() const { return m_target; }
std::vector<InfoTagType> GetItemTypes(std::vector<InfoTagType> &itemTypes) const
{
itemTypes.clear();
for (std::map<InfoTagType, std::shared_ptr<CThumbLoader> >::const_iterator
i = m_thumbloaders.begin(); i != m_thumbloaders.end(); ++i)
itemTypes.push_back(i->first);
return itemTypes;
}
private:
std::string m_url;
std::string m_target;
unsigned int m_limit;
int m_parentID;
std::vector<CGUIStaticItemPtr> m_items;
std::map<InfoTagType, std::shared_ptr<CThumbLoader> > m_thumbloaders;
};
CDirectoryProvider::CDirectoryProvider(const TiXmlElement *element, int parentID)
: IListProvider(parentID),
m_updateTime(0),
m_updateState(OK),
m_isAnnounced(false),
m_jobID(0),
m_currentLimit(0)
{
assert(element);
if (!element->NoChildren())
{
const char *target = element->Attribute("target");
if (target)
m_target.SetLabel(target, "", parentID);
const char *limit = element->Attribute("limit");
if (limit)
m_limit.SetLabel(limit, "", parentID);
m_url.SetLabel(element->FirstChild()->ValueStr(), "", parentID);
}
}
CDirectoryProvider::~CDirectoryProvider()
{
Reset(true);
}
bool CDirectoryProvider::Update(bool forceRefresh)
{
// we never need to force refresh here
bool changed = false;
bool fireJob = false;
{
CSingleLock lock(m_section);
if (m_updateState == DONE)
changed = true;
else if (m_updateState == PENDING)
fireJob = true;
m_updateState = OK;
}
// update the URL & limit and fire off a new job if needed
fireJob |= UpdateURL();
fireJob |= UpdateLimit();
if (fireJob)
FireJob();
for (vector<CGUIStaticItemPtr>::iterator i = m_items.begin(); i != m_items.end(); ++i)
changed |= (*i)->UpdateVisibility(m_parentID);
return changed; // TODO: Also returned changed if properties are changed (if so, need to update scroll to letter).
}
void CDirectoryProvider::Announce(AnnouncementFlag flag, const char *sender, const char *message, const CVariant &data)
{
// we are only interested in library changes
if ((flag & (VideoLibrary | AudioLibrary)) == 0)
return;
{
CSingleLock lock(m_section);
// we don't need to refresh anything if there are no fitting
// items in this list provider for the announcement flag
if (((flag & VideoLibrary) &&
(std::find(m_itemTypes.begin(), m_itemTypes.end(), VIDEO) == m_itemTypes.end())) ||
((flag & AudioLibrary) &&
(std::find(m_itemTypes.begin(), m_itemTypes.end(), AUDIO) == m_itemTypes.end())))
return;
// if we're in a database transaction, don't bother doing anything just yet
if (data.isMember("transaction") && data["transaction"].asBoolean())
return;
// if there was a database update, we set the update state
// to PENDING to fire off a new job in the next update
if (strcmp(message, "OnScanFinished") == 0 ||
strcmp(message, "OnCleanFinished") == 0 ||
strcmp(message, "OnUpdate") == 0 ||
strcmp(message, "OnRemove") == 0)
m_updateState = PENDING;
}
}
void CDirectoryProvider::Fetch(vector<CGUIListItemPtr> &items) const
{
CSingleLock lock(m_section);
items.clear();
for (vector<CGUIStaticItemPtr>::const_iterator i = m_items.begin(); i != m_items.end(); ++i)
{
if ((*i)->IsVisible())
items.push_back(*i);
}
}
void CDirectoryProvider::Reset(bool immediately /* = false */)
{
// cancel any pending jobs
CSingleLock lock(m_section);
if (m_jobID)
CJobManager::GetInstance().CancelJob(m_jobID);
m_jobID = 0;
// reset only if this is going to be destructed
if (immediately)
{
m_items.clear();
m_currentTarget.clear();
m_currentUrl.clear();
m_itemTypes.clear();
m_currentLimit = 0;
m_updateState = OK;
RegisterListProvider(false);
}
}
void CDirectoryProvider::OnJobComplete(unsigned int jobID, bool success, CJob *job)
{
CSingleLock lock(m_section);
if (success)
{
m_items = ((CDirectoryJob*)job)->GetItems();
m_currentTarget = ((CDirectoryJob*)job)->GetTarget();
((CDirectoryJob*)job)->GetItemTypes(m_itemTypes);
m_updateState = DONE;
}
m_jobID = 0;
}
bool CDirectoryProvider::OnClick(const CGUIListItemPtr &item)
{
CFileItem fileItem(*std::static_pointer_cast<CFileItem>(item));
string target = fileItem.GetProperty("node.target").asString();
if (target.empty())
target = m_currentTarget;
if (target.empty())
target = m_target.GetLabel(m_parentID, false);
if (fileItem.HasProperty("node.target_url"))
fileItem.SetPath(fileItem.GetProperty("node.target_url").asString());
// grab the execute string
string execute = CFavouritesDirectory::GetExecutePath(fileItem, target);
if (!execute.empty())
{
CGUIMessage message(GUI_MSG_EXECUTE, 0, 0);
message.SetStringParam(execute);
g_windowManager.SendMessage(message);
return true;
}
return false;
}
bool CDirectoryProvider::IsUpdating() const
{
CSingleLock lock(m_section);
return m_jobID || (m_updateState == DONE);
}
void CDirectoryProvider::FireJob()
{
CSingleLock lock(m_section);
if (m_jobID)
CJobManager::GetInstance().CancelJob(m_jobID);
m_jobID = CJobManager::GetInstance().AddJob(new CDirectoryJob(m_currentUrl, m_currentLimit, m_parentID), this);
}
void CDirectoryProvider::RegisterListProvider(bool hasLibraryContent)
{
if (hasLibraryContent && !m_isAnnounced)
{
m_isAnnounced = true;
CAnnouncementManager::Get().AddAnnouncer(this);
}
else if (!hasLibraryContent && m_isAnnounced)
{
m_isAnnounced = false;
CAnnouncementManager::Get().RemoveAnnouncer(this);
}
}
bool CDirectoryProvider::UpdateURL()
{
std::string value(m_url.GetLabel(m_parentID, false));
if (value == m_currentUrl)
return false;
m_currentUrl = value;
// Register this provider only if we have library content
RegisterListProvider(URIUtils::IsLibraryContent(m_currentUrl));
return true;
}
bool CDirectoryProvider::UpdateLimit()
{
unsigned int value = m_limit.GetIntValue(m_parentID);
if (value == m_currentLimit)
return false;
m_currentLimit = value;
return true;
}
| jmarcet/kodi | xbmc/listproviders/DirectoryProvider.cpp | C++ | gpl-2.0 | 9,724 |
/*
* Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.jtt.bytecode;
import org.junit.Test;
import org.graalvm.compiler.jtt.JTTTest;
/*
*/
public class BC_d2f extends JTTTest {
public static float test(double d) {
return (float) d;
}
@Test
public void run0() throws Throwable {
runTest("test", 0.0d);
}
@Test
public void run1() throws Throwable {
runTest("test", 1.0d);
}
@Test
public void run2() throws Throwable {
runTest("test", -1.06d);
}
}
| YouDiSN/OpenJDK-Research | jdk9/hotspot/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.jtt/src/org/graalvm/compiler/jtt/bytecode/BC_d2f.java | Java | gpl-2.0 | 1,561 |
"use strict";
function $__interopRequire(id) {
id = require(id);
return id && id.__esModule && id || {default: id};
}
Object.defineProperties(module.exports, {
__esModule: {value: true},
entries: {
enumerable: true,
get: function() {
return entries;
}
},
keys: {
enumerable: true,
get: function() {
return keys;
}
},
values: {
enumerable: true,
get: function() {
return values;
}
}
});
var $__createClass = $__interopRequire("traceur/dist/commonjs/runtime/modules/createClass.js").default;
var $__3 = require("./utils.js"),
toObject = $__3.toObject,
toUint32 = $__3.toUint32,
createIteratorResultObject = $__3.createIteratorResultObject;
var ARRAY_ITERATOR_KIND_KEYS = 1;
var ARRAY_ITERATOR_KIND_VALUES = 2;
var ARRAY_ITERATOR_KIND_ENTRIES = 3;
var ArrayIterator = function() {
var $__1;
function ArrayIterator() {}
return ($__createClass)(ArrayIterator, ($__1 = {}, Object.defineProperty($__1, "next", {
value: function() {
var iterator = toObject(this);
var array = iterator.iteratorObject_;
if (!array) {
throw new TypeError('Object is not an ArrayIterator');
}
var index = iterator.arrayIteratorNextIndex_;
var itemKind = iterator.arrayIterationKind_;
var length = toUint32(array.length);
if (index >= length) {
iterator.arrayIteratorNextIndex_ = Infinity;
return createIteratorResultObject(undefined, true);
}
iterator.arrayIteratorNextIndex_ = index + 1;
if (itemKind == ARRAY_ITERATOR_KIND_VALUES)
return createIteratorResultObject(array[index], false);
if (itemKind == ARRAY_ITERATOR_KIND_ENTRIES)
return createIteratorResultObject([index, array[index]], false);
return createIteratorResultObject(index, false);
},
configurable: true,
enumerable: true,
writable: true
}), Object.defineProperty($__1, Symbol.iterator, {
value: function() {
return this;
},
configurable: true,
enumerable: true,
writable: true
}), $__1), {});
}();
function createArrayIterator(array, kind) {
var object = toObject(array);
var iterator = new ArrayIterator;
iterator.iteratorObject_ = object;
iterator.arrayIteratorNextIndex_ = 0;
iterator.arrayIterationKind_ = kind;
return iterator;
}
function entries() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_ENTRIES);
}
function keys() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_KEYS);
}
function values() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_VALUES);
}
| Haeresis/TestCaseAtlas | webapp/src/assets/traceur/dist/commonjs/runtime/polyfills/ArrayIterator.js | JavaScript | gpl-2.0 | 2,600 |
<?php
/**
*
* Handle the waitinglist
*
* @package VirtueMart
* @subpackage Product
* @author RolandD
* @link http://www.virtuemart.net
* @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* @version $Id: product_edit_waitinglist.php 2978 2011-04-06 14:21:19Z alatak $
*/
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');
if (isset($this->product->customfields_parent_id)) { ?>
<label><?php echo JText::_('COM_VIRTUEMART_CUSTOM_SAVE_FROM_CHILD');?><input type="checkbox" name="save_customfields" value="1" /></label>
<?php } else {?>
<input type="hidden" name="save_customfields" value="1" />
<?php } ?>
<table id="customfieldsTable" width="100%">
<tr>
<td valign="top" width="%100">
<?php
$i=0;
$tables= array('categories'=>'','products'=>'','fields'=>'','customPlugins'=>'',);
if (isset($this->product->customfields)) {
foreach ($this->product->customfields as $customfield) {
if ($customfield->is_cart_attribute) $cartIcone= 'default';
else $cartIcone= 'default-off';
if ($customfield->field_type == 'Z') {
$tables['categories'] .= '
<div class="vm_thumb_image">
<span>'.$customfield->display.'</span>'.
VirtueMartModelCustomfields::setEditCustomHidden($customfield, $i)
.'<div class="vmicon vmicon-16-remove"></div>
</div>';
} elseif ($customfield->field_type == 'R') {
$tables['products'] .= '
<div class="vm_thumb_image">
<span>'.$customfield->display.'</span>'.
VirtueMartModelCustomfields::setEditCustomHidden($customfield, $i)
.'<div class="vmicon vmicon-16-remove"></div>
</div>';
} elseif ($customfield->field_type == 'G') {
// no display (group of) child , handled by plugin;
} elseif ($customfield->field_type == 'E'){
$tables['customPlugins'] .= '
<fieldset class="removable">
<legend>'.JText::_($customfield->custom_title).'</legend>
<span>'.$customfield->display.$customfield->custom_tip.'</span>'.
VirtueMartModelCustomfields::setEditCustomHidden($customfield, $i)
.'<span class="vmicon icon-nofloat vmicon-16-'.$cartIcone.'"></span>
<span class="vmicon vmicon-16-remove"></span>
</fieldset>';
} else {
$tables['fields'] .= '<tr class="removable">
<td>'.JText::_($customfield->custom_title).'</td>
<td>'.$customfield->custom_tip.'</td>
<td>'.$customfield->display.'</td>
<td>'.JText::_($this->fieldTypes[$customfield->field_type]).
VirtueMartModelCustomfields::setEditCustomHidden($customfield, $i)
.'</td>
<td>
<span class="vmicon vmicon-16-'.$cartIcone.'"></span>
</td>
<td><span class="vmicon vmicon-16-remove"></span><input class="ordering" type="hidden" value="'.$customfield->ordering.'" name="field['.$i .'][ordering]" /></td>
</tr>';
}
$i++;
}
}
$emptyTable = '
<tr>
<td colspan="7">'.JText::_( 'COM_VIRTUEMART_CUSTOM_NO_TYPES').'</td>
<tr>';
?>
<fieldset style="background-color:#F9F9F9;">
<legend><?php echo JText::_('COM_VIRTUEMART_RELATED_CATEGORIES'); ?></legend>
<?php echo JText::_('COM_VIRTUEMART_CATEGORIES_RELATED_SEARCH'); ?>
<div class="jsonSuggestResults" style="width: auto;">
<input type="text" size="40" name="search" id="relatedcategoriesSearch" value="" />
<button class="reset-value"><?php echo JText::_('COM_VIRTUEMART_RESET') ?></button>
</div>
<div id="custom_categories"><?php echo $tables['categories']; ?></div>
</fieldset>
<fieldset style="background-color:#F9F9F9;">
<legend><?php echo JText::_('COM_VIRTUEMART_RELATED_PRODUCTS'); ?></legend>
<?php echo JText::_('COM_VIRTUEMART_PRODUCT_RELATED_SEARCH'); ?>
<div class="jsonSuggestResults" style="width: auto;">
<input type="text" size="40" name="search" id="relatedproductsSearch" value="" />
<button class="reset-value"><?php echo JText::_('COM_VIRTUEMART_RESET') ?></button>
</div>
<div id="custom_products"><?php echo $tables['products']; ?></div>
</fieldset>
<fieldset style="background-color:#F9F9F9;">
<legend><?php echo JText::_('COM_VIRTUEMART_CUSTOM_FIELD_TYPE' );?></legend>
<div><?php echo '<div class="inline">'.$this->customsList; ?></div>
<table id="custom_fields" class="adminlist" cellspacing="0" cellpadding="0">
<thead>
<tr class="row1">
<th><?php echo JText::_('COM_VIRTUEMART_TITLE');?></th>
<th><?php echo JText::_('COM_VIRTUEMART_CUSTOM_TIP');?></th>
<th><?php echo JText::_('COM_VIRTUEMART_VALUE');?></th>
<th><?php echo JText::_('COM_VIRTUEMART_CART_PRICE');?></th>
<th><?php echo JText::_('COM_VIRTUEMART_TYPE');?></th>
<th><?php echo JText::_('COM_VIRTUEMART_CUSTOM_IS_CART_ATTRIBUTE');?></th>
<th><?php echo JText::_('COM_VIRTUEMART_DELETE'); ?></th>
</tr>
</thead>
<tbody id="custom_field">
<?php
if ($tables['fields']) echo $tables['fields'] ;
else echo $emptyTable;
?>
</tbody>
</table><!-- custom_fields -->
</fieldset>
<fieldset style="background-color:#F9F9F9;">
<legend><?php echo JText::_('COM_VIRTUEMART_CUSTOM_EXTENSION'); ?></legend>
<div id="custom_customPlugins"><?php echo $tables['customPlugins']; ?></div>
</fieldset>
</td>
</tr>
</table>
<div style="clear:both;"></div>
<script type="text/javascript">
nextCustom = <?php echo $i ?>;
jQuery(document).ready(function(){
jQuery('#custom_field').sortable({
update: function(event, ui) {
jQuery(this).find('.ordering').each(function(index,element) {
jQuery(element).val(index);
//console.log(index+' ');
});
}
});
});
jQuery('select#customlist').chosen().change(function() {
selected = jQuery(this).find( 'option:selected').val() ;
jQuery.getJSON('index.php?option=com_virtuemart&view=product&task=getData&format=json&type=fields&id='+selected+'&row='+nextCustom+'&virtuemart_product_id=<?php echo $this->product->virtuemart_product_id; ?>',
function(data) {
jQuery.each(data.value, function(index, value){
jQuery("#custom_"+data.table).append(value);
});
});
nextCustom++;
});
jQuery('input#relatedproductsSearch').autocomplete({
source: 'index.php?option=com_virtuemart&view=product&task=getData&format=json&type=relatedproducts&row='+nextCustom,
select: function(event, ui){
jQuery("#custom_products").append(ui.item.label);
nextCustom++;
jQuery(this).autocomplete( "option" , 'source' , 'index.php?option=com_virtuemart&view=product&task=getData&format=json&type=relatedproducts&row='+nextCustom )
jQuery('input#relatedcategoriesSearch').autocomplete( "option" , 'source' , 'index.php?option=com_virtuemart&view=product&task=getData&format=json&type=relatedcategories&row='+nextCustom )
},
minLength:1,
html: true
});
jQuery('input#relatedcategoriesSearch').autocomplete({
source: 'index.php?option=com_virtuemart&view=product&task=getData&format=json&type=relatedcategories&row='+nextCustom,
select: function(event, ui){
jQuery("#custom_categories").append(ui.item.label);
nextCustom++;
jQuery(this).autocomplete( "option" , 'source' , 'index.php?option=com_virtuemart&view=product&task=getData&format=json&type=relatedcategories&row='+nextCustom )
jQuery('input#relatedcategoriesSearch').autocomplete( "option" , 'source' , 'index.php?option=com_virtuemart&view=product&task=getData&format=json&type=relatedproducts&row='+nextCustom )
},
minLength:1,
html: true
});
// jQuery('#customfieldsTable').delegate('td','click', function() {
// jQuery('#customfieldsParent').remove();
// jQuery(this).undelegate('td','click');
// });
// jQuery.each(jQuery('#customfieldsTable').filter(":input").data('events'), function(i, event) {
// jQuery.each(event, function(i, handler){
// console.log(handler);
// });
// });
eventNames = "click.remove keydown.remove change.remove focus.remove"; // all events you wish to bind to
function removeParent() {jQuery('#customfieldsParent').remove();console.log($(this));//jQuery('#customfieldsTable input').unbind(eventNames, removeParent)
};
// jQuery('#customfieldsTable input').bind(eventNames, removeParent);
// jQuery('#customfieldsTable').delegate('*',eventNames,function(event) {
// var $thisCell, $tgt = jQuery(event.target);
// console.log (event);
// });
jQuery('#customfieldsTable').find('input').each(function(i){
current = jQuery(this);
// var dEvents = curent.data('events');
// if (!dEvents) {return;}
current.click(function(){
jQuery('#customfieldsParent').remove();
});
//console.log (curent);
// jQuery.each(dEvents, function(name, handler){
// if((new RegExp('^(' + (events === '*' ? '.+' : events.replace(',','|').replace(/^on/i,'')) + ')$' ,'i')).test(name)) {
// jQuery.each(handler, function(i,handler){
// outputFunction(elem, '\n' + i + ': [' + name + '] : ' + handler );
// });
// }
// });
});
//onsole.log(jQuery('#customfieldsTable').data('events'));
</script> | Fundacion-AG/PaginaWebFAG | tmp/install_535533f62cdf3/administrator/components/com_virtuemart/views/product/tmpl/product_edit_custom.php | PHP | gpl-2.0 | 9,558 |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// The ClearCanvas RIS/PACS open source project is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using ClearCanvas.Common;
using ClearCanvas.Common.Utilities;
using ClearCanvas.Controls.WinForms;
using ClearCanvas.Desktop;
using ClearCanvas.Desktop.Actions;
using ClearCanvas.Desktop.View.WinForms;
namespace ClearCanvas.ImageViewer.Explorer.Local.View.WinForms
{
public partial class LocalImageExplorerControl : UserControl
{
private LocalImageExplorerComponent _component;
private DelayedEventPublisher _folderViewSelectionUpdatePublisher;
private Pidl _homeLocation = null;
public LocalImageExplorerControl(LocalImageExplorerComponent component)
{
_component = component;
_folderViewSelectionUpdatePublisher = new DelayedEventPublisher(OnFolderViewSelectionUpdatePublished);
InitializeComponent();
InitializeHistoryMenu();
InitializeIcons();
InitializeFocusList();
SetViewMode(Settings.Default.FolderViewMode, false);
SetHomeLocation(Settings.Default.HomeLocation);
_folderView.ExceptionRaised += OnFolderControlExceptionRaised;
_folderTree.ExceptionRaised += OnFolderControlExceptionRaised;
ResetFocus(); // reset focus must happen after explorer controls are initially populated
// Initialize menus here
ToolStripBuilder.BuildMenu(_folderViewContextMenu.Items, _component.ContextMenuModel.ChildNodes);
ToolStripBuilder.BuildMenu(_folderTreeContextMenu.Items, _component.ContextMenuModel.ChildNodes);
}
private void PerformDispose(bool disposing)
{
if (disposing)
{
// this is a managed wrapper so it should only be disposed on disposing
if (_homeLocation != null)
{
_homeLocation.Dispose();
_homeLocation = null;
}
if (_folderViewSelectionUpdatePublisher != null)
{
_folderViewSelectionUpdatePublisher.Dispose();
_folderViewSelectionUpdatePublisher = null;
}
}
}
private void OnFolderControlExceptionRaised(object sender, ItemEventArgs<Exception> e)
{
Exception ex = e.Item;
Platform.Log(LogLevel.Debug, "FolderControl exception detected. Last Known Location: {0}", _txtAddress.Text);
ExceptionHandler.Report(ex, _component.DesktopWindow);
}
private void UpdateFolderTreeSelection()
{
_component.Selection = new PathSelection(_folderTree.SelectedItem);
}
private void OnFolderViewSelectionUpdatePublished(object sender, EventArgs e)
{
_component.Selection = new PathSelection(CollectionUtils.Cast<FolderObject>(_folderView.SelectedItems));
}
private void OnItemOpened(object sender, EventArgs e)
{
if (_component.DefaultActionHandler != null)
{
_component.DefaultActionHandler();
}
}
private void SetViewMode(System.Windows.Forms.View view, bool saveSetting)
{
_mnuIconsView.Checked = (view == System.Windows.Forms.View.LargeIcon);
_mnuListView.Checked = (view == System.Windows.Forms.View.List);
_mnuDetailsView.Checked = (view == System.Windows.Forms.View.Details);
_mnuTilesView.Checked = (view == System.Windows.Forms.View.Tile);
_folderView.View = view;
if (saveSetting)
{
Settings settings = Settings.Default;
settings.FolderViewMode = view;
settings.Save();
}
}
private void SetHomeLocation(string homeLocation)
{
if (!string.IsNullOrEmpty(homeLocation))
{
try
{
Environment.SpecialFolder specialFolder = (Environment.SpecialFolder) Enum.Parse(typeof (Environment.SpecialFolder), homeLocation);
_homeLocation = new Pidl(specialFolder);
return;
}
catch (ArgumentException) {}
catch (NotSupportedException) {}
catch (Exception ex)
{
Platform.Log(LogLevel.Debug, ex, "The special folder {0} isn't available.", homeLocation);
}
Pidl pidl;
if (Pidl.TryParse(homeLocation, out pidl))
{
_homeLocation = pidl;
return;
}
_homeLocation = null;
}
}
public void BrowseToHome()
{
if (_homeLocation == null)
_folderCoordinator.BrowseToHome();
else
_folderCoordinator.BrowseTo(_homeLocation);
}
#region Tab Order
private delegate bool FocusDelegate(bool forward);
private IList<KeyValuePair<Control, FocusDelegate>> _focusDelegates = null;
private void InitializeFocusList()
{
// initialize control focus list
List<KeyValuePair<Control, FocusDelegate>> focusDelegates = new List<KeyValuePair<Control, FocusDelegate>>(3);
focusDelegates.Add(new KeyValuePair<Control, FocusDelegate>(_folderTree, f => _folderTree.SelectNextControl(_folderTree, f, false, true, false)));
focusDelegates.Add(new KeyValuePair<Control, FocusDelegate>(_folderView, f => _folderView.SelectNextControl(_folderView, f, false, true, false)));
focusDelegates.Add(new KeyValuePair<Control, FocusDelegate>(_addressStrip, f =>
{
_txtAddress.Focus();
return _addressStrip.ContainsFocus;
}));
_focusDelegates = focusDelegates.AsReadOnly();
}
private void ResetFocus()
{
if (_focusDelegates.Count > 0)
_focusDelegates[0].Value.Invoke(true);
}
protected override bool ProcessTabKey(bool forward)
{
// overrides the tab order using the focus delegates list
int indexFocusedControl = 0;
while (indexFocusedControl < _focusDelegates.Count)
{
// find the control that is currently focused
if (_focusDelegates[indexFocusedControl].Key.ContainsFocus)
{
// try to focus the next control in sequence
for (int offset = 1; offset < _focusDelegates.Count; offset++)
{
int index = (indexFocusedControl + (forward ? offset : _focusDelegates.Count - offset))%_focusDelegates.Count;
if (_focusDelegates[index].Value.Invoke(forward))
break; // end loop on first control that successfully focused
}
return true;
}
indexFocusedControl++;
}
return base.ProcessTabKey(forward);
}
#endregion
#region Explorer Control
private const int ShowHistoryCount = 10;
private string _lastValidLocation = string.Empty;
private static void InitializeImageList(ImageList imageList, string sizeString)
{
Type type = typeof (LocalImageExplorerControl);
var resourceResolver = new ActionResourceResolver(type);
string[] icons = {"Back", "Next", "Up", "Refresh", "Home", "ShowFolders", "View", "Go"};
foreach (string iconName in icons)
{
var resourceName = string.Format("{0}.Icons.{1}Tool{2}.png", type.Namespace, iconName, sizeString);
using (var ioStream = resourceResolver.OpenResource(resourceName))
{
if (ioStream == null)
continue;
imageList.Images.Add(iconName, Image.FromStream(ioStream));
}
}
}
private ImageList GetImageList(IconSize iconSize)
{
if (iconSize == IconSize.Small)
return _smallIconImageList;
if (iconSize == IconSize.Medium)
return _mediumIconImageList;
return _largeIconImageList;
}
private void InitializeIcons()
{
InitializeImageList(_largeIconImageList, "Large");
InitializeImageList(_mediumIconImageList, "Medium");
InitializeImageList(_smallIconImageList, "Small");
_toolStrip.ImageList = GetImageList(Settings.Default.ToolbarIconSize);
_btnBack.ImageKey = @"Back";
_btnForward.ImageKey = @"Next";
_btnUp.ImageKey = @"Up";
_btnRefresh.ImageKey = @"Refresh";
_btnHome.ImageKey = @"Home";
_btnShowFolders.ImageKey = @"ShowFolders";
_btnViews.ImageKey = @"View";
_addressStrip.ImageList = _smallIconImageList;
_btnGo.ImageKey = @"Go";
}
private void InitializeHistoryMenu()
{
for (int n = 0; n < ShowHistoryCount; n++)
{
ToolStripMenuItem menuBack = new ToolStripMenuItem();
menuBack.Click += _mnuHistoryItem_Click;
menuBack.Tag = -(n + 1);
menuBack.Visible = false;
_btnBack.DropDownItems.Add(menuBack);
ToolStripMenuItem menuForward = new ToolStripMenuItem();
menuForward.Click += _mnuHistoryItem_Click;
menuForward.Tag = n + 1;
menuForward.Visible = false;
_btnForward.DropDownItems.Add(menuForward);
}
}
protected override void OnLoad(EventArgs e)
{
try
{
this.BrowseToHome();
}
catch (Exception ex)
{
OnFolderControlExceptionRaised(null, new ItemEventArgs<Exception>(ex));
}
base.OnLoad(e);
}
private void _folderCoordinator_CurrentPidlChanged(object sender, EventArgs e)
{
_btnUp.Enabled = _folderCoordinator.CanBrowseToParent;
_btnBack.Enabled = _folderCoordinator.CanBrowseToPrevious;
_btnForward.Enabled = _folderCoordinator.CanBrowseToNext;
_lastValidLocation = _txtAddress.Text = _folderCoordinator.CurrentPath;
this.Text = _folderCoordinator.CurrentDisplayName;
this.UpdateBackButtonMenu();
this.UpdateForwardButtonMenu();
}
private void UpdateBackButtonMenu()
{
int count = 0;
foreach (Pidl pastPidl in _folderCoordinator.EnumeratePreviousLocations(false))
{
if (count >= ShowHistoryCount)
break;
_btnBack.DropDownItems[count].Text = pastPidl.DisplayName;
_btnBack.DropDownItems[count].Visible = true;
count++;
}
for (int n = count; n < ShowHistoryCount; n++)
_btnBack.DropDownItems[n].Visible = false;
}
private void UpdateForwardButtonMenu()
{
int count = 0;
foreach (Pidl futurePidl in _folderCoordinator.EnumerateNextLocations(false))
{
if (count >= ShowHistoryCount)
break;
_btnForward.DropDownItems[count].Text = futurePidl.DisplayName;
_btnForward.DropDownItems[count].Visible = true;
count++;
}
for (int n = count; n < ShowHistoryCount; n++)
_btnForward.DropDownItems[n].Visible = false;
}
private void _btnUp_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
try
{
_folderCoordinator.BrowseToParent();
}
catch (Exception ex)
{
OnFolderControlExceptionRaised(null, new ItemEventArgs<Exception>(ex));
}
finally
{
this.ResetCursor();
}
}
private void _btnBack_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
try
{
_folderCoordinator.BrowseToPrevious();
}
catch (Exception ex)
{
OnFolderControlExceptionRaised(null, new ItemEventArgs<Exception>(ex));
}
finally
{
this.ResetCursor();
}
}
private void _btnForward_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
try
{
_folderCoordinator.BrowseToNext();
}
catch (Exception ex)
{
OnFolderControlExceptionRaised(null, new ItemEventArgs<Exception>(ex));
}
finally
{
this.ResetCursor();
}
}
private void _btnHome_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
try
{
this.BrowseToHome();
}
catch (Exception ex)
{
OnFolderControlExceptionRaised(null, new ItemEventArgs<Exception>(ex));
}
finally
{
this.ResetCursor();
}
}
private void _btnRefresh_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
try
{
_folderCoordinator.Refresh();
}
catch(Exception ex)
{
OnFolderControlExceptionRaised(null, new ItemEventArgs<Exception>(ex));
}
finally
{
this.ResetCursor();
}
}
private void _btnGo_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
try
{
if (!string.IsNullOrEmpty(_txtAddress.Text))
_folderCoordinator.BrowseTo(_txtAddress.Text);
}
catch (Exception ex)
{
this.OnFolderControlExceptionRaised(null, new ItemEventArgs<Exception>(ex));
_txtAddress.Text = _lastValidLocation;
}
finally
{
this.ResetCursor();
}
}
private void _txtAddress_KeyEnterPressed(object sender, EventArgs e)
{
_btnGo.PerformClick();
}
private void _mnuHistoryItem_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
try
{
_folderCoordinator.BrowseTo((int) ((ToolStripMenuItem) sender).Tag);
}
catch (Exception ex)
{
OnFolderControlExceptionRaised(null, new ItemEventArgs<Exception>(ex));
}
finally
{
this.ResetCursor();
}
}
private void _btnShowFolders_Click(object sender, EventArgs e)
{
_btnShowFolders.Checked = !_btnShowFolders.Checked;
_folderTree.Visible = _splitter.Visible = _btnShowFolders.Checked;
}
private void _mnuTilesView_Click(object sender, EventArgs e)
{
SetViewMode(System.Windows.Forms.View.Tile, true);
}
private void _mnuIconsView_Click(object sender, EventArgs e)
{
SetViewMode(System.Windows.Forms.View.LargeIcon, true);
}
private void _mnuListView_Click(object sender, EventArgs e)
{
SetViewMode(System.Windows.Forms.View.List, true);
}
private void _mnuDetailsView_Click(object sender, EventArgs e)
{
SetViewMode(System.Windows.Forms.View.Details, true);
}
private void _folderView_ItemDoubleClick(object sender, FolderViewItemEventArgs e)
{
if (!e.Item.IsFolder)
{
_folderViewSelectionUpdatePublisher.PublishNow(sender, e);
OnItemOpened(sender, e);
e.Handled = true;
}
}
private void _folderView_SelectedItemsChanged(object sender, EventArgs e)
{
// listview-type controls fire the event for each item in the selection
// (because each item selection change is conceptually separate in this type of GUI)
// this can generate a lot of unecessary calls to update the component's selection
// so we delay the event here until the selection settles down
_folderViewSelectionUpdatePublisher.Publish(sender, e);
}
private void _folderTree_SelectedItemsChanged(object sender, EventArgs e)
{
UpdateFolderTreeSelection();
}
private void _folderControl_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == (Keys.Control | Keys.A))
{
_folderView.SelectNextControl(_folderView, true, false, true, false);
_folderView.SelectAll();
e.Handled = true;
e.SuppressKeyPress = true;
}
}
private void _folderControl_BeginBrowse(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
}
private void _folderControl_EndBrowse(object sender, EventArgs e)
{
this.ResetCursor();
}
private void _folderViewContextMenu_Opening(object sender, CancelEventArgs e)
{
_folderViewSelectionUpdatePublisher.PublishNow(sender, e);
}
private void _folderTreeContextMenu_Opening(object sender, CancelEventArgs e)
{
UpdateFolderTreeSelection();
}
#endregion
#region ExceptionPolicy Class
[ExceptionPolicyFor(typeof (PathNotFoundException))]
[ExceptionPolicyFor(typeof (PathAccessException))]
[ExtensionOf(typeof (ExceptionPolicyExtensionPoint))]
private class ExceptionPolicy : IExceptionPolicy
{
public void Handle(Exception ex, IExceptionHandlingContext exceptionHandlingContext)
{
if (ex is PathNotFoundException)
Handle((PathNotFoundException) ex, exceptionHandlingContext);
else if (ex is PathAccessException)
Handle((PathAccessException) ex, exceptionHandlingContext);
}
private static void Handle(PathNotFoundException ex, IExceptionHandlingContext exceptionHandlingContext)
{
var sb = new StringBuilder();
sb.AppendLine(SR.ErrorPathUnavailable);
if (!string.IsNullOrEmpty(ex.Path))
sb.AppendLine(string.Format(SR.FormatPath, ex.Path));
exceptionHandlingContext.ShowMessageBox(sb.ToString());
}
private static void Handle(PathAccessException ex, IExceptionHandlingContext exceptionHandlingContext)
{
var sb = new StringBuilder();
sb.AppendLine(SR.ErrorPathSecurity);
if (!string.IsNullOrEmpty(ex.Path))
sb.AppendLine(string.Format(SR.FormatPath, ex.Path));
exceptionHandlingContext.ShowMessageBox(sb.ToString());
}
}
#endregion
#region PathSelection Class
/// <summary>
/// Custom <see cref="IPathSelection"/> implementation that allows for delayed shortcut resolution.
/// </summary>
/// <remarks>
/// Resolving shortcuts can be expensive, so always call at the last possible moment (in conjunction with a user GUI action, preferably).
/// </remarks>
private class PathSelection : Selection<FolderObject>, IPathSelection
{
public PathSelection(FolderObject item) : base(item) {}
public PathSelection(IEnumerable<FolderObject> folderObjects) : base(folderObjects) {}
public string this[int index]
{
get { return Items[index].GetPath(true); }
}
public bool Contains(string path)
{
foreach (var item in Items)
if (string.Equals(path, item.GetPath(true), StringComparison.InvariantCultureIgnoreCase))
return true;
return false;
}
public new IEnumerator<string> GetEnumerator()
{
foreach (var item in Items)
yield return item.GetPath(true);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
#endregion
}
} | chinapacs/ImageViewer | ImageViewer/Explorer/Local/View/WinForms/LocalImageExplorerControl.cs | C# | gpl-3.0 | 18,653 |
<?php
class ExternalStoreForTesting {
protected $data = [
'cluster1' => [
'200' => 'Hello',
'300' => [
'Hello', 'World',
],
// gzip string below generated with gzdeflate( 'AAAABBAAA' )
'12345' => "sttttr\002\022\000",
],
];
/**
* Fetch data from given URL
* @param string $url An url of the form FOO://cluster/id or FOO://cluster/id/itemid.
* @return mixed
*/
public function fetchFromURL( $url ) {
// Based on ExternalStoreDB
$path = explode( '/', $url );
$cluster = $path[2];
$id = $path[3];
if ( isset( $path[4] ) ) {
$itemID = $path[4];
} else {
$itemID = false;
}
if ( !isset( $this->data[$cluster][$id] ) ) {
return null;
}
if ( $itemID !== false
&& is_array( $this->data[$cluster][$id] )
&& isset( $this->data[$cluster][$id][$itemID] )
) {
return $this->data[$cluster][$id][$itemID];
}
return $this->data[$cluster][$id];
}
}
| kylethayer/bioladder | wiki/tests/phpunit/includes/externalstore/ExternalStoreForTesting.php | PHP | gpl-3.0 | 919 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0-b52-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.12.20 at 12:48:21 PM GMT
//
package weka.core.pmml.jaxbbindings;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for AnovaRow element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="AnovaRow">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://www.dmg.org/PMML-4_1}Extension" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="degreesOfFreedom" use="required" type="{http://www.dmg.org/PMML-4_1}NUMBER" />
* <attribute name="fValue" type="{http://www.dmg.org/PMML-4_1}NUMBER" />
* <attribute name="meanOfSquares" type="{http://www.dmg.org/PMML-4_1}NUMBER" />
* <attribute name="pValue" type="{http://www.dmg.org/PMML-4_1}PROB-NUMBER" />
* <attribute name="sumOfSquares" use="required" type="{http://www.dmg.org/PMML-4_1}NUMBER" />
* <attribute name="type" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Model"/>
* <enumeration value="Error"/>
* <enumeration value="Total"/>
* </restriction>
* </simpleType>
* </attribute>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"extension"
})
@XmlRootElement(name = "AnovaRow")
public class AnovaRow {
@XmlElement(name = "Extension", namespace = "http://www.dmg.org/PMML-4_1", required = true)
protected List<Extension> extension;
@XmlAttribute(required = true)
protected double degreesOfFreedom;
@XmlAttribute
protected Double fValue;
@XmlAttribute
protected Double meanOfSquares;
@XmlAttribute
protected BigDecimal pValue;
@XmlAttribute(required = true)
protected double sumOfSquares;
@XmlAttribute(required = true)
protected String type;
/**
* Gets the value of the extension property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the extension property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getExtension().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Extension }
*
*
*/
public List<Extension> getExtension() {
if (extension == null) {
extension = new ArrayList<Extension>();
}
return this.extension;
}
/**
* Gets the value of the degreesOfFreedom property.
*
*/
public double getDegreesOfFreedom() {
return degreesOfFreedom;
}
/**
* Sets the value of the degreesOfFreedom property.
*
*/
public void setDegreesOfFreedom(double value) {
this.degreesOfFreedom = value;
}
/**
* Gets the value of the fValue property.
*
* @return
* possible object is
* {@link Double }
*
*/
public Double getFValue() {
return fValue;
}
/**
* Sets the value of the fValue property.
*
* @param value
* allowed object is
* {@link Double }
*
*/
public void setFValue(Double value) {
this.fValue = value;
}
/**
* Gets the value of the meanOfSquares property.
*
* @return
* possible object is
* {@link Double }
*
*/
public Double getMeanOfSquares() {
return meanOfSquares;
}
/**
* Sets the value of the meanOfSquares property.
*
* @param value
* allowed object is
* {@link Double }
*
*/
public void setMeanOfSquares(Double value) {
this.meanOfSquares = value;
}
/**
* Gets the value of the pValue property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getPValue() {
return pValue;
}
/**
* Sets the value of the pValue property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setPValue(BigDecimal value) {
this.pValue = value;
}
/**
* Gets the value of the sumOfSquares property.
*
*/
public double getSumOfSquares() {
return sumOfSquares;
}
/**
* Sets the value of the sumOfSquares property.
*
*/
public void setSumOfSquares(double value) {
this.sumOfSquares = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
}
| mydzigear/weka.kmeanspp.silhouette_score | src/weka/core/pmml/jaxbbindings/AnovaRow.java | Java | gpl-3.0 | 6,195 |
/*
* 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.commons.codec.net;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.BitSet;
import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.StringDecoder;
import org.apache.commons.codec.StringEncoder;
/**
* Similar to the Quoted-Printable content-transfer-encoding defined in
* <a href="http://www.ietf.org/rfc/rfc1521.txt">RFC 1521</a> and designed to allow text containing mostly ASCII
* characters to be decipherable on an ASCII terminal without decoding.
* <p>
* <a href="http://www.ietf.org/rfc/rfc1522.txt">RFC 1522</a> describes techniques to allow the encoding of non-ASCII
* text in various portions of a RFC 822 [2] message header, in a manner which is unlikely to confuse existing message
* handling software.
* <p>
* This class is conditionally thread-safe.
* The instance field {@link #encodeBlanks} is mutable {@link #setEncodeBlanks(boolean)}
* but is not volatile, and accesses are not synchronised.
* If an instance of the class is shared between threads, the caller needs to ensure that suitable synchronisation
* is used to ensure safe publication of the value between threads, and must not invoke
* {@link #setEncodeBlanks(boolean)} after initial setup.
*
* @see <a href="http://www.ietf.org/rfc/rfc1522.txt">MIME (Multipurpose Internet Mail Extensions) Part Two: Message
* Header Extensions for Non-ASCII Text</a>
*
* @since 1.3
* @version $Id$
*/
public class QCodec extends RFC1522Codec implements StringEncoder, StringDecoder {
/**
* The default charset used for string decoding and encoding.
*/
private final Charset charset;
/**
* BitSet of printable characters as defined in RFC 1522.
*/
private static final BitSet PRINTABLE_CHARS = new BitSet(256);
// Static initializer for printable chars collection
static {
// alpha characters
PRINTABLE_CHARS.set(' ');
PRINTABLE_CHARS.set('!');
PRINTABLE_CHARS.set('"');
PRINTABLE_CHARS.set('#');
PRINTABLE_CHARS.set('$');
PRINTABLE_CHARS.set('%');
PRINTABLE_CHARS.set('&');
PRINTABLE_CHARS.set('\'');
PRINTABLE_CHARS.set('(');
PRINTABLE_CHARS.set(')');
PRINTABLE_CHARS.set('*');
PRINTABLE_CHARS.set('+');
PRINTABLE_CHARS.set(',');
PRINTABLE_CHARS.set('-');
PRINTABLE_CHARS.set('.');
PRINTABLE_CHARS.set('/');
for (int i = '0'; i <= '9'; i++) {
PRINTABLE_CHARS.set(i);
}
PRINTABLE_CHARS.set(':');
PRINTABLE_CHARS.set(';');
PRINTABLE_CHARS.set('<');
PRINTABLE_CHARS.set('>');
PRINTABLE_CHARS.set('@');
for (int i = 'A'; i <= 'Z'; i++) {
PRINTABLE_CHARS.set(i);
}
PRINTABLE_CHARS.set('[');
PRINTABLE_CHARS.set('\\');
PRINTABLE_CHARS.set(']');
PRINTABLE_CHARS.set('^');
PRINTABLE_CHARS.set('`');
for (int i = 'a'; i <= 'z'; i++) {
PRINTABLE_CHARS.set(i);
}
PRINTABLE_CHARS.set('{');
PRINTABLE_CHARS.set('|');
PRINTABLE_CHARS.set('}');
PRINTABLE_CHARS.set('~');
}
private static final byte BLANK = 32;
private static final byte UNDERSCORE = 95;
private boolean encodeBlanks = false;
/**
* Default constructor.
*/
public QCodec() {
this(Charsets.UTF_8);
}
/**
* Constructor which allows for the selection of a default charset.
*
* @param charset
* the default string charset to use.
*
* @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
* @since 1.7
*/
public QCodec(final Charset charset) {
super();
this.charset = charset;
}
/**
* Constructor which allows for the selection of a default charset.
*
* @param charsetName
* the charset to use.
* @throws java.nio.charset.UnsupportedCharsetException
* If the named charset is unavailable
* @since 1.7 throws UnsupportedCharsetException if the named charset is unavailable
* @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
*/
public QCodec(final String charsetName) {
this(Charset.forName(charsetName));
}
@Override
protected String getEncoding() {
return "Q";
}
@Override
protected byte[] doEncoding(final byte[] bytes) {
if (bytes == null) {
return null;
}
final byte[] data = QuotedPrintableCodec.encodeQuotedPrintable(PRINTABLE_CHARS, bytes);
if (this.encodeBlanks) {
for (int i = 0; i < data.length; i++) {
if (data[i] == BLANK) {
data[i] = UNDERSCORE;
}
}
}
return data;
}
@Override
protected byte[] doDecoding(final byte[] bytes) throws DecoderException {
if (bytes == null) {
return null;
}
boolean hasUnderscores = false;
for (final byte b : bytes) {
if (b == UNDERSCORE) {
hasUnderscores = true;
break;
}
}
if (hasUnderscores) {
final byte[] tmp = new byte[bytes.length];
for (int i = 0; i < bytes.length; i++) {
final byte b = bytes[i];
if (b != UNDERSCORE) {
tmp[i] = b;
} else {
tmp[i] = BLANK;
}
}
return QuotedPrintableCodec.decodeQuotedPrintable(tmp);
}
return QuotedPrintableCodec.decodeQuotedPrintable(bytes);
}
/**
* Encodes a string into its quoted-printable form using the specified charset. Unsafe characters are escaped.
*
* @param str
* string to convert to quoted-printable form
* @param charset
* the charset for str
* @return quoted-printable string
* @throws EncoderException
* thrown if a failure condition is encountered during the encoding process.
* @since 1.7
*/
public String encode(final String str, final Charset charset) throws EncoderException {
if (str == null) {
return null;
}
return encodeText(str, charset);
}
/**
* Encodes a string into its quoted-printable form using the specified charset. Unsafe characters are escaped.
*
* @param str
* string to convert to quoted-printable form
* @param charset
* the charset for str
* @return quoted-printable string
* @throws EncoderException
* thrown if a failure condition is encountered during the encoding process.
*/
public String encode(final String str, final String charset) throws EncoderException {
if (str == null) {
return null;
}
try {
return encodeText(str, charset);
} catch (final UnsupportedEncodingException e) {
throw new EncoderException(e.getMessage(), e);
}
}
/**
* Encodes a string into its quoted-printable form using the default charset. Unsafe characters are escaped.
*
* @param str
* string to convert to quoted-printable form
* @return quoted-printable string
* @throws EncoderException
* thrown if a failure condition is encountered during the encoding process.
*/
@Override
public String encode(final String str) throws EncoderException {
if (str == null) {
return null;
}
return encode(str, getCharset());
}
/**
* Decodes a quoted-printable string into its original form. Escaped characters are converted back to their original
* representation.
*
* @param str
* quoted-printable string to convert into its original form
* @return original string
* @throws DecoderException
* A decoder exception is thrown if a failure condition is encountered during the decode process.
*/
@Override
public String decode(final String str) throws DecoderException {
if (str == null) {
return null;
}
try {
return decodeText(str);
} catch (final UnsupportedEncodingException e) {
throw new DecoderException(e.getMessage(), e);
}
}
/**
* Encodes an object into its quoted-printable form using the default charset. Unsafe characters are escaped.
*
* @param obj
* object to convert to quoted-printable form
* @return quoted-printable object
* @throws EncoderException
* thrown if a failure condition is encountered during the encoding process.
*/
@Override
public Object encode(final Object obj) throws EncoderException {
if (obj == null) {
return null;
} else if (obj instanceof String) {
return encode((String) obj);
} else {
throw new EncoderException("Objects of type " +
obj.getClass().getName() +
" cannot be encoded using Q codec");
}
}
/**
* Decodes a quoted-printable object into its original form. Escaped characters are converted back to their original
* representation.
*
* @param obj
* quoted-printable object to convert into its original form
* @return original object
* @throws DecoderException
* Thrown if the argument is not a <code>String</code>. Thrown if a failure condition is encountered
* during the decode process.
*/
@Override
public Object decode(final Object obj) throws DecoderException {
if (obj == null) {
return null;
} else if (obj instanceof String) {
return decode((String) obj);
} else {
throw new DecoderException("Objects of type " +
obj.getClass().getName() +
" cannot be decoded using Q codec");
}
}
/**
* Gets the default charset name used for string decoding and encoding.
*
* @return the default charset name
* @since 1.7
*/
public Charset getCharset() {
return this.charset;
}
/**
* Gets the default charset name used for string decoding and encoding.
*
* @return the default charset name
*/
public String getDefaultCharset() {
return this.charset.name();
}
/**
* Tests if optional transformation of SPACE characters is to be used
*
* @return <code>true</code> if SPACE characters are to be transformed, <code>false</code> otherwise
*/
public boolean isEncodeBlanks() {
return this.encodeBlanks;
}
/**
* Defines whether optional transformation of SPACE characters is to be used
*
* @param b
* <code>true</code> if SPACE characters are to be transformed, <code>false</code> otherwise
*/
public void setEncodeBlanks(final boolean b) {
this.encodeBlanks = b;
}
}
| foreni-packages/bytecode-viewer | src/org/apache/commons/codec/net/QCodec.java | Java | gpl-3.0 | 12,271 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
?>
this.connectPrereqCallback = {
success: function(o) {
YUI.use('yui2-treeview', 'yui2-layout', function(Y) {
scorm_tree_node = Y.YUI2.widget.TreeView.getTree('scorm_tree');
if (o.responseText !== undefined) {
//alert('got a response: ' + o.responseText);
if (scorm_tree_node && o.responseText) {
var hnode = scorm_tree_node.getHighlightedNode();
var hidx = null;
if (hnode) {
hidx = hnode.index + scorm_tree_node.getNodeCount();
}
// all gone
var root_node = scorm_tree_node.getRoot();
while (root_node.children.length > 0) {
scorm_tree_node.removeNode(root_node.children[0]);
}
}
// make sure the temporary tree element is not there
var el_old_tree = document.getElementById('scormtree123');
if (el_old_tree) {
el_old_tree.parentNode.removeChild(el_old_tree);
}
var el_new_tree = document.createElement('div');
var pagecontent = document.getElementById("page-content");
el_new_tree.setAttribute('id','scormtree123');
el_new_tree.innerHTML = o.responseText;
// make sure it doesnt show
el_new_tree.style.display = 'none';
pagecontent.appendChild(el_new_tree)
// ignore the first level element as this is the title
var startNode = el_new_tree.firstChild.firstChild;
if (startNode.tagName == 'LI') {
// go back to the beginning
startNode = el_new_tree;
}
//var sXML = new XMLSerializer().serializeToString(startNode);
scorm_tree_node.buildTreeFromMarkup('scormtree123');
var el = document.getElementById('scormtree123');
el.parentNode.removeChild(el);
scorm_tree_node.expandAll();
scorm_tree_node.render();
if (hidx != null) {
hnode = scorm_tree_node.getNodeByIndex(hidx);
if (hnode) {
hnode.highlight();
scorm_layout_widget = Y.YUI2.widget.Layout.getLayoutById('scorm_layout');
var left = scorm_layout_widget.getUnitByPosition('left');
if (left.expanded) {
hnode.focus();
}
}
}
}
});
},
failure: function(o) {
// do some sort of error handling
var sURL = "<?php echo $CFG->wwwroot; ?>" + "/mod/scorm/prereqs.php?a=<?php echo $scorm->id ?>&scoid=<?php echo $scoid ?>&attempt=<?php echo $attempt ?>&mode=<?php echo $mode ?>¤torg=<?php echo $currentorg ?>&sesskey=<?php echo sesskey(); ?>";
//TODO: Enable this error handing correctly - avoiding issues when closing player MDL-23470
//alert('Prerequisites update failed - must restart SCORM player');
//window.location.href = sURL;
}
};
| chiefdome/integration | mod/scorm/datamodels/callback.js.php | PHP | gpl-3.0 | 4,242 |
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/* jshint node: true, browser: false */
/* eslint-env node */
/**
* @copyright 2014 Andrew Nicols
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Grunt configuration
*/
module.exports = function(grunt) {
var path = require('path'),
tasks = {},
cwd = process.env.PWD || process.cwd(),
async = require('async'),
DOMParser = require('xmldom').DOMParser,
xpath = require('xpath'),
semver = require('semver');
// Verify the node version is new enough.
var expected = semver.validRange(grunt.file.readJSON('package.json').engines.node);
var actual = semver.valid(process.version);
if (!semver.satisfies(actual, expected)) {
grunt.fail.fatal('Node version too old. Require ' + expected + ', version installed: ' + actual);
}
// Windows users can't run grunt in a subdirectory, so allow them to set
// the root by passing --root=path/to/dir.
if (grunt.option('root')) {
var root = grunt.option('root');
if (grunt.file.exists(__dirname, root)) {
cwd = path.join(__dirname, root);
grunt.log.ok('Setting root to ' + cwd);
} else {
grunt.fail.fatal('Setting root to ' + root + ' failed - path does not exist');
}
}
var inAMD = path.basename(cwd) == 'amd';
// Globbing pattern for matching all AMD JS source files.
var amdSrc = [inAMD ? cwd + '/src/*.js' : '**/amd/src/*.js'];
/**
* Function to generate the destination for the uglify task
* (e.g. build/file.min.js). This function will be passed to
* the rename property of files array when building dynamically:
* http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
*
* @param {String} destPath the current destination
* @param {String} srcPath the matched src path
* @return {String} The rewritten destination path.
*/
var uglifyRename = function(destPath, srcPath) {
destPath = srcPath.replace('src', 'build');
destPath = destPath.replace('.js', '.min.js');
destPath = path.resolve(cwd, destPath);
return destPath;
};
/**
* Find thirdpartylibs.xml and generate an array of paths contained within
* them (used to generate ignore files and so on).
*
* @return {array} The list of thirdparty paths.
*/
var getThirdPartyPathsFromXML = function() {
var thirdpartyfiles = grunt.file.expand('*/**/thirdpartylibs.xml');
var libs = ['node_modules/', 'vendor/'];
thirdpartyfiles.forEach(function(file) {
var dirname = path.dirname(file);
var doc = new DOMParser().parseFromString(grunt.file.read(file));
var nodes = xpath.select("/libraries/library/location/text()", doc);
nodes.forEach(function(node) {
var lib = path.join(dirname, node.toString());
if (grunt.file.isDir(lib)) {
// Ensure trailing slash on dirs.
lib = lib.replace(/\/?$/, '/');
}
// Look for duplicate paths before adding to array.
if (libs.indexOf(lib) === -1) {
libs.push(lib);
}
});
});
return libs;
};
// Project configuration.
grunt.initConfig({
eslint: {
// Even though warnings dont stop the build we don't display warnings by default because
// at this moment we've got too many core warnings.
options: {quiet: !grunt.option('show-lint-warnings')},
amd: {
src: amdSrc,
// Check AMD with some slightly stricter rules.
rules: {
'no-unused-vars': 'error',
'no-implicit-globals': 'error'
}
},
// Check YUI module source files.
yui: {
src: ['**/yui/src/**/*.js', '!*/**/yui/src/*/meta/*.js'],
options: {
// Disable some rules which we can't safely define for YUI rollups.
rules: {
'no-undef': 'off',
'no-unused-vars': 'off',
'no-unused-expressions': 'off'
}
}
}
},
uglify: {
amd: {
files: [{
expand: true,
src: amdSrc,
rename: uglifyRename
}],
options: {report: 'none'}
}
},
less: {
bootstrapbase: {
files: {
"theme/bootstrapbase/style/moodle.css": "theme/bootstrapbase/less/moodle.less",
"theme/bootstrapbase/style/editor.css": "theme/bootstrapbase/less/editor.less",
},
options: {
compress: false // We must not compress to keep the comments.
}
}
},
watch: {
options: {
nospawn: true // We need not to spawn so config can be changed dynamically.
},
amd: {
files: ['**/amd/src/**/*.js'],
tasks: ['amd']
},
bootstrapbase: {
files: ["theme/bootstrapbase/less/**/*.less"],
tasks: ["css"]
},
yui: {
files: ['**/yui/src/**/*.js'],
tasks: ['yui']
},
gherkinlint: {
files: ['**/tests/behat/*.feature'],
tasks: ['gherkinlint']
}
},
shifter: {
options: {
recursive: true,
paths: [cwd]
}
},
gherkinlint: {
options: {
files: ['**/tests/behat/*.feature'],
}
},
stylelint: {
less: {
options: {
syntax: 'less',
configOverrides: {
rules: {
// These rules have to be disabled in .stylelintrc for scss compat.
"at-rule-no-unknown": true,
"no-browser-hacks": [true, {"severity": "warning"}]
}
}
},
src: ['theme/**/*.less']
},
scss: {
options: {syntax: 'scss'},
src: ['*/**/*.scss']
},
css: {
src: ['*/**/*.css'],
options: {
configOverrides: {
rules: {
// These rules have to be disabled in .stylelintrc for scss compat.
"at-rule-no-unknown": true,
"no-browser-hacks": [true, {"severity": "warning"}]
}
}
}
}
}
});
/**
* Generate ignore files (utilising thirdpartylibs.xml data)
*/
tasks.ignorefiles = function() {
// An array of paths to third party directories.
var thirdPartyPaths = getThirdPartyPathsFromXML();
// Generate .eslintignore.
var eslintIgnores = ['# Generated by "grunt ignorefiles"', '*/**/yui/src/*/meta/', '*/**/build/'].concat(thirdPartyPaths);
grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
// Generate .stylelintignore.
var stylelintIgnores = [
'# Generated by "grunt ignorefiles"',
'theme/bootstrapbase/style/',
'theme/clean/style/custom.css',
'theme/more/style/custom.css'
].concat(thirdPartyPaths);
grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
};
/**
* Shifter task. Is configured with a path to a specific file or a directory,
* in the case of a specific file it will work out the right module to be built.
*
* Note that this task runs the invidiaul shifter jobs async (becase it spawns
* so be careful to to call done().
*/
tasks.shifter = function() {
var done = this.async(),
options = grunt.config('shifter.options');
// Run the shifter processes one at a time to avoid confusing output.
async.eachSeries(options.paths, function(src, filedone) {
var args = [];
args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
// Always ignore the node_modules directory.
args.push('--excludes', 'node_modules');
// Determine the most appropriate options to run with based upon the current location.
if (grunt.file.isMatch('**/yui/**/*.js', src)) {
// When passed a JS file, build our containing module (this happen with
// watch).
grunt.log.debug('Shifter passed a specific JS file');
src = path.dirname(path.dirname(src));
options.recursive = false;
} else if (grunt.file.isMatch('**/yui/src', src)) {
// When in a src directory --walk all modules.
grunt.log.debug('In a src directory');
args.push('--walk');
options.recursive = false;
} else if (grunt.file.isMatch('**/yui/src/*', src)) {
// When in module, only build our module.
grunt.log.debug('In a module directory');
options.recursive = false;
} else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
// When in module src, only build our module.
grunt.log.debug('In a source directory');
src = path.dirname(src);
options.recursive = false;
}
if (grunt.option('watch')) {
grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
}
// Add the stderr option if appropriate
if (grunt.option('verbose')) {
args.push('--lint-stderr');
}
if (grunt.option('no-color')) {
args.push('--color=false');
}
var execShifter = function() {
grunt.log.ok("Running shifter on " + src);
grunt.util.spawn({
cmd: "node",
args: args,
opts: {cwd: src, stdio: 'inherit', env: process.env}
}, function(error, result, code) {
if (code) {
grunt.fail.fatal('Shifter failed with code: ' + code);
} else {
grunt.log.ok('Shifter build complete.');
filedone();
}
});
};
// Actually run shifter.
if (!options.recursive) {
execShifter();
} else {
// Check that there are yui modules otherwise shifter ends with exit code 1.
if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
args.push('--recursive');
execShifter();
} else {
grunt.log.ok('No YUI modules to build.');
filedone();
}
}
}, done);
};
tasks.gherkinlint = function() {
var done = this.async(),
options = grunt.config('gherkinlint.options');
var args = grunt.file.expand(options.files);
args.unshift(path.normalize(__dirname + '/node_modules/.bin/gherkin-lint'));
grunt.util.spawn({
cmd: 'node',
args: args,
opts: {stdio: 'inherit', env: process.env}
}, function(error, result, code) {
// Propagate the exit code.
done(code === 0);
});
};
tasks.startup = function() {
// Are we in a YUI directory?
if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
grunt.task.run('yui');
// Are we in an AMD directory?
} else if (inAMD) {
grunt.task.run('amd');
} else {
// Run them all!.
grunt.task.run('css');
grunt.task.run('js');
grunt.task.run('gherkinlint');
}
};
// On watch, we dynamically modify config to build only affected files. This
// method is slightly complicated to deal with multiple changed files at once (copied
// from the grunt-contrib-watch readme).
var changedFiles = Object.create(null);
var onChange = grunt.util._.debounce(function() {
var files = Object.keys(changedFiles);
grunt.config('eslint.amd.src', files);
grunt.config('eslint.yui.src', files);
grunt.config('uglify.amd.files', [{expand: true, src: files, rename: uglifyRename}]);
grunt.config('shifter.options.paths', files);
grunt.config('stylelint.less.src', files);
grunt.config('gherkinlint.options.files', files);
changedFiles = Object.create(null);
}, 200);
grunt.event.on('watch', function(action, filepath) {
changedFiles[filepath] = action;
onChange();
});
// Register NPM tasks.
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-eslint');
grunt.loadNpmTasks('grunt-stylelint');
// Register JS tasks.
grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
grunt.registerTask('yui', ['eslint:yui', 'shifter']);
grunt.registerTask('amd', ['eslint:amd', 'uglify']);
grunt.registerTask('js', ['amd', 'yui']);
// Register CSS taks.
grunt.registerTask('css', ['stylelint:scss', 'stylelint:less', 'less:bootstrapbase', 'stylelint:css']);
// Register the startup task.
grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
// Register the default task.
grunt.registerTask('default', ['startup']);
};
| macuco/moodlemacuco | Gruntfile.js | JavaScript | gpl-3.0 | 15,185 |
<?php
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* 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 Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*/
namespace Shopware\Bundle\StoreFrontBundle\Gateway\DBAL;
use Doctrine\DBAL\Connection;
use Shopware\Bundle\StoreFrontBundle\Struct;
use Shopware\Bundle\StoreFrontBundle\Gateway;
/**
* @category Shopware
* @package Shopware\Bundle\StoreFrontBundle\Gateway\DBAL
* @copyright Copyright (c) shopware AG (http://www.shopware.de)
*/
class MediaGateway implements Gateway\MediaGatewayInterface
{
/**
* @var Connection
*/
private $connection;
/**
* @var FieldHelper
*/
private $fieldHelper;
/**
* @var Hydrator\MediaHydrator
*/
private $hydrator;
/**
* @param Connection $connection
* @param FieldHelper $fieldHelper
* @param Hydrator\MediaHydrator $hydrator
*/
public function __construct(
Connection $connection,
FieldHelper $fieldHelper,
Hydrator\MediaHydrator $hydrator
) {
$this->connection = $connection;
$this->fieldHelper = $fieldHelper;
$this->hydrator = $hydrator;
}
/**
* @inheritdoc
*/
public function get($id, Struct\ShopContextInterface $context)
{
$media = $this->getList([$id], $context);
return array_shift($media);
}
/**
* @inheritdoc
*/
public function getList($ids, Struct\ShopContextInterface $context)
{
$query = $this->getQuery($context);
$query->setParameter(':ids', $ids, Connection::PARAM_INT_ARRAY);
/**@var $statement \Doctrine\DBAL\Driver\ResultStatement */
$statement = $query->execute();
$data = $statement->fetchAll(\PDO::FETCH_ASSOC);
$result = [];
foreach ($data as $row) {
$mediaId = $row['__media_id'];
$result[$mediaId] = $this->hydrator->hydrate($row);
}
return $result;
}
/**
* @return \Doctrine\DBAL\Query\QueryBuilder
*/
private function getQuery()
{
$query = $this->connection->createQueryBuilder();
$query->select($this->fieldHelper->getMediaFields());
$query->from('s_media', 'media')
->innerJoin('media', 's_media_album_settings', 'mediaSettings', 'mediaSettings.albumID = media.albumID')
->leftJoin('media', 's_media_attributes', 'mediaAttribute', 'mediaAttribute.mediaID = media.id');
$query->where('media.id IN (:ids)');
return $query;
}
}
| jenalgit/shopware | engine/Shopware/Bundle/StoreFrontBundle/Gateway/DBAL/MediaGateway.php | PHP | agpl-3.0 | 3,335 |
<?php
/**
* PHP-DI
*
* @link http://mnapoli.github.com/PHP-DI/
* @copyright Matthieu Napoli (http://mnapoli.fr/)
* @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file)
*/
namespace DI\Definition\Resolver;
use DI\Definition\Definition;
use DI\Definition\EnvironmentVariableDefinition;
use DI\Definition\Exception\DefinitionException;
use DI\Definition\Helper\DefinitionHelper;
/**
* Resolves a environment variable definition to a value.
*
* @author James Harris <james.harris@icecave.com.au>
*/
class EnvironmentVariableResolver implements DefinitionResolver
{
/**
* @var DefinitionResolver
*/
private $definitionResolver;
/**
* @var callable
*/
private $variableReader;
public function __construct(DefinitionResolver $definitionResolver, $variableReader = 'getenv')
{
$this->definitionResolver = $definitionResolver;
$this->variableReader = $variableReader;
}
/**
* Resolve an environment variable definition to a value.
*
* @param EnvironmentVariableDefinition $definition
*
* {@inheritdoc}
*/
public function resolve(Definition $definition, array $parameters = array())
{
$this->assertIsEnvironmentVariableDefinition($definition);
$value = call_user_func($this->variableReader, $definition->getVariableName());
if (false !== $value) {
return $value;
} elseif (!$definition->isOptional()) {
throw new DefinitionException(sprintf(
"The environment variable '%s' has not been defined",
$definition->getVariableName()
));
}
$value = $definition->getDefaultValue();
// Nested definition
if ($value instanceof DefinitionHelper) {
return $this->definitionResolver->resolve($value->getDefinition(''));
}
return $value;
}
/**
* @param EnvironmentVariableDefinition $definition
*
* {@inheritdoc}
*/
public function isResolvable(Definition $definition, array $parameters = array())
{
$this->assertIsEnvironmentVariableDefinition($definition);
return $definition->isOptional()
|| false !== call_user_func($this->variableReader, $definition->getVariableName());
}
private function assertIsEnvironmentVariableDefinition(Definition $definition)
{
if (!$definition instanceof EnvironmentVariableDefinition) {
throw new \InvalidArgumentException(sprintf(
'This definition resolver is only compatible with EnvironmentVariableDefinition objects, %s given',
get_class($definition)
));
}
}
}
| befair/soulShape | wp/soulshape.earth/piwik/vendor/php-di/php-di/src/DI/Definition/Resolver/EnvironmentVariableResolver.php | PHP | agpl-3.0 | 2,757 |
// ThreadNotify.cs: implements a notification for the thread running the Gtk main
// loop from another thread
//
// Authors:
// Miguel de Icaza (miguel@ximian.com).
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// Copyright (c) 2002 Ximian, Inc.
// Copyright (c) 2004 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace Gtk {
using System.Runtime.InteropServices;
using System.Threading;
using System;
// <summary>
// This delegate will be invoked on the main Gtk thread.
// </summary>
public delegate void ReadyEvent ();
/// <summary>
/// Utility class to help writting multi-threaded Gtk applications
/// </summary>
/// <remarks/>
///
public class ThreadNotify : IDisposable {
bool disposed;
ReadyEvent re;
GLib.IdleHandler idle;
bool notified;
/// <summary>
/// The ReadyEvent delegate will be invoked on the current thread (which should
/// be the Gtk thread) when another thread wakes us up by calling WakeupMain
/// </summary>
public ThreadNotify (ReadyEvent re)
{
this.re = re;
idle = new GLib.IdleHandler (CallbackWrapper);
}
bool CallbackWrapper ()
{
lock (this) {
if (disposed)
return false;
notified = false;
}
re ();
return false;
}
/// <summary>
/// Invoke this function from a thread to call the `ReadyEvent'
/// delegate provided in the constructor on the Main Gtk thread
/// </summary>
public void WakeupMain ()
{
lock (this){
if (notified)
return;
notified = true;
GLib.Idle.Add (idle);
}
}
public void Close ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
~ThreadNotify ()
{
Dispose (false);
}
void IDisposable.Dispose ()
{
Close ();
}
protected virtual void Dispose (bool disposing)
{
lock (this) {
disposed = true;
}
}
}
}
| stsundermann/gtk-sharp-gi | sources/custom/ThreadNotify.cs | C# | lgpl-3.0 | 2,506 |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SampleSmartConsole")]
[assembly: AssemblyDescription("")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7aa1ea3e-415f-4b0d-a3eb-0cb6aaacd87b")] | imbugs/StockSharp | Samples/SmartCom/SampleSmartConsole/Properties/AssemblyInfo.cs | C# | lgpl-3.0 | 481 |
/*
* 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.jena.hadoop.rdf.mapreduce.filter;
import java.io.IOException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mrunit.mapreduce.MapDriver;
import org.apache.jena.hadoop.rdf.mapreduce.AbstractMapperTests;
import org.apache.jena.hadoop.rdf.mapreduce.filter.AbstractNodeTupleFilterMapper;
import org.apache.jena.hadoop.rdf.types.AbstractNodeTupleWritable;
import org.junit.Test;
/**
* Abstract tests for {@link AbstractNodeTupleFilterMapper} implementations
* which filter based on the validity of tuples
*
*
*
* @param <TValue>
* Tuple type
* @param <T>
* Writable tuple type
*/
public abstract class AbstractNodeTupleFilterTests<TValue, T extends AbstractNodeTupleWritable<TValue>> extends
AbstractMapperTests<LongWritable, T, LongWritable, T> {
protected final void generateData(MapDriver<LongWritable, T, LongWritable, T> driver, int num) {
for (int i = 0; i < num; i++) {
LongWritable key = new LongWritable(i);
if (i % 2 == 0 && !this.noValidInputs()) {
T value = this.createValidValue(i);
driver.addInput(key, value);
if (!this.isInverted())
driver.addOutput(key, value);
} else {
T value = this.createInvalidValue(i);
driver.addInput(key, value);
if (this.isInverted())
driver.addOutput(key, value);
}
}
}
/**
* Method that may be overridden for testing filters where all the generated
* data will be rejected as invalid
*
* @return True if there are no valid inputs, false otherwise (default)
*/
protected boolean noValidInputs() {
return false;
}
/**
* Method that may be overridden for testing filters with inverted mode
* enabled i.e. where normally valid input is considered invalid and vice
* versa
*
* @return True if inverted, false otherwise (default)
*/
protected boolean isInverted() {
return false;
}
/**
* Creates an invalid value
*
* @param i
* Key
* @return Invalid value
*/
protected abstract T createInvalidValue(int i);
/**
* Creates a valid value
*
* @param i
* Key
* @return Valid value
*/
protected abstract T createValidValue(int i);
protected final void testFilterValid(int num) throws IOException {
MapDriver<LongWritable, T, LongWritable, T> driver = this.getMapDriver();
this.generateData(driver, num);
driver.runTest();
}
/**
* Test splitting tuples into their constituent nodes
*
* @throws IOException
*/
@Test
public final void filter_valid_01() throws IOException {
this.testFilterValid(1);
}
/**
* Test splitting tuples into their constituent nodes
*
* @throws IOException
*/
@Test
public final void filter_valid_02() throws IOException {
this.testFilterValid(100);
}
/**
* Test splitting tuples into their constituent nodes
*
* @throws IOException
*/
@Test
public final void filter_valid_03() throws IOException {
this.testFilterValid(1000);
}
/**
* Test splitting tuples into their constituent nodes
*
* @throws IOException
*/
@Test
public final void filter_valid_04() throws IOException {
this.testFilterValid(2500);
}
}
| samaitra/jena | jena-elephas/jena-elephas-mapreduce/src/test/java/org/apache/jena/hadoop/rdf/mapreduce/filter/AbstractNodeTupleFilterTests.java | Java | apache-2.0 | 4,405 |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticloadbalancing-2012-06-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElasticLoadBalancing.Model
{
/// <summary>
/// Container for the parameters to the CreateLoadBalancerPolicy operation.
/// Creates a new policy that contains the necessary attributes depending on the policy
/// type. Policies are settings that are saved for your load balancer and that can be
/// applied to the front-end listener, or the back-end application server, depending on
/// your policy type.
/// </summary>
public partial class CreateLoadBalancerPolicyRequest : AmazonElasticLoadBalancingRequest
{
private string _loadBalancerName;
private List<PolicyAttribute> _policyAttributes = new List<PolicyAttribute>();
private string _policyName;
private string _policyTypeName;
/// <summary>
/// Gets and sets the property LoadBalancerName.
/// <para>
/// The name associated with the LoadBalancer for which the policy is being created.
///
/// </para>
/// </summary>
public string LoadBalancerName
{
get { return this._loadBalancerName; }
set { this._loadBalancerName = value; }
}
// Check to see if LoadBalancerName property is set
internal bool IsSetLoadBalancerName()
{
return this._loadBalancerName != null;
}
/// <summary>
/// Gets and sets the property PolicyAttributes.
/// <para>
/// A list of attributes associated with the policy being created.
/// </para>
/// </summary>
public List<PolicyAttribute> PolicyAttributes
{
get { return this._policyAttributes; }
set { this._policyAttributes = value; }
}
// Check to see if PolicyAttributes property is set
internal bool IsSetPolicyAttributes()
{
return this._policyAttributes != null && this._policyAttributes.Count > 0;
}
/// <summary>
/// Gets and sets the property PolicyName.
/// <para>
/// The name of the load balancer policy being created. The name must be unique within
/// the set of policies for this load balancer.
/// </para>
/// </summary>
public string PolicyName
{
get { return this._policyName; }
set { this._policyName = value; }
}
// Check to see if PolicyName property is set
internal bool IsSetPolicyName()
{
return this._policyName != null;
}
/// <summary>
/// Gets and sets the property PolicyTypeName.
/// <para>
/// The name of the base policy type being used to create this policy. To get the list
/// of policy types, use the <a>DescribeLoadBalancerPolicyTypes</a> action.
/// </para>
/// </summary>
public string PolicyTypeName
{
get { return this._policyTypeName; }
set { this._policyTypeName = value; }
}
// Check to see if PolicyTypeName property is set
internal bool IsSetPolicyTypeName()
{
return this._policyTypeName != null;
}
}
} | ykbarros/aws-sdk-xamarin | AWS.XamarinSDK/AWSSDK_iOS/Amazon.ElasticLoadBalancing/Model/CreateLoadBalancerPolicyRequest.cs | C# | apache-2.0 | 4,107 |
/* ====================================================================
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.
==================================================================== */
using NPOI.HWPF.UserModel;
using NPOI.HWPF.Model;
using System;
namespace NPOI.HWPF.UserModel
{
/**
* A HeaderStory is a Header, a Footer, or footnote/endnote
* separator.
* All the Header Stories get stored in the same Range in the
* document, and this handles Getting out all the individual
* parts.
*
* WARNING - you shouldn't change the headers or footers,
* as offSets are not yet updated!
*/
public class HeaderStories
{
private Range headerStories;
private PlexOfCps plcfHdd;
private bool stripFields = false;
public HeaderStories(HWPFDocument doc)
{
this.headerStories = doc.GetHeaderStoryRange();
FileInformationBlock fib = doc.GetFileInformationBlock();
// If there's no PlcfHdd, nothing to do
if (fib.GetCcpHdd() == 0)
{
return;
}
if (fib.GetPlcfHddSize() == 0)
{
return;
}
// Handle the PlcfHdd
plcfHdd = new PlexOfCps(
doc.GetTableStream(), fib.GetPlcfHddOffset(),
fib.GetPlcfHddSize(), 0
);
}
public String FootnoteSeparator
{
get{
return GetAt(0);
}
}
public String FootnoteContSeparator
{
get{
return GetAt(1);
}
}
public String FootnoteContNote
{
get{
return GetAt(2);
}
}
public String EndnoteSeparator
{
get{
return GetAt(3);
}
}
public String EndnoteContSeparator
{
get{
return GetAt(4);
}
}
public String EndnoteContNote
{
get
{
return GetAt(5);
}
}
public String EvenHeader
{
get
{
return GetAt(6 + 0);
}
}
public String OddHeader
{
get
{
return GetAt(6 + 1);
}
}
public String FirstHeader
{
get
{
return GetAt(6 + 4);
}
}
/**
* Returns the correct, defined header for the given
* one based page
* @param pageNumber The one based page number
*/
public String GetHeader(int pageNumber)
{
// First page header is optional, only return
// if it's set
if (pageNumber == 1)
{
if (FirstHeader.Length > 0)
{
return FirstHeader;
}
}
// Even page header is optional, only return
// if it's set
if (pageNumber % 2 == 0)
{
if (EvenHeader.Length > 0)
{
return EvenHeader;
}
}
// Odd is the default
return OddHeader;
}
public String EvenFooter
{
get
{
return GetAt(6 + 2);
}
}
public String OddFooter
{
get
{
return GetAt(6 + 3);
}
}
public String FirstFooter
{
get
{
return GetAt(6 + 5);
}
}
/**
* Returns the correct, defined footer for the given
* one based page
* @param pageNumber The one based page number
*/
public String GetFooter(int pageNumber)
{
// First page footer is optional, only return
// if it's set
if (pageNumber == 1)
{
if (FirstFooter.Length > 0)
{
return FirstFooter;
}
}
// Even page footer is optional, only return
// if it's set
if (pageNumber % 2 == 0)
{
if (EvenFooter.Length > 0)
{
return EvenFooter;
}
}
// Odd is the default
return OddFooter;
}
/**
* Get the string that's pointed to by the
* given plcfHdd index
*/
private String GetAt(int plcfHddIndex)
{
if (plcfHdd == null) return null;
GenericPropertyNode prop = plcfHdd.GetProperty(plcfHddIndex);
if (prop.Start == prop.End)
{
// Empty story
return "";
}
if (prop.End < prop.Start)
{
// Broken properties?
return "";
}
// Ensure we're Getting a sensible length
String rawText = headerStories.Text;
int start = Math.Min(prop.Start, rawText.Length);
int end = Math.Min(prop.End, rawText.Length);
// Grab the contents
String text = rawText.Substring(start, end-start);
// Strip off fields and macros if requested
if (stripFields)
{
return Range.StripFields(text);
}
// If you create a header/footer, then remove it again, word
// will leave \r\r. Turn these back into an empty string,
// which is more what you'd expect
if (text.Equals("\r\r"))
{
return "";
}
return text;
}
public Range GetRange()
{
return headerStories;
}
internal PlexOfCps GetPlcfHdd()
{
return plcfHdd;
}
/**
* Are fields currently being stripped from
* the text that this {@link HeaderStories} returns?
* Default is false, but can be Changed
*/
public bool AreFieldsStripped
{
get
{
return stripFields;
}
set
{
this.stripFields = value;
}
}
}
}
| antony-liu/npoi | scratchpad/HWPF/UserModel/HeaderStories.cs | C# | apache-2.0 | 7,342 |
package org.apache.helix;
/*
* 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.
*/
import java.util.List;
import org.apache.helix.model.Message;
/**
* Interface to implement when there is a change to messages
*/
public interface MessageListener {
/**
* Invoked when message changes
* @param instanceName
* @param messages
* @param changeContext
*/
public void onMessage(String instanceName, List<Message> messages,
NotificationContext changeContext);
}
| OopsOutOfMemory/helix | helix-core/src/main/java/org/apache/helix/MessageListener.java | Java | apache-2.0 | 1,237 |
/*
* Copyright (C) 2011 the original author or authors.
* See the notice.md file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.iq80.leveldb.impl;
import org.iq80.leveldb.util.Slice;
import java.io.File;
import java.io.IOException;
public interface LogWriter
{
boolean isClosed();
void close()
throws IOException;
void delete()
throws IOException;
File getFile();
long getFileNumber();
// Writes a stream of chunks such that no chunk is split across a block boundary
void addRecord(Slice record, boolean force)
throws IOException;
}
| gaoch023/leveldb-1 | leveldb/src/main/java/org/iq80/leveldb/impl/LogWriter.java | Java | apache-2.0 | 1,222 |
package com.crawljax.core;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.Lock;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.crawljax.core.configuration.BrowserConfiguration;
import com.crawljax.core.state.Eventable.EventType;
import com.crawljax.core.state.StateFlowGraph;
import com.crawljax.core.state.StateVertex;
import com.crawljax.metrics.MetricsModule;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.common.collect.Queues;
import com.google.common.util.concurrent.Striped;
/**
* Contains all the {@link CandidateCrawlAction}s that still have to be fired to get a result.
*/
@Singleton
public class UnfiredCandidateActions {
private static final Logger LOG = LoggerFactory.getLogger(UnfiredCandidateActions.class);
private final Map<Integer, Queue<CandidateCrawlAction>> cache;
private final BlockingQueue<Integer> statesWithCandidates;
private final Striped<Lock> locks;
private final Provider<StateFlowGraph> sfg;
private final Counter crawlerLostCount;
private final Counter unfiredActionsCount;
@Inject
UnfiredCandidateActions(BrowserConfiguration config, Provider<StateFlowGraph> sfg,
MetricRegistry registry) {
this.sfg = sfg;
cache = Maps.newHashMap();
statesWithCandidates = Queues.newLinkedBlockingQueue();
// Every browser gets a lock.
locks = Striped.lock(config.getNumberOfBrowsers());
crawlerLostCount =
registry.register(MetricsModule.EVENTS_PREFIX + "crawler_lost", new Counter());
unfiredActionsCount =
registry.register(MetricsModule.EVENTS_PREFIX + "unfired_actions", new Counter());
}
/**
* @param state
* The state you want to poll an {@link CandidateCrawlAction} for.
* @return The next to-be-crawled action or <code>null</code> if none available.
*/
CandidateCrawlAction pollActionOrNull(StateVertex state) {
LOG.debug("Polling action for state {}", state.getName());
Lock lock = locks.get(state.getId());
try {
lock.lock();
Queue<CandidateCrawlAction> queue = cache.get(state.getId());
if (queue == null) {
return null;
} else {
CandidateCrawlAction action = queue.poll();
if (queue.isEmpty()) {
LOG.debug("All actions polled for state {}", state.getName());
cache.remove(state.getId());
removeStateFromQueue(state.getId());
LOG.debug("There are now {} states with unfinished actions", cache.size());
}
return action;
}
} finally {
lock.unlock();
}
}
private void removeStateFromQueue(int id) {
while (statesWithCandidates.remove(id)) {
LOG.trace("Removed id {} from the queue", id);
}
}
/**
* @param extract
* The actions you want to add to a state.
* @param currentState
* The state you are in.
*/
public void addActions(ImmutableList<CandidateElement> extract, StateVertex currentState) {
List<CandidateCrawlAction> actions = new ArrayList<>(extract.size());
for (CandidateElement candidateElement : extract) {
actions.add(new CandidateCrawlAction(candidateElement, EventType.click));
}
addActions(actions, currentState);
}
/**
* @param actions
* The actions you want to add to a state.
* @param state
* The state name. This should be unique per state.
*/
void addActions(Collection<CandidateCrawlAction> actions, StateVertex state) {
if (actions.isEmpty()) {
LOG.debug("Received empty actions list. Ignoring...");
return;
}
Lock lock = locks.get(state.getId());
try {
lock.lock();
LOG.debug("Adding {} crawl actions for state {}", actions.size(), state.getId());
if (cache.containsKey(state.getId())) {
cache.get(state.getId()).addAll(actions);
} else {
cache.put(state.getId(), Queues.newConcurrentLinkedQueue(actions));
}
statesWithCandidates.add(state.getId());
LOG.info("There are {} states with unfired actions", statesWithCandidates.size());
} finally {
lock.unlock();
}
}
/**
* @return If there are any pending actions to be crawled. This method is not threadsafe and
* might return a stale value.
*/
public boolean isEmpty() {
return statesWithCandidates.isEmpty();
}
/**
* @return A new crawl task as soon as one is ready. Until then, it blocks.
* @throws InterruptedException
* when taking from the queue is interrupted.
*/
public StateVertex awaitNewTask() throws InterruptedException {
int id = statesWithCandidates.take();
// Put it back the end of the queue. It will be removed later.
statesWithCandidates.add(id);
LOG.debug("New task polled for state {}", id);
LOG.info("There are {} states with unfired actions", statesWithCandidates.size());
return sfg.get().getById(id);
}
public void purgeActionsForState(StateVertex crawlTask) {
Lock lock = locks.get(crawlTask.getId());
try {
lock.lock();
LOG.debug("Removing tasks for target state {}", crawlTask.getName());
removeStateFromQueue(crawlTask.getId());
Queue<CandidateCrawlAction> removed = cache.remove(crawlTask.getId());
if (removed != null) {
unfiredActionsCount.inc(removed.size());
}
} finally {
lock.unlock();
crawlerLostCount.inc();
}
}
}
| fivejjs/crawljax | core/src/main/java/com/crawljax/core/UnfiredCandidateActions.java | Java | apache-2.0 | 5,551 |
/**
* 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 java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.server.common.HdfsConstants;
import org.apache.hadoop.hdfs.server.common.InconsistentFSStateException;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol;
import org.apache.hadoop.http.HttpServer;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.metrics2.source.JvmMetricsSource;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.Krb5AndCertsSslSocketConnector;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.Daemon;
import org.apache.hadoop.util.StringUtils;
/**********************************************************
* The Secondary NameNode is a helper to the primary NameNode.
* The Secondary is responsible for supporting periodic checkpoints
* of the HDFS metadata. The current design allows only one Secondary
* NameNode per HDFs cluster.
*
* The Secondary NameNode is a daemon that periodically wakes
* up (determined by the schedule specified in the configuration),
* triggers a periodic checkpoint and then goes back to sleep.
* The Secondary NameNode uses the ClientProtocol to talk to the
* primary NameNode.
*
**********************************************************/
public class SecondaryNameNode implements Runnable {
static{
Configuration.addDefaultResource("hdfs-default.xml");
Configuration.addDefaultResource("hdfs-site.xml");
}
public static final Log LOG =
LogFactory.getLog(SecondaryNameNode.class.getName());
private String fsName;
private CheckpointStorage checkpointImage;
private NamenodeProtocol namenode;
private Configuration conf;
private InetSocketAddress nameNodeAddr;
private volatile boolean shouldRun;
private HttpServer infoServer;
private int infoPort;
private int imagePort;
private String infoBindAddress;
private Collection<File> checkpointDirs;
private Collection<File> checkpointEditsDirs;
private long checkpointPeriod; // in seconds
private long checkpointSize; // size (in MB) of current Edit Log
/**
* Utility class to facilitate junit test error simulation.
*/
static class ErrorSimulator {
private static boolean[] simulation = null; // error simulation events
static void initializeErrorSimulationEvent(int numberOfEvents) {
simulation = new boolean[numberOfEvents];
for (int i = 0; i < numberOfEvents; i++) {
simulation[i] = false;
}
}
static boolean getErrorSimulation(int index) {
if(simulation == null)
return false;
assert(index < simulation.length);
return simulation[index];
}
static void setErrorSimulation(int index) {
assert(index < simulation.length);
simulation[index] = true;
}
static void clearErrorSimulation(int index) {
assert(index < simulation.length);
simulation[index] = false;
}
}
FSImage getFSImage() {
return checkpointImage;
}
/**
* Create a connection to the primary namenode.
*/
public SecondaryNameNode(Configuration conf) throws IOException {
try {
initialize(conf);
} catch(IOException e) {
shutdown();
throw e;
}
}
@SuppressWarnings("deprecation")
public static InetSocketAddress getHttpAddress(Configuration conf) {
String infoAddr = NetUtils.getServerAddress(conf,
"dfs.secondary.info.bindAddress", "dfs.secondary.info.port",
"dfs.secondary.http.address");
return NetUtils.createSocketAddr(infoAddr);
}
/**
* Initialize SecondaryNameNode.
*/
private void initialize(final Configuration conf) throws IOException {
final InetSocketAddress infoSocAddr = getHttpAddress(conf);
infoBindAddress = infoSocAddr.getHostName();
if (UserGroupInformation.isSecurityEnabled()) {
SecurityUtil.login(conf,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_USER_NAME_KEY,
infoBindAddress);
}
// initiate Java VM metrics
JvmMetricsSource.create("SecondaryNameNode", conf.get("session.id"));
// Create connection to the namenode.
shouldRun = true;
nameNodeAddr = NameNode.getServiceAddress(conf, true);
this.conf = conf;
this.namenode =
(NamenodeProtocol) RPC.waitForProxy(NamenodeProtocol.class,
NamenodeProtocol.versionID, nameNodeAddr, conf);
// initialize checkpoint directories
fsName = getInfoServer();
checkpointDirs = FSImage.getCheckpointDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointEditsDirs = FSImage.getCheckpointEditsDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointImage = new CheckpointStorage();
checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);
// Initialize other scheduling parameters from the configuration
checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
checkpointSize = conf.getLong("fs.checkpoint.size", 4194304);
// initialize the webserver for uploading files.
// Kerberized SSL servers must be run from the host principal...
UserGroupInformation httpUGI =
UserGroupInformation.loginUserFromKeytabAndReturnUGI(
SecurityUtil.getServerPrincipal(conf
.get(DFSConfigKeys.DFS_SECONDARY_NAMENODE_KRB_HTTPS_USER_NAME_KEY),
infoBindAddress),
conf.get(DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY));
try {
infoServer = httpUGI.doAs(new PrivilegedExceptionAction<HttpServer>() {
@Override
public HttpServer run() throws IOException, InterruptedException {
LOG.info("Starting web server as: " +
UserGroupInformation.getCurrentUser().getUserName());
int tmpInfoPort = infoSocAddr.getPort();
infoServer = new HttpServer("secondary", infoBindAddress, tmpInfoPort,
tmpInfoPort == 0, conf,
SecurityUtil.getAdminAcls(conf, DFSConfigKeys.DFS_ADMIN));
if(UserGroupInformation.isSecurityEnabled()) {
System.setProperty("https.cipherSuites",
Krb5AndCertsSslSocketConnector.KRB5_CIPHER_SUITES.get(0));
InetSocketAddress secInfoSocAddr =
NetUtils.createSocketAddr(infoBindAddress + ":"+ conf.get(
"dfs.secondary.https.port", infoBindAddress + ":" + 0));
imagePort = secInfoSocAddr.getPort();
infoServer.addSslListener(secInfoSocAddr, conf, false, true);
}
infoServer.setAttribute("name.system.image", checkpointImage);
infoServer.setAttribute(JspHelper.CURRENT_CONF, conf);
infoServer.addInternalServlet("getimage", "/getimage",
GetImageServlet.class, true);
infoServer.start();
return infoServer;
}
});
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
LOG.info("Web server init done");
// The web-server port can be ephemeral... ensure we have the correct info
infoPort = infoServer.getPort();
if(!UserGroupInformation.isSecurityEnabled())
imagePort = infoPort;
conf.set("dfs.secondary.http.address", infoBindAddress + ":" +infoPort);
LOG.info("Secondary Web-server up at: " + infoBindAddress + ":" +infoPort);
LOG.info("Secondary image servlet up at: " + infoBindAddress + ":" + imagePort);
LOG.warn("Checkpoint Period :" + checkpointPeriod + " secs " +
"(" + checkpointPeriod/60 + " min)");
LOG.warn("Log Size Trigger :" + checkpointSize + " bytes " +
"(" + checkpointSize/1024 + " KB)");
}
/**
* Shut down this instance of the datanode.
* Returns only after shutdown is complete.
*/
public void shutdown() {
shouldRun = false;
try {
if (infoServer != null) infoServer.stop();
} catch (Exception e) {
LOG.warn("Exception shutting down SecondaryNameNode", e);
}
try {
if (checkpointImage != null) checkpointImage.close();
} catch(IOException e) {
LOG.warn(StringUtils.stringifyException(e));
}
}
public void run() {
if (UserGroupInformation.isSecurityEnabled()) {
UserGroupInformation ugi = null;
try {
ugi = UserGroupInformation.getLoginUser();
} catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
Runtime.getRuntime().exit(-1);
}
ugi.doAs(new PrivilegedAction<Object>() {
@Override
public Object run() {
doWork();
return null;
}
});
} else {
doWork();
}
}
//
// The main work loop
//
public void doWork() {
//
// Poll the Namenode (once every 5 minutes) to find the size of the
// pending edit log.
//
long period = 5 * 60; // 5 minutes
long lastCheckpointTime = 0;
if (checkpointPeriod < period) {
period = checkpointPeriod;
}
while (shouldRun) {
try {
Thread.sleep(1000 * period);
} catch (InterruptedException ie) {
// do nothing
}
if (!shouldRun) {
break;
}
try {
// We may have lost our ticket since last checkpoint, log in again, just in case
if(UserGroupInformation.isSecurityEnabled())
UserGroupInformation.getCurrentUser().reloginFromKeytab();
long now = System.currentTimeMillis();
long size = namenode.getEditLogSize();
if (size >= checkpointSize ||
now >= lastCheckpointTime + 1000 * checkpointPeriod) {
doCheckpoint();
lastCheckpointTime = now;
}
} catch (IOException e) {
LOG.error("Exception in doCheckpoint: ");
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
} catch (Throwable e) {
LOG.error("Throwable Exception in doCheckpoint: ");
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
Runtime.getRuntime().exit(-1);
}
}
}
/**
* Download <code>fsimage</code> and <code>edits</code>
* files from the name-node.
* @throws IOException
*/
private void downloadCheckpointFiles(final CheckpointSignature sig
) throws IOException {
try {
UserGroupInformation.getCurrentUser().doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
checkpointImage.cTime = sig.cTime;
checkpointImage.checkpointTime = sig.checkpointTime;
// get fsimage
String fileid = "getimage=1";
File[] srcNames = checkpointImage.getImageFiles();
assert srcNames.length > 0 : "No checkpoint targets.";
TransferFsImage.getFileClient(fsName, fileid, srcNames);
LOG.info("Downloaded file " + srcNames[0].getName() + " size " +
srcNames[0].length() + " bytes.");
// get edits file
fileid = "getedit=1";
srcNames = checkpointImage.getEditsFiles();
assert srcNames.length > 0 : "No checkpoint targets.";
TransferFsImage.getFileClient(fsName, fileid, srcNames);
LOG.info("Downloaded file " + srcNames[0].getName() + " size " +
srcNames[0].length() + " bytes.");
checkpointImage.checkpointUploadDone();
return null;
}
});
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
/**
* Copy the new fsimage into the NameNode
*/
private void putFSImage(CheckpointSignature sig) throws IOException {
String fileid = "putimage=1&port=" + imagePort +
"&machine=" + infoBindAddress +
"&token=" + sig.toString();
LOG.info("Posted URL " + fsName + fileid);
TransferFsImage.getFileClient(fsName, fileid, (File[])null);
}
/**
* Returns the Jetty server that the Namenode is listening on.
*/
private String getInfoServer() throws IOException {
URI fsName = FileSystem.getDefaultUri(conf);
if (!"hdfs".equals(fsName.getScheme())) {
throw new IOException("This is not a DFS");
}
String infoAddr = NameNode.getInfoServer(conf);
LOG.debug("infoAddr = " + infoAddr);
return infoAddr;
}
/**
* Create a new checkpoint
*/
void doCheckpoint() throws IOException {
// Do the required initialization of the merge work area.
startCheckpoint();
// Tell the namenode to start logging transactions in a new edit file
// Retuns a token that would be used to upload the merged image.
CheckpointSignature sig = (CheckpointSignature)namenode.rollEditLog();
// error simulation code for junit test
if (ErrorSimulator.getErrorSimulation(0)) {
throw new IOException("Simulating error0 " +
"after creating edits.new");
}
downloadCheckpointFiles(sig); // Fetch fsimage and edits
doMerge(sig); // Do the merge
//
// Upload the new image into the NameNode. Then tell the Namenode
// to make this new uploaded image as the most current image.
//
putFSImage(sig);
// error simulation code for junit test
if (ErrorSimulator.getErrorSimulation(1)) {
throw new IOException("Simulating error1 " +
"after uploading new image to NameNode");
}
namenode.rollFsImage();
checkpointImage.endCheckpoint();
LOG.warn("Checkpoint done. New Image Size: "
+ checkpointImage.getFsImageName().length());
}
private void startCheckpoint() throws IOException {
checkpointImage.unlockAll();
checkpointImage.getEditLog().close();
checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);
checkpointImage.startCheckpoint();
}
/**
* Merge downloaded image and edits and write the new image into
* current storage directory.
*/
private void doMerge(CheckpointSignature sig) throws IOException {
FSNamesystem namesystem =
new FSNamesystem(checkpointImage, conf);
assert namesystem.dir.fsImage == checkpointImage;
checkpointImage.doMerge(sig);
}
/**
* @param argv The parameters passed to this program.
* @exception Exception if the filesystem does not exist.
* @return 0 on success, non zero on error.
*/
private int processArgs(String[] argv) throws Exception {
if (argv.length < 1) {
printUsage("");
return -1;
}
int exitCode = -1;
int i = 0;
String cmd = argv[i++];
//
// verify that we have enough command line parameters
//
if ("-geteditsize".equals(cmd)) {
if (argv.length != 1) {
printUsage(cmd);
return exitCode;
}
} else if ("-checkpoint".equals(cmd)) {
if (argv.length != 1 && argv.length != 2) {
printUsage(cmd);
return exitCode;
}
if (argv.length == 2 && !"force".equals(argv[i])) {
printUsage(cmd);
return exitCode;
}
}
exitCode = 0;
try {
if ("-checkpoint".equals(cmd)) {
long size = namenode.getEditLogSize();
if (size >= checkpointSize ||
argv.length == 2 && "force".equals(argv[i])) {
doCheckpoint();
} else {
System.err.println("EditLog size " + size + " bytes is " +
"smaller than configured checkpoint " +
"size " + checkpointSize + " bytes.");
System.err.println("Skipping checkpoint.");
}
} else if ("-geteditsize".equals(cmd)) {
long size = namenode.getEditLogSize();
System.out.println("EditLog size is " + size + " bytes");
} else {
exitCode = -1;
LOG.error(cmd.substring(1) + ": Unknown command");
printUsage("");
}
} catch (RemoteException e) {
//
// This is a error returned by hadoop server. Print
// out the first line of the error mesage, ignore the stack trace.
exitCode = -1;
try {
String[] content;
content = e.getLocalizedMessage().split("\n");
LOG.error(cmd.substring(1) + ": "
+ content[0]);
} catch (Exception ex) {
LOG.error(cmd.substring(1) + ": "
+ ex.getLocalizedMessage());
}
} catch (IOException e) {
//
// IO exception encountered locally.
//
exitCode = -1;
LOG.error(cmd.substring(1) + ": "
+ e.getLocalizedMessage());
} finally {
// Does the RPC connection need to be closed?
}
return exitCode;
}
/**
* Displays format of commands.
* @param cmd The command that is being executed.
*/
private void printUsage(String cmd) {
if ("-geteditsize".equals(cmd)) {
System.err.println("Usage: java SecondaryNameNode"
+ " [-geteditsize]");
} else if ("-checkpoint".equals(cmd)) {
System.err.println("Usage: java SecondaryNameNode"
+ " [-checkpoint [force]]");
} else {
System.err.println("Usage: java SecondaryNameNode " +
"[-checkpoint [force]] " +
"[-geteditsize] ");
}
}
/**
* main() has some simple utility methods.
* @param argv Command line parameters.
* @exception Exception if the filesystem does not exist.
*/
public static void main(String[] argv) throws Exception {
StringUtils.startupShutdownMessage(SecondaryNameNode.class, argv, LOG);
Configuration tconf = new Configuration();
if (argv.length >= 1) {
SecondaryNameNode secondary = new SecondaryNameNode(tconf);
int ret = secondary.processArgs(argv);
System.exit(ret);
}
// Create a never ending deamon
Daemon checkpointThread = new Daemon(new SecondaryNameNode(tconf));
checkpointThread.start();
}
static class CheckpointStorage extends FSImage {
/**
*/
CheckpointStorage() throws IOException {
super();
}
@Override
public
boolean isConversionNeeded(StorageDirectory sd) {
return false;
}
/**
* Analyze checkpoint directories.
* Create directories if they do not exist.
* Recover from an unsuccessful checkpoint is necessary.
*
* @param dataDirs
* @param editsDirs
* @throws IOException
*/
void recoverCreate(Collection<File> dataDirs,
Collection<File> editsDirs) throws IOException {
Collection<File> tempDataDirs = new ArrayList<File>(dataDirs);
Collection<File> tempEditsDirs = new ArrayList<File>(editsDirs);
this.storageDirs = new ArrayList<StorageDirectory>();
setStorageDirectories(tempDataDirs, tempEditsDirs);
for (Iterator<StorageDirectory> it =
dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
boolean isAccessible = true;
try { // create directories if don't exist yet
if(!sd.getRoot().mkdirs()) {
// do nothing, directory is already created
}
} catch(SecurityException se) {
isAccessible = false;
}
if(!isAccessible)
throw new InconsistentFSStateException(sd.getRoot(),
"cannot access checkpoint directory.");
StorageState curState;
try {
curState = sd.analyzeStorage(HdfsConstants.StartupOption.REGULAR);
// sd is locked but not opened
switch(curState) {
case NON_EXISTENT:
// fail if any of the configured checkpoint dirs are inaccessible
throw new InconsistentFSStateException(sd.getRoot(),
"checkpoint directory does not exist or is not accessible.");
case NOT_FORMATTED:
break; // it's ok since initially there is no current and VERSION
case NORMAL:
break;
default: // recovery is possible
sd.doRecover(curState);
}
} catch (IOException ioe) {
sd.unlock();
throw ioe;
}
}
}
/**
* Prepare directories for a new checkpoint.
* <p>
* Rename <code>current</code> to <code>lastcheckpoint.tmp</code>
* and recreate <code>current</code>.
* @throws IOException
*/
void startCheckpoint() throws IOException {
for(StorageDirectory sd : storageDirs) {
moveCurrent(sd);
}
}
void endCheckpoint() throws IOException {
for(StorageDirectory sd : storageDirs) {
moveLastCheckpoint(sd);
}
}
/**
* Merge image and edits, and verify consistency with the signature.
*/
private void doMerge(CheckpointSignature sig) throws IOException {
getEditLog().open();
StorageDirectory sdName = null;
StorageDirectory sdEdits = null;
Iterator<StorageDirectory> it = null;
it = dirIterator(NameNodeDirType.IMAGE);
if (it.hasNext())
sdName = it.next();
it = dirIterator(NameNodeDirType.EDITS);
if (it.hasNext())
sdEdits = it.next();
if ((sdName == null) || (sdEdits == null))
throw new IOException("Could not locate checkpoint directories");
loadFSImage(FSImage.getImageFile(sdName, NameNodeFile.IMAGE));
loadFSEdits(sdEdits);
sig.validateStorageInfo(this);
saveNamespace(false);
}
}
}
| pombredanne/brisk-hadoop-common | src/hdfs/org/apache/hadoop/hdfs/server/namenode/SecondaryNameNode.java | Java | apache-2.0 | 23,008 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.engine;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.Iterator;
public class SegmentsStats implements Streamable, ToXContent {
private long count;
private long memoryInBytes;
private long termsMemoryInBytes;
private long storedFieldsMemoryInBytes;
private long termVectorsMemoryInBytes;
private long normsMemoryInBytes;
private long pointsMemoryInBytes;
private long docValuesMemoryInBytes;
private long indexWriterMemoryInBytes;
private long versionMapMemoryInBytes;
private long bitsetMemoryInBytes;
private ImmutableOpenMap<String, Long> fileSizes = ImmutableOpenMap.of();
/*
* A map to provide a best-effort approach describing Lucene index files.
*
* Ideally this should be in sync to what the current version of Lucene is using, but it's harmless to leave extensions out,
* they'll just miss a proper description in the stats
*/
private static ImmutableOpenMap<String, String> fileDescriptions = ImmutableOpenMap.<String, String>builder()
.fPut("si", "Segment Info")
.fPut("fnm", "Fields")
.fPut("fdx", "Field Index")
.fPut("fdt", "Field Data")
.fPut("tim", "Term Dictionary")
.fPut("tip", "Term Index")
.fPut("doc", "Frequencies")
.fPut("pos", "Positions")
.fPut("pay", "Payloads")
.fPut("nvd", "Norms")
.fPut("nvm", "Norms")
.fPut("dii", "Points")
.fPut("dim", "Points")
.fPut("dvd", "DocValues")
.fPut("dvm", "DocValues")
.fPut("tvx", "Term Vector Index")
.fPut("tvd", "Term Vector Documents")
.fPut("tvf", "Term Vector Fields")
.fPut("liv", "Live Documents")
.build();
public SegmentsStats() {}
public void add(long count, long memoryInBytes) {
this.count += count;
this.memoryInBytes += memoryInBytes;
}
public void addTermsMemoryInBytes(long termsMemoryInBytes) {
this.termsMemoryInBytes += termsMemoryInBytes;
}
public void addStoredFieldsMemoryInBytes(long storedFieldsMemoryInBytes) {
this.storedFieldsMemoryInBytes += storedFieldsMemoryInBytes;
}
public void addTermVectorsMemoryInBytes(long termVectorsMemoryInBytes) {
this.termVectorsMemoryInBytes += termVectorsMemoryInBytes;
}
public void addNormsMemoryInBytes(long normsMemoryInBytes) {
this.normsMemoryInBytes += normsMemoryInBytes;
}
public void addPointsMemoryInBytes(long pointsMemoryInBytes) {
this.pointsMemoryInBytes += pointsMemoryInBytes;
}
public void addDocValuesMemoryInBytes(long docValuesMemoryInBytes) {
this.docValuesMemoryInBytes += docValuesMemoryInBytes;
}
public void addIndexWriterMemoryInBytes(long indexWriterMemoryInBytes) {
this.indexWriterMemoryInBytes += indexWriterMemoryInBytes;
}
public void addVersionMapMemoryInBytes(long versionMapMemoryInBytes) {
this.versionMapMemoryInBytes += versionMapMemoryInBytes;
}
public void addBitsetMemoryInBytes(long bitsetMemoryInBytes) {
this.bitsetMemoryInBytes += bitsetMemoryInBytes;
}
public void addFileSizes(ImmutableOpenMap<String, Long> fileSizes) {
ImmutableOpenMap.Builder<String, Long> map = ImmutableOpenMap.builder(this.fileSizes);
for (Iterator<ObjectObjectCursor<String, Long>> it = fileSizes.iterator(); it.hasNext();) {
ObjectObjectCursor<String, Long> entry = it.next();
if (map.containsKey(entry.key)) {
Long oldValue = map.get(entry.key);
map.put(entry.key, oldValue + entry.value);
} else {
map.put(entry.key, entry.value);
}
}
this.fileSizes = map.build();
}
public void add(SegmentsStats mergeStats) {
if (mergeStats == null) {
return;
}
add(mergeStats.count, mergeStats.memoryInBytes);
addTermsMemoryInBytes(mergeStats.termsMemoryInBytes);
addStoredFieldsMemoryInBytes(mergeStats.storedFieldsMemoryInBytes);
addTermVectorsMemoryInBytes(mergeStats.termVectorsMemoryInBytes);
addNormsMemoryInBytes(mergeStats.normsMemoryInBytes);
addPointsMemoryInBytes(mergeStats.pointsMemoryInBytes);
addDocValuesMemoryInBytes(mergeStats.docValuesMemoryInBytes);
addIndexWriterMemoryInBytes(mergeStats.indexWriterMemoryInBytes);
addVersionMapMemoryInBytes(mergeStats.versionMapMemoryInBytes);
addBitsetMemoryInBytes(mergeStats.bitsetMemoryInBytes);
addFileSizes(mergeStats.fileSizes);
}
/**
* The number of segments.
*/
public long getCount() {
return this.count;
}
/**
* Estimation of the memory usage used by a segment.
*/
public long getMemoryInBytes() {
return this.memoryInBytes;
}
public ByteSizeValue getMemory() {
return new ByteSizeValue(memoryInBytes);
}
/**
* Estimation of the terms dictionary memory usage by a segment.
*/
public long getTermsMemoryInBytes() {
return this.termsMemoryInBytes;
}
public ByteSizeValue getTermsMemory() {
return new ByteSizeValue(termsMemoryInBytes);
}
/**
* Estimation of the stored fields memory usage by a segment.
*/
public long getStoredFieldsMemoryInBytes() {
return this.storedFieldsMemoryInBytes;
}
public ByteSizeValue getStoredFieldsMemory() {
return new ByteSizeValue(storedFieldsMemoryInBytes);
}
/**
* Estimation of the term vectors memory usage by a segment.
*/
public long getTermVectorsMemoryInBytes() {
return this.termVectorsMemoryInBytes;
}
public ByteSizeValue getTermVectorsMemory() {
return new ByteSizeValue(termVectorsMemoryInBytes);
}
/**
* Estimation of the norms memory usage by a segment.
*/
public long getNormsMemoryInBytes() {
return this.normsMemoryInBytes;
}
public ByteSizeValue getNormsMemory() {
return new ByteSizeValue(normsMemoryInBytes);
}
/**
* Estimation of the points memory usage by a segment.
*/
public long getPointsMemoryInBytes() {
return this.pointsMemoryInBytes;
}
public ByteSizeValue getPointsMemory() {
return new ByteSizeValue(pointsMemoryInBytes);
}
/**
* Estimation of the doc values memory usage by a segment.
*/
public long getDocValuesMemoryInBytes() {
return this.docValuesMemoryInBytes;
}
public ByteSizeValue getDocValuesMemory() {
return new ByteSizeValue(docValuesMemoryInBytes);
}
/**
* Estimation of the memory usage by index writer
*/
public long getIndexWriterMemoryInBytes() {
return this.indexWriterMemoryInBytes;
}
public ByteSizeValue getIndexWriterMemory() {
return new ByteSizeValue(indexWriterMemoryInBytes);
}
/**
* Estimation of the memory usage by version map
*/
public long getVersionMapMemoryInBytes() {
return this.versionMapMemoryInBytes;
}
public ByteSizeValue getVersionMapMemory() {
return new ByteSizeValue(versionMapMemoryInBytes);
}
/**
* Estimation of how much the cached bit sets are taking. (which nested and p/c rely on)
*/
public long getBitsetMemoryInBytes() {
return bitsetMemoryInBytes;
}
public ByteSizeValue getBitsetMemory() {
return new ByteSizeValue(bitsetMemoryInBytes);
}
public ImmutableOpenMap<String, Long> getFileSizes() {
return fileSizes;
}
public static SegmentsStats readSegmentsStats(StreamInput in) throws IOException {
SegmentsStats stats = new SegmentsStats();
stats.readFrom(in);
return stats;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(Fields.SEGMENTS);
builder.field(Fields.COUNT, count);
builder.byteSizeField(Fields.MEMORY_IN_BYTES, Fields.MEMORY, memoryInBytes);
builder.byteSizeField(Fields.TERMS_MEMORY_IN_BYTES, Fields.TERMS_MEMORY, termsMemoryInBytes);
builder.byteSizeField(Fields.STORED_FIELDS_MEMORY_IN_BYTES, Fields.STORED_FIELDS_MEMORY, storedFieldsMemoryInBytes);
builder.byteSizeField(Fields.TERM_VECTORS_MEMORY_IN_BYTES, Fields.TERM_VECTORS_MEMORY, termVectorsMemoryInBytes);
builder.byteSizeField(Fields.NORMS_MEMORY_IN_BYTES, Fields.NORMS_MEMORY, normsMemoryInBytes);
builder.byteSizeField(Fields.POINTS_MEMORY_IN_BYTES, Fields.POINTS_MEMORY, pointsMemoryInBytes);
builder.byteSizeField(Fields.DOC_VALUES_MEMORY_IN_BYTES, Fields.DOC_VALUES_MEMORY, docValuesMemoryInBytes);
builder.byteSizeField(Fields.INDEX_WRITER_MEMORY_IN_BYTES, Fields.INDEX_WRITER_MEMORY, indexWriterMemoryInBytes);
builder.byteSizeField(Fields.VERSION_MAP_MEMORY_IN_BYTES, Fields.VERSION_MAP_MEMORY, versionMapMemoryInBytes);
builder.byteSizeField(Fields.FIXED_BIT_SET_MEMORY_IN_BYTES, Fields.FIXED_BIT_SET, bitsetMemoryInBytes);
builder.startObject(Fields.FILE_SIZES);
for (Iterator<ObjectObjectCursor<String, Long>> it = fileSizes.iterator(); it.hasNext();) {
ObjectObjectCursor<String, Long> entry = it.next();
builder.startObject(entry.key);
builder.byteSizeField(Fields.SIZE_IN_BYTES, Fields.SIZE, entry.value);
builder.field(Fields.DESCRIPTION, fileDescriptions.getOrDefault(entry.key, "Others"));
builder.endObject();
}
builder.endObject();
builder.endObject();
return builder;
}
static final class Fields {
static final String SEGMENTS = "segments";
static final String COUNT = "count";
static final String MEMORY = "memory";
static final String MEMORY_IN_BYTES = "memory_in_bytes";
static final String TERMS_MEMORY = "terms_memory";
static final String TERMS_MEMORY_IN_BYTES = "terms_memory_in_bytes";
static final String STORED_FIELDS_MEMORY = "stored_fields_memory";
static final String STORED_FIELDS_MEMORY_IN_BYTES = "stored_fields_memory_in_bytes";
static final String TERM_VECTORS_MEMORY = "term_vectors_memory";
static final String TERM_VECTORS_MEMORY_IN_BYTES = "term_vectors_memory_in_bytes";
static final String NORMS_MEMORY = "norms_memory";
static final String NORMS_MEMORY_IN_BYTES = "norms_memory_in_bytes";
static final String POINTS_MEMORY = "points_memory";
static final String POINTS_MEMORY_IN_BYTES = "points_memory_in_bytes";
static final String DOC_VALUES_MEMORY = "doc_values_memory";
static final String DOC_VALUES_MEMORY_IN_BYTES = "doc_values_memory_in_bytes";
static final String INDEX_WRITER_MEMORY = "index_writer_memory";
static final String INDEX_WRITER_MEMORY_IN_BYTES = "index_writer_memory_in_bytes";
static final String VERSION_MAP_MEMORY = "version_map_memory";
static final String VERSION_MAP_MEMORY_IN_BYTES = "version_map_memory_in_bytes";
static final String FIXED_BIT_SET = "fixed_bit_set";
static final String FIXED_BIT_SET_MEMORY_IN_BYTES = "fixed_bit_set_memory_in_bytes";
static final String FILE_SIZES = "file_sizes";
static final String SIZE = "size";
static final String SIZE_IN_BYTES = "size_in_bytes";
static final String DESCRIPTION = "description";
}
@Override
public void readFrom(StreamInput in) throws IOException {
count = in.readVLong();
memoryInBytes = in.readLong();
termsMemoryInBytes = in.readLong();
storedFieldsMemoryInBytes = in.readLong();
termVectorsMemoryInBytes = in.readLong();
normsMemoryInBytes = in.readLong();
pointsMemoryInBytes = in.readLong();
docValuesMemoryInBytes = in.readLong();
indexWriterMemoryInBytes = in.readLong();
versionMapMemoryInBytes = in.readLong();
bitsetMemoryInBytes = in.readLong();
int size = in.readVInt();
ImmutableOpenMap.Builder<String, Long> map = ImmutableOpenMap.builder(size);
for (int i = 0; i < size; i++) {
String key = in.readString();
Long value = in.readLong();
map.put(key, value);
}
fileSizes = map.build();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVLong(count);
out.writeLong(memoryInBytes);
out.writeLong(termsMemoryInBytes);
out.writeLong(storedFieldsMemoryInBytes);
out.writeLong(termVectorsMemoryInBytes);
out.writeLong(normsMemoryInBytes);
out.writeLong(pointsMemoryInBytes);
out.writeLong(docValuesMemoryInBytes);
out.writeLong(indexWriterMemoryInBytes);
out.writeLong(versionMapMemoryInBytes);
out.writeLong(bitsetMemoryInBytes);
out.writeVInt(fileSizes.size());
for (Iterator<ObjectObjectCursor<String, Long>> it = fileSizes.iterator(); it.hasNext();) {
ObjectObjectCursor<String, Long> entry = it.next();
out.writeString(entry.key);
out.writeLong(entry.value);
}
}
}
| danielmitterdorfer/elasticsearch | core/src/main/java/org/elasticsearch/index/engine/SegmentsStats.java | Java | apache-2.0 | 14,688 |