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 |
|---|---|---|---|---|---|
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "platform/platform.h"
#include "gui/core/guiControl.h"
#include "console/consoleTypes.h"
#include "T3D/shapeBase.h"
#include "gfx/gfxDrawUtil.h"
#include "console/engineAPI.h"
//-----------------------------------------------------------------------------
/// Vary basic HUD clock.
/// Displays the current simulation time offset from some base. The base time
/// is usually synchronized with the server as mission start time. This hud
/// currently only displays minutes:seconds.
class GuiClockHud : public GuiControl
{
typedef GuiControl Parent;
bool mShowFrame;
bool mShowFill;
bool mTimeReversed;
LinearColorF mFillColor;
LinearColorF mFrameColor;
LinearColorF mTextColor;
S32 mTimeOffset;
public:
GuiClockHud();
void setTime(F32 newTime);
void setReverseTime(F32 reverseTime);
F32 getTime();
void onRender( Point2I, const RectI &);
static void initPersistFields();
DECLARE_CONOBJECT( GuiClockHud );
DECLARE_CATEGORY( "Gui Game" );
DECLARE_DESCRIPTION( "Basic HUD clock. Displays the current simulation time offset from some base." );
};
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT( GuiClockHud );
ConsoleDocClass( GuiClockHud,
"@brief Basic HUD clock. Displays the current simulation time offset from some base.\n"
"@tsexample\n"
"\n new GuiClockHud()"
"{\n"
" fillColor = \"0.0 1.0 0.0 1.0\"; // Fills with a solid green color\n"
" frameColor = \"1.0 1.0 1.0 1.0\"; // Solid white frame color\n"
" textColor = \"1.0 1.0 1.0 1.0\"; // Solid white text Color\n"
" showFill = \"true\";\n"
" showFrame = \"true\";\n"
"};\n"
"@endtsexample\n\n"
"@ingroup GuiGame\n"
);
GuiClockHud::GuiClockHud()
{
mShowFrame = mShowFill = true;
mTimeReversed = false;
mFillColor.set(0, 0, 0, 0.5);
mFrameColor.set(0, 1, 0, 1);
mTextColor.set( 0, 1, 0, 1 );
mTimeOffset = 0;
}
void GuiClockHud::initPersistFields()
{
addGroup("Misc");
addField( "showFill", TypeBool, Offset( mShowFill, GuiClockHud ), "If true, draws a background color behind the control.");
addField( "showFrame", TypeBool, Offset( mShowFrame, GuiClockHud ), "If true, draws a frame around the control." );
addField( "fillColor", TypeColorF, Offset( mFillColor, GuiClockHud ), "Standard color for the background of the control." );
addField( "frameColor", TypeColorF, Offset( mFrameColor, GuiClockHud ), "Color for the control's frame." );
addField( "textColor", TypeColorF, Offset( mTextColor, GuiClockHud ), "Color for the text on this control." );
endGroup("Misc");
Parent::initPersistFields();
}
//-----------------------------------------------------------------------------
void GuiClockHud::onRender(Point2I offset, const RectI &updateRect)
{
GFXDrawUtil* drawUtil = GFX->getDrawUtil();
// Background first
if (mShowFill)
drawUtil->drawRectFill(updateRect, mFillColor.toColorI());
// Convert ms time into hours, minutes and seconds.
S32 time = S32(getTime());
S32 secs = time % 60;
S32 mins = (time % 3600) / 60;
// Currently only displays min/sec
char buf[256];
dSprintf(buf,sizeof(buf), "%02d:%02d",mins,secs);
// Center the text
offset.x += (getWidth() - mProfile->mFont->getStrWidth((const UTF8 *)buf)) / 2;
offset.y += (getHeight() - mProfile->mFont->getHeight()) / 2;
drawUtil->setBitmapModulation(mTextColor.toColorI());
drawUtil->drawText(mProfile->mFont, offset, buf);
drawUtil->clearBitmapModulation();
// Border last
if (mShowFrame)
drawUtil->drawRect(updateRect, mFrameColor.toColorI());
}
//-----------------------------------------------------------------------------
void GuiClockHud::setReverseTime(F32 time)
{
// Set the current time in seconds.
mTimeReversed = true;
mTimeOffset = S32(time * 1000) + Platform::getVirtualMilliseconds();
}
void GuiClockHud::setTime(F32 time)
{
// Set the current time in seconds.
mTimeReversed = false;
mTimeOffset = S32(time * 1000) - Platform::getVirtualMilliseconds();
}
F32 GuiClockHud::getTime()
{
// Return elapsed time in seconds.
if(mTimeReversed)
return F32(mTimeOffset - Platform::getVirtualMilliseconds()) / 1000;
else
return F32(mTimeOffset + Platform::getVirtualMilliseconds()) / 1000;
}
DefineEngineMethod(GuiClockHud, setTime, void, (F32 timeInSeconds),(60), "Sets the current base time for the clock.\n"
"@param timeInSeconds Time to set the clock, in seconds (IE: 00:02 would be 120)\n"
"@tsexample\n"
"// Define the time, in seconds\n"
"%timeInSeconds = 120;\n\n"
"// Change the time on the GuiClockHud control\n"
"%guiClockHud.setTime(%timeInSeconds);\n"
"@endtsexample\n"
)
{
object->setTime(timeInSeconds);
}
DefineEngineMethod(GuiClockHud, setReverseTime, void, (F32 timeInSeconds),(60), "@brief Sets a time for a countdown clock.\n\n"
"Setting the time like this will cause the clock to count backwards from the specified time.\n\n"
"@param timeInSeconds Time to set the clock, in seconds (IE: 00:02 would be 120)\n\n"
"@see setTime\n"
)
{
object->setReverseTime(timeInSeconds);
}
DefineEngineMethod(GuiClockHud, getTime, F32, (),, "Returns the current time, in seconds.\n"
"@return timeInseconds Current time, in seconds\n"
"@tsexample\n"
"// Get the current time from the GuiClockHud control\n"
"%timeInSeconds = %guiClockHud.getTime();\n"
"@endtsexample\n"
)
{
return object->getTime();
}
| Bloodknight/Torque3D | Engine/source/T3D/fps/guiClockHud.cpp | C++ | mit | 6,994 |
import { Omit } from '@material-ui/types';
import {
CreateCSSProperties,
StyledComponentProps,
WithStylesOptions,
} from '@material-ui/styles/withStyles';
import { Theme as DefaultTheme } from './createMuiTheme';
import * as React from 'react';
// These definitions are almost identical to the ones in @material-ui/styles/styled
// Only difference is that ComponentCreator has a default theme type
// If you need to change these types, update the ones in @material-ui/styles as well
/**
* @internal
*/
export type ComponentCreator<Component extends React.ElementType> = <
Theme = DefaultTheme,
Props extends {} = {}
>(
styles:
| CreateCSSProperties<Props>
| ((props: { theme: Theme } & Props) => CreateCSSProperties<Props>),
options?: WithStylesOptions<Theme>,
) => React.ComponentType<
Omit<
JSX.LibraryManagedAttributes<Component, React.ComponentProps<Component>>,
'classes' | 'className'
> &
StyledComponentProps<'root'> & { className?: string } & (Props extends { theme: Theme }
? Omit<Props, 'theme'> & { theme?: Theme }
: Props)
>;
export interface StyledProps {
className: string;
}
export default function styled<Component extends React.ElementType>(
Component: Component,
): ComponentCreator<Component>;
| cdnjs/cdnjs | ajax/libs/material-ui/4.9.9/styles/styled.d.ts | TypeScript | mit | 1,273 |
/*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* 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
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.security.oauth.shared;
/**
* Represents an User with unique identifier. Have such interface to be able use GWT AutoBean feature. Any interface
* that represents an User should extend this interface.
*/
public interface User {
String getId();
void setId(String id);
String getName();
void setName(String name);
String getEmail();
void setEmail(String email);
}
| slemeur/che | wsmaster/che-core-api-auth/src/main/java/org/eclipse/che/security/oauth/shared/User.java | Java | epl-1.0 | 939 |
/*
* Copyright (c) 2002 Frodo
* Portions Copyright (c) by the authors of ffmpeg and xvid
* Copyright (C) 2002-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/>.
*
*/
// IoSupport.cpp: implementation of the CIoSupport class.
//
//////////////////////////////////////////////////////////////////////
#include "system.h"
#include "IoSupport.h"
#include "utils/log.h"
#ifdef TARGET_WINDOWS
#include "my_ntddcdrm.h"
#include "WIN32Util.h"
#include "utils/CharsetConverter.h"
#endif
#if defined(TARGET_LINUX)
#include <linux/limits.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/cdrom.h>
#endif
#if defined(TARGET_DARWIN)
#include <sys/param.h>
#include <mach-o/dyld.h>
#if defined(TARGET_DARWIN_OSX)
#include <IOKit/IOKitLib.h>
#include <IOKit/IOBSD.h>
#include <IOKit/storage/IOCDTypes.h>
#include <IOKit/storage/IODVDTypes.h>
#include <IOKit/storage/IOMedia.h>
#include <IOKit/storage/IOCDMedia.h>
#include <IOKit/storage/IODVDMedia.h>
#include <IOKit/storage/IOCDMediaBSDClient.h>
#include <IOKit/storage/IODVDMediaBSDClient.h>
#include <IOKit/storage/IOStorageDeviceCharacteristics.h>
#endif
#endif
#ifdef TARGET_FREEBSD
#include <sys/syslimits.h>
#endif
#include "cdioSupport.h"
#include "filesystem/iso9660.h"
#include "MediaManager.h"
#ifdef TARGET_POSIX
#include "XHandle.h"
#endif
PVOID CIoSupport::m_rawXferBuffer;
HANDLE CIoSupport::OpenCDROM()
{
HANDLE hDevice = 0;
#ifdef HAS_DVD_DRIVE
#if defined(TARGET_POSIX)
int fd = open(CLibcdio::GetInstance()->GetDeviceFileName(), O_RDONLY | O_NONBLOCK);
hDevice = new CXHandle(CXHandle::HND_FILE);
hDevice->fd = fd;
hDevice->m_bCDROM = true;
#elif defined(TARGET_WINDOWS)
hDevice = CreateFile(g_mediaManager.TranslateDevicePath("",true), GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING,
FILE_FLAG_RANDOM_ACCESS, NULL );
#else
hDevice = CreateFile("\\\\.\\Cdrom0", GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING,
FILE_FLAG_RANDOM_ACCESS, NULL );
#endif
#endif
return hDevice;
}
void CIoSupport::AllocReadBuffer()
{
#ifndef TARGET_POSIX
m_rawXferBuffer = GlobalAlloc(GPTR, RAW_SECTOR_SIZE);
#endif
}
void CIoSupport::FreeReadBuffer()
{
#ifndef TARGET_POSIX
GlobalFree(m_rawXferBuffer);
#endif
}
INT CIoSupport::ReadSector(HANDLE hDevice, DWORD dwSector, LPSTR lpczBuffer)
{
DWORD dwRead;
DWORD dwSectorSize = 2048;
#if defined(TARGET_DARWIN) && defined(HAS_DVD_DRIVE)
dk_cd_read_t cd_read;
memset( &cd_read, 0, sizeof(cd_read) );
cd_read.sectorArea = kCDSectorAreaUser;
cd_read.buffer = lpczBuffer;
cd_read.sectorType = kCDSectorTypeMode1;
cd_read.offset = dwSector * kCDSectorSizeMode1;
cd_read.bufferLength = 2048;
if( ioctl(hDevice->fd, DKIOCCDREAD, &cd_read ) == -1 )
{
return -1;
}
return 2048;
#elif defined(TARGET_POSIX)
if (hDevice->m_bCDROM)
{
int fd = hDevice->fd;
// seek to requested sector
off_t offset = (off_t)dwSector * (off_t)MODE1_DATA_SIZE;
if (lseek(fd, offset, SEEK_SET) < 0)
{
CLog::Log(LOGERROR, "CD: ReadSector Request to read sector %d\n", (int)dwSector);
CLog::Log(LOGERROR, "CD: ReadSector error: %s\n", strerror(errno));
OutputDebugString("CD Read error\n");
return (-1);
}
// read data block of this sector
while (read(fd, lpczBuffer, MODE1_DATA_SIZE) < 0)
{
// read was interrupted - try again
if (errno == EINTR)
continue;
// error reading sector
CLog::Log(LOGERROR, "CD: ReadSector Request to read sector %d\n", (int)dwSector);
CLog::Log(LOGERROR, "CD: ReadSector error: %s\n", strerror(errno));
OutputDebugString("CD Read error\n");
return (-1);
}
return MODE1_DATA_SIZE;
}
#endif
LARGE_INTEGER Displacement;
Displacement.QuadPart = ((INT64)dwSector) * dwSectorSize;
for (int i = 0; i < 5; i++)
{
if (SetFilePointer(hDevice, Displacement.u.LowPart, &Displacement.u.HighPart, FILE_BEGIN) != (DWORD)-1)
{
if (ReadFile(hDevice, m_rawXferBuffer, dwSectorSize, &dwRead, NULL))
{
memcpy(lpczBuffer, m_rawXferBuffer, dwSectorSize);
return dwRead;
}
}
}
OutputDebugString("CD Read error\n");
return -1;
}
INT CIoSupport::ReadSectorMode2(HANDLE hDevice, DWORD dwSector, LPSTR lpczBuffer)
{
#ifdef HAS_DVD_DRIVE
#if defined(TARGET_DARWIN)
dk_cd_read_t cd_read;
memset( &cd_read, 0, sizeof(cd_read) );
cd_read.sectorArea = kCDSectorAreaUser;
cd_read.buffer = lpczBuffer;
cd_read.offset = dwSector * kCDSectorSizeMode2Form2;
cd_read.sectorType = kCDSectorTypeMode2Form2;
cd_read.bufferLength = kCDSectorSizeMode2Form2;
if( ioctl( hDevice->fd, DKIOCCDREAD, &cd_read ) == -1 )
{
return -1;
}
return MODE2_DATA_SIZE;
#elif defined(TARGET_FREEBSD)
// NYI
#elif defined(TARGET_POSIX)
if (hDevice->m_bCDROM)
{
int fd = hDevice->fd;
int lba = (dwSector + CD_MSF_OFFSET) ;
int m,s,f;
union
{
struct cdrom_msf msf;
char buffer[2356];
} arg;
// convert sector offset to minute, second, frame format
// since that is what the 'ioctl' requires as input
f = lba % CD_FRAMES;
lba /= CD_FRAMES;
s = lba % CD_SECS;
lba /= CD_SECS;
m = lba;
arg.msf.cdmsf_min0 = m;
arg.msf.cdmsf_sec0 = s;
arg.msf.cdmsf_frame0 = f;
int ret = ioctl(fd, CDROMREADMODE2, &arg);
if (ret==0)
{
memcpy(lpczBuffer, arg.buffer, MODE2_DATA_SIZE); // don't think offset is needed here
return MODE2_DATA_SIZE;
}
CLog::Log(LOGERROR, "CD: ReadSectorMode2 Request to read sector %d\n", (int)dwSector);
CLog::Log(LOGERROR, "CD: ReadSectorMode2 error: %s\n", strerror(errno));
CLog::Log(LOGERROR, "CD: ReadSectorMode2 minute %d, second %d, frame %d\n", m, s, f);
OutputDebugString("CD Read error\n");
return -1;
}
#else
DWORD dwBytesReturned;
RAW_READ_INFO rawRead = {0};
// Oddly enough, DiskOffset uses the Red Book sector size
rawRead.DiskOffset.QuadPart = 2048 * dwSector;
rawRead.SectorCount = 1;
rawRead.TrackMode = XAForm2;
for (int i = 0; i < 5; i++)
{
if ( DeviceIoControl( hDevice,
IOCTL_CDROM_RAW_READ,
&rawRead,
sizeof(RAW_READ_INFO),
m_rawXferBuffer,
RAW_SECTOR_SIZE,
&dwBytesReturned,
NULL ) != 0 )
{
memcpy(lpczBuffer, (char*)m_rawXferBuffer+MODE2_DATA_START, MODE2_DATA_SIZE);
return MODE2_DATA_SIZE;
}
else
{
int iErr = GetLastError();
}
}
#endif
#endif
return -1;
}
INT CIoSupport::ReadSectorCDDA(HANDLE hDevice, DWORD dwSector, LPSTR lpczBuffer)
{
return -1;
}
VOID CIoSupport::CloseCDROM(HANDLE hDevice)
{
CloseHandle(hDevice);
}
| gripped/xbmc | xbmc/storage/IoSupport.cpp | C++ | gpl-2.0 | 7,593 |
<?php
if (! interface_exists ( 'PostmanZendMailTransportConfigurationFactory' )) {
interface PostmanZendMailTransportConfigurationFactory {
static function createConfig(PostmanTransport $transport);
}
}
if (! class_exists ( 'PostmanBasicAuthConfigurationFactory' )) {
class PostmanBasicAuthConfigurationFactory implements PostmanZendMailTransportConfigurationFactory {
public static function createConfig(PostmanTransport $transport) {
// create Logger
$logger = new PostmanLogger ( "PostmanBasicAuthConfigurationFactory" );
// retrieve the hostname and port form the transport
$hostname = $transport->getHostname ();
$port = $transport->getPort ();
$securityType = $transport->getSecurityType ();
$authType = $transport->getAuthenticationType ();
$username = $transport->getCredentialsId ();
$password = $transport->getCredentialsSecret ();
// create the Configuration structure for Zend_Mail
$config = array (
'port' => $port
);
$logger->debug ( sprintf ( 'Using %s:%s ', $hostname, $port ) );
if ($securityType != PostmanOptions::SECURITY_TYPE_NONE) {
$config ['ssl'] = $securityType;
$logger->debug ( 'Using encryption ' . $securityType );
} else {
$logger->debug ( 'Using no encryption' );
}
if ($authType != PostmanOptions::AUTHENTICATION_TYPE_NONE) {
$config ['auth'] = $authType;
$config ['username'] = $username;
$config ['password'] = $password;
$logger->debug ( sprintf ( 'Using auth %s with username %s and password %s', $authType, $username, PostmanUtils::obfuscatePassword ( $password ) ) );
} else {
$logger->debug ( 'Using no authentication' );
}
// return the Configuration structure
return $config;
}
}
}
if (! class_exists ( 'PostmanOAuth2ConfigurationFactory' )) {
class PostmanOAuth2ConfigurationFactory implements PostmanZendMailTransportConfigurationFactory {
public static function createConfig(PostmanTransport $transport) {
// create Logger
$logger = new PostmanLogger ( 'PostmanOAuth2ConfigurationFactory' );
// retrieve the hostname and port form the transport
$hostname = $transport->getHostname ();
$port = $transport->getPort ();
// the sender email is needed for the OAuth2 Bearer token
$senderEmail = PostmanOptions::getInstance ()->getEnvelopeSender ();
assert ( ! empty ( $senderEmail ) );
// the vendor is required for Yahoo's OAuth2 implementation
$vendor = self::createVendorString ( $hostname );
// create the OAuth2 SMTP Authentication string
$initClientRequestEncoded = self::createAuthenticationString ( $senderEmail, PostmanOAuthToken::getInstance ()->getAccessToken (), $vendor );
// create the Configuration structure for Zend_Mail
$config = self::createConfiguration ( $logger, $hostname, $port, $transport->getSecurityType (), $transport->getAuthenticationType (), $initClientRequestEncoded );
// return the Configuration structure
return $config;
}
/**
*
* Create the Configuration structure for Zend_Mail
*
* @param unknown $hostname
* @param unknown $port
* @param unknown $securityType
* @param unknown $authenticationType
* @param unknown $initClientRequestEncoded
* @return multitype:unknown NULL
*/
private static function createConfiguration($logger, $hostname, $port, $securityType, $authenticationType, $initClientRequestEncoded) {
$config = array (
'ssl' => $securityType,
'port' => $port,
'auth' => $authenticationType,
'xoauth2_request' => $initClientRequestEncoded
);
$logger->debug ( sprintf ( 'Using auth %s with encryption %s to %s:%s ', $config ['auth'], $config ['ssl'], $hostname, $config ['port'] ) );
return $config;
}
/**
* Create the vendor string (for Yahoo servers only)
*
* @param unknown $hostname
* @return string
*/
private static function createVendorString($hostname) {
// the vendor is required for Yahoo's OAuth2 implementation
$vendor = '';
if (PostmanUtils::endsWith ( $hostname, 'yahoo.com' )) {
// Yahoo Mail requires a Vendor - see http://imapclient.freshfoo.com/changeset/535%3A80ae438f4e4a/
$pluginData = apply_filters ( 'postman_get_plugin_metadata', null );
$vendor = sprintf ( "vendor=Postman SMTP %s\1", $pluginData ['version'] );
}
return $vendor;
}
/**
* Create the standard OAuth2 SMTP Authentication string
*
* @param unknown $senderEmail
* @param unknown $oauth2AccessToken
* @param unknown $vendor
* @return string
*/
private static function createAuthenticationString($senderEmail, $oauth2AccessToken, $vendor) {
$initClientRequestEncoded = base64_encode ( sprintf ( "user=%s\1auth=Bearer %s\1%s\1", $senderEmail, $oauth2AccessToken, $vendor ) );
return $initClientRequestEncoded;
}
}
}
| jasonglisson/susannerossi | wp-content/plugins/postman-smtp/Postman/Postman-Mail/PostmanZendMailTransportConfigurationFactory.php | PHP | gpl-2.0 | 4,937 |
<?php
/**
* Image select field class which uses images as radio options.
*/
class RWMB_Image_Select_Field extends RWMB_Field
{
/**
* Enqueue scripts and styles
*/
static function admin_enqueue_scripts()
{
wp_enqueue_style( 'rwmb-image-select', RWMB_CSS_URL . 'image-select.css', array(), RWMB_VER );
wp_enqueue_script( 'rwmb-image-select', RWMB_JS_URL . 'image-select.js', array( 'jquery' ), RWMB_VER, true );
}
/**
* Get field HTML
*
* @param mixed $meta
* @param array $field
* @return string
*/
static function html( $meta, $field )
{
$html = array();
$tpl = '<label class="rwmb-image-select"><img src="%s"><input type="%s" class="rwmb-image_select hidden" name="%s" value="%s"%s></label>';
$meta = (array) $meta;
foreach ( $field['options'] as $value => $image )
{
$html[] = sprintf(
$tpl,
$image,
$field['multiple'] ? 'checkbox' : 'radio',
$field['field_name'],
$value,
checked( in_array( $value, $meta ), true, false )
);
}
return implode( ' ', $html );
}
/**
* Normalize parameters for field
*
* @param array $field
* @return array
*/
static function normalize( $field )
{
$field = parent::normalize( $field );
$field['field_name'] .= $field['multiple'] ? '[]' : '';
return $field;
}
/**
* Format a single value for the helper functions.
* @param array $field Field parameter
* @param string $value The value
* @return string
*/
static function format_single_value( $field, $value )
{
return sprintf( '<img src="%s">', esc_url( $field['options'][$value] ) );
}
}
| davydavv/carodech2 | wp-content/themes/oshin/meta-box/inc/fields/image-select.php | PHP | gpl-2.0 | 1,589 |
/*
* jQuery Plugin: Tokenizing Autocomplete Text Entry
* Version 1.6.2
*
* Copyright (c) 2009 James Smith (http://loopj.com)
* Licensed jointly under the GPL and MIT licenses,
* choose which one suits your project best!
*
*/
;(function ($) {
var DEFAULT_SETTINGS = {
// Search settings
method: "GET",
queryParam: "q",
searchDelay: 300,
minChars: 1,
propertyToSearch: "name",
jsonContainer: null,
contentType: "json",
excludeCurrent: false,
excludeCurrentParameter: "x",
// Prepopulation settings
prePopulate: null,
processPrePopulate: false,
// Display settings
hintText: "Type in a search term",
noResultsText: "No results",
searchingText: "Searching...",
deleteText: "×",
animateDropdown: true,
placeholder: null,
theme: null,
overwriteClasses: null,
zindex: 999,
resultsLimit: null,
enableHTML: false,
resultsFormatter: function(item) {
var string = item[this.propertyToSearch];
return "<li>" + (this.enableHTML ? string : _escapeHTML(string)) + "</li>";
},
tokenFormatter: function(item) {
var string = item[this.propertyToSearch];
return "<li><p>" + (this.enableHTML ? string : _escapeHTML(string)) + "</p></li>";
},
// Tokenization settings
tokenLimit: null,
tokenDelimiter: ",",
preventDuplicates: false,
tokenValue: "id",
// Behavioral settings
allowFreeTagging: false,
allowTabOut: false,
autoSelectFirstResult: false,
// Callbacks
onResult: null,
onCachedResult: null,
onAdd: null,
onFreeTaggingAdd: null,
onDelete: null,
onReady: null,
// Other settings
idPrefix: "token-input-",
// Keep track if the input is currently in disabled mode
disabled: false
};
// Default classes to use when theming
var DEFAULT_CLASSES = {
tokenList : "token-input-list",
token : "token-input-token",
tokenReadOnly : "token-input-token-readonly",
tokenDelete : "token-input-delete-token",
selectedToken : "token-input-selected-token",
highlightedToken : "token-input-highlighted-token",
dropdown : "token-input-dropdown",
dropdownItem : "token-input-dropdown-item",
dropdownItem2 : "token-input-dropdown-item2",
selectedDropdownItem : "token-input-selected-dropdown-item",
inputToken : "token-input-input-token",
focused : "token-input-focused",
disabled : "token-input-disabled"
};
// Input box position "enum"
var POSITION = {
BEFORE : 0,
AFTER : 1,
END : 2
};
// Keys "enum"
var KEY = {
BACKSPACE : 8,
TAB : 9,
ENTER : 13,
ESCAPE : 27,
SPACE : 32,
PAGE_UP : 33,
PAGE_DOWN : 34,
END : 35,
HOME : 36,
LEFT : 37,
UP : 38,
RIGHT : 39,
DOWN : 40,
NUMPAD_ENTER : 108,
COMMA : 188
};
var HTML_ESCAPES = {
'&' : '&',
'<' : '<',
'>' : '>',
'"' : '"',
"'" : ''',
'/' : '/'
};
var HTML_ESCAPE_CHARS = /[&<>"'\/]/g;
function coerceToString(val) {
return String((val === null || val === undefined) ? '' : val);
}
function _escapeHTML(text) {
return coerceToString(text).replace(HTML_ESCAPE_CHARS, function(match) {
return HTML_ESCAPES[match];
});
}
// Additional public (exposed) methods
var methods = {
init: function(url_or_data_or_function, options) {
var settings = $.extend({}, DEFAULT_SETTINGS, options || {});
return this.each(function () {
$(this).data("settings", settings);
$(this).data("tokenInputObject", new $.TokenList(this, url_or_data_or_function, settings));
});
},
clear: function() {
this.data("tokenInputObject").clear();
return this;
},
add: function(item) {
this.data("tokenInputObject").add(item);
return this;
},
remove: function(item) {
this.data("tokenInputObject").remove(item);
return this;
},
get: function() {
return this.data("tokenInputObject").getTokens();
},
toggleDisabled: function(disable) {
this.data("tokenInputObject").toggleDisabled(disable);
return this;
},
setOptions: function(options){
$(this).data("settings", $.extend({}, $(this).data("settings"), options || {}));
return this;
},
destroy: function () {
if (this.data("tokenInputObject")) {
this.data("tokenInputObject").clear();
var tmpInput = this;
var closest = this.parent();
closest.empty();
tmpInput.show();
closest.append(tmpInput);
return tmpInput;
}
}
};
// Expose the .tokenInput function to jQuery as a plugin
$.fn.tokenInput = function (method) {
// Method calling and initialization logic
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else {
return methods.init.apply(this, arguments);
}
};
// TokenList class for each input
$.TokenList = function (input, url_or_data, settings) {
//
// Initialization
//
// Configure the data source
if (typeof(url_or_data) === "string" || typeof(url_or_data) === "function") {
// Set the url to query against
$(input).data("settings").url = url_or_data;
// If the URL is a function, evaluate it here to do our initalization work
var url = computeURL();
// Make a smart guess about cross-domain if it wasn't explicitly specified
if ($(input).data("settings").crossDomain === undefined && typeof url === "string") {
if(url.indexOf("://") === -1) {
$(input).data("settings").crossDomain = false;
} else {
$(input).data("settings").crossDomain = (location.href.split(/\/+/g)[1] !== url.split(/\/+/g)[1]);
}
}
} else if (typeof(url_or_data) === "object") {
// Set the local data to search through
$(input).data("settings").local_data = url_or_data;
}
// Build class names
if($(input).data("settings").classes) {
// Use custom class names
$(input).data("settings").classes = $.extend({}, DEFAULT_CLASSES, $(input).data("settings").classes);
} else if($(input).data("settings").overwriteClasses) {
$(input).data("settings").classes = $.extend({}, DEFAULT_CLASSES, $(input).data("settings").overwriteClasses);
} else if($(input).data("settings").theme) {
// Use theme-suffixed default class names
$(input).data("settings").classes = {};
$.each(DEFAULT_CLASSES, function(key, value) {
$(input).data("settings").classes[key] = value + "-" + $(input).data("settings").theme;
});
} else {
$(input).data("settings").classes = DEFAULT_CLASSES;
}
// Save the tokens
var saved_tokens = [];
// Keep track of the number of tokens in the list
var token_count = 0;
// Basic cache to save on db hits
var cache = new $.TokenList.Cache();
// Keep track of the timeout, old vals
var timeout;
var input_val;
// Create a new text input an attach keyup events
var input_box = $("<input type=\"text\" autocomplete=\"off\" autocapitalize=\"off\"/>")
.css({
outline: "none"
})
.attr("id", $(input).data("settings").idPrefix + input.id)
.focus(function () {
if ($(input).data("settings").disabled) {
return false;
} else
if ($(input).data("settings").tokenLimit === null || $(input).data("settings").tokenLimit !== token_count) {
show_dropdown_hint();
}
token_list.addClass($(input).data("settings").classes.focused);
})
.blur(function () {
hide_dropdown();
if ($(input).data("settings").allowFreeTagging) {
add_freetagging_tokens();
}
$(this).val("");
token_list.removeClass($(input).data("settings").classes.focused);
})
.bind("keyup keydown blur update", resize_input)
.keydown(function (event) {
var previous_token;
var next_token;
switch(event.keyCode) {
case KEY.LEFT:
case KEY.RIGHT:
case KEY.UP:
case KEY.DOWN:
if(this.value.length === 0) {
previous_token = input_token.prev();
next_token = input_token.next();
if((previous_token.length && previous_token.get(0) === selected_token) ||
(next_token.length && next_token.get(0) === selected_token)) {
// Check if there is a previous/next token and it is selected
if(event.keyCode === KEY.LEFT || event.keyCode === KEY.UP) {
deselect_token($(selected_token), POSITION.BEFORE);
} else {
deselect_token($(selected_token), POSITION.AFTER);
}
} else if((event.keyCode === KEY.LEFT || event.keyCode === KEY.UP) && previous_token.length) {
// We are moving left, select the previous token if it exists
select_token($(previous_token.get(0)));
} else if((event.keyCode === KEY.RIGHT || event.keyCode === KEY.DOWN) && next_token.length) {
// We are moving right, select the next token if it exists
select_token($(next_token.get(0)));
}
} else {
var dropdown_item = null;
if (event.keyCode === KEY.DOWN || event.keyCode === KEY.RIGHT) {
dropdown_item = $(dropdown).find('li').first();
if (selected_dropdown_item) {
dropdown_item = $(selected_dropdown_item).next();
}
} else {
dropdown_item = $(dropdown).find('li').last();
if (selected_dropdown_item) {
dropdown_item = $(selected_dropdown_item).prev();
}
}
select_dropdown_item(dropdown_item);
}
break;
case KEY.BACKSPACE:
previous_token = input_token.prev();
if (this.value.length === 0) {
if (selected_token) {
delete_token($(selected_token));
hiddenInput.change();
} else if(previous_token.length) {
select_token($(previous_token.get(0)));
}
return false;
} else if($(this).val().length === 1) {
hide_dropdown();
} else {
// set a timeout just long enough to let this function finish.
setTimeout(function(){ do_search(); }, 5);
}
break;
case KEY.TAB:
case KEY.ENTER:
case KEY.NUMPAD_ENTER:
case KEY.COMMA:
if(selected_dropdown_item) {
add_token($(selected_dropdown_item).data("tokeninput"));
hiddenInput.change();
} else {
if ($(input).data("settings").allowFreeTagging) {
if($(input).data("settings").allowTabOut && $(this).val() === "") {
return true;
} else {
add_freetagging_tokens();
}
} else {
$(this).val("");
if($(input).data("settings").allowTabOut) {
return true;
}
}
event.stopPropagation();
event.preventDefault();
}
return false;
case KEY.ESCAPE:
hide_dropdown();
return true;
default:
if (String.fromCharCode(event.which)) {
// set a timeout just long enough to let this function finish.
setTimeout(function(){ do_search(); }, 5);
}
break;
}
});
// Keep reference for placeholder
if (settings.placeholder) {
input_box.attr("placeholder", settings.placeholder);
}
// Keep a reference to the original input box
var hiddenInput = $(input)
.hide()
.val("")
.focus(function () {
focusWithTimeout(input_box);
})
.blur(function () {
input_box.blur();
//return the object to this can be referenced in the callback functions.
return hiddenInput;
})
;
// Keep a reference to the selected token and dropdown item
var selected_token = null;
var selected_token_index = 0;
var selected_dropdown_item = null;
// The list to store the token items in
var token_list = $("<ul />")
.addClass($(input).data("settings").classes.tokenList)
.click(function (event) {
var li = $(event.target).closest("li");
if(li && li.get(0) && $.data(li.get(0), "tokeninput")) {
toggle_select_token(li);
} else {
// Deselect selected token
if(selected_token) {
deselect_token($(selected_token), POSITION.END);
}
// Focus input box
focusWithTimeout(input_box);
}
})
.mouseover(function (event) {
var li = $(event.target).closest("li");
if(li && selected_token !== this) {
li.addClass($(input).data("settings").classes.highlightedToken);
}
})
.mouseout(function (event) {
var li = $(event.target).closest("li");
if(li && selected_token !== this) {
li.removeClass($(input).data("settings").classes.highlightedToken);
}
})
.insertBefore(hiddenInput);
// The token holding the input box
var input_token = $("<li />")
.addClass($(input).data("settings").classes.inputToken)
.appendTo(token_list)
.append(input_box);
// The list to store the dropdown items in
var dropdown = $("<div/>")
.addClass($(input).data("settings").classes.dropdown)
.appendTo("body")
.hide();
// Magic element to help us resize the text input
var input_resizer = $("<tester/>")
.insertAfter(input_box)
.css({
position: "absolute",
top: -9999,
left: -9999,
width: "auto",
fontSize: input_box.css("fontSize"),
fontFamily: input_box.css("fontFamily"),
fontWeight: input_box.css("fontWeight"),
letterSpacing: input_box.css("letterSpacing"),
whiteSpace: "nowrap"
});
// Pre-populate list if items exist
hiddenInput.val("");
var li_data = $(input).data("settings").prePopulate || hiddenInput.data("pre");
if ($(input).data("settings").processPrePopulate && $.isFunction($(input).data("settings").onResult)) {
li_data = $(input).data("settings").onResult.call(hiddenInput, li_data);
}
if (li_data && li_data.length) {
$.each(li_data, function (index, value) {
insert_token(value);
checkTokenLimit();
input_box.attr("placeholder", null)
});
}
// Check if widget should initialize as disabled
if ($(input).data("settings").disabled) {
toggleDisabled(true);
}
// Initialization is done
if (typeof($(input).data("settings").onReady) === "function") {
$(input).data("settings").onReady.call();
}
//
// Public functions
//
this.clear = function() {
token_list.children("li").each(function() {
if ($(this).children("input").length === 0) {
delete_token($(this));
}
});
};
this.add = function(item) {
add_token(item);
};
this.remove = function(item) {
token_list.children("li").each(function() {
if ($(this).children("input").length === 0) {
var currToken = $(this).data("tokeninput");
var match = true;
for (var prop in item) {
if (item[prop] !== currToken[prop]) {
match = false;
break;
}
}
if (match) {
delete_token($(this));
}
}
});
};
this.getTokens = function() {
return saved_tokens;
};
this.toggleDisabled = function(disable) {
toggleDisabled(disable);
};
// Resize input to maximum width so the placeholder can be seen
resize_input();
//
// Private functions
//
function escapeHTML(text) {
return $(input).data("settings").enableHTML ? text : _escapeHTML(text);
}
// Toggles the widget between enabled and disabled state, or according
// to the [disable] parameter.
function toggleDisabled(disable) {
if (typeof disable === 'boolean') {
$(input).data("settings").disabled = disable
} else {
$(input).data("settings").disabled = !$(input).data("settings").disabled;
}
input_box.attr('disabled', $(input).data("settings").disabled);
token_list.toggleClass($(input).data("settings").classes.disabled, $(input).data("settings").disabled);
// if there is any token selected we deselect it
if(selected_token) {
deselect_token($(selected_token), POSITION.END);
}
hiddenInput.attr('disabled', $(input).data("settings").disabled);
}
function checkTokenLimit() {
if($(input).data("settings").tokenLimit !== null && token_count >= $(input).data("settings").tokenLimit) {
input_box.hide();
hide_dropdown();
return;
}
}
function resize_input() {
if(input_val === (input_val = input_box.val())) {return;}
// Get width left on the current line
var width_left = token_list.width() - input_box.offset().left - token_list.offset().left;
// Enter new content into resizer and resize input accordingly
input_resizer.html(_escapeHTML(input_val) || _escapeHTML(settings.placeholder));
// Get maximum width, minimum the size of input and maximum the widget's width
input_box.width(Math.min(token_list.width(),
Math.max(width_left, input_resizer.width() + 30)));
}
function add_freetagging_tokens() {
var value = $.trim(input_box.val());
var tokens = value.split($(input).data("settings").tokenDelimiter);
$.each(tokens, function(i, token) {
if (!token) {
return;
}
if ($.isFunction($(input).data("settings").onFreeTaggingAdd)) {
token = $(input).data("settings").onFreeTaggingAdd.call(hiddenInput, token);
}
var object = {};
object[$(input).data("settings").tokenValue] = object[$(input).data("settings").propertyToSearch] = token;
add_token(object);
});
}
// Inner function to a token to the list
function insert_token(item) {
var $this_token = $($(input).data("settings").tokenFormatter(item));
var readonly = item.readonly === true;
if(readonly) $this_token.addClass($(input).data("settings").classes.tokenReadOnly);
$this_token.addClass($(input).data("settings").classes.token).insertBefore(input_token);
// The 'delete token' button
if(!readonly) {
$("<span>" + $(input).data("settings").deleteText + "</span>")
.addClass($(input).data("settings").classes.tokenDelete)
.appendTo($this_token)
.click(function () {
if (!$(input).data("settings").disabled) {
delete_token($(this).parent());
hiddenInput.change();
return false;
}
});
}
// Store data on the token
var token_data = item;
$.data($this_token.get(0), "tokeninput", item);
// Save this token for duplicate checking
saved_tokens = saved_tokens.slice(0,selected_token_index).concat([token_data]).concat(saved_tokens.slice(selected_token_index));
selected_token_index++;
// Update the hidden input
update_hiddenInput(saved_tokens, hiddenInput);
token_count += 1;
// Check the token limit
if($(input).data("settings").tokenLimit !== null && token_count >= $(input).data("settings").tokenLimit) {
input_box.hide();
hide_dropdown();
}
return $this_token;
}
// Add a token to the token list based on user input
function add_token (item) {
var callback = $(input).data("settings").onAdd;
// See if the token already exists and select it if we don't want duplicates
if(token_count > 0 && $(input).data("settings").preventDuplicates) {
var found_existing_token = null;
token_list.children().each(function () {
var existing_token = $(this);
var existing_data = $.data(existing_token.get(0), "tokeninput");
if(existing_data && existing_data[settings.tokenValue] === item[settings.tokenValue]) {
found_existing_token = existing_token;
return false;
}
});
if(found_existing_token) {
select_token(found_existing_token);
input_token.insertAfter(found_existing_token);
focusWithTimeout(input_box);
return;
}
}
// Squeeze input_box so we force no unnecessary line break
input_box.width(1);
// Insert the new tokens
if($(input).data("settings").tokenLimit == null || token_count < $(input).data("settings").tokenLimit) {
insert_token(item);
// Remove the placeholder so it's not seen after you've added a token
input_box.attr("placeholder", null);
checkTokenLimit();
}
// Clear input box
input_box.val("");
// Don't show the help dropdown, they've got the idea
hide_dropdown();
// Execute the onAdd callback if defined
if($.isFunction(callback)) {
callback.call(hiddenInput,item);
}
}
// Select a token in the token list
function select_token (token) {
if (!$(input).data("settings").disabled) {
token.addClass($(input).data("settings").classes.selectedToken);
selected_token = token.get(0);
// Hide input box
input_box.val("");
// Hide dropdown if it is visible (eg if we clicked to select token)
hide_dropdown();
}
}
// Deselect a token in the token list
function deselect_token (token, position) {
token.removeClass($(input).data("settings").classes.selectedToken);
selected_token = null;
if(position === POSITION.BEFORE) {
input_token.insertBefore(token);
selected_token_index--;
} else if(position === POSITION.AFTER) {
input_token.insertAfter(token);
selected_token_index++;
} else {
input_token.appendTo(token_list);
selected_token_index = token_count;
}
// Show the input box and give it focus again
focusWithTimeout(input_box);
}
// Toggle selection of a token in the token list
function toggle_select_token(token) {
var previous_selected_token = selected_token;
if(selected_token) {
deselect_token($(selected_token), POSITION.END);
}
if(previous_selected_token === token.get(0)) {
deselect_token(token, POSITION.END);
} else {
select_token(token);
}
}
// Delete a token from the token list
function delete_token (token) {
// Remove the id from the saved list
var token_data = $.data(token.get(0), "tokeninput");
var callback = $(input).data("settings").onDelete;
var index = token.prevAll().length;
if(index > selected_token_index) index--;
// Delete the token
token.remove();
selected_token = null;
// Show the input box and give it focus again
focusWithTimeout(input_box);
// Remove this token from the saved list
saved_tokens = saved_tokens.slice(0,index).concat(saved_tokens.slice(index+1));
if (saved_tokens.length == 0) {
input_box.attr("placeholder", settings.placeholder)
}
if(index < selected_token_index) selected_token_index--;
// Update the hidden input
update_hiddenInput(saved_tokens, hiddenInput);
token_count -= 1;
if($(input).data("settings").tokenLimit !== null) {
input_box
.show()
.val("");
focusWithTimeout(input_box);
}
// Execute the onDelete callback if defined
if($.isFunction(callback)) {
callback.call(hiddenInput,token_data);
}
}
// Update the hidden input box value
function update_hiddenInput(saved_tokens, hiddenInput) {
var token_values = $.map(saved_tokens, function (el) {
if(typeof $(input).data("settings").tokenValue == 'function')
return $(input).data("settings").tokenValue.call(this, el);
return el[$(input).data("settings").tokenValue];
});
hiddenInput.val(token_values.join($(input).data("settings").tokenDelimiter));
}
// Hide and clear the results dropdown
function hide_dropdown () {
dropdown.hide().empty();
selected_dropdown_item = null;
}
function show_dropdown() {
dropdown
.css({
position: "absolute",
top: token_list.offset().top + token_list.outerHeight(true),
left: token_list.offset().left,
width: token_list.width(),
'z-index': $(input).data("settings").zindex
})
.show();
}
function show_dropdown_searching () {
if($(input).data("settings").searchingText) {
dropdown.html("<p>" + escapeHTML($(input).data("settings").searchingText) + "</p>");
show_dropdown();
}
}
function show_dropdown_hint () {
if($(input).data("settings").hintText) {
dropdown.html("<p>" + escapeHTML($(input).data("settings").hintText) + "</p>");
show_dropdown();
}
}
var regexp_special_chars = new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\-]', 'g');
function regexp_escape(term) {
return term.replace(regexp_special_chars, '\\$&');
}
// Highlight the query part of the search term
function highlight_term(value, term) {
return value.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" + regexp_escape(term) + ")(?![^<>]*>)(?![^&;]+;)",
"gi"
), function(match, p1) {
return "<b>" + escapeHTML(p1) + "</b>";
}
);
}
function find_value_and_highlight_term(template, value, term) {
return template.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + regexp_escape(value) + ")(?![^<>]*>)(?![^&;]+;)", "g"), highlight_term(value, term));
}
// exclude existing tokens from dropdown, so the list is clearer
function excludeCurrent(results) {
if ($(input).data("settings").excludeCurrent) {
var currentTokens = $(input).data("tokenInputObject").getTokens(),
trimmedList = [];
if (currentTokens.length) {
$.each(results, function(index, value) {
var notFound = true;
$.each(currentTokens, function(cIndex, cValue) {
if (value[$(input).data("settings").propertyToSearch] == cValue[$(input).data("settings").propertyToSearch]) {
notFound = false;
return false;
}
});
if (notFound) {
trimmedList.push(value);
}
});
results = trimmedList;
}
}
return results;
}
// Populate the results dropdown with some results
function populateDropdown (query, results) {
// exclude current tokens if configured
results = excludeCurrent(results);
if(results && results.length) {
dropdown.empty();
var dropdown_ul = $("<ul/>")
.appendTo(dropdown)
.mouseover(function (event) {
select_dropdown_item($(event.target).closest("li"));
})
.mousedown(function (event) {
add_token($(event.target).closest("li").data("tokeninput"));
hiddenInput.change();
return false;
})
.hide();
if ($(input).data("settings").resultsLimit && results.length > $(input).data("settings").resultsLimit) {
results = results.slice(0, $(input).data("settings").resultsLimit);
}
$.each(results, function(index, value) {
var this_li = $(input).data("settings").resultsFormatter(value);
this_li = find_value_and_highlight_term(this_li ,value[$(input).data("settings").propertyToSearch], query);
this_li = $(this_li).appendTo(dropdown_ul);
if(index % 2) {
this_li.addClass($(input).data("settings").classes.dropdownItem);
} else {
this_li.addClass($(input).data("settings").classes.dropdownItem2);
}
if(index === 0 && $(input).data("settings").autoSelectFirstResult) {
select_dropdown_item(this_li);
}
$.data(this_li.get(0), "tokeninput", value);
});
show_dropdown();
if($(input).data("settings").animateDropdown) {
dropdown_ul.slideDown("fast");
} else {
dropdown_ul.show();
}
} else {
if($(input).data("settings").noResultsText) {
dropdown.html("<p>" + escapeHTML($(input).data("settings").noResultsText) + "</p>");
show_dropdown();
}
}
}
// Highlight an item in the results dropdown
function select_dropdown_item (item) {
if(item) {
if(selected_dropdown_item) {
deselect_dropdown_item($(selected_dropdown_item));
}
item.addClass($(input).data("settings").classes.selectedDropdownItem);
selected_dropdown_item = item.get(0);
}
}
// Remove highlighting from an item in the results dropdown
function deselect_dropdown_item (item) {
item.removeClass($(input).data("settings").classes.selectedDropdownItem);
selected_dropdown_item = null;
}
// Do a search and show the "searching" dropdown if the input is longer
// than $(input).data("settings").minChars
function do_search() {
var query = input_box.val();
if(query && query.length) {
if(selected_token) {
deselect_token($(selected_token), POSITION.AFTER);
}
if(query.length >= $(input).data("settings").minChars) {
show_dropdown_searching();
clearTimeout(timeout);
timeout = setTimeout(function(){
run_search(query);
}, $(input).data("settings").searchDelay);
} else {
hide_dropdown();
}
}
}
// Do the actual search
function run_search(query) {
var cache_key = query + computeURL();
var cached_results = cache.get(cache_key);
if (cached_results) {
if ($.isFunction($(input).data("settings").onCachedResult)) {
cached_results = $(input).data("settings").onCachedResult.call(hiddenInput, cached_results);
}
populateDropdown(query, cached_results);
} else {
// Are we doing an ajax search or local data search?
if($(input).data("settings").url) {
var url = computeURL();
// Extract existing get params
var ajax_params = {};
ajax_params.data = {};
if(url.indexOf("?") > -1) {
var parts = url.split("?");
ajax_params.url = parts[0];
var param_array = parts[1].split("&");
$.each(param_array, function (index, value) {
var kv = value.split("=");
ajax_params.data[kv[0]] = kv[1];
});
} else {
ajax_params.url = url;
}
// Prepare the request
ajax_params.data[$(input).data("settings").queryParam] = query;
ajax_params.type = $(input).data("settings").method;
ajax_params.dataType = $(input).data("settings").contentType;
if ($(input).data("settings").crossDomain) {
ajax_params.dataType = "jsonp";
}
// exclude current tokens?
// send exclude list to the server, so it can also exclude existing tokens
if ($(input).data("settings").excludeCurrent) {
var currentTokens = $(input).data("tokenInputObject").getTokens();
var tokenList = $.map(currentTokens, function (el) {
if(typeof $(input).data("settings").tokenValue == 'function')
return $(input).data("settings").tokenValue.call(this, el);
return el[$(input).data("settings").tokenValue];
});
ajax_params.data[$(input).data("settings").excludeCurrentParameter] = tokenList.join($(input).data("settings").tokenDelimiter);
}
// Attach the success callback
ajax_params.success = function(results) {
cache.add(cache_key, $(input).data("settings").jsonContainer ? results[$(input).data("settings").jsonContainer] : results);
if($.isFunction($(input).data("settings").onResult)) {
results = $(input).data("settings").onResult.call(hiddenInput, results);
}
// only populate the dropdown if the results are associated with the active search query
if(input_box.val() === query) {
populateDropdown(query, $(input).data("settings").jsonContainer ? results[$(input).data("settings").jsonContainer] : results);
}
};
// Provide a beforeSend callback
if (settings.onSend) {
settings.onSend(ajax_params);
}
// Make the request
$.ajax(ajax_params);
} else if($(input).data("settings").local_data) {
// Do the search through local data
var results = $.grep($(input).data("settings").local_data, function (row) {
return row[$(input).data("settings").propertyToSearch].toLowerCase().indexOf(query.toLowerCase()) > -1;
});
cache.add(cache_key, results);
if($.isFunction($(input).data("settings").onResult)) {
results = $(input).data("settings").onResult.call(hiddenInput, results);
}
populateDropdown(query, results);
}
}
}
// compute the dynamic URL
function computeURL() {
var settings = $(input).data("settings");
return typeof settings.url == 'function' ? settings.url.call(settings) : settings.url;
}
// Bring browser focus to the specified object.
// Use of setTimeout is to get around an IE bug.
// (See, e.g., http://stackoverflow.com/questions/2600186/focus-doesnt-work-in-ie)
//
// obj: a jQuery object to focus()
function focusWithTimeout(object) {
setTimeout(
function() {
object.focus();
},
50
);
}
};
// Really basic cache for the results
$.TokenList.Cache = function (options) {
var settings, data = {}, size = 0, flush;
settings = $.extend({ max_size: 500 }, options);
flush = function () {
data = {};
size = 0;
};
this.add = function (query, results) {
if (size > settings.max_size) {
flush();
}
if (!data[query]) {
size += 1;
}
data[query] = results;
};
this.get = function (query) {
return data[query];
};
};
}(jQuery));
| younisd/domjudge | www/js/jquery.tokeninput.js | JavaScript | gpl-2.0 | 39,820 |
/* 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 |
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package core
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// ListCrossConnectLocationsRequest wrapper for the ListCrossConnectLocations operation
type ListCrossConnectLocationsRequest struct {
// The OCID of the compartment.
CompartmentId *string `mandatory:"true" contributesTo:"query" name:"compartmentId"`
// The maximum number of items to return in a paginated "List" call.
// Example: `500`
Limit *int `mandatory:"false" contributesTo:"query" name:"limit"`
// The value of the `opc-next-page` response header from the previous "List" call.
Page *string `mandatory:"false" contributesTo:"query" name:"page"`
// Unique Oracle-assigned identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request ListCrossConnectLocationsRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request ListCrossConnectLocationsRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request ListCrossConnectLocationsRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// ListCrossConnectLocationsResponse wrapper for the ListCrossConnectLocations operation
type ListCrossConnectLocationsResponse struct {
// The underlying http response
RawResponse *http.Response
// A list of []CrossConnectLocation instances
Items []CrossConnectLocation `presentIn:"body"`
// For pagination of a list of items. When paging through a list, if this header appears in the response,
// then a partial list might have been returned. Include this value as the `page` parameter for the
// subsequent GET request to get the next batch of items.
OpcNextPage *string `presentIn:"header" name:"opc-next-page"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response ListCrossConnectLocationsResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response ListCrossConnectLocationsResponse) HTTPResponse() *http.Response {
return response.RawResponse
}
| bryson/packer | vendor/github.com/oracle/oci-go-sdk/core/list_cross_connect_locations_request_response.go | GO | mpl-2.0 | 2,903 |
/*
* 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 |
// ---------------------------------------------------------------------
//
// Copyright (C) 2009 - 2015 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// since early 2009, the FEValues objects try to be more efficient by only
// recomputing things like gradients of shape functions if the cell on which
// we are is not a translation of the previous one. in this series of tests we
// make sure that this actually works the way it's supposed to be; in
// particular, if we create a mesh of two identical cells but one has a curved
// boundary, then they are the same if we use a Q1 mapping, but not a Q2
// mapping. so we test that the mass matrix we get from each of these cells is
// actually different in the latter case, but the same in the former
//
// the various tests cell_similarity_dgp_nonparametric_?? differ in the mappings and finite
// elements in use
#include "../tests.h"
#include <deal.II/base/logstream.h>
#include <deal.II/base/function.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/lac/vector.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/tria_boundary_lib.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/fe/fe_q.h>
#include <deal.II/fe/fe_dgp_nonparametric.h>
#include <deal.II/fe/fe_system.h>
#include <deal.II/fe/fe_values.h>
#include <deal.II/fe/mapping_q1.h>
#include <deal.II/fe/mapping_q.h>
#include <deal.II/fe/mapping_c1.h>
#include <fstream>
bool equal (const FullMatrix<double> &m1,
const FullMatrix<double> &m2)
{
double d = 0, s = 0;
for (unsigned int i=0; i<m1.m(); ++i)
for (unsigned int j=0; j<m1.n(); ++j)
{
d += (m1(i,j)-m2(i,j)) * (m1(i,j)-m2(i,j));
s += m1(i,j) * m1(i,j);
}
return (d<1e-8*s);
}
template<int dim>
void test (const Triangulation<dim> &tr)
{
FE_DGPNonparametric<dim> fe(1);
deallog << "FE=" << fe.get_name() << std::endl;
MappingQ1<dim> mapping;
deallog << "Mapping=Q1" << std::endl;
DoFHandler<dim> dof(tr);
dof.distribute_dofs(fe);
const QGauss<dim> quadrature(2);
FEValues<dim> fe_values (mapping, fe, quadrature,
update_values | update_gradients |
update_JxW_values);
FullMatrix<double> mass_matrix[2], laplace_matrix[2];
mass_matrix[0].reinit(fe.dofs_per_cell, fe.dofs_per_cell);
mass_matrix[1].reinit(fe.dofs_per_cell, fe.dofs_per_cell);
laplace_matrix[0].reinit(fe.dofs_per_cell, fe.dofs_per_cell);
laplace_matrix[1].reinit(fe.dofs_per_cell, fe.dofs_per_cell);
for (typename DoFHandler<dim>::active_cell_iterator
cell = dof.begin_active();
cell != dof.end(); ++cell)
{
fe_values.reinit (cell);
for (unsigned int i=0; i<fe_values.dofs_per_cell; ++i)
for (unsigned int j=0; j<fe_values.dofs_per_cell; ++j)
for (unsigned int q=0; q<fe_values.n_quadrature_points; ++q)
{
mass_matrix[cell->index()](i,j) += fe_values.shape_value (i,q) *
fe_values.shape_value (j,q) *
fe_values.JxW(q);
laplace_matrix[cell->index()](i,j) += fe_values.shape_grad (i,q) *
fe_values.shape_grad (j,q) *
fe_values.JxW(q);
}
}
// check what we expect for this mapping
// about equality or inequality of the
// matrices
deallog << "Mass matrices "
<< (equal (mass_matrix[0], mass_matrix[1]) ? "are" : "are not")
<< " equal."
<< std::endl;
deallog << "Laplace matrices "
<< (equal (laplace_matrix[0], laplace_matrix[1]) ? "are" : "are not")
<< " equal."
<< std::endl;
for (unsigned int cell=0; cell<2; ++cell)
{
deallog << "cell=" << cell << std::endl;
deallog << "mass_matrix:" << std::endl;
for (unsigned int i=0; i<fe_values.dofs_per_cell; ++i)
{
for (unsigned int j=0; j<fe_values.dofs_per_cell; ++j)
deallog << mass_matrix[cell](i,j) << ' ';
deallog << std::endl;
}
deallog << "laplace_matrix:" << std::endl;
for (unsigned int i=0; i<fe_values.dofs_per_cell; ++i)
{
for (unsigned int j=0; j<fe_values.dofs_per_cell; ++j)
deallog << laplace_matrix[cell](i,j) << ' ';
deallog << std::endl;
}
}
}
template <int dim>
void test()
{
Triangulation<dim> tr;
Point<dim> p1 = Point<dim>();
Point<dim> p2 = (dim == 2 ?
Point<dim>(2,1) :
Point<dim>(2,1,1));
std::vector<unsigned int> subdivisions (dim, 1);
subdivisions[0] = 2;
GridGenerator::subdivided_hyper_rectangle(tr, subdivisions, p1, p2);
static const HyperBallBoundary<dim> boundary(tr.begin_active()->center());
tr.set_boundary (1, boundary);
// set boundary id on cell 1
for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)
if (tr.begin_active()->at_boundary(f))
tr.begin_active()->face(f)->set_boundary_id (1);
test(tr);
}
int main()
{
std::ofstream logfile ("output");
deallog << std::setprecision (4);
deallog.attach(logfile);
deallog.depth_console (0);
deallog.threshold_double(1.e-7);
test<2>();
test<3>();
}
| lue/dealii | tests/fe/cell_similarity_dgp_nonparametric_01.cc | C++ | lgpl-2.1 | 5,812 |
<?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 |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// 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/.
#include "main.h"
template<typename MatrixType> void product_selfadjoint(const MatrixType& m)
{
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
typedef Matrix<Scalar, 1, MatrixType::RowsAtCompileTime> RowVectorType;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, Dynamic, RowMajor> RhsMatrixType;
Index rows = m.rows();
Index cols = m.cols();
MatrixType m1 = MatrixType::Random(rows, cols),
m2 = MatrixType::Random(rows, cols),
m3;
VectorType v1 = VectorType::Random(rows),
v2 = VectorType::Random(rows),
v3(rows);
RowVectorType r1 = RowVectorType::Random(rows),
r2 = RowVectorType::Random(rows);
RhsMatrixType m4 = RhsMatrixType::Random(rows,10);
Scalar s1 = internal::random<Scalar>(),
s2 = internal::random<Scalar>(),
s3 = internal::random<Scalar>();
m1 = (m1.adjoint() + m1).eval();
// rank2 update
m2 = m1.template triangularView<Lower>();
m2.template selfadjointView<Lower>().rankUpdate(v1,v2);
VERIFY_IS_APPROX(m2, (m1 + v1 * v2.adjoint()+ v2 * v1.adjoint()).template triangularView<Lower>().toDenseMatrix());
m2 = m1.template triangularView<Upper>();
m2.template selfadjointView<Upper>().rankUpdate(-v1,s2*v2,s3);
VERIFY_IS_APPROX(m2, (m1 + (s3*(-v1)*(s2*v2).adjoint()+numext::conj(s3)*(s2*v2)*(-v1).adjoint())).template triangularView<Upper>().toDenseMatrix());
m2 = m1.template triangularView<Upper>();
m2.template selfadjointView<Upper>().rankUpdate(-s2*r1.adjoint(),r2.adjoint()*s3,s1);
VERIFY_IS_APPROX(m2, (m1 + s1*(-s2*r1.adjoint())*(r2.adjoint()*s3).adjoint() + numext::conj(s1)*(r2.adjoint()*s3) * (-s2*r1.adjoint()).adjoint()).template triangularView<Upper>().toDenseMatrix());
if (rows>1)
{
m2 = m1.template triangularView<Lower>();
m2.block(1,1,rows-1,cols-1).template selfadjointView<Lower>().rankUpdate(v1.tail(rows-1),v2.head(cols-1));
m3 = m1;
m3.block(1,1,rows-1,cols-1) += v1.tail(rows-1) * v2.head(cols-1).adjoint()+ v2.head(cols-1) * v1.tail(rows-1).adjoint();
VERIFY_IS_APPROX(m2, m3.template triangularView<Lower>().toDenseMatrix());
}
}
void test_product_selfadjoint()
{
int s = 0;
for(int i = 0; i < g_repeat ; i++) {
CALL_SUBTEST_1( product_selfadjoint(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( product_selfadjoint(Matrix<float, 2, 2>()) );
CALL_SUBTEST_3( product_selfadjoint(Matrix3d()) );
s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2);
CALL_SUBTEST_4( product_selfadjoint(MatrixXcf(s, s)) );
TEST_SET_BUT_UNUSED_VARIABLE(s)
s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2);
CALL_SUBTEST_5( product_selfadjoint(MatrixXcd(s,s)) );
TEST_SET_BUT_UNUSED_VARIABLE(s)
s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE);
CALL_SUBTEST_6( product_selfadjoint(MatrixXd(s,s)) );
TEST_SET_BUT_UNUSED_VARIABLE(s)
s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE);
CALL_SUBTEST_7( product_selfadjoint(Matrix<float,Dynamic,Dynamic,RowMajor>(s,s)) );
TEST_SET_BUT_UNUSED_VARIABLE(s)
}
}
| OSVR/OSVR-Core | vendor/eigen/test/product_selfadjoint.cpp | C++ | apache-2.0 | 3,502 |
/*
* 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 |
import unittest
import os
from os.path import abspath, join
from robot.running.importer import ImportCache
from robot.errors import FrameworkError
from robot.utils.asserts import assert_equal, assert_true, assert_raises
from robot.utils import normpath
class TestImportCache(unittest.TestCase):
def setUp(self):
self.cache = ImportCache()
self.cache[('lib', ['a1', 'a2'])] = 'Library'
self.cache['res'] = 'Resource'
def test_add_item(self):
assert_equal(self.cache._keys, [('lib', ['a1', 'a2']), 'res'])
assert_equal(self.cache._items, ['Library', 'Resource'])
def test_overwrite_item(self):
self.cache['res'] = 'New Resource'
assert_equal(self.cache['res'], 'New Resource')
assert_equal(self.cache._keys, [('lib', ['a1', 'a2']), 'res'])
assert_equal(self.cache._items, ['Library', 'New Resource'])
def test_get_existing_item(self):
assert_equal(self.cache['res'], 'Resource')
assert_equal(self.cache[('lib', ['a1', 'a2'])], 'Library')
assert_equal(self.cache[('lib', ['a1', 'a2'])], 'Library')
assert_equal(self.cache['res'], 'Resource')
def test_contains_item(self):
assert_true(('lib', ['a1', 'a2']) in self.cache)
assert_true('res' in self.cache)
assert_true(('lib', ['a1', 'a2', 'wrong']) not in self.cache)
assert_true('nonex' not in self.cache)
def test_get_non_existing_item(self):
assert_raises(KeyError, self.cache.__getitem__, 'nonex')
assert_raises(KeyError, self.cache.__getitem__, ('lib1', ['wrong']))
def test_invalid_key(self):
assert_raises(FrameworkError, self.cache.__setitem__, ['inv'], None)
def test_existing_absolute_paths_are_normalized(self):
cache = ImportCache()
path = join(abspath('.'), '.', os.listdir('.')[0])
value = object()
cache[path] = value
assert_equal(cache[path], value)
assert_equal(cache._keys[0], normpath(path, case_normalize=True))
def test_existing_non_absolute_paths_are_not_normalized(self):
cache = ImportCache()
path = os.listdir('.')[0]
value = object()
cache[path] = value
assert_equal(cache[path], value)
assert_equal(cache._keys[0], path)
def test_non_existing_absolute_paths_are_not_normalized(self):
cache = ImportCache()
path = join(abspath('.'), '.', 'NonExisting.file')
value = object()
cache[path] = value
assert_equal(cache[path], value)
assert_equal(cache._keys[0], path)
if __name__ == '__main__':
unittest.main()
| alexandrul-ci/robotframework | utest/running/test_importer.py | Python | apache-2.0 | 2,640 |
/*
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 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for XLA op wrappers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
from tensorflow.compiler.tests import xla_test
from tensorflow.compiler.tf2xla.python import xla
from tensorflow.compiler.xla import xla_data_pb2
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import function
from tensorflow.python.ops import array_ops
from tensorflow.python.platform import googletest
class XlaOpsTest(xla_test.XLATestCase, parameterized.TestCase):
def _assertOpOutputMatchesExpected(self, op, args, expected,
equality_fn=None):
with self.test_session() as session:
with self.test_scope():
placeholders = [
array_ops.placeholder(dtypes.as_dtype(arg.dtype), arg.shape)
for arg in args
]
feeds = {placeholders[i]: args[i] for i in range(0, len(args))}
output = op(*placeholders)
result = session.run(output, feeds)
if not equality_fn:
equality_fn = self.assertAllClose
equality_fn(result, expected, rtol=1e-3)
def testAdd(self):
for dtype in self.numeric_types:
self._assertOpOutputMatchesExpected(
xla.add,
args=(np.array([1, 2, 3], dtype=dtype),
np.array([4, 5, 6], dtype=dtype)),
expected=np.array([5, 7, 9], dtype=dtype))
self._assertOpOutputMatchesExpected(
lambda x, y: xla.add(x, y, broadcast_dims=(0,)),
args=(np.array([[1, 2], [3, 4]], dtype=dtype),
np.array([7, 11], dtype=dtype)),
expected=np.array([[8, 9], [14, 15]], dtype=dtype))
self._assertOpOutputMatchesExpected(
lambda x, y: xla.add(x, y, broadcast_dims=(1,)),
args=(np.array([[1, 2], [3, 4]], dtype=dtype),
np.array([7, 11], dtype=dtype)),
expected=np.array([[8, 13], [10, 15]], dtype=dtype))
def testBroadcast(self):
for dtype in self.numeric_types:
v = np.arange(4, dtype=np.int32).astype(dtype).reshape([2, 2])
self._assertOpOutputMatchesExpected(
lambda x: xla.broadcast(x, (7, 42)),
args=(v,),
expected=np.tile(v, (7, 42, 1, 1)))
def testShiftRightLogical(self):
self._assertOpOutputMatchesExpected(
xla.shift_right_logical,
args=(np.array([-1, 16], dtype=np.int32), np.int32(4)),
expected=np.array([0x0FFFFFFF, 1], dtype=np.int32))
self._assertOpOutputMatchesExpected(
xla.shift_right_logical,
args=(np.array([0xFFFFFFFF, 16], dtype=np.uint32), np.uint32(4)),
expected=np.array([0x0FFFFFFF, 1], dtype=np.uint32))
def testShiftRightArithmetic(self):
self._assertOpOutputMatchesExpected(
xla.shift_right_arithmetic,
args=(np.array([-1, 16], dtype=np.int32), np.int32(4)),
expected=np.array([-1, 1], dtype=np.int32))
self._assertOpOutputMatchesExpected(
xla.shift_right_arithmetic,
args=(np.array([0xFFFFFFFF, 16], dtype=np.uint32), np.uint32(4)),
expected=np.array([0xFFFFFFFF, 1], dtype=np.uint32))
PRECISION_VALUES = (None, xla_data_pb2.PrecisionConfig.DEFAULT,
xla_data_pb2.PrecisionConfig.HIGH,
xla_data_pb2.PrecisionConfig.HIGHEST)
@parameterized.parameters(*PRECISION_VALUES)
def testConv(self, precision):
for dtype in set(self.float_types).intersection(
set([dtypes.bfloat16.as_numpy_dtype, np.float32])):
def conv_1d_fn(lhs, rhs):
dnums = xla_data_pb2.ConvolutionDimensionNumbers()
num_spatial_dims = 1
dnums.input_batch_dimension = 0
dnums.input_feature_dimension = 1
dnums.output_batch_dimension = 0
dnums.output_feature_dimension = 1
dnums.kernel_output_feature_dimension = 0
dnums.kernel_input_feature_dimension = 1
dnums.input_spatial_dimensions.extend(range(2, 2 + num_spatial_dims))
dnums.kernel_spatial_dimensions.extend(range(2, 2 + num_spatial_dims))
dnums.output_spatial_dimensions.extend(range(2, 2 + num_spatial_dims))
precision_config = None
if precision:
precision_config = xla_data_pb2.PrecisionConfig()
precision_config.operand_precision.extend([precision, precision])
return xla.conv(
lhs,
rhs,
window_strides=(1,),
padding=((2, 1),),
lhs_dilation=(1,),
rhs_dilation=(2,),
dimension_numbers=dnums)
self._assertOpOutputMatchesExpected(
conv_1d_fn,
args=(
np.array([[[3, 4, 5, 6]]], dtype=dtype),
np.array([[[-2, -3]]], dtype=dtype),
),
expected=np.array([[[-9, -12, -21, -26, -10]]], dtype=dtype))
@parameterized.parameters(*PRECISION_VALUES)
def testDotGeneral(self, precision):
for dtype in self.float_types:
def dot_fn(lhs, rhs):
dnums = xla_data_pb2.DotDimensionNumbers()
dnums.lhs_contracting_dimensions.append(2)
dnums.rhs_contracting_dimensions.append(1)
dnums.lhs_batch_dimensions.append(0)
dnums.rhs_batch_dimensions.append(0)
precision_config = None
if precision:
precision_config = xla_data_pb2.PrecisionConfig()
precision_config.operand_precision.extend([precision, precision])
return xla.dot_general(
lhs,
rhs,
dimension_numbers=dnums,
precision_config=precision_config)
lhs = np.array(
[
[[1, 2], [3, 4]],
[[5, 6], [7, 8]],
], dtype=dtype)
rhs = np.array(
[
[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]],
], dtype=dtype)
self._assertOpOutputMatchesExpected(
dot_fn,
args=(lhs, rhs),
expected=np.array(
[
[[9, 12, 15], [19, 26, 33]],
[[95, 106, 117], [129, 144, 159]],
],
dtype=dtype))
def testNeg(self):
for dtype in self.numeric_types - {np.uint8, np.int8}:
self._assertOpOutputMatchesExpected(
xla.neg,
args=(np.array([1, 2, 3], dtype=dtype),),
expected=np.array([-1, -2, -3], dtype=dtype))
def testPad(self):
for dtype in self.numeric_types:
def pad_fn(x):
return xla.pad(
x,
padding_value=7,
padding_low=[2, 1],
padding_high=[1, 2],
padding_interior=[1, 0])
self._assertOpOutputMatchesExpected(
pad_fn,
args=(np.arange(4, dtype=np.int32).astype(dtype).reshape([2, 2]),),
expected=np.array(
[[7, 7, 7, 7, 7], [7, 7, 7, 7, 7], [7, 0, 1, 7, 7],
[7, 7, 7, 7, 7], [7, 2, 3, 7, 7], [7, 7, 7, 7, 7]],
dtype=dtype))
def testReduce(self):
for dtype in set(self.numeric_types).intersection(
set([dtypes.bfloat16.as_numpy_dtype, np.float32])):
@function.Defun(dtype, dtype)
def sum_reducer(x, y):
return x + y
def sum_reduction(dims):
def fn(x):
return xla.reduce(
x, init_value=0, dimensions_to_reduce=dims, reducer=sum_reducer)
return fn
self._assertOpOutputMatchesExpected(
sum_reduction(dims=[]),
args=(np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]),),
expected=np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]))
self._assertOpOutputMatchesExpected(
sum_reduction(dims=[0]),
args=(np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]),),
expected=np.array([12, 15, 18, 21], dtype=dtype))
self._assertOpOutputMatchesExpected(
sum_reduction(dims=[1]),
args=(np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]),),
expected=np.array([6, 22, 38], dtype=dtype))
self._assertOpOutputMatchesExpected(
sum_reduction(dims=[0, 1]),
args=(np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]),),
expected=dtype(66))
@function.Defun(dtype, dtype)
def mul_reducer(x, y):
return x * y
def mul_reduction(dims):
def fn(x):
return xla.reduce(
x, init_value=1, dimensions_to_reduce=dims, reducer=mul_reducer)
return fn
self._assertOpOutputMatchesExpected(
mul_reduction(dims=[0]),
args=(np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]),),
expected=np.array([0, 45, 120, 231], dtype=dtype))
def testSelectAndScatter(self):
for dtype in set(self.numeric_types).intersection(
set([dtypes.bfloat16.as_numpy_dtype, np.float32])):
@function.Defun(dtype, dtype)
def add_scatter(x, y):
return x + y
@function.Defun(dtype, dtype)
def ge_select(x, y):
return x >= y
def test_fn(operand, source):
return xla.select_and_scatter(
operand,
window_dimensions=[2, 3, 1, 1],
window_strides=[2, 2, 1, 1],
padding=[[0, 0]] * 4,
source=source,
init_value=0,
select=ge_select,
scatter=add_scatter)
self._assertOpOutputMatchesExpected(
test_fn,
args=(np.array(
[[7, 2, 5, 3, 8], [3, 8, 9, 3, 4], [1, 5, 7, 5, 6],
[0, 6, 2, 10, 2]],
dtype=dtype).reshape((4, 5, 1, 1)),
np.array([[2, 6], [3, 1]], dtype=dtype).reshape((2, 2, 1, 1))),
expected=np.array(
[[0, 0, 0, 0, 0], [0, 0, 8, 0, 0], [0, 0, 3, 0, 0],
[0, 0, 0, 1, 0]],
dtype=dtype).reshape((4, 5, 1, 1)))
def testTranspose(self):
for dtype in self.numeric_types:
v = np.arange(4, dtype=np.int32).astype(dtype).reshape([2, 2])
self._assertOpOutputMatchesExpected(
lambda x: xla.transpose(x, [1, 0]), args=(v,), expected=v.T)
def testDynamicSlice(self):
for dtype in self.numeric_types:
self._assertOpOutputMatchesExpected(
xla.dynamic_slice,
args=(np.arange(1000,
dtype=np.int32).astype(dtype).reshape([10, 10, 10]),
np.array([5, 7, 3]), np.array([2, 3, 2])),
expected=np.array(
np.array([[[573, 574], [583, 584], [593, 594]],
[[673, 674], [683, 684], [693, 694]]]),
dtype=dtype))
def testDynamicSliceWithIncorrectStartIndicesShape(self):
with self.test_session() as session:
with self.test_scope():
output = xla.dynamic_slice(
np.arange(1000, dtype=np.int32).reshape([10, 10, 10]),
np.array([5, 7]), np.array([2, 3, 4]))
with self.assertRaises(errors.InvalidArgumentError) as invalid_arg_error:
session.run(output)
self.assertRegexpMatches(
invalid_arg_error.exception.message,
(r'start_indices must be a vector with length equal to input rank, '
r'but input rank is 3 and start_indices has shape \[2\].*'))
def testDynamicSliceWithIncorrectSizeIndicesShape(self):
with self.test_session() as session:
with self.test_scope():
output = xla.dynamic_slice(
np.arange(1000, dtype=np.int32).reshape([10, 10, 10]),
np.array([5, 7, 3]), np.array([2, 3]))
with self.assertRaises(errors.InvalidArgumentError) as invalid_arg_error:
session.run(output)
self.assertRegexpMatches(
invalid_arg_error.exception.message,
(r'size_indices must be a vector with length equal to input rank, '
r'but input rank is 3 and size_indices has shape \[2\].*'))
if __name__ == '__main__':
googletest.main()
| jendap/tensorflow | tensorflow/compiler/tests/xla_ops_test.py | Python | apache-2.0 | 12,658 |
/*
* 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 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.hbase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.nifi.hbase.put.PutFlowFile;
import org.apache.nifi.provenance.ProvenanceEventRecord;
import org.apache.nifi.provenance.ProvenanceEventType;
import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Test;
public class TestPutHBaseJSON {
public static final String DEFAULT_TABLE_NAME = "nifi";
public static final String DEFAULT_ROW = "row1";
public static final String DEFAULT_COLUMN_FAMILY = "family1";
@Test
public void testCustomValidate() throws InitializationException {
// missing row id and row id field name should be invalid
TestRunner runner = getTestRunner(DEFAULT_TABLE_NAME, DEFAULT_COLUMN_FAMILY, "1");
getHBaseClientService(runner);
runner.assertNotValid();
// setting both properties should still be invalid
runner = getTestRunner(DEFAULT_TABLE_NAME, DEFAULT_COLUMN_FAMILY, "1");
getHBaseClientService(runner);
runner.setProperty(PutHBaseJSON.ROW_ID, "rowId");
runner.setProperty(PutHBaseJSON.ROW_FIELD_NAME, "rowFieldName");
runner.assertNotValid();
// only a row id field name should make it valid
runner = getTestRunner(DEFAULT_TABLE_NAME, DEFAULT_COLUMN_FAMILY, "1");
getHBaseClientService(runner);
runner.setProperty(PutHBaseJSON.ROW_FIELD_NAME, "rowFieldName");
runner.assertValid();
// only a row id should make it valid
runner = getTestRunner(DEFAULT_TABLE_NAME, DEFAULT_COLUMN_FAMILY, "1");
getHBaseClientService(runner);
runner.setProperty(PutHBaseJSON.ROW_ID, "rowId");
runner.assertValid();
}
@Test
public void testSingleJsonDocAndProvidedRowId() throws IOException, InitializationException {
final TestRunner runner = getTestRunner(DEFAULT_TABLE_NAME, DEFAULT_COLUMN_FAMILY, "1");
final MockHBaseClientService hBaseClient = getHBaseClientService(runner);
runner.setProperty(PutHBaseJSON.ROW_ID, DEFAULT_ROW);
final String content = "{ \"field1\" : \"value1\", \"field2\" : \"value2\" }";
runner.enqueue(content.getBytes("UTF-8"));
runner.run();
runner.assertAllFlowFilesTransferred(PutHBaseCell.REL_SUCCESS);
final MockFlowFile outFile = runner.getFlowFilesForRelationship(PutHBaseCell.REL_SUCCESS).get(0);
outFile.assertContentEquals(content);
assertNotNull(hBaseClient.getFlowFilePuts());
assertEquals(1, hBaseClient.getFlowFilePuts().size());
final List<PutFlowFile> puts = hBaseClient.getFlowFilePuts().get(DEFAULT_TABLE_NAME);
assertEquals(1, puts.size());
final Map<String,byte[]> expectedColumns = new HashMap<>();
expectedColumns.put("field1", hBaseClient.toBytes("value1"));
expectedColumns.put("field2", hBaseClient.toBytes("value2"));
HBaseTestUtil.verifyPut(DEFAULT_ROW, DEFAULT_COLUMN_FAMILY, expectedColumns, puts);
final List<ProvenanceEventRecord> events = runner.getProvenanceEvents();
assertEquals(1, events.size());
final ProvenanceEventRecord event = events.get(0);
assertEquals("hbase://" + DEFAULT_TABLE_NAME + "/" + DEFAULT_ROW, event.getTransitUri());
}
@Test
public void testSingleJsonDocAndProvidedRowIdwithNonString() throws IOException, InitializationException {
final TestRunner runner = getTestRunner(DEFAULT_TABLE_NAME, DEFAULT_COLUMN_FAMILY, "1");
runner.setProperty(PutHBaseJSON.FIELD_ENCODING_STRATEGY, PutHBaseJSON.BYTES_ENCODING_VALUE);
final MockHBaseClientService hBaseClient = getHBaseClientService(runner);
runner.setProperty(PutHBaseJSON.ROW_ID, DEFAULT_ROW);
final String content = "{ \"field1\" : 1.23456, \"field2\" : 2345235, \"field3\" : false }";
runner.enqueue(content.getBytes("UTF-8"));
runner.run();
runner.assertAllFlowFilesTransferred(PutHBaseCell.REL_SUCCESS);
final MockFlowFile outFile = runner.getFlowFilesForRelationship(PutHBaseCell.REL_SUCCESS).get(0);
outFile.assertContentEquals(content);
assertNotNull(hBaseClient.getFlowFilePuts());
assertEquals(1, hBaseClient.getFlowFilePuts().size());
final List<PutFlowFile> puts = hBaseClient.getFlowFilePuts().get(DEFAULT_TABLE_NAME);
assertEquals(1, puts.size());
final Map<String,byte[]> expectedColumns = new HashMap<>();
expectedColumns.put("field1", hBaseClient.toBytes(1.23456d));
expectedColumns.put("field2", hBaseClient.toBytes(2345235l));
expectedColumns.put("field3", hBaseClient.toBytes(false));
HBaseTestUtil.verifyPut(DEFAULT_ROW, DEFAULT_COLUMN_FAMILY, expectedColumns, puts);
final List<ProvenanceEventRecord> events = runner.getProvenanceEvents();
assertEquals(1, events.size());
final ProvenanceEventRecord event = events.get(0);
assertEquals("hbase://" + DEFAULT_TABLE_NAME + "/" + DEFAULT_ROW, event.getTransitUri());
}
@Test
public void testSingJsonDocAndExtractedRowId() throws IOException, InitializationException {
final TestRunner runner = getTestRunner(DEFAULT_TABLE_NAME, DEFAULT_COLUMN_FAMILY, "1");
final MockHBaseClientService hBaseClient = getHBaseClientService(runner);
runner.setProperty(PutHBaseJSON.ROW_FIELD_NAME, "rowField");
final String content = "{ \"rowField\" : \"myRowId\", \"field1\" : \"value1\", \"field2\" : \"value2\" }";
runner.enqueue(content.getBytes(StandardCharsets.UTF_8));
runner.run();
runner.assertAllFlowFilesTransferred(PutHBaseCell.REL_SUCCESS);
final MockFlowFile outFile = runner.getFlowFilesForRelationship(PutHBaseCell.REL_SUCCESS).get(0);
outFile.assertContentEquals(content);
assertNotNull(hBaseClient.getFlowFilePuts());
assertEquals(1, hBaseClient.getFlowFilePuts().size());
final List<PutFlowFile> puts = hBaseClient.getFlowFilePuts().get(DEFAULT_TABLE_NAME);
assertEquals(1, puts.size());
// should be a put with row id of myRowId, and rowField shouldn't end up in the columns
final Map<String,byte[]> expectedColumns1 = new HashMap<>();
expectedColumns1.put("field1", hBaseClient.toBytes("value1"));
expectedColumns1.put("field2", hBaseClient.toBytes("value2"));
HBaseTestUtil.verifyPut("myRowId", DEFAULT_COLUMN_FAMILY, expectedColumns1, puts);
final List<ProvenanceEventRecord> events = runner.getProvenanceEvents();
assertEquals(1, events.size());
HBaseTestUtil.verifyEvent(runner.getProvenanceEvents(), "hbase://" + DEFAULT_TABLE_NAME + "/myRowId", ProvenanceEventType.SEND);
}
@Test
public void testSingJsonDocAndExtractedRowIdMissingField() throws IOException, InitializationException {
final TestRunner runner = getTestRunner(DEFAULT_TABLE_NAME, DEFAULT_COLUMN_FAMILY, "1");
final MockHBaseClientService hBaseClient = getHBaseClientService(runner);
runner.setProperty(PutHBaseJSON.ROW_FIELD_NAME, "rowField");
final String content = "{ \"field1\" : \"value1\", \"field2\" : \"value2\" }";
runner.enqueue(content.getBytes(StandardCharsets.UTF_8));
runner.run();
runner.assertAllFlowFilesTransferred(PutHBaseCell.REL_FAILURE, 1);
final MockFlowFile outFile = runner.getFlowFilesForRelationship(PutHBaseCell.REL_FAILURE).get(0);
outFile.assertContentEquals(content);
// should be no provenance events
assertEquals(0, runner.getProvenanceEvents().size());
// no puts should have made it to the client
assertEquals(0, hBaseClient.getFlowFilePuts().size());
}
@Test
public void testMultipleJsonDocsRouteToFailure() throws IOException, InitializationException {
final TestRunner runner = getTestRunner(DEFAULT_TABLE_NAME, DEFAULT_COLUMN_FAMILY, "1");
final MockHBaseClientService hBaseClient = getHBaseClientService(runner);
runner.setProperty(PutHBaseJSON.ROW_ID, DEFAULT_ROW);
final String content1 = "{ \"field1\" : \"value1\", \"field2\" : \"value2\" }";
final String content2 = "{ \"field3\" : \"value3\", \"field4\" : \"value4\" }";
final String content = "[ " + content1 + " , " + content2 + " ]";
runner.enqueue(content.getBytes(StandardCharsets.UTF_8));
runner.run();
runner.assertAllFlowFilesTransferred(PutHBaseCell.REL_FAILURE, 1);
final MockFlowFile outFile = runner.getFlowFilesForRelationship(PutHBaseCell.REL_FAILURE).get(0);
outFile.assertContentEquals(content);
// should be no provenance events
assertEquals(0, runner.getProvenanceEvents().size());
// no puts should have made it to the client
assertEquals(0, hBaseClient.getFlowFilePuts().size());
}
@Test
public void testELWithProvidedRowId() throws IOException, InitializationException {
final TestRunner runner = getTestRunner("${hbase.table}", "${hbase.colFamily}", "1");
final MockHBaseClientService hBaseClient = getHBaseClientService(runner);
runner.setProperty(PutHBaseJSON.ROW_ID, "${hbase.rowId}");
final Map<String,String> attributes = new HashMap<>();
attributes.put("hbase.table", "myTable");
attributes.put("hbase.colFamily", "myColFamily");
attributes.put("hbase.rowId", "myRowId");
final String content = "{ \"field1\" : \"value1\", \"field2\" : \"value2\" }";
runner.enqueue(content.getBytes("UTF-8"), attributes);
runner.run();
runner.assertAllFlowFilesTransferred(PutHBaseCell.REL_SUCCESS);
final MockFlowFile outFile = runner.getFlowFilesForRelationship(PutHBaseCell.REL_SUCCESS).get(0);
outFile.assertContentEquals(content);
assertNotNull(hBaseClient.getFlowFilePuts());
assertEquals(1, hBaseClient.getFlowFilePuts().size());
final List<PutFlowFile> puts = hBaseClient.getFlowFilePuts().get("myTable");
assertEquals(1, puts.size());
final Map<String,byte[]> expectedColumns = new HashMap<>();
expectedColumns.put("field1", hBaseClient.toBytes("value1"));
expectedColumns.put("field2", hBaseClient.toBytes("value2"));
HBaseTestUtil.verifyPut("myRowId", "myColFamily", expectedColumns, puts);
final List<ProvenanceEventRecord> events = runner.getProvenanceEvents();
assertEquals(1, events.size());
HBaseTestUtil.verifyEvent(runner.getProvenanceEvents(), "hbase://myTable/myRowId", ProvenanceEventType.SEND);
}
@Test
public void testELWithExtractedRowId() throws IOException, InitializationException {
final TestRunner runner = getTestRunner("${hbase.table}", "${hbase.colFamily}", "1");
final MockHBaseClientService hBaseClient = getHBaseClientService(runner);
runner.setProperty(PutHBaseJSON.ROW_FIELD_NAME, "${hbase.rowField}");
final Map<String,String> attributes = new HashMap<>();
attributes.put("hbase.table", "myTable");
attributes.put("hbase.colFamily", "myColFamily");
attributes.put("hbase.rowField", "field1");
final String content = "{ \"field1\" : \"value1\", \"field2\" : \"value2\" }";
runner.enqueue(content.getBytes("UTF-8"), attributes);
runner.run();
runner.assertAllFlowFilesTransferred(PutHBaseCell.REL_SUCCESS);
final MockFlowFile outFile = runner.getFlowFilesForRelationship(PutHBaseCell.REL_SUCCESS).get(0);
outFile.assertContentEquals(content);
assertNotNull(hBaseClient.getFlowFilePuts());
assertEquals(1, hBaseClient.getFlowFilePuts().size());
final List<PutFlowFile> puts = hBaseClient.getFlowFilePuts().get("myTable");
assertEquals(1, puts.size());
final Map<String,byte[]> expectedColumns = new HashMap<>();
expectedColumns.put("field2", hBaseClient.toBytes("value2"));
HBaseTestUtil.verifyPut("value1", "myColFamily", expectedColumns, puts);
final List<ProvenanceEventRecord> events = runner.getProvenanceEvents();
assertEquals(1, events.size());
HBaseTestUtil.verifyEvent(runner.getProvenanceEvents(), "hbase://myTable/value1", ProvenanceEventType.SEND);
}
@Test
public void testNullAndArrayElementsWithWarnStrategy() throws InitializationException {
final TestRunner runner = getTestRunner(DEFAULT_TABLE_NAME, DEFAULT_COLUMN_FAMILY, "1");
final MockHBaseClientService hBaseClient = getHBaseClientService(runner);
runner.setProperty(PutHBaseJSON.ROW_ID, DEFAULT_ROW);
runner.setProperty(PutHBaseJSON.COMPLEX_FIELD_STRATEGY, PutHBaseJSON.COMPLEX_FIELD_WARN.getValue());
// should route to success because there is at least one valid field
final String content = "{ \"field1\" : [{ \"child_field1\" : \"child_value1\" }], \"field2\" : \"value2\", \"field3\" : null }";
runner.enqueue(content.getBytes(StandardCharsets.UTF_8));
runner.run();
runner.assertAllFlowFilesTransferred(PutHBaseCell.REL_SUCCESS);
assertNotNull(hBaseClient.getFlowFilePuts());
assertEquals(1, hBaseClient.getFlowFilePuts().size());
final List<PutFlowFile> puts = hBaseClient.getFlowFilePuts().get(DEFAULT_TABLE_NAME);
assertEquals(1, puts.size());
// should have skipped field1 and field3
final Map<String,byte[]> expectedColumns = new HashMap<>();
expectedColumns.put("field2", hBaseClient.toBytes("value2"));
HBaseTestUtil.verifyPut(DEFAULT_ROW, DEFAULT_COLUMN_FAMILY, expectedColumns, puts);
}
@Test
public void testNullAndArrayElementsWithIgnoreStrategy() throws InitializationException {
final TestRunner runner = getTestRunner(DEFAULT_TABLE_NAME, DEFAULT_COLUMN_FAMILY, "1");
final MockHBaseClientService hBaseClient = getHBaseClientService(runner);
runner.setProperty(PutHBaseJSON.ROW_ID, DEFAULT_ROW);
runner.setProperty(PutHBaseJSON.COMPLEX_FIELD_STRATEGY, PutHBaseJSON.COMPLEX_FIELD_IGNORE.getValue());
// should route to success because there is at least one valid field
final String content = "{ \"field1\" : [{ \"child_field1\" : \"child_value1\" }], \"field2\" : \"value2\", \"field3\" : null }";
runner.enqueue(content.getBytes(StandardCharsets.UTF_8));
runner.run();
runner.assertAllFlowFilesTransferred(PutHBaseCell.REL_SUCCESS);
assertNotNull(hBaseClient.getFlowFilePuts());
assertEquals(1, hBaseClient.getFlowFilePuts().size());
final List<PutFlowFile> puts = hBaseClient.getFlowFilePuts().get(DEFAULT_TABLE_NAME);
assertEquals(1, puts.size());
// should have skipped field1 and field3
final Map<String,byte[]> expectedColumns = new HashMap<>();
expectedColumns.put("field2", hBaseClient.toBytes("value2"));
HBaseTestUtil.verifyPut(DEFAULT_ROW, DEFAULT_COLUMN_FAMILY, expectedColumns, puts);
}
@Test
public void testNullAndArrayElementsWithFailureStrategy() throws InitializationException {
final TestRunner runner = getTestRunner(DEFAULT_TABLE_NAME, DEFAULT_COLUMN_FAMILY, "1");
final MockHBaseClientService hBaseClient = getHBaseClientService(runner);
runner.setProperty(PutHBaseJSON.ROW_ID, DEFAULT_ROW);
runner.setProperty(PutHBaseJSON.COMPLEX_FIELD_STRATEGY, PutHBaseJSON.COMPLEX_FIELD_FAIL.getValue());
// should route to success because there is at least one valid field
final String content = "{ \"field1\" : [{ \"child_field1\" : \"child_value1\" }], \"field2\" : \"value2\", \"field3\" : null }";
runner.enqueue(content.getBytes(StandardCharsets.UTF_8));
runner.run();
runner.assertAllFlowFilesTransferred(PutHBaseCell.REL_FAILURE, 1);
final MockFlowFile outFile = runner.getFlowFilesForRelationship(PutHBaseCell.REL_FAILURE).get(0);
outFile.assertContentEquals(content);
// should be no provenance events
assertEquals(0, runner.getProvenanceEvents().size());
// no puts should have made it to the client
assertEquals(0, hBaseClient.getFlowFilePuts().size());
}
@Test
public void testNullAndArrayElementsWithTextStrategy() throws InitializationException {
final TestRunner runner = getTestRunner(DEFAULT_TABLE_NAME, DEFAULT_COLUMN_FAMILY, "1");
final MockHBaseClientService hBaseClient = getHBaseClientService(runner);
runner.setProperty(PutHBaseJSON.ROW_ID, DEFAULT_ROW);
runner.setProperty(PutHBaseJSON.COMPLEX_FIELD_STRATEGY, PutHBaseJSON.COMPLEX_FIELD_TEXT.getValue());
// should route to success because there is at least one valid field
final String content = "{ \"field1\" : [{ \"child_field1\" : \"child_value1\" }], \"field2\" : \"value2\", \"field3\" : null }";
runner.enqueue(content.getBytes(StandardCharsets.UTF_8));
runner.run();
runner.assertAllFlowFilesTransferred(PutHBaseCell.REL_SUCCESS);
assertNotNull(hBaseClient.getFlowFilePuts());
assertEquals(1, hBaseClient.getFlowFilePuts().size());
final List<PutFlowFile> puts = hBaseClient.getFlowFilePuts().get(DEFAULT_TABLE_NAME);
assertEquals(1, puts.size());
// should have skipped field1 and field3
final Map<String,byte[]> expectedColumns = new HashMap<>();
expectedColumns.put("field1", hBaseClient.toBytes("[{\"child_field1\":\"child_value1\"}]"));
expectedColumns.put("field2", hBaseClient.toBytes("value2"));
HBaseTestUtil.verifyPut(DEFAULT_ROW, DEFAULT_COLUMN_FAMILY, expectedColumns, puts);
}
@Test
public void testNestedDocWithTextStrategy() throws InitializationException {
final TestRunner runner = getTestRunner(DEFAULT_TABLE_NAME, DEFAULT_COLUMN_FAMILY, "1");
final MockHBaseClientService hBaseClient = getHBaseClientService(runner);
runner.setProperty(PutHBaseJSON.ROW_ID, DEFAULT_ROW);
runner.setProperty(PutHBaseJSON.COMPLEX_FIELD_STRATEGY, PutHBaseJSON.COMPLEX_FIELD_TEXT.getValue());
// should route to success because there is at least one valid field
final String content = "{ \"field1\" : { \"child_field1\" : \"child_value1\" }, \"field2\" : \"value2\", \"field3\" : null }";
runner.enqueue(content.getBytes(StandardCharsets.UTF_8));
runner.run();
runner.assertAllFlowFilesTransferred(PutHBaseCell.REL_SUCCESS);
assertNotNull(hBaseClient.getFlowFilePuts());
assertEquals(1, hBaseClient.getFlowFilePuts().size());
final List<PutFlowFile> puts = hBaseClient.getFlowFilePuts().get(DEFAULT_TABLE_NAME);
assertEquals(1, puts.size());
// should have skipped field1 and field3
final Map<String,byte[]> expectedColumns = new HashMap<>();
expectedColumns.put("field1", hBaseClient.toBytes("{\"child_field1\":\"child_value1\"}"));
expectedColumns.put("field2", hBaseClient.toBytes("value2"));
HBaseTestUtil.verifyPut(DEFAULT_ROW, DEFAULT_COLUMN_FAMILY, expectedColumns, puts);
}
@Test
public void testAllElementsAreNullOrArrays() throws InitializationException {
final TestRunner runner = getTestRunner(DEFAULT_TABLE_NAME, DEFAULT_COLUMN_FAMILY, "1");
final MockHBaseClientService hBaseClient = getHBaseClientService(runner);
runner.setProperty(PutHBaseJSON.ROW_ID, DEFAULT_ROW);
runner.setProperty(PutHBaseJSON.COMPLEX_FIELD_STRATEGY, PutHBaseJSON.COMPLEX_FIELD_WARN.getValue());
// should route to failure since it would produce a put with no columns
final String content = "{ \"field1\" : [{ \"child_field1\" : \"child_value1\" }], \"field2\" : null }";
runner.enqueue(content.getBytes(StandardCharsets.UTF_8));
runner.run();
runner.assertAllFlowFilesTransferred(PutHBaseCell.REL_FAILURE, 1);
final MockFlowFile outFile = runner.getFlowFilesForRelationship(PutHBaseCell.REL_FAILURE).get(0);
outFile.assertContentEquals(content);
// should be no provenance events
assertEquals(0, runner.getProvenanceEvents().size());
// no puts should have made it to the client
assertEquals(0, hBaseClient.getFlowFilePuts().size());
}
@Test
public void testInvalidJson() throws InitializationException {
final TestRunner runner = getTestRunner(DEFAULT_TABLE_NAME, DEFAULT_COLUMN_FAMILY, "1");
getHBaseClientService(runner);
runner.setProperty(PutHBaseJSON.ROW_ID, DEFAULT_ROW);
final String content = "NOT JSON";
runner.enqueue(content.getBytes(StandardCharsets.UTF_8));
runner.run();
runner.assertAllFlowFilesTransferred(PutHBaseCell.REL_FAILURE, 1);
}
private TestRunner getTestRunner(String table, String columnFamily, String batchSize) {
final TestRunner runner = TestRunners.newTestRunner(PutHBaseJSON.class);
runner.setProperty(PutHBaseJSON.TABLE_NAME, table);
runner.setProperty(PutHBaseJSON.COLUMN_FAMILY, columnFamily);
runner.setProperty(PutHBaseJSON.BATCH_SIZE, batchSize);
return runner;
}
private MockHBaseClientService getHBaseClientService(final TestRunner runner) throws InitializationException {
final MockHBaseClientService hBaseClient = new MockHBaseClientService();
runner.addControllerService("hbaseClient", hBaseClient);
runner.enableControllerService(hBaseClient);
runner.setProperty(PutHBaseCell.HBASE_CLIENT_SERVICE, "hbaseClient");
return hBaseClient;
}
}
| ShellyLC/nifi | nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/test/java/org/apache/nifi/hbase/TestPutHBaseJSON.java | Java | apache-2.0 | 22,814 |
/*
* 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 |
/**
* 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.testng;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.apache.camel.CamelContext;
import org.apache.camel.ConsumerTemplate;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.Message;
import org.apache.camel.NoSuchEndpointException;
import org.apache.camel.Predicate;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.Service;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.component.properties.PropertiesComponent;
import org.apache.camel.impl.BreakpointSupport;
import org.apache.camel.impl.DefaultCamelBeanPostProcessor;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.DefaultDebugger;
import org.apache.camel.impl.InterceptSendToMockEndpointStrategy;
import org.apache.camel.impl.JndiRegistry;
import org.apache.camel.management.JmxSystemPropertyKeys;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.spi.Language;
import org.apache.camel.util.StopWatch;
import org.apache.camel.util.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
/**
* A useful base class which creates a {@link org.apache.camel.CamelContext} with some routes
* along with a {@link org.apache.camel.ProducerTemplate} for use in the test case
*/
public abstract class CamelTestSupport extends TestSupport {
private static final Logger LOG = LoggerFactory.getLogger(TestSupport.class);
private static final ThreadLocal<Boolean> INIT = new ThreadLocal<Boolean>();
private static ThreadLocal<ModelCamelContext> threadCamelContext
= new ThreadLocal<ModelCamelContext>();
private static ThreadLocal<ProducerTemplate> threadTemplate
= new ThreadLocal<ProducerTemplate>();
private static ThreadLocal<ConsumerTemplate> threadConsumer
= new ThreadLocal<ConsumerTemplate>();
private static ThreadLocal<Service> threadService
= new ThreadLocal<Service>();
protected volatile ModelCamelContext context;
protected volatile ProducerTemplate template;
protected volatile ConsumerTemplate consumer;
protected volatile Service camelContextService;
private boolean useRouteBuilder = true;
private final DebugBreakpoint breakpoint = new DebugBreakpoint();
private final StopWatch watch = new StopWatch();
/**
* Use the RouteBuilder or not
* @return <tt>true</tt> then {@link CamelContext} will be auto started,
* <tt>false</tt> then {@link CamelContext} will <b>not</b> be auto started (you will have to start it manually)
*/
public boolean isUseRouteBuilder() {
return useRouteBuilder;
}
public void setUseRouteBuilder(boolean useRouteBuilder) {
this.useRouteBuilder = useRouteBuilder;
}
/**
* Override when using <a href="http://camel.apache.org/advicewith.html">advice with</a> and return <tt>true</tt>.
* This helps knowing advice with is to be used, and {@link CamelContext} will not be started before
* the advice with takes place. This helps by ensuring the advice with has been property setup before the
* {@link CamelContext} is started
* <p/>
* <b>Important:</b> Its important to start {@link CamelContext} manually from the unit test
* after you are done doing all the advice with.
*
* @return <tt>true</tt> if you use advice with in your unit tests.
*/
public boolean isUseAdviceWith() {
return false;
}
/**
* Override to control whether {@link CamelContext} should be setup per test or per class.
* <p/>
* By default it will be setup/teardown per test (per test method). If you want to re-use
* {@link CamelContext} between test methods you can override this method and return <tt>true</tt>
* <p/>
* <b>Important:</b> Use this with care as the {@link CamelContext} will carry over state
* from previous tests, such as endpoints, components etc. So you cannot use this in all your tests.
* <p/>
* Setting up {@link CamelContext} uses the {@link #doPreSetup()}, {@link #doSetUp()}, and {@link #doPostSetup()}
* methods in that given order.
*
* @return <tt>true</tt> per class, <tt>false</tt> per test.
*/
public boolean isCreateCamelContextPerClass() {
return false;
}
/**
* Override to enable auto mocking endpoints based on the pattern.
* <p/>
* Return <tt>*</tt> to mock all endpoints.
*
* @see org.apache.camel.util.EndpointHelper#matchEndpoint(String, String)
*/
public String isMockEndpoints() {
return null;
}
/**
* Override to enable auto mocking endpoints based on the pattern, and <b>skip</b> sending
* to original endpoint.
* <p/>
* Return <tt>*</tt> to mock all endpoints.
*
* @see org.apache.camel.util.EndpointHelper#matchEndpoint(String, String)
*/
public String isMockEndpointsAndSkip() {
return null;
}
/**
* Override to enable debugger
* <p/>
* Is default <tt>false</tt>
*/
public boolean isUseDebugger() {
return false;
}
public Service getCamelContextService() {
return camelContextService;
}
public Service camelContextService() {
return camelContextService;
}
public CamelContext context() {
return context;
}
public ProducerTemplate template() {
return template;
}
public ConsumerTemplate consumer() {
return consumer;
}
/**
* Allows a service to be registered a separate lifecycle service to start
* and stop the context; such as for Spring when the ApplicationContext is
* started and stopped, rather than directly stopping the CamelContext
*/
public void setCamelContextService(Service service) {
camelContextService = service;
threadService.set(camelContextService);
}
@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception {
log.info("********************************************************************************");
log.info("Testing: " + getTestMethodName() + "(" + getClass().getName() + ")");
log.info("********************************************************************************");
if (isCreateCamelContextPerClass()) {
// test is per class, so only setup once (the first time)
boolean first = INIT.get() == null;
if (first) {
doPreSetup();
doSetUp();
doPostSetup();
} else {
// and in between tests we must do IoC and reset mocks
postProcessTest();
resetMocks();
}
} else {
// test is per test so always setup
doPreSetup();
doSetUp();
doPostSetup();
}
// only start timing after all the setup
watch.restart();
}
/**
* Strategy to perform any pre setup, before {@link CamelContext} is created
*/
protected void doPreSetup() throws Exception {
// noop
}
/**
* Strategy to perform any post setup after {@link CamelContext} is createt.
*/
protected void doPostSetup() throws Exception {
// noop
}
private void doSetUp() throws Exception {
log.debug("setUp test");
if (!useJmx()) {
disableJMX();
} else {
enableJMX();
}
CamelContext c2 = createCamelContext();
if (c2 instanceof ModelCamelContext) {
context = (ModelCamelContext)c2;
} else {
throw new Exception("Context must be a ModelCamelContext");
}
threadCamelContext.set(context);
assertNotNull(context, "No context found!");
// reduce default shutdown timeout to avoid waiting for 300 seconds
context.getShutdownStrategy().setTimeout(getShutdownTimeout());
// set debugger if enabled
if (isUseDebugger()) {
context.setDebugger(new DefaultDebugger());
context.getDebugger().addBreakpoint(breakpoint);
// note: when stopping CamelContext it will automatic remove the breakpoint
}
template = context.createProducerTemplate();
template.start();
consumer = context.createConsumerTemplate();
consumer.start();
threadTemplate.set(template);
threadConsumer.set(consumer);
// enable auto mocking if enabled
String pattern = isMockEndpoints();
if (pattern != null) {
context.addRegisterEndpointCallback(new InterceptSendToMockEndpointStrategy(pattern));
}
pattern = isMockEndpointsAndSkip();
if (pattern != null) {
context.addRegisterEndpointCallback(new InterceptSendToMockEndpointStrategy(pattern, true));
}
// configure properties component (mandatory for testing)
context.getComponent("properties", PropertiesComponent.class);
postProcessTest();
if (isUseRouteBuilder()) {
RoutesBuilder[] builders = createRouteBuilders();
for (RoutesBuilder builder : builders) {
log.debug("Using created route builder: " + builder);
context.addRoutes(builder);
}
boolean skip = "true".equalsIgnoreCase(System.getProperty("skipStartingCamelContext"));
if (skip) {
log.info("Skipping starting CamelContext as system property skipStartingCamelContext is set to be true.");
} else if (isUseAdviceWith()) {
log.info("Skipping starting CamelContext as isUseAdviceWith is set to true.");
} else {
startCamelContext();
}
} else {
log.debug("Using route builder from the created context: " + context);
}
log.debug("Routing Rules are: " + context.getRoutes());
assertValidContext(context);
INIT.set(true);
}
@AfterMethod(alwaysRun = true)
public void tearDown() throws Exception {
long time = watch.stop();
log.info("********************************************************************************");
log.info("Testing done: " + getTestMethodName() + "(" + getClass().getName() + ")");
log.info("Took: " + TimeUtils.printDuration(time) + " (" + time + " millis)");
log.info("********************************************************************************");
if (isCreateCamelContextPerClass()) {
// we tear down in after class
return;
}
LOG.debug("tearDown test");
doStopTemplates(consumer, template);
doStopCamelContext(context, camelContextService);
}
@AfterClass(alwaysRun = true)
public static void tearDownAfterClass() throws Exception {
INIT.remove();
LOG.debug("tearDownAfterClass test");
doStopTemplates(threadConsumer.get(), threadTemplate.get());
doStopCamelContext(threadCamelContext.get(), threadService.get());
}
/**
* Returns the timeout to use when shutting down (unit in seconds).
* <p/>
* Will default use 10 seconds.
*
* @return the timeout to use
*/
protected int getShutdownTimeout() {
return 10;
}
/**
* Whether or not JMX should be used during testing.
*
* @return <tt>false</tt> by default.
*/
protected boolean useJmx() {
return false;
}
/**
* Whether or not type converters should be lazy loaded (notice core converters is always loaded)
*
* @return <tt>false</tt> by default.
*/
@Deprecated
protected boolean isLazyLoadingTypeConverter() {
return false;
}
/**
* Lets post process this test instance to process any Camel annotations.
* Note that using Spring Test or Guice is a more powerful approach.
*/
protected void postProcessTest() throws Exception {
context = threadCamelContext.get();
template = threadTemplate.get();
consumer = threadConsumer.get();
camelContextService = threadService.get();
// use the default bean post processor from camel-core
DefaultCamelBeanPostProcessor processor = new DefaultCamelBeanPostProcessor(context);
processor.postProcessBeforeInitialization(this, getClass().getName());
processor.postProcessAfterInitialization(this, getClass().getName());
}
protected void stopCamelContext() throws Exception {
doStopCamelContext(context, camelContextService);
}
private static void doStopCamelContext(CamelContext context,
Service camelContextService) throws Exception {
if (camelContextService != null) {
if (camelContextService == threadService.get()) {
threadService.remove();
}
camelContextService.stop();
camelContextService = null;
} else {
if (context != null) {
if (context == threadCamelContext.get()) {
threadCamelContext.remove();
}
context.stop();
context = null;
}
}
}
private static void doStopTemplates(ConsumerTemplate consumer,
ProducerTemplate template) throws Exception {
if (consumer != null) {
if (consumer == threadConsumer.get()) {
threadConsumer.remove();
}
consumer.stop();
consumer = null;
}
if (template != null) {
if (template == threadTemplate.get()) {
threadTemplate.remove();
}
template.stop();
template = null;
}
}
protected void startCamelContext() throws Exception {
if (camelContextService != null) {
camelContextService.start();
} else {
if (context instanceof DefaultCamelContext) {
DefaultCamelContext defaultCamelContext = (DefaultCamelContext)context;
if (!defaultCamelContext.isStarted()) {
defaultCamelContext.start();
}
} else {
context.start();
}
}
}
@SuppressWarnings("deprecation")
protected CamelContext createCamelContext() throws Exception {
CamelContext context = new DefaultCamelContext(createRegistry());
context.setLazyLoadTypeConverters(isLazyLoadingTypeConverter());
return context;
}
protected JndiRegistry createRegistry() throws Exception {
return new JndiRegistry(createJndiContext());
}
protected Context createJndiContext() throws Exception {
Properties properties = new Properties();
// jndi.properties is optional
InputStream in = getClass().getClassLoader().getResourceAsStream("jndi.properties");
if (in != null) {
log.debug("Using jndi.properties from classpath root");
properties.load(in);
} else {
properties.put("java.naming.factory.initial", "org.apache.camel.util.jndi.CamelInitialContextFactory");
}
return new InitialContext(new Hashtable<Object, Object>(properties));
}
/**
* Factory method which derived classes can use to create a {@link RoutesBuilder}
* to define the routes for testing
*/
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() {
// no routes added by default
}
};
}
/**
* Factory method which derived classes can use to create an array of
* {@link org.apache.camel.RoutesBuilder}s to define the routes for testing
*
* @see #createRouteBuilder()
*/
protected RoutesBuilder[] createRouteBuilders() throws Exception {
return new RoutesBuilder[] {createRouteBuilder()};
}
/**
* Resolves a mandatory endpoint for the given URI or an exception is thrown
*
* @param uri the Camel <a href="">URI</a> to use to create or resolve an endpoint
* @return the endpoint
*/
protected Endpoint resolveMandatoryEndpoint(String uri) {
return resolveMandatoryEndpoint(context, uri);
}
/**
* Resolves a mandatory endpoint for the given URI and expected type or an exception is thrown
*
* @param uri the Camel <a href="">URI</a> to use to create or resolve an endpoint
* @return the endpoint
*/
protected <T extends Endpoint> T resolveMandatoryEndpoint(String uri, Class<T> endpointType) {
return resolveMandatoryEndpoint(context, uri, endpointType);
}
/**
* Resolves the mandatory Mock endpoint using a URI of the form <code>mock:someName</code>
*
* @param uri the URI which typically starts with "mock:" and has some name
* @return the mandatory mock endpoint or an exception is thrown if it could not be resolved
*/
protected MockEndpoint getMockEndpoint(String uri) {
return getMockEndpoint(uri, true);
}
/**
* Resolves the {@link MockEndpoint} using a URI of the form <code>mock:someName</code>, optionally
* creating it if it does not exist.
*
* @param uri the URI which typically starts with "mock:" and has some name
* @param create whether or not to allow the endpoint to be created if it doesn't exist
* @return the mock endpoint or an {@link NoSuchEndpointException} is thrown if it could not be resolved
* @throws NoSuchEndpointException is the mock endpoint does not exists
*/
protected MockEndpoint getMockEndpoint(String uri, boolean create) throws NoSuchEndpointException {
if (create) {
return resolveMandatoryEndpoint(uri, MockEndpoint.class);
} else {
Endpoint endpoint = context.hasEndpoint(uri);
if (endpoint instanceof MockEndpoint) {
return (MockEndpoint) endpoint;
}
throw new NoSuchEndpointException(String.format("MockEndpoint %s does not exist.", uri));
}
}
/**
* Sends a message to the given endpoint URI with the body value
*
* @param endpointUri the URI of the endpoint to send to
* @param body the body for the message
*/
protected void sendBody(String endpointUri, final Object body) {
template.send(endpointUri, new Processor() {
public void process(Exchange exchange) {
Message in = exchange.getIn();
in.setBody(body);
}
});
}
/**
* Sends a message to the given endpoint URI with the body value and specified headers
*
* @param endpointUri the URI of the endpoint to send to
* @param body the body for the message
* @param headers any headers to set on the message
*/
protected void sendBody(String endpointUri, final Object body, final Map<String, Object> headers) {
template.send(endpointUri, new Processor() {
public void process(Exchange exchange) {
Message in = exchange.getIn();
in.setBody(body);
for (Map.Entry<String, Object> entry : headers.entrySet()) {
in.setHeader(entry.getKey(), entry.getValue());
}
}
});
}
/**
* Sends messages to the given endpoint for each of the specified bodies
*
* @param endpointUri the endpoint URI to send to
* @param bodies the bodies to send, one per message
*/
protected void sendBodies(String endpointUri, Object... bodies) {
for (Object body : bodies) {
sendBody(endpointUri, body);
}
}
/**
* Creates an exchange with the given body
*/
protected Exchange createExchangeWithBody(Object body) {
return createExchangeWithBody(context, body);
}
/**
* Asserts that the given language name and expression evaluates to the
* given value on a specific exchange
*/
protected void assertExpression(Exchange exchange, String languageName, String expressionText, Object expectedValue) {
Language language = assertResolveLanguage(languageName);
Expression expression = language.createExpression(expressionText);
assertNotNull(expression, "No Expression could be created for text: " + expressionText + " language: " + language);
assertExpression(expression, exchange, expectedValue);
}
/**
* Asserts that the given language name and predicate expression evaluates
* to the expected value on the message exchange
*/
protected void assertPredicate(String languageName, String expressionText, Exchange exchange, boolean expected) {
Language language = assertResolveLanguage(languageName);
Predicate predicate = language.createPredicate(expressionText);
assertNotNull(predicate, "No Predicate could be created for text: " + expressionText + " language: " + language);
assertPredicate(predicate, exchange, expected);
}
/**
* Asserts that the language name can be resolved
*/
protected Language assertResolveLanguage(String languageName) {
Language language = context.resolveLanguage(languageName);
assertNotNull(language, "No language found for name: " + languageName);
return language;
}
/**
* Asserts that all the expectations of the Mock endpoints are valid
*/
protected void assertMockEndpointsSatisfied() throws InterruptedException {
MockEndpoint.assertIsSatisfied(context);
}
/**
* Asserts that all the expectations of the Mock endpoints are valid
*/
protected void assertMockEndpointsSatisfied(long timeout, TimeUnit unit) throws InterruptedException {
MockEndpoint.assertIsSatisfied(context, timeout, unit);
}
/**
* Reset all Mock endpoints.
*/
protected void resetMocks() {
MockEndpoint.resetMocks(context);
}
protected void assertValidContext(CamelContext context) {
assertNotNull(context, "No context found!");
}
protected <T extends Endpoint> T getMandatoryEndpoint(String uri, Class<T> type) {
T endpoint = context.getEndpoint(uri, type);
assertNotNull(endpoint, "No endpoint found for uri: " + uri);
return endpoint;
}
protected Endpoint getMandatoryEndpoint(String uri) {
Endpoint endpoint = context.getEndpoint(uri);
assertNotNull(endpoint, "No endpoint found for uri: " + uri);
return endpoint;
}
/**
* Disables the JMX agent. Must be called before the {@link #setUp()} method.
*/
protected void disableJMX() {
System.setProperty(JmxSystemPropertyKeys.DISABLED, "true");
}
/**
* Enables the JMX agent. Must be called before the {@link #setUp()} method.
*/
protected void enableJMX() {
System.setProperty(JmxSystemPropertyKeys.DISABLED, "false");
}
/**
* Single step debugs and Camel invokes this method before entering the given processor
*/
protected void debugBefore(Exchange exchange, Processor processor, ProcessorDefinition<?> definition,
String id, String label) {
}
/**
* Single step debugs and Camel invokes this method after processing the given processor
*/
protected void debugAfter(Exchange exchange, Processor processor, ProcessorDefinition<?> definition,
String id, String label, long timeTaken) {
}
/**
* To easily debug by overriding the <tt>debugBefore</tt> and <tt>debugAfter</tt> methods.
*/
private class DebugBreakpoint extends BreakpointSupport {
@Override
public void beforeProcess(Exchange exchange, Processor processor, ProcessorDefinition<?> definition) {
CamelTestSupport.this.debugBefore(exchange, processor, definition, definition.getId(), definition.getLabel());
}
@Override
public void afterProcess(Exchange exchange, Processor processor, ProcessorDefinition<?> definition, long timeTaken) {
CamelTestSupport.this.debugAfter(exchange, processor, definition, definition.getId(), definition.getLabel(), timeTaken);
}
}
}
| CandleCandle/camel | components/camel-testng/src/main/java/org/apache/camel/testng/CamelTestSupport.java | Java | apache-2.0 | 25,944 |
"""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 |
<?php
/**
* @file
* Definition of Drupal\views\Tests\TokenReplaceTest.
*/
namespace Drupal\views\Tests;
/**
* Tests core view token replacement.
*/
class TokenReplaceTest extends ViewUnitTestBase {
public static $modules = array('system');
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = array('test_tokens');
public static function getInfo() {
return array(
'name' => 'View core token replacement',
'description' => 'Checks view core token replacements.',
'group' => 'Views',
);
}
function setUp() {
parent::setUp();
$this->installSchema('system', 'url_alias');
}
/**
* Tests core token replacements generated from a view.
*/
function testTokenReplacement() {
$token_handler = \Drupal::token();
$view = views_get_view('test_tokens');
$view->setDisplay('page_1');
$this->executeView($view);
$expected = array(
'[view:label]' => 'Test tokens',
'[view:description]' => 'Test view to token replacement tests.',
'[view:id]' => 'test_tokens',
'[view:title]' => 'Test token page',
'[view:url]' => url('test_tokens', array('absolute' => TRUE)),
'[view:total-rows]' => (string) $view->total_rows,
'[view:base-table]' => 'views_test_data',
'[view:base-field]' => 'id',
'[view:items-per-page]' => '10',
'[view:current-page]' => '1',
'[view:page-count]' => '1',
);
foreach ($expected as $token => $expected_output) {
$output = $token_handler->replace($token, array('view' => $view));
$this->assertIdentical($output, $expected_output, format_string('Token %token replaced correctly.', array('%token' => $token)));
}
}
}
| nickopris/musicapp | www/core/modules/views/lib/Drupal/views/Tests/TokenReplaceTest.php | PHP | apache-2.0 | 1,734 |
// 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 |
using System.Web.Mvc;
using System.Web.Routing;
using Nop.Web.Framework;
using Nop.Web.Framework.Mvc;
namespace Nop.Admin.Models.Shipping
{
public partial class ShippingRateComputationMethodModel : BaseNopModel
{
[NopResourceDisplayName("Admin.Configuration.Shipping.Providers.Fields.FriendlyName")]
[AllowHtml]
public string FriendlyName { get; set; }
[NopResourceDisplayName("Admin.Configuration.Shipping.Providers.Fields.SystemName")]
[AllowHtml]
public string SystemName { get; set; }
[NopResourceDisplayName("Admin.Configuration.Shipping.Providers.Fields.DisplayOrder")]
public int DisplayOrder { get; set; }
[NopResourceDisplayName("Admin.Configuration.Shipping.Providers.Fields.IsActive")]
public bool IsActive { get; set; }
[NopResourceDisplayName("Admin.Configuration.Shipping.Providers.Fields.Logo")]
public string LogoUrl { get; set; }
public string ConfigurationActionName { get; set; }
public string ConfigurationControllerName { get; set; }
public RouteValueDictionary ConfigurationRouteValues { get; set; }
}
} | jornfilho/nopCommerce | source/Presentation/Nop.Web/Administration/Models/Shipping/ShippingRateComputationMethodModel.cs | C# | apache-2.0 | 1,179 |
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 |
/*
* Copyright 2021 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.services.clientpolicy.condition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.keycloak.Config.Scope;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.provider.ProviderConfigProperty;
/**
* @author <a href="mailto:takashi.norimatsu.ws@hitachi.com">Takashi Norimatsu</a>
*/
public class ClientUpdaterContextConditionFactory implements ClientPolicyConditionProviderFactory {
public static final String PROVIDER_ID = "client-updater-context";
public static final String UPDATE_CLIENT_SOURCE = "update-client-source";
public static final String BY_AUTHENTICATED_USER = "ByAuthenticatedUser";
public static final String BY_ANONYMOUS = "ByAnonymous";
public static final String BY_INITIAL_ACCESS_TOKEN = "ByInitialAccessToken";
public static final String BY_REGISTRATION_ACCESS_TOKEN = "ByRegistrationAccessToken";
private static final List<ProviderConfigProperty> configProperties = new ArrayList<ProviderConfigProperty>();
static {
ProviderConfigProperty property;
property = new ProviderConfigProperty(UPDATE_CLIENT_SOURCE, "Update Client Context", "Specifies the context how is client created or updated. " +
"ByInitialAccessToken is usually OpenID Connect client registration with the initial access token. " +
"ByRegistrationAccessToken is usually OpenID Connect client update request with the registration access token. " +
"ByAuthenticatedUser is usually Admin REST request with the token on behalf of authenticated user or client (service account). ByAnonymous is usually anonymous OpenID Client registration request.",
ProviderConfigProperty.MULTIVALUED_LIST_TYPE, BY_AUTHENTICATED_USER);
List<String> updateProfileValues = Arrays.asList(BY_AUTHENTICATED_USER, BY_ANONYMOUS, BY_INITIAL_ACCESS_TOKEN, BY_REGISTRATION_ACCESS_TOKEN);
property.setOptions(updateProfileValues);
configProperties.add(property);
}
@Override
public ClientPolicyConditionProvider create(KeycloakSession session) {
return new ClientUpdaterContextCondition(session);
}
@Override
public void init(Scope config) {
}
@Override
public void postInit(KeycloakSessionFactory factory) {
}
@Override
public void close() {
}
@Override
public String getId() {
return PROVIDER_ID;
}
@Override
public String getHelpText() {
return "The condition checks the context how is client created/updated to determine whether the policy is applied. For example it checks if client is created with admin REST API or OIDC dynamic client registration. And for the letter case if it is ANONYMOUS client registration or AUTHENTICATED client registration with Initial access token or Registration access token and so on.";
}
@Override
public List<ProviderConfigProperty> getConfigProperties() {
return configProperties;
}
}
| thomasdarimont/keycloak | services/src/main/java/org/keycloak/services/clientpolicy/condition/ClientUpdaterContextConditionFactory.java | Java | apache-2.0 | 3,749 |
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 (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 "gpu/command_buffer/service/test_helper.h"
#include <algorithm>
#include <string>
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_tokenizer.h"
#include "gpu/command_buffer/service/buffer_manager.h"
#include "gpu/command_buffer/service/error_state_mock.h"
#include "gpu/command_buffer/service/gl_utils.h"
#include "gpu/command_buffer/service/gpu_switches.h"
#include "gpu/command_buffer/service/mocks.h"
#include "gpu/command_buffer/service/program_manager.h"
#include "gpu/command_buffer/service/texture_manager.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gl/gl_mock.h"
using ::testing::_;
using ::testing::DoAll;
using ::testing::InSequence;
using ::testing::MatcherCast;
using ::testing::Pointee;
using ::testing::NotNull;
using ::testing::Return;
using ::testing::SetArrayArgument;
using ::testing::SetArgumentPointee;
using ::testing::StrEq;
using ::testing::StrictMock;
namespace gpu {
namespace gles2 {
namespace {
template<typename T>
T ConstructShaderVariable(
GLenum type, GLint array_size, GLenum precision,
bool static_use, const std::string& name) {
T var;
var.type = type;
var.arraySize = array_size;
var.precision = precision;
var.staticUse = static_use;
var.name = name;
var.mappedName = name; // No name hashing.
return var;
}
} // namespace anonymous
// GCC requires these declarations, but MSVC requires they not be present
#ifndef COMPILER_MSVC
const GLuint TestHelper::kServiceBlackTexture2dId;
const GLuint TestHelper::kServiceDefaultTexture2dId;
const GLuint TestHelper::kServiceBlackTextureCubemapId;
const GLuint TestHelper::kServiceDefaultTextureCubemapId;
const GLuint TestHelper::kServiceBlackExternalTextureId;
const GLuint TestHelper::kServiceDefaultExternalTextureId;
const GLuint TestHelper::kServiceBlackRectangleTextureId;
const GLuint TestHelper::kServiceDefaultRectangleTextureId;
const GLint TestHelper::kMaxSamples;
const GLint TestHelper::kMaxRenderbufferSize;
const GLint TestHelper::kMaxTextureSize;
const GLint TestHelper::kMaxCubeMapTextureSize;
const GLint TestHelper::kMaxRectangleTextureSize;
const GLint TestHelper::kNumVertexAttribs;
const GLint TestHelper::kNumTextureUnits;
const GLint TestHelper::kMaxTextureImageUnits;
const GLint TestHelper::kMaxVertexTextureImageUnits;
const GLint TestHelper::kMaxFragmentUniformVectors;
const GLint TestHelper::kMaxFragmentUniformComponents;
const GLint TestHelper::kMaxVaryingVectors;
const GLint TestHelper::kMaxVaryingFloats;
const GLint TestHelper::kMaxVertexUniformVectors;
const GLint TestHelper::kMaxVertexUniformComponents;
#endif
void TestHelper::SetupTextureInitializationExpectations(
::gfx::MockGLInterface* gl,
GLenum target,
bool use_default_textures) {
InSequence sequence;
bool needs_initialization = (target != GL_TEXTURE_EXTERNAL_OES);
bool needs_faces = (target == GL_TEXTURE_CUBE_MAP);
static GLuint texture_2d_ids[] = {
kServiceBlackTexture2dId,
kServiceDefaultTexture2dId };
static GLuint texture_cube_map_ids[] = {
kServiceBlackTextureCubemapId,
kServiceDefaultTextureCubemapId };
static GLuint texture_external_oes_ids[] = {
kServiceBlackExternalTextureId,
kServiceDefaultExternalTextureId };
static GLuint texture_rectangle_arb_ids[] = {
kServiceBlackRectangleTextureId,
kServiceDefaultRectangleTextureId };
const GLuint* texture_ids = NULL;
switch (target) {
case GL_TEXTURE_2D:
texture_ids = &texture_2d_ids[0];
break;
case GL_TEXTURE_CUBE_MAP:
texture_ids = &texture_cube_map_ids[0];
break;
case GL_TEXTURE_EXTERNAL_OES:
texture_ids = &texture_external_oes_ids[0];
break;
case GL_TEXTURE_RECTANGLE_ARB:
texture_ids = &texture_rectangle_arb_ids[0];
break;
default:
NOTREACHED();
}
int array_size = use_default_textures ? 2 : 1;
EXPECT_CALL(*gl, GenTextures(array_size, _))
.WillOnce(SetArrayArgument<1>(texture_ids,
texture_ids + array_size))
.RetiresOnSaturation();
for (int ii = 0; ii < array_size; ++ii) {
EXPECT_CALL(*gl, BindTexture(target, texture_ids[ii]))
.Times(1)
.RetiresOnSaturation();
if (needs_initialization) {
if (needs_faces) {
static GLenum faces[] = {
GL_TEXTURE_CUBE_MAP_POSITIVE_X,
GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
};
for (size_t ii = 0; ii < arraysize(faces); ++ii) {
EXPECT_CALL(*gl, TexImage2D(faces[ii], 0, GL_RGBA, 1, 1, 0, GL_RGBA,
GL_UNSIGNED_BYTE, _))
.Times(1)
.RetiresOnSaturation();
}
} else {
EXPECT_CALL(*gl, TexImage2D(target, 0, GL_RGBA, 1, 1, 0, GL_RGBA,
GL_UNSIGNED_BYTE, _))
.Times(1)
.RetiresOnSaturation();
}
}
}
EXPECT_CALL(*gl, BindTexture(target, 0))
.Times(1)
.RetiresOnSaturation();
}
void TestHelper::SetupTextureManagerInitExpectations(
::gfx::MockGLInterface* gl,
const char* extensions,
bool use_default_textures) {
InSequence sequence;
SetupTextureInitializationExpectations(
gl, GL_TEXTURE_2D, use_default_textures);
SetupTextureInitializationExpectations(
gl, GL_TEXTURE_CUBE_MAP, use_default_textures);
bool ext_image_external = false;
bool arb_texture_rectangle = false;
base::CStringTokenizer t(extensions, extensions + strlen(extensions), " ");
while (t.GetNext()) {
if (t.token() == "GL_OES_EGL_image_external") {
ext_image_external = true;
break;
}
if (t.token() == "GL_ARB_texture_rectangle") {
arb_texture_rectangle = true;
break;
}
}
if (ext_image_external) {
SetupTextureInitializationExpectations(
gl, GL_TEXTURE_EXTERNAL_OES, use_default_textures);
}
if (arb_texture_rectangle) {
SetupTextureInitializationExpectations(
gl, GL_TEXTURE_RECTANGLE_ARB, use_default_textures);
}
}
void TestHelper::SetupTextureDestructionExpectations(
::gfx::MockGLInterface* gl,
GLenum target,
bool use_default_textures) {
if (!use_default_textures)
return;
GLuint texture_id = 0;
switch (target) {
case GL_TEXTURE_2D:
texture_id = kServiceDefaultTexture2dId;
break;
case GL_TEXTURE_CUBE_MAP:
texture_id = kServiceDefaultTextureCubemapId;
break;
case GL_TEXTURE_EXTERNAL_OES:
texture_id = kServiceDefaultExternalTextureId;
break;
case GL_TEXTURE_RECTANGLE_ARB:
texture_id = kServiceDefaultRectangleTextureId;
break;
default:
NOTREACHED();
}
EXPECT_CALL(*gl, DeleteTextures(1, Pointee(texture_id)))
.Times(1)
.RetiresOnSaturation();
}
void TestHelper::SetupTextureManagerDestructionExpectations(
::gfx::MockGLInterface* gl,
const char* extensions,
bool use_default_textures) {
SetupTextureDestructionExpectations(gl, GL_TEXTURE_2D, use_default_textures);
SetupTextureDestructionExpectations(
gl, GL_TEXTURE_CUBE_MAP, use_default_textures);
bool ext_image_external = false;
bool arb_texture_rectangle = false;
base::CStringTokenizer t(extensions, extensions + strlen(extensions), " ");
while (t.GetNext()) {
if (t.token() == "GL_OES_EGL_image_external") {
ext_image_external = true;
break;
}
if (t.token() == "GL_ARB_texture_rectangle") {
arb_texture_rectangle = true;
break;
}
}
if (ext_image_external) {
SetupTextureDestructionExpectations(
gl, GL_TEXTURE_EXTERNAL_OES, use_default_textures);
}
if (arb_texture_rectangle) {
SetupTextureDestructionExpectations(
gl, GL_TEXTURE_RECTANGLE_ARB, use_default_textures);
}
EXPECT_CALL(*gl, DeleteTextures(4, _))
.Times(1)
.RetiresOnSaturation();
}
void TestHelper::SetupContextGroupInitExpectations(
::gfx::MockGLInterface* gl,
const DisallowedFeatures& disallowed_features,
const char* extensions,
const char* gl_version,
bool bind_generates_resource) {
InSequence sequence;
SetupFeatureInfoInitExpectationsWithGLVersion(gl, extensions, "", gl_version);
std::string l_version(base::StringToLowerASCII(std::string(gl_version)));
bool is_es3 = (l_version.substr(0, 12) == "opengl es 3.");
EXPECT_CALL(*gl, GetIntegerv(GL_MAX_RENDERBUFFER_SIZE, _))
.WillOnce(SetArgumentPointee<1>(kMaxRenderbufferSize))
.RetiresOnSaturation();
if (strstr(extensions, "GL_EXT_framebuffer_multisample") ||
strstr(extensions, "GL_EXT_multisampled_render_to_texture") || is_es3) {
EXPECT_CALL(*gl, GetIntegerv(GL_MAX_SAMPLES, _))
.WillOnce(SetArgumentPointee<1>(kMaxSamples))
.RetiresOnSaturation();
} else if (strstr(extensions, "GL_IMG_multisampled_render_to_texture")) {
EXPECT_CALL(*gl, GetIntegerv(GL_MAX_SAMPLES_IMG, _))
.WillOnce(SetArgumentPointee<1>(kMaxSamples))
.RetiresOnSaturation();
}
EXPECT_CALL(*gl, GetIntegerv(GL_MAX_VERTEX_ATTRIBS, _))
.WillOnce(SetArgumentPointee<1>(kNumVertexAttribs))
.RetiresOnSaturation();
EXPECT_CALL(*gl, GetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, _))
.WillOnce(SetArgumentPointee<1>(kNumTextureUnits))
.RetiresOnSaturation();
EXPECT_CALL(*gl, GetIntegerv(GL_MAX_TEXTURE_SIZE, _))
.WillOnce(SetArgumentPointee<1>(kMaxTextureSize))
.RetiresOnSaturation();
EXPECT_CALL(*gl, GetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, _))
.WillOnce(SetArgumentPointee<1>(kMaxCubeMapTextureSize))
.RetiresOnSaturation();
if (strstr(extensions, "GL_ARB_texture_rectangle")) {
EXPECT_CALL(*gl, GetIntegerv(GL_MAX_RECTANGLE_TEXTURE_SIZE, _))
.WillOnce(SetArgumentPointee<1>(kMaxRectangleTextureSize))
.RetiresOnSaturation();
}
EXPECT_CALL(*gl, GetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, _))
.WillOnce(SetArgumentPointee<1>(kMaxTextureImageUnits))
.RetiresOnSaturation();
EXPECT_CALL(*gl, GetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, _))
.WillOnce(SetArgumentPointee<1>(kMaxVertexTextureImageUnits))
.RetiresOnSaturation();
EXPECT_CALL(*gl, GetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, _))
.WillOnce(SetArgumentPointee<1>(kMaxFragmentUniformComponents))
.RetiresOnSaturation();
EXPECT_CALL(*gl, GetIntegerv(GL_MAX_VARYING_FLOATS, _))
.WillOnce(SetArgumentPointee<1>(kMaxVaryingFloats))
.RetiresOnSaturation();
EXPECT_CALL(*gl, GetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, _))
.WillOnce(SetArgumentPointee<1>(kMaxVertexUniformComponents))
.RetiresOnSaturation();
bool use_default_textures = bind_generates_resource;
SetupTextureManagerInitExpectations(gl, extensions, use_default_textures);
}
void TestHelper::SetupFeatureInfoInitExpectations(
::gfx::MockGLInterface* gl, const char* extensions) {
SetupFeatureInfoInitExpectationsWithGLVersion(gl, extensions, "", "");
}
void TestHelper::SetupFeatureInfoInitExpectationsWithGLVersion(
::gfx::MockGLInterface* gl,
const char* extensions,
const char* gl_renderer,
const char* gl_version) {
InSequence sequence;
EXPECT_CALL(*gl, GetString(GL_EXTENSIONS))
.WillOnce(Return(reinterpret_cast<const uint8*>(extensions)))
.RetiresOnSaturation();
EXPECT_CALL(*gl, GetString(GL_RENDERER))
.WillOnce(Return(reinterpret_cast<const uint8*>(gl_renderer)))
.RetiresOnSaturation();
EXPECT_CALL(*gl, GetString(GL_VERSION))
.WillOnce(Return(reinterpret_cast<const uint8*>(gl_version)))
.RetiresOnSaturation();
std::string l_version(base::StringToLowerASCII(std::string(gl_version)));
bool is_es3 = (l_version.substr(0, 12) == "opengl es 3.");
if (strstr(extensions, "GL_ARB_texture_float") ||
(is_es3 && strstr(extensions, "GL_EXT_color_buffer_float"))) {
static const GLuint tx_ids[] = {101, 102};
static const GLuint fb_ids[] = {103, 104};
const GLsizei width = 16;
EXPECT_CALL(*gl, GetIntegerv(GL_FRAMEBUFFER_BINDING, _))
.WillOnce(SetArgumentPointee<1>(fb_ids[0]))
.RetiresOnSaturation();
EXPECT_CALL(*gl, GetIntegerv(GL_TEXTURE_BINDING_2D, _))
.WillOnce(SetArgumentPointee<1>(tx_ids[0]))
.RetiresOnSaturation();
EXPECT_CALL(*gl, GenTextures(1, _))
.WillOnce(SetArrayArgument<1>(tx_ids + 1, tx_ids + 2))
.RetiresOnSaturation();
EXPECT_CALL(*gl, GenFramebuffersEXT(1, _))
.WillOnce(SetArrayArgument<1>(fb_ids + 1, fb_ids + 2))
.RetiresOnSaturation();
EXPECT_CALL(*gl, BindTexture(GL_TEXTURE_2D, tx_ids[1]))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl, TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_NEAREST))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl, TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, width, 0,
GL_RGBA, GL_FLOAT, _))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl, BindFramebufferEXT(GL_FRAMEBUFFER, fb_ids[1]))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl, FramebufferTexture2DEXT(GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tx_ids[1], 0))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl, CheckFramebufferStatusEXT(GL_FRAMEBUFFER))
.WillOnce(Return(GL_FRAMEBUFFER_COMPLETE))
.RetiresOnSaturation();
EXPECT_CALL(*gl, TexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, width, width, 0,
GL_RGB, GL_FLOAT, _))
.Times(1)
.RetiresOnSaturation();
if (is_es3) {
EXPECT_CALL(*gl, CheckFramebufferStatusEXT(GL_FRAMEBUFFER))
.WillOnce(Return(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT))
.RetiresOnSaturation();
} else {
EXPECT_CALL(*gl, CheckFramebufferStatusEXT(GL_FRAMEBUFFER))
.WillOnce(Return(GL_FRAMEBUFFER_COMPLETE))
.RetiresOnSaturation();
}
EXPECT_CALL(*gl, DeleteFramebuffersEXT(1, _))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl, DeleteTextures(1, _))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl, BindFramebufferEXT(GL_FRAMEBUFFER, fb_ids[0]))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl, BindTexture(GL_TEXTURE_2D, tx_ids[0]))
.Times(1)
.RetiresOnSaturation();
#if DCHECK_IS_ON()
EXPECT_CALL(*gl, GetError())
.WillOnce(Return(GL_NO_ERROR))
.RetiresOnSaturation();
#endif
}
if (strstr(extensions, "GL_EXT_draw_buffers") ||
strstr(extensions, "GL_ARB_draw_buffers") ||
(is_es3 && strstr(extensions, "GL_NV_draw_buffers"))) {
EXPECT_CALL(*gl, GetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, _))
.WillOnce(SetArgumentPointee<1>(8))
.RetiresOnSaturation();
EXPECT_CALL(*gl, GetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, _))
.WillOnce(SetArgumentPointee<1>(8))
.RetiresOnSaturation();
}
if (is_es3 || strstr(extensions, "GL_EXT_texture_rg") ||
(strstr(extensions, "GL_ARB_texture_rg"))) {
static const GLuint tx_ids[] = {101, 102};
static const GLuint fb_ids[] = {103, 104};
const GLsizei width = 1;
EXPECT_CALL(*gl, GetIntegerv(GL_FRAMEBUFFER_BINDING, _))
.WillOnce(SetArgumentPointee<1>(fb_ids[0]))
.RetiresOnSaturation();
EXPECT_CALL(*gl, GetIntegerv(GL_TEXTURE_BINDING_2D, _))
.WillOnce(SetArgumentPointee<1>(tx_ids[0]))
.RetiresOnSaturation();
EXPECT_CALL(*gl, GenTextures(1, _))
.WillOnce(SetArrayArgument<1>(tx_ids + 1, tx_ids + 2))
.RetiresOnSaturation();
EXPECT_CALL(*gl, BindTexture(GL_TEXTURE_2D, tx_ids[1]))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl, TexImage2D(GL_TEXTURE_2D, 0, _, width, width, 0,
GL_RED_EXT, GL_UNSIGNED_BYTE, _))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl, GenFramebuffersEXT(1, _))
.WillOnce(SetArrayArgument<1>(fb_ids + 1, fb_ids + 2))
.RetiresOnSaturation();
EXPECT_CALL(*gl, BindFramebufferEXT(GL_FRAMEBUFFER, fb_ids[1]))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl, FramebufferTexture2DEXT(GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tx_ids[1], 0))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl, CheckFramebufferStatusEXT(GL_FRAMEBUFFER))
.WillOnce(Return(GL_FRAMEBUFFER_COMPLETE))
.RetiresOnSaturation();
EXPECT_CALL(*gl, DeleteFramebuffersEXT(1, _))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl, DeleteTextures(1, _))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl, BindFramebufferEXT(GL_FRAMEBUFFER, fb_ids[0]))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl, BindTexture(GL_TEXTURE_2D, tx_ids[0]))
.Times(1)
.RetiresOnSaturation();
#if DCHECK_IS_ON()
EXPECT_CALL(*gl, GetError())
.WillOnce(Return(GL_NO_ERROR))
.RetiresOnSaturation();
#endif
}
}
void TestHelper::SetupExpectationsForClearingUniforms(
::gfx::MockGLInterface* gl, UniformInfo* uniforms, size_t num_uniforms) {
for (size_t ii = 0; ii < num_uniforms; ++ii) {
const UniformInfo& info = uniforms[ii];
switch (info.type) {
case GL_FLOAT:
EXPECT_CALL(*gl, Uniform1fv(info.real_location, info.size, _))
.Times(1)
.RetiresOnSaturation();
break;
case GL_FLOAT_VEC2:
EXPECT_CALL(*gl, Uniform2fv(info.real_location, info.size, _))
.Times(1)
.RetiresOnSaturation();
break;
case GL_FLOAT_VEC3:
EXPECT_CALL(*gl, Uniform3fv(info.real_location, info.size, _))
.Times(1)
.RetiresOnSaturation();
break;
case GL_FLOAT_VEC4:
EXPECT_CALL(*gl, Uniform4fv(info.real_location, info.size, _))
.Times(1)
.RetiresOnSaturation();
break;
case GL_INT:
case GL_BOOL:
case GL_SAMPLER_2D:
case GL_SAMPLER_CUBE:
case GL_SAMPLER_EXTERNAL_OES:
case GL_SAMPLER_3D_OES:
case GL_SAMPLER_2D_RECT_ARB:
EXPECT_CALL(*gl, Uniform1iv(info.real_location, info.size, _))
.Times(1)
.RetiresOnSaturation();
break;
case GL_INT_VEC2:
case GL_BOOL_VEC2:
EXPECT_CALL(*gl, Uniform2iv(info.real_location, info.size, _))
.Times(1)
.RetiresOnSaturation();
break;
case GL_INT_VEC3:
case GL_BOOL_VEC3:
EXPECT_CALL(*gl, Uniform3iv(info.real_location, info.size, _))
.Times(1)
.RetiresOnSaturation();
break;
case GL_INT_VEC4:
case GL_BOOL_VEC4:
EXPECT_CALL(*gl, Uniform4iv(info.real_location, info.size, _))
.Times(1)
.RetiresOnSaturation();
break;
case GL_FLOAT_MAT2:
EXPECT_CALL(*gl, UniformMatrix2fv(
info.real_location, info.size, false, _))
.Times(1)
.RetiresOnSaturation();
break;
case GL_FLOAT_MAT3:
EXPECT_CALL(*gl, UniformMatrix3fv(
info.real_location, info.size, false, _))
.Times(1)
.RetiresOnSaturation();
break;
case GL_FLOAT_MAT4:
EXPECT_CALL(*gl, UniformMatrix4fv(
info.real_location, info.size, false, _))
.Times(1)
.RetiresOnSaturation();
break;
default:
NOTREACHED();
break;
}
}
}
void TestHelper::SetupProgramSuccessExpectations(
::gfx::MockGLInterface* gl,
AttribInfo* attribs, size_t num_attribs,
UniformInfo* uniforms, size_t num_uniforms,
GLuint service_id) {
EXPECT_CALL(*gl,
GetProgramiv(service_id, GL_LINK_STATUS, _))
.WillOnce(SetArgumentPointee<2>(1))
.RetiresOnSaturation();
EXPECT_CALL(*gl,
GetProgramiv(service_id, GL_INFO_LOG_LENGTH, _))
.WillOnce(SetArgumentPointee<2>(0))
.RetiresOnSaturation();
EXPECT_CALL(*gl,
GetProgramiv(service_id, GL_ACTIVE_ATTRIBUTES, _))
.WillOnce(SetArgumentPointee<2>(num_attribs))
.RetiresOnSaturation();
size_t max_attrib_len = 0;
for (size_t ii = 0; ii < num_attribs; ++ii) {
size_t len = strlen(attribs[ii].name) + 1;
max_attrib_len = std::max(max_attrib_len, len);
}
EXPECT_CALL(*gl,
GetProgramiv(service_id, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, _))
.WillOnce(SetArgumentPointee<2>(max_attrib_len))
.RetiresOnSaturation();
for (size_t ii = 0; ii < num_attribs; ++ii) {
const AttribInfo& info = attribs[ii];
EXPECT_CALL(*gl,
GetActiveAttrib(service_id, ii,
max_attrib_len, _, _, _, _))
.WillOnce(DoAll(
SetArgumentPointee<3>(strlen(info.name)),
SetArgumentPointee<4>(info.size),
SetArgumentPointee<5>(info.type),
SetArrayArgument<6>(info.name,
info.name + strlen(info.name) + 1)))
.RetiresOnSaturation();
if (!ProgramManager::IsInvalidPrefix(info.name, strlen(info.name))) {
EXPECT_CALL(*gl, GetAttribLocation(service_id, StrEq(info.name)))
.WillOnce(Return(info.location))
.RetiresOnSaturation();
}
}
EXPECT_CALL(*gl,
GetProgramiv(service_id, GL_ACTIVE_UNIFORMS, _))
.WillOnce(SetArgumentPointee<2>(num_uniforms))
.RetiresOnSaturation();
size_t max_uniform_len = 0;
for (size_t ii = 0; ii < num_uniforms; ++ii) {
size_t len = strlen(uniforms[ii].name) + 1;
max_uniform_len = std::max(max_uniform_len, len);
}
EXPECT_CALL(*gl,
GetProgramiv(service_id, GL_ACTIVE_UNIFORM_MAX_LENGTH, _))
.WillOnce(SetArgumentPointee<2>(max_uniform_len))
.RetiresOnSaturation();
for (size_t ii = 0; ii < num_uniforms; ++ii) {
const UniformInfo& info = uniforms[ii];
EXPECT_CALL(*gl,
GetActiveUniform(service_id, ii,
max_uniform_len, _, _, _, _))
.WillOnce(DoAll(
SetArgumentPointee<3>(strlen(info.name)),
SetArgumentPointee<4>(info.size),
SetArgumentPointee<5>(info.type),
SetArrayArgument<6>(info.name,
info.name + strlen(info.name) + 1)))
.RetiresOnSaturation();
}
for (int pass = 0; pass < 2; ++pass) {
for (size_t ii = 0; ii < num_uniforms; ++ii) {
const UniformInfo& info = uniforms[ii];
if (ProgramManager::IsInvalidPrefix(info.name, strlen(info.name))) {
continue;
}
if (pass == 0) {
EXPECT_CALL(*gl, GetUniformLocation(service_id, StrEq(info.name)))
.WillOnce(Return(info.real_location))
.RetiresOnSaturation();
}
if ((pass == 0 && info.desired_location >= 0) ||
(pass == 1 && info.desired_location < 0)) {
if (info.size > 1) {
std::string base_name = info.name;
size_t array_pos = base_name.rfind("[0]");
if (base_name.size() > 3 && array_pos == base_name.size() - 3) {
base_name = base_name.substr(0, base_name.size() - 3);
}
for (GLsizei jj = 1; jj < info.size; ++jj) {
std::string element_name(
std::string(base_name) + "[" + base::IntToString(jj) + "]");
EXPECT_CALL(*gl, GetUniformLocation(
service_id, StrEq(element_name)))
.WillOnce(Return(info.real_location + jj * 2))
.RetiresOnSaturation();
}
}
}
}
}
}
void TestHelper::SetupShader(
::gfx::MockGLInterface* gl,
AttribInfo* attribs, size_t num_attribs,
UniformInfo* uniforms, size_t num_uniforms,
GLuint service_id) {
InSequence s;
EXPECT_CALL(*gl,
LinkProgram(service_id))
.Times(1)
.RetiresOnSaturation();
SetupProgramSuccessExpectations(
gl, attribs, num_attribs, uniforms, num_uniforms, service_id);
}
void TestHelper::DoBufferData(
::gfx::MockGLInterface* gl, MockErrorState* error_state,
BufferManager* manager, Buffer* buffer, GLsizeiptr size, GLenum usage,
const GLvoid* data, GLenum error) {
EXPECT_CALL(*error_state, CopyRealGLErrorsToWrapper(_, _, _))
.Times(1)
.RetiresOnSaturation();
if (manager->IsUsageClientSideArray(usage)) {
EXPECT_CALL(*gl, BufferData(
buffer->target(), 0, _, usage))
.Times(1)
.RetiresOnSaturation();
} else {
EXPECT_CALL(*gl, BufferData(
buffer->target(), size, _, usage))
.Times(1)
.RetiresOnSaturation();
}
EXPECT_CALL(*error_state, PeekGLError(_, _, _))
.WillOnce(Return(error))
.RetiresOnSaturation();
manager->DoBufferData(error_state, buffer, size, usage, data);
}
void TestHelper::SetTexParameteriWithExpectations(
::gfx::MockGLInterface* gl, MockErrorState* error_state,
TextureManager* manager, TextureRef* texture_ref,
GLenum pname, GLint value, GLenum error) {
if (error == GL_NO_ERROR) {
if (pname != GL_TEXTURE_POOL_CHROMIUM) {
EXPECT_CALL(*gl, TexParameteri(texture_ref->texture()->target(),
pname, value))
.Times(1)
.RetiresOnSaturation();
}
} else if (error == GL_INVALID_ENUM) {
EXPECT_CALL(*error_state, SetGLErrorInvalidEnum(_, _, _, value, _))
.Times(1)
.RetiresOnSaturation();
} else {
EXPECT_CALL(*error_state, SetGLErrorInvalidParami(_, _, error, _, _, _))
.Times(1)
.RetiresOnSaturation();
}
manager->SetParameteri("", error_state, texture_ref, pname, value);
}
// static
void TestHelper::SetShaderStates(
::gfx::MockGLInterface* gl, Shader* shader,
bool expected_valid,
const std::string* const expected_log_info,
const std::string* const expected_translated_source,
const AttributeMap* const expected_attrib_map,
const UniformMap* const expected_uniform_map,
const VaryingMap* const expected_varying_map,
const NameMap* const expected_name_map) {
const std::string empty_log_info;
const std::string* log_info = (expected_log_info && !expected_valid) ?
expected_log_info : &empty_log_info;
const std::string empty_translated_source;
const std::string* translated_source =
(expected_translated_source && expected_valid) ?
expected_translated_source : &empty_translated_source;
const AttributeMap empty_attrib_map;
const AttributeMap* attrib_map = (expected_attrib_map && expected_valid) ?
expected_attrib_map : &empty_attrib_map;
const UniformMap empty_uniform_map;
const UniformMap* uniform_map = (expected_uniform_map && expected_valid) ?
expected_uniform_map : &empty_uniform_map;
const VaryingMap empty_varying_map;
const VaryingMap* varying_map = (expected_varying_map && expected_valid) ?
expected_varying_map : &empty_varying_map;
const NameMap empty_name_map;
const NameMap* name_map = (expected_name_map && expected_valid) ?
expected_name_map : &empty_name_map;
MockShaderTranslator translator;
EXPECT_CALL(translator, Translate(_,
NotNull(), // log_info
NotNull(), // translated_source
NotNull(), // attrib_map
NotNull(), // uniform_map
NotNull(), // varying_map
NotNull())) // name_map
.WillOnce(DoAll(SetArgumentPointee<1>(*log_info),
SetArgumentPointee<2>(*translated_source),
SetArgumentPointee<3>(*attrib_map),
SetArgumentPointee<4>(*uniform_map),
SetArgumentPointee<5>(*varying_map),
SetArgumentPointee<6>(*name_map),
Return(expected_valid)))
.RetiresOnSaturation();
if (expected_valid) {
EXPECT_CALL(*gl, ShaderSource(shader->service_id(), 1, _, NULL))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl, CompileShader(shader->service_id()))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl, GetShaderiv(shader->service_id(),
GL_COMPILE_STATUS,
NotNull())) // status
.WillOnce(SetArgumentPointee<2>(GL_TRUE))
.RetiresOnSaturation();
}
shader->DoCompile(&translator, Shader::kGL);
}
// static
void TestHelper::SetShaderStates(
::gfx::MockGLInterface* gl, Shader* shader, bool valid) {
SetShaderStates(gl, shader, valid, NULL, NULL, NULL, NULL, NULL, NULL);
}
// static
sh::Attribute TestHelper::ConstructAttribute(
GLenum type, GLint array_size, GLenum precision,
bool static_use, const std::string& name) {
return ConstructShaderVariable<sh::Attribute>(
type, array_size, precision, static_use, name);
}
// static
sh::Uniform TestHelper::ConstructUniform(
GLenum type, GLint array_size, GLenum precision,
bool static_use, const std::string& name) {
return ConstructShaderVariable<sh::Uniform>(
type, array_size, precision, static_use, name);
}
// static
sh::Varying TestHelper::ConstructVarying(
GLenum type, GLint array_size, GLenum precision,
bool static_use, const std::string& name) {
return ConstructShaderVariable<sh::Varying>(
type, array_size, precision, static_use, name);
}
ScopedGLImplementationSetter::ScopedGLImplementationSetter(
gfx::GLImplementation implementation)
: old_implementation_(gfx::GetGLImplementation()) {
gfx::SetGLImplementation(implementation);
}
ScopedGLImplementationSetter::~ScopedGLImplementationSetter() {
gfx::SetGLImplementation(old_implementation_);
}
} // namespace gles2
} // namespace gpu
| jaruba/chromium.src | gpu/command_buffer/service/test_helper.cc | C++ | bsd-3-clause | 29,937 |
# 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 |
//===- llvm/unittest/ADT/FoldingSetTest.cpp -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// FoldingSet unit tests.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/FoldingSet.h"
#include "gtest/gtest.h"
#include <string>
using namespace llvm;
namespace {
// Unaligned string test.
TEST(FoldingSetTest, UnalignedStringTest) {
SCOPED_TRACE("UnalignedStringTest");
FoldingSetNodeID a, b;
// An aligned string.
std::string str1= "a test string";
a.AddString(str1);
// An unaligned string.
std::string str2 = ">" + str1;
b.AddString(str2.c_str() + 1);
EXPECT_EQ(a.ComputeHash(), b.ComputeHash());
}
TEST(FoldingSetTest, LongLongComparison) {
struct LongLongContainer : FoldingSetNode {
unsigned long long A, B;
LongLongContainer(unsigned long long A, unsigned long long B)
: A(A), B(B) {}
void Profile(FoldingSetNodeID &ID) const {
ID.AddInteger(A);
ID.AddInteger(B);
}
};
LongLongContainer C1((1ULL << 32) + 1, 1ULL);
LongLongContainer C2(1ULL, (1ULL << 32) + 1);
FoldingSet<LongLongContainer> Set;
EXPECT_EQ(&C1, Set.GetOrInsertNode(&C1));
EXPECT_EQ(&C2, Set.GetOrInsertNode(&C2));
EXPECT_EQ(2U, Set.size());
}
struct TrivialPair : public FoldingSetNode {
unsigned Key = 0;
unsigned Value = 0;
TrivialPair(unsigned K, unsigned V) : FoldingSetNode(), Key(K), Value(V) {}
void Profile(FoldingSetNodeID &ID) const {
ID.AddInteger(Key);
ID.AddInteger(Value);
}
};
TEST(FoldingSetTest, IDComparison) {
FoldingSet<TrivialPair> Trivial;
TrivialPair T(99, 42);
Trivial.InsertNode(&T);
void *InsertPos = nullptr;
FoldingSetNodeID ID;
T.Profile(ID);
TrivialPair *N = Trivial.FindNodeOrInsertPos(ID, InsertPos);
EXPECT_EQ(&T, N);
EXPECT_EQ(nullptr, InsertPos);
}
TEST(FoldingSetTest, MissedIDComparison) {
FoldingSet<TrivialPair> Trivial;
TrivialPair S(100, 42);
TrivialPair T(99, 42);
Trivial.InsertNode(&T);
void *InsertPos = nullptr;
FoldingSetNodeID ID;
S.Profile(ID);
TrivialPair *N = Trivial.FindNodeOrInsertPos(ID, InsertPos);
EXPECT_EQ(nullptr, N);
EXPECT_NE(nullptr, InsertPos);
}
TEST(FoldingSetTest, RemoveNodeThatIsPresent) {
FoldingSet<TrivialPair> Trivial;
TrivialPair T(99, 42);
Trivial.InsertNode(&T);
EXPECT_EQ(Trivial.size(), 1U);
bool WasThere = Trivial.RemoveNode(&T);
EXPECT_TRUE(WasThere);
EXPECT_EQ(0U, Trivial.size());
}
TEST(FoldingSetTest, RemoveNodeThatIsAbsent) {
FoldingSet<TrivialPair> Trivial;
TrivialPair T(99, 42);
bool WasThere = Trivial.RemoveNode(&T);
EXPECT_FALSE(WasThere);
EXPECT_EQ(0U, Trivial.size());
}
TEST(FoldingSetTest, GetOrInsertInserting) {
FoldingSet<TrivialPair> Trivial;
TrivialPair T(99, 42);
TrivialPair *N = Trivial.GetOrInsertNode(&T);
EXPECT_EQ(&T, N);
}
TEST(FoldingSetTest, GetOrInsertGetting) {
FoldingSet<TrivialPair> Trivial;
TrivialPair T(99, 42);
TrivialPair T2(99, 42);
Trivial.InsertNode(&T);
TrivialPair *N = Trivial.GetOrInsertNode(&T2);
EXPECT_EQ(&T, N);
}
TEST(FoldingSetTest, InsertAtPos) {
FoldingSet<TrivialPair> Trivial;
void *InsertPos = nullptr;
TrivialPair Finder(99, 42);
FoldingSetNodeID ID;
Finder.Profile(ID);
Trivial.FindNodeOrInsertPos(ID, InsertPos);
TrivialPair T(99, 42);
Trivial.InsertNode(&T, InsertPos);
EXPECT_EQ(1U, Trivial.size());
}
TEST(FoldingSetTest, EmptyIsTrue) {
FoldingSet<TrivialPair> Trivial;
EXPECT_TRUE(Trivial.empty());
}
TEST(FoldingSetTest, EmptyIsFalse) {
FoldingSet<TrivialPair> Trivial;
TrivialPair T(99, 42);
Trivial.InsertNode(&T);
EXPECT_FALSE(Trivial.empty());
}
TEST(FoldingSetTest, ClearOnEmpty) {
FoldingSet<TrivialPair> Trivial;
Trivial.clear();
EXPECT_TRUE(Trivial.empty());
}
TEST(FoldingSetTest, ClearOnNonEmpty) {
FoldingSet<TrivialPair> Trivial;
TrivialPair T(99, 42);
Trivial.InsertNode(&T);
Trivial.clear();
EXPECT_TRUE(Trivial.empty());
}
TEST(FoldingSetTest, CapacityLargerThanReserve) {
FoldingSet<TrivialPair> Trivial;
auto OldCapacity = Trivial.capacity();
Trivial.reserve(OldCapacity + 1);
EXPECT_GE(Trivial.capacity(), OldCapacity + 1);
}
TEST(FoldingSetTest, SmallReserveChangesNothing) {
FoldingSet<TrivialPair> Trivial;
auto OldCapacity = Trivial.capacity();
Trivial.reserve(OldCapacity - 1);
EXPECT_EQ(Trivial.capacity(), OldCapacity);
}
}
| endlessm/chromium-browser | third_party/swiftshader/third_party/llvm-7.0/llvm/unittests/ADT/FoldingSet.cpp | C++ | bsd-3-clause | 4,642 |
# 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 |
#include <string>
#if !defined (STLPORT) || !defined (_STLP_USE_NO_IOSTREAMS)
# include <fstream>
# include <iostream>
# include <iomanip>
# include <sstream>
# include <vector>
# include <memory>
# include "full_streambuf.h"
# include "cppunit/cppunit_proxy.h"
# if !defined (STLPORT) || defined(_STLP_USE_NAMESPACES)
using namespace std;
# endif
//The macro value gives approximately the generated file
//size in Go
//#define CHECK_BIG_FILE 4
# if !defined (STLPORT) || !defined (_STLP_NO_CUSTOM_IO) && !defined (_STLP_NO_MEMBER_TEMPLATES) && \
!((defined (_STLP_MSVC) && (_STLP_MSVC < 1300)) || \
(defined (__GNUC__) && (__GNUC__ < 3)) || \
(defined (__SUNPRO_CC)) || \
(defined (__DMC__) && defined (_DLL)))
# define DO_CUSTOM_FACET_TEST
# endif
//
// TestCase class
//
class FstreamTest : public CPPUNIT_NS::TestCase
{
CPPUNIT_TEST_SUITE(FstreamTest);
CPPUNIT_TEST(output);
CPPUNIT_TEST(input);
CPPUNIT_TEST(input_char);
CPPUNIT_TEST(io);
CPPUNIT_TEST(err);
CPPUNIT_TEST(tellg);
CPPUNIT_TEST(buf);
CPPUNIT_TEST(rdbuf);
#if !defined (STLPORT) || !defined (_STLP_WIN32)
CPPUNIT_TEST(offset);
#endif
# if defined (__DMC__)
CPPUNIT_IGNORE;
# endif
CPPUNIT_TEST(streambuf_output);
CPPUNIT_STOP_IGNORE;
CPPUNIT_TEST(win32_file_format);
# if defined (CHECK_BIG_FILE)
CPPUNIT_TEST(big_file);
# endif
# if !defined (DO_CUSTOM_FACET_TEST)
CPPUNIT_IGNORE;
#endif
CPPUNIT_TEST(custom_facet);
CPPUNIT_TEST_SUITE_END();
protected:
void output();
void input();
void input_char();
void io();
void err();
void tellg();
void buf();
void rdbuf();
void streambuf_output();
void win32_file_format();
void custom_facet();
# if !defined (STLPORT) || !defined (_STLP_WIN32)
void offset();
# endif
# if defined (CHECK_BIG_FILE)
void big_file();
# endif
};
CPPUNIT_TEST_SUITE_REGISTRATION(FstreamTest);
//
// tests implementation
//
void FstreamTest::output()
{
ofstream f( "test_file.txt" );
f << 1 << '\n' << 2.0 << '\n' << "abcd\n" << "ghk lm\n" << "abcd ef";
CPPUNIT_ASSERT (f.good());
// CPPUNIT_ASSERT( s.str() == "1\n2\nabcd\nghk lm\nabcd ef" );
}
void FstreamTest::input()
{
ifstream f( "test_file.txt" );
int i = 0;
f >> i;
CPPUNIT_ASSERT( f.good() );
CPPUNIT_ASSERT( i == 1 );
double d = 0.0;
f >> d;
CPPUNIT_ASSERT( f.good() );
CPPUNIT_ASSERT( d == 2.0 );
string str;
f >> str;
CPPUNIT_ASSERT( f.good() );
CPPUNIT_ASSERT( str == "abcd" );
char c;
f.get(c); // extract newline, that not extracted by operator >>
CPPUNIT_ASSERT( f.good() );
CPPUNIT_ASSERT( c == '\n' );
getline( f, str );
CPPUNIT_ASSERT( f.good() );
CPPUNIT_ASSERT( str == "ghk lm" );
getline( f, str );
CPPUNIT_ASSERT( f.eof() );
CPPUNIT_ASSERT( str == "abcd ef" );
}
void FstreamTest::input_char()
{
char buf[16] = { 0, '1', '2', '3' };
ifstream s( "test_file.txt" );
s >> buf;
CPPUNIT_ASSERT( buf[0] == '1' );
CPPUNIT_ASSERT( buf[1] == 0 );
CPPUNIT_ASSERT( buf[2] == '2' );
}
void FstreamTest::io()
{
basic_fstream<char,char_traits<char> > f( "test_file.txt", ios_base::in | ios_base::out | ios_base::trunc );
CPPUNIT_ASSERT( f.is_open() );
f << 1 << '\n' << 2.0 << '\n' << "abcd\n" << "ghk lm\n" << "abcd ef";
// f.flush();
f.seekg( 0, ios_base::beg );
int i = 0;
f >> i;
CPPUNIT_ASSERT( f.good() );
CPPUNIT_ASSERT( i == 1 );
double d = 0.0;
f >> d;
CPPUNIT_ASSERT( d == 2.0 );
string s;
f >> s;
CPPUNIT_ASSERT( f.good() );
CPPUNIT_ASSERT( s == "abcd" );
char c;
f.get(c); // extract newline, that not extracted by operator >>
CPPUNIT_ASSERT( f.good() );
CPPUNIT_ASSERT( c == '\n' );
getline( f, s );
CPPUNIT_ASSERT( f.good() );
CPPUNIT_ASSERT( s == "ghk lm" );
getline( f, s );
CPPUNIT_ASSERT( !f.fail() );
CPPUNIT_ASSERT( s == "abcd ef" );
CPPUNIT_ASSERT( f.eof() );
}
void FstreamTest::err()
{
basic_fstream<char,char_traits<char> > f( "test_file.txt", ios_base::in | ios_base::out | ios_base::trunc );
CPPUNIT_ASSERT( f.is_open() );
int i = 9;
f << i;
CPPUNIT_ASSERT( f.good() );
i = 0;
f.seekg( 0, ios_base::beg );
f >> i;
CPPUNIT_ASSERT( !f.fail() );
CPPUNIT_ASSERT( i == 9 );
f >> i;
CPPUNIT_ASSERT( f.fail() );
CPPUNIT_ASSERT( f.eof() );
CPPUNIT_ASSERT( i == 9 );
}
void FstreamTest::tellg()
{
{
// bogus ios_base::binary is for Wins
ofstream of("test_file.txt", ios_base::out | ios_base::binary | ios_base::trunc);
CPPUNIT_ASSERT( of.is_open() );
for (int i = 0; i < 50; ++i) {
of << "line " << setiosflags(ios_base::right) << setfill('0') << setw(2) << i << "\n";
CPPUNIT_ASSERT( !of.fail() );
}
of.close();
}
{
// bogus ios_base::binary is for Wins
ifstream is("test_file.txt", ios_base::in | ios_base::binary);
CPPUNIT_ASSERT( is.is_open() );
char buf[64];
// CPPUNIT_ASSERT( is.tellg() == 0 );
streampos p = 0;
for (int i = 0; i < 50; ++i) {
CPPUNIT_ASSERT( is.tellg() == p );
is.read( buf, 8 );
CPPUNIT_ASSERT( !is.fail() );
p += 8;
}
}
{
// bogus ios_base::binary is for Wins
ifstream is("test_file.txt", ios_base::in | ios_base::binary);
CPPUNIT_ASSERT( is.is_open() );
streampos p = 0;
for (int i = 0; i < 50; ++i) {
CPPUNIT_ASSERT( !is.fail() );
is.tellg();
CPPUNIT_ASSERT( is.tellg() == p );
p += 8;
is.seekg( p, ios_base::beg );
CPPUNIT_ASSERT( !is.fail() );
}
}
{
// bogus ios_base::binary is for Wins
ifstream is("test_file.txt", ios_base::in | ios_base::binary);
CPPUNIT_ASSERT( is.is_open() );
streampos p = 0;
for (int i = 0; i < 50; ++i) {
CPPUNIT_ASSERT( is.tellg() == p );
p += 8;
is.seekg( 8, ios_base::cur );
CPPUNIT_ASSERT( !is.fail() );
}
}
}
void FstreamTest::buf()
{
fstream ss( "test_file.txt", ios_base::in | ios_base::out | ios_base::binary | ios_base::trunc );
ss << "1234567\n89\n";
ss.seekg( 0, ios_base::beg );
char buf[10];
buf[7] = 'x';
ss.get( buf, 10 );
CPPUNIT_ASSERT( !ss.fail() );
CPPUNIT_ASSERT( buf[0] == '1' );
CPPUNIT_ASSERT( buf[1] == '2' );
CPPUNIT_ASSERT( buf[2] == '3' );
CPPUNIT_ASSERT( buf[3] == '4' );
CPPUNIT_ASSERT( buf[4] == '5' );
CPPUNIT_ASSERT( buf[5] == '6' );
CPPUNIT_ASSERT( buf[6] == '7' ); // 27.6.1.3 paragraph 10, paragraph 7
CPPUNIT_ASSERT( buf[7] == 0 ); // 27.6.1.3 paragraph 8
char c;
ss.get(c);
CPPUNIT_ASSERT( !ss.fail() );
CPPUNIT_ASSERT( c == '\n' ); // 27.6.1.3 paragraph 10, paragraph 7
ss.get(c);
CPPUNIT_ASSERT( !ss.fail() );
CPPUNIT_ASSERT( c == '8' );
}
void FstreamTest::rdbuf()
{
fstream ss( "test_file.txt", ios_base::in | ios_base::out | ios_base::binary | ios_base::trunc );
ss << "1234567\n89\n";
ss.seekg( 0, ios_base::beg );
ostringstream os;
ss.get( *os.rdbuf(), '\n' );
CPPUNIT_ASSERT( !ss.fail() );
char c;
ss.get(c);
CPPUNIT_ASSERT( !ss.fail() );
CPPUNIT_ASSERT( c == '\n' ); // 27.6.1.3 paragraph 12
CPPUNIT_ASSERT( os.str() == "1234567" );
}
void FstreamTest::streambuf_output()
{
{
ofstream ofstr("test_file.txt", ios_base::binary);
if (!ofstr)
//No test if we cannot create the file
return;
ofstr << "01234567890123456789";
CPPUNIT_ASSERT( ofstr );
}
{
ifstream in("test_file.txt", ios_base::binary);
CPPUNIT_ASSERT( in );
auto_ptr<full_streambuf> pfull_buf(new full_streambuf(10));
ostream out(pfull_buf.get());
CPPUNIT_ASSERT( out );
out << in.rdbuf();
CPPUNIT_ASSERT( out );
CPPUNIT_ASSERT( in );
CPPUNIT_ASSERT( pfull_buf->str() == "0123456789" );
out << in.rdbuf();
CPPUNIT_ASSERT( out.fail() );
CPPUNIT_ASSERT( in );
ostringstream ostr;
ostr << in.rdbuf();
CPPUNIT_ASSERT( ostr );
CPPUNIT_ASSERT( in );
CPPUNIT_ASSERT( ostr.str() == "0123456789" );
}
# if !defined (STLPORT) || defined (_STLP_USE_EXCEPTIONS)
{
//If the output stream buffer throws:
ifstream in("test_file.txt", ios_base::binary);
CPPUNIT_ASSERT( in );
auto_ptr<full_streambuf> pfull_buf(new full_streambuf(10, true));
ostream out(pfull_buf.get());
CPPUNIT_ASSERT( out );
out << in.rdbuf();
CPPUNIT_ASSERT( out.bad() );
CPPUNIT_ASSERT( in );
//out is bad we have no guaranty on what has been extracted:
//CPPUNIT_ASSERT( pfull_buf->str() == "0123456789" );
out.clear();
out << in.rdbuf();
CPPUNIT_ASSERT( out.fail() && out.bad() );
CPPUNIT_ASSERT( in );
ostringstream ostr;
ostr << in.rdbuf();
CPPUNIT_ASSERT( ostr );
CPPUNIT_ASSERT( in );
CPPUNIT_ASSERT( ostr.str() == "0123456789" );
}
# endif
}
void FstreamTest::win32_file_format()
{
const char* file_name = "win32_file_format.tmp";
const size_t nb_lines = 2049;
{
ofstream out(file_name);
CPPUNIT_ASSERT( out.good() );
out << 'a';
for (size_t i = 0; i < nb_lines - 1; ++i) {
out << '\n';
}
out << '\r';
CPPUNIT_ASSERT( out.good() );
}
{
ifstream in(file_name);
CPPUNIT_ASSERT( in.good() );
string line, last_line;
size_t nb_read_lines = 0;
while (getline(in, line)) {
++nb_read_lines;
last_line = line;
}
CPPUNIT_ASSERT( in.eof() );
CPPUNIT_ASSERT( nb_read_lines == nb_lines );
CPPUNIT_ASSERT( !last_line.empty() && (last_line[0] == '\r') );
}
}
#if defined (DO_CUSTOM_FACET_TEST)
struct my_state {
char dummy;
};
struct my_traits : public char_traits<char> {
typedef my_state state_type;
typedef fpos<state_type> pos_type;
};
class my_codecvt
# if defined (STLPORT)
: public codecvt<char, char, my_state> {
# else
: public locale::facet, public codecvt_base {
//STLport grant the same default implementation, other Standard libs implementation
//do not necessarily do the same:
public:
typedef char intern_type;
typedef char extern_type;
typedef my_state state_type;
explicit my_codecvt(size_t __refs = 0) : locale::facet(__refs) {}
result out(state_type&,
const intern_type* __from,
const intern_type*,
const intern_type*& __from_next,
extern_type* __to,
extern_type*,
extern_type*& __to_next) const
{ __from_next = __from; __to_next = __to; return noconv; }
result in (state_type&,
const extern_type* __from,
const extern_type*,
const extern_type*& __from_next,
intern_type* __to,
intern_type*,
intern_type*& __to_next) const
{ __from_next = __from; __to_next = __to; return noconv; }
result unshift(state_type&,
extern_type* __to,
extern_type*,
extern_type*& __to_next) const
{ __to_next = __to; return noconv; }
int encoding() const throw()
{ return 1; }
bool always_noconv() const throw()
{ return true; }
int length(const state_type&,
const extern_type* __from,
const extern_type* __end,
size_t __max) const
{ return (int)min(static_cast<size_t>(__end - __from), __max); }
int max_length() const throw()
{ return 1; }
static locale::id id;
# endif
};
# if !defined (STLPORT)
locale::id my_codecvt::id;
# else
# if defined (__BORLANDC__)
template <>
locale::id codecvt<char, char, my_state>::id;
# endif
# endif
#endif
void FstreamTest::custom_facet()
{
#if defined (DO_CUSTOM_FACET_TEST)
const char* fileName = "test_file.txt";
//File preparation:
{
ofstream ofstr(fileName, ios_base::binary);
ofstr << "0123456789";
CPPUNIT_ASSERT( ofstr );
}
{
typedef basic_ifstream<char, my_traits> my_ifstream;
typedef basic_string<char, my_traits> my_string;
my_ifstream ifstr(fileName);
CPPUNIT_ASSERT( ifstr );
# if !defined (STLPORT) || defined (_STLP_USE_EXCEPTIONS)
ifstr.imbue(locale::classic());
CPPUNIT_ASSERT( ifstr.fail() && !ifstr.bad() );
ifstr.clear();
# endif
locale my_loc(locale::classic(), new my_codecvt());
ifstr.imbue(my_loc);
CPPUNIT_ASSERT( ifstr.good() );
/*
my_string res;
ifstr >> res;
CPPUNIT_ASSERT( !ifstr.fail() );
CPPUNIT_ASSERT( !ifstr.bad() );
CPPUNIT_ASSERT( ifstr.eof() );
CPPUNIT_ASSERT( res == "0123456789" );
*/
}
#endif
}
# if defined (CHECK_BIG_FILE)
void FstreamTest::big_file()
{
vector<pair<streamsize, streamoff> > file_pos;
//Big file creation:
{
ofstream out("big_file.txt");
CPPUNIT_ASSERT( out );
//We are going to generate a file with the following schema for the content:
//0(1019 times)0000 //1023 characters + 1 charater for \n (for some platforms it will be a 1 ko line)
//0(1019 times)0001
//...
//0(1019 times)1234
//...
//Generation of the number of loop:
streamoff nb = 1;
for (int i = 0; i < 20; ++i) {
//This assertion check that the streamoff can at least represent the necessary integers values
//for this test:
CPPUNIT_ASSERT( (nb << 1) > nb );
nb <<= 1;
}
CPPUNIT_ASSERT( nb * CHECK_BIG_FILE >= nb );
nb *= CHECK_BIG_FILE;
//Preparation of the ouput stream state:
out << setiosflags(ios_base::right) << setfill('*');
for (streamoff index = 0; index < nb; ++index) {
if (index % 1024 == 0) {
file_pos.push_back(make_pair(out.tellp(), index));
CPPUNIT_ASSERT( file_pos.back().first != streamsize(-1) );
if (file_pos.size() > 1) {
CPPUNIT_ASSERT( file_pos[file_pos.size() - 1].first > file_pos[file_pos.size() - 2].first );
}
}
out << setw(1023) << index << '\n';
}
}
{
ifstream in("big_file.txt");
CPPUNIT_ASSERT( in );
string line;
vector<pair<streamsize, streamsize> >::const_iterator pit(file_pos.begin()),
pitEnd(file_pos.end());
for (; pit != pitEnd; ++pit) {
in.seekg((*pit).first);
CPPUNIT_ASSERT( in );
in >> line;
size_t lastStarPos = line.rfind('*');
CPPUNIT_ASSERT( atoi(line.substr(lastStarPos + 1).c_str()) == (*pit).second );
}
}
/*
The following test has been used to check that STLport do not generate
an infinite loop when the file size is larger than the streamsize and
streamoff representation (32 bits or 64 bits).
{
ifstream in("big_file.txt");
CPPUNIT_ASSERT( in );
char tmp[4096];
streamsize nb_reads = 0;
while ((!in.eof()) && in.good()){
in.read(tmp, 4096);
nb_reads += in.gcount();
}
}
*/
}
# endif
# if !defined (STLPORT) || !defined (_STLP_WIN32)
void FstreamTest::offset()
{
# if (defined(_LARGEFILE_SOURCE) || defined(_LARGEFILE64_SOURCE)) && !defined(_STLP_USE_DEFAULT_FILE_OFFSET)
CPPUNIT_CHECK( sizeof(streamoff) == 8 );
# else
CPPUNIT_CHECK( sizeof(streamoff) == sizeof(off_t) );
# endif
}
# endif
#endif
| jdrider/rhodes | platform/shared/stlport/test/unit/fstream_test.cpp | C++ | mit | 15,172 |
# 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 |
<?php
/**
* Go! OOP&AOP PHP framework
*
* @copyright Copyright 2011, Lissachenko Alexander <lisachenko.it@gmail.com>
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
namespace Go\Aop\Framework;
class MethodAfterInterceptorTest extends AbstractMethodInterceptorTest
{
public function testAdviceIsCalledAfterInvocation()
{
$sequence = array();
$advice = $this->getAdvice($sequence);
$invocation = $this->getInvocation($sequence);
$interceptor = new MethodAfterInterceptor($advice);
$result = $interceptor->invoke($invocation);
$this->assertEquals('invocation', $result, "Advice should not affect the return value of invocation");
$this->assertEquals(array('invocation', 'advice'), $sequence, "After advice should be invoked after invocation");
}
public function testAdviceIsCalledAfterExceptionInInvocation()
{
$sequence = array();
$advice = $this->getAdvice($sequence);
$invocation = $this->getInvocation($sequence, true);
$interceptor = new MethodAfterInterceptor($advice);
$this->setExpectedException('RuntimeException');
try {
$interceptor->invoke($invocation);
} catch (\Exception $e) {
$this->assertEquals(array('invocation', 'advice'), $sequence, "After advice should be invoked after invocation");
throw $e;
}
}
}
| clausche/laragit | vendor/lisachenko/go-aop-php/tests/Go/Aop/Framework/MethodAfterInterceptorTest.php | PHP | mit | 1,467 |
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 |
require File.expand_path "../test_helper", __FILE__
context "ShowOff Utils tests" do
setup do
end
# create, init - Create new showoff presentation
test "can initialize a new preso" do
files = []
in_temp_dir do
ShowOffUtils.create('testing', true)
files = Dir.glob('testing/**/*')
end
assert_equal %w(testing/one testing/one/01_slide.md testing/showoff.json), files.sort
end
# heroku - Setup your presentation to serve on Heroku
test "can herokuize" do
files = []
in_basic_dir do
ShowOffUtils.heroku('test')
files = Dir.glob('**/*')
content = File.read('Gemfile')
assert_match 'showoff', content
assert_match 'heroku', content
end
assert files.include?('config.ru')
assert files.include?('Gemfile')
end
test "can herokuize with password" do
in_basic_dir do
ShowOffUtils.heroku('test', false, 'pwpw')
content = File.read('config.ru')
assert_match 'Rack::Auth::Basic', content
assert_match 'pwpw', content
end
end
# static - Generate static version of presentation
test "can create a static version" do
in_image_dir do
ShowOff.do_static(nil)
content = File.read('static/index.html')
assert_match 'My Presentation', content
assert_equal 2, content.scan(/div class="slide"/).size
if Object.const_defined? :RMagick
assert_match 'img src="./file/one/chacon.jpg" width="300" height="300" alt="chacon"', content
else
assert_match 'img src="./file/one/chacon.jpg" alt="chacon"', content
end
end
end
# github - Puts your showoff presentation into a gh-pages branch
test "can create a github version" do
in_image_dir do
ShowOffUtils.github
files = `git ls-tree gh-pages`.chomp.split("\n")
assert_equal 4, files.size
content = `git cat-file -p gh-pages:index.html`
assert_match 'My Presentation', content
assert_equal 2, content.scan(/div class="slide"/).size
if Object.const_defined? :RMagick
assert_match 'img src="./file/one/chacon.jpg" width="300" height="300" alt="chacon"', content
else
assert_match 'img src="./file/one/chacon.jpg" alt="chacon"', content
end
end
end
test 'should obtain value for pause_msg setting' do
dir = File.join(File.dirname(__FILE__), 'fixtures', 'simple')
msg = ShowOffUtils.pause_msg(dir)
assert_match 'Test_paused', msg
end
test 'should obtain default value for pause_msg setting' do
msg = ShowOffUtils.pause_msg
assert_match 'PAUSED', msg
end
end
| travisvalentine/7.27_showoff | test/utils_test.rb | Ruby | mit | 2,616 |
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 |
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(UWPHolsService.Startup))]
namespace UWPHolsService
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureMobileApp(app);
}
}
} | Windows-Readiness/WinDevWorkshop | RU/!RU 05. Cloud Integration/05. Exercise 1/Begin-Cloud/UWPHolsService/Startup.cs | C# | mit | 273 |
<?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 |
package org.wordpress.android.util;
import android.test.InstrumentationTestCase;
import java.util.HashMap;
import java.util.Map;
public class UrlUtilsTest extends InstrumentationTestCase {
public void testGetDomainFromUrlWithEmptyStringDoesNotReturnNull() {
assertNotNull(UrlUtils.getDomainFromUrl(""));
}
public void testGetDomainFromUrlWithNoHostDoesNotReturnNull() {
assertNotNull(UrlUtils.getDomainFromUrl("wordpress"));
}
public void testGetDomainFromUrlWithHostReturnsHost() {
String url = "http://www.wordpress.com";
String host = UrlUtils.getDomainFromUrl(url);
assertTrue(host.equals("www.wordpress.com"));
}
public void testAppendUrlParameter1() {
String url = UrlUtils.appendUrlParameter("http://wp.com/test", "preview", "true");
assertEquals("http://wp.com/test?preview=true", url);
}
public void testAppendUrlParameter2() {
String url = UrlUtils.appendUrlParameter("http://wp.com/test?q=pony", "preview", "true");
assertEquals("http://wp.com/test?q=pony&preview=true", url);
}
public void testAppendUrlParameter3() {
String url = UrlUtils.appendUrlParameter("http://wp.com/test?q=pony#unicorn", "preview", "true");
assertEquals("http://wp.com/test?q=pony&preview=true#unicorn", url);
}
public void testAppendUrlParameter4() {
String url = UrlUtils.appendUrlParameter("/relative/test", "preview", "true");
assertEquals("/relative/test?preview=true", url);
}
public void testAppendUrlParameter5() {
String url = UrlUtils.appendUrlParameter("/relative/", "preview", "true");
assertEquals("/relative/?preview=true", url);
}
public void testAppendUrlParameter6() {
String url = UrlUtils.appendUrlParameter("http://wp.com/test/", "preview", "true");
assertEquals("http://wp.com/test/?preview=true", url);
}
public void testAppendUrlParameter7() {
String url = UrlUtils.appendUrlParameter("http://wp.com/test/?q=pony", "preview", "true");
assertEquals("http://wp.com/test/?q=pony&preview=true", url);
}
public void testAppendUrlParameters1() {
Map<String, String> params = new HashMap<>();
params.put("w", "200");
params.put("h", "300");
String url = UrlUtils.appendUrlParameters("http://wp.com/test", params);
if (!url.equals("http://wp.com/test?h=300&w=200") && !url.equals("http://wp.com/test?w=200&h=300")) {
assertTrue("failed test on url: " + url, false);
}
}
public void testAppendUrlParameters2() {
Map<String, String> params = new HashMap<>();
params.put("h", "300");
params.put("w", "200");
String url = UrlUtils.appendUrlParameters("/relative/test", params);
if (!url.equals("/relative/test?h=300&w=200") && !url.equals("/relative/test?w=200&h=300")) {
assertTrue("failed test on url: " + url, false);
}
}
}
| AftonTroll/WordPress-Android | libs/utils/WordPressUtils/src/androidTest/java/org/wordpress/android/util/UrlUtilsTest.java | Java | gpl-2.0 | 3,008 |
<?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 |