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
|
---|---|---|---|---|---|
package md5530bd51e982e6e7b340b73e88efe666e;
public class FormsApplicationActivity
extends android.app.Activity
implements
mono.android.IGCUserPeer
{
static final String __md_methods;
static {
__md_methods =
"n_onCreate:(Landroid/os/Bundle;)V:GetOnCreate_Landroid_os_Bundle_Handler\n" +
"n_onStart:()V:GetOnStartHandler\n" +
"n_onResume:()V:GetOnResumeHandler\n" +
"n_onPause:()V:GetOnPauseHandler\n" +
"n_onStop:()V:GetOnStopHandler\n" +
"n_onRestart:()V:GetOnRestartHandler\n" +
"n_onDestroy:()V:GetOnDestroyHandler\n" +
"n_onBackPressed:()V:GetOnBackPressedHandler\n" +
"n_onOptionsItemSelected:(Landroid/view/MenuItem;)Z:GetOnOptionsItemSelected_Landroid_view_MenuItem_Handler\n" +
"n_onPrepareOptionsMenu:(Landroid/view/Menu;)Z:GetOnPrepareOptionsMenu_Landroid_view_Menu_Handler\n" +
"n_onConfigurationChanged:(Landroid/content/res/Configuration;)V:GetOnConfigurationChanged_Landroid_content_res_Configuration_Handler\n" +
"";
mono.android.Runtime.register ("Xamarin.Forms.Platform.Android.FormsApplicationActivity, Xamarin.Forms.Platform.Android, Version=1.4.0.0, Culture=neutral, PublicKeyToken=null", FormsApplicationActivity.class, __md_methods);
}
public FormsApplicationActivity () throws java.lang.Throwable
{
super ();
if (getClass () == FormsApplicationActivity.class)
mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.FormsApplicationActivity, Xamarin.Forms.Platform.Android, Version=1.4.0.0, Culture=neutral, PublicKeyToken=null", "", this, new java.lang.Object[] { });
}
public void onCreate (android.os.Bundle p0)
{
n_onCreate (p0);
}
private native void n_onCreate (android.os.Bundle p0);
public void onStart ()
{
n_onStart ();
}
private native void n_onStart ();
public void onResume ()
{
n_onResume ();
}
private native void n_onResume ();
public void onPause ()
{
n_onPause ();
}
private native void n_onPause ();
public void onStop ()
{
n_onStop ();
}
private native void n_onStop ();
public void onRestart ()
{
n_onRestart ();
}
private native void n_onRestart ();
public void onDestroy ()
{
n_onDestroy ();
}
private native void n_onDestroy ();
public void onBackPressed ()
{
n_onBackPressed ();
}
private native void n_onBackPressed ();
public boolean onOptionsItemSelected (android.view.MenuItem p0)
{
return n_onOptionsItemSelected (p0);
}
private native boolean n_onOptionsItemSelected (android.view.MenuItem p0);
public boolean onPrepareOptionsMenu (android.view.Menu p0)
{
return n_onPrepareOptionsMenu (p0);
}
private native boolean n_onPrepareOptionsMenu (android.view.Menu p0);
public void onConfigurationChanged (android.content.res.Configuration p0)
{
n_onConfigurationChanged (p0);
}
private native void n_onConfigurationChanged (android.content.res.Configuration p0);
java.util.ArrayList refList;
public void monodroidAddReference (java.lang.Object obj)
{
if (refList == null)
refList = new java.util.ArrayList ();
refList.add (obj);
}
public void monodroidClearReferences ()
{
if (refList != null)
refList.clear ();
}
}
| fabianwilliams/aalpix | XamarinPagesDemo/Droid/obj/Debug/android/src/md5530bd51e982e6e7b340b73e88efe666e/FormsApplicationActivity.java | Java | mit | 3,159 |
/**
*
*/
package org.junit.internal.runners.statements;
import java.util.ArrayList;
import java.util.List;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.MultipleFailureException;
import org.junit.runners.model.Statement;
public class RunAfters extends Statement {
private final Statement fNext;
private final Object fTarget;
private final List<FrameworkMethod> fAfters;
public RunAfters(Statement next, List<FrameworkMethod> afters, Object target) {
fNext= next;
fAfters= afters;
fTarget= target;
}
@Override
public void evaluate() throws Throwable {
List<Throwable> errors = new ArrayList<Throwable>();
try {
fNext.evaluate();
} catch (Throwable e) {
errors.add(e);
} finally {
for (FrameworkMethod each : fAfters)
try {
each.invokeExplosively(fTarget);
} catch (Throwable e) {
errors.add(e);
}
}
MultipleFailureException.assertEmpty(errors);
}
} | MarkAufdencamp/junit | src/main/java/org/junit/internal/runners/statements/RunAfters.java | Java | epl-1.0 | 948 |
/*
===========================================================================
Copyright (C) 2000 - 2013, Raven Software, Inc.
Copyright (C) 2001 - 2013, Activision, Inc.
Copyright (C) 2013 - 2015, OpenJK contributors
This file is part of the OpenJK source code.
OpenJK is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
// tr_image.c
#include "tr_local.h"
#include <map>
bool gServerSkinHack = false;
shader_t *R_FindServerShader( const char *name, const int *lightmapIndex, const byte *styles, qboolean mipRawImage );
static char *CommaParse( char **data_p );
/*
===============
RE_SplitSkins
input = skinname, possibly being a macro for three skins
return= true if three part skins found
output= qualified names to three skins if return is true, undefined if false
===============
*/
bool RE_SplitSkins(const char *INname, char *skinhead, char *skintorso, char *skinlower)
{ //INname= "models/players/jedi_tf/|head01_skin1|torso01|lower01";
if (strchr(INname, '|'))
{
char name[MAX_QPATH];
strcpy(name, INname);
char *p = strchr(name, '|');
*p=0;
p++;
//fill in the base path
strcpy (skinhead, name);
strcpy (skintorso, name);
strcpy (skinlower, name);
//now get the the individual files
//advance to second
char *p2 = strchr(p, '|');
assert(p2);
if (!p2)
{
return false;
}
*p2=0;
p2++;
strcat (skinhead, p);
strcat (skinhead, ".skin");
//advance to third
p = strchr(p2, '|');
assert(p);
if (!p)
{
return false;
}
*p=0;
p++;
strcat (skintorso,p2);
strcat (skintorso, ".skin");
strcat (skinlower,p);
strcat (skinlower, ".skin");
return true;
}
return false;
}
// given a name, go get the skin we want and return
qhandle_t RE_RegisterIndividualSkin( const char *name , qhandle_t hSkin)
{
skin_t *skin;
skinSurface_t *surf;
char *text, *text_p;
char *token;
char surfName[MAX_QPATH];
// load and parse the skin file
ri.FS_ReadFile( name, (void **)&text );
if ( !text ) {
#ifndef FINAL_BUILD
Com_Printf( "WARNING: RE_RegisterSkin( '%s' ) failed to load!\n", name );
#endif
return 0;
}
assert (tr.skins[hSkin]); //should already be setup, but might be an 3part append
skin = tr.skins[hSkin];
text_p = text;
while ( text_p && *text_p ) {
// get surface name
token = CommaParse( &text_p );
Q_strncpyz( surfName, token, sizeof( surfName ) );
if ( !token[0] ) {
break;
}
// lowercase the surface name so skin compares are faster
Q_strlwr( surfName );
if ( *text_p == ',' ) {
text_p++;
}
if ( !strncmp( token, "tag_", 4 ) ) { //these aren't in there, but just in case you load an id style one...
continue;
}
// parse the shader name
token = CommaParse( &text_p );
if ( !strcmp( &surfName[strlen(surfName)-4], "_off") )
{
if ( !strcmp( token ,"*off" ) )
{
continue; //don't need these double offs
}
surfName[strlen(surfName)-4] = 0; //remove the "_off"
}
if ((int)(sizeof( skin->surfaces) / sizeof( skin->surfaces[0] )) <= skin->numSurfaces)
{
assert( (int)(sizeof( skin->surfaces) / sizeof( skin->surfaces[0] )) > skin->numSurfaces );
Com_Printf( "WARNING: RE_RegisterSkin( '%s' ) more than %u surfaces!\n", name, (unsigned int)ARRAY_LEN(skin->surfaces) );
break;
}
surf = (skinSurface_t *) Hunk_Alloc( sizeof( *skin->surfaces[0] ), h_low );
skin->surfaces[skin->numSurfaces] = (_skinSurface_t *)surf;
Q_strncpyz( surf->name, surfName, sizeof( surf->name ) );
if (gServerSkinHack) surf->shader = R_FindServerShader( token, lightmapsNone, stylesDefault, qtrue );
else surf->shader = R_FindShader( token, lightmapsNone, stylesDefault, qtrue );
skin->numSurfaces++;
}
ri.FS_FreeFile( text );
// never let a skin have 0 shaders
if ( skin->numSurfaces == 0 ) {
return 0; // use default skin
}
return hSkin;
}
qhandle_t RE_RegisterSkin( const char *name ) {
qhandle_t hSkin;
skin_t *skin;
if ( !name || !name[0] ) {
Com_Printf( "Empty name passed to RE_RegisterSkin\n" );
return 0;
}
if ( strlen( name ) >= MAX_QPATH ) {
Com_Printf( "Skin name exceeds MAX_QPATH\n" );
return 0;
}
// see if the skin is already loaded
for ( hSkin = 1; hSkin < tr.numSkins ; hSkin++ ) {
skin = tr.skins[hSkin];
if ( !Q_stricmp( skin->name, name ) ) {
if( skin->numSurfaces == 0 ) {
return 0; // default skin
}
return hSkin;
}
}
// allocate a new skin
if ( tr.numSkins == MAX_SKINS ) {
Com_Printf( "WARNING: RE_RegisterSkin( '%s' ) MAX_SKINS hit\n", name );
return 0;
}
tr.numSkins++;
skin = (struct skin_s *)Hunk_Alloc( sizeof( skin_t ), h_low );
tr.skins[hSkin] = skin;
Q_strncpyz( skin->name, name, sizeof( skin->name ) );
skin->numSurfaces = 0;
// make sure the render thread is stopped
R_IssuePendingRenderCommands();
// If not a .skin file, load as a single shader
if ( strcmp( name + strlen( name ) - 5, ".skin" ) ) {
/* skin->numSurfaces = 1;
skin->surfaces[0] = (skinSurface_t *)Hunk_Alloc( sizeof(skin->surfaces[0]), h_low );
skin->surfaces[0]->shader = R_FindShader( name, lightmapsNone, stylesDefault, qtrue );
return hSkin;
*/
}
char skinhead[MAX_QPATH]={0};
char skintorso[MAX_QPATH]={0};
char skinlower[MAX_QPATH]={0};
if ( RE_SplitSkins(name, (char*)&skinhead, (char*)&skintorso, (char*)&skinlower ) )
{//three part
hSkin = RE_RegisterIndividualSkin(skinhead, hSkin);
if (hSkin)
{
hSkin = RE_RegisterIndividualSkin(skintorso, hSkin);
if (hSkin)
{
hSkin = RE_RegisterIndividualSkin(skinlower, hSkin);
}
}
}
else
{//single skin
hSkin = RE_RegisterIndividualSkin(name, hSkin);
}
return(hSkin);
}
/*
==================
CommaParse
This is unfortunate, but the skin files aren't
compatible with our normal parsing rules.
==================
*/
static char *CommaParse( char **data_p ) {
int c = 0, len;
char *data;
static char com_token[MAX_TOKEN_CHARS];
data = *data_p;
len = 0;
com_token[0] = 0;
// make sure incoming data is valid
if ( !data ) {
*data_p = NULL;
return com_token;
}
while ( 1 ) {
// skip whitespace
while( (c = *(const unsigned char* /*eurofix*/)data) <= ' ') {
if( !c ) {
break;
}
data++;
}
c = *data;
// skip double slash comments
if ( c == '/' && data[1] == '/' )
{
while (*data && *data != '\n')
data++;
}
// skip /* */ comments
else if ( c=='/' && data[1] == '*' )
{
while ( *data && ( *data != '*' || data[1] != '/' ) )
{
data++;
}
if ( *data )
{
data += 2;
}
}
else
{
break;
}
}
if ( c == 0 ) {
return "";
}
// handle quoted strings
if (c == '\"')
{
data++;
while (1)
{
c = *data++;
if (c=='\"' || !c)
{
com_token[len] = 0;
*data_p = ( char * ) data;
return com_token;
}
if (len < MAX_TOKEN_CHARS - 1)
{
com_token[len] = c;
len++;
}
}
}
// parse a regular word
do
{
if (len < MAX_TOKEN_CHARS - 1)
{
com_token[len] = c;
len++;
}
data++;
c = *data;
} while (c>32 && c != ',' );
com_token[len] = 0;
*data_p = ( char * ) data;
return com_token;
}
/*
===============
RE_RegisterServerSkin
Mangled version of the above function to load .skin files on the server.
===============
*/
qhandle_t RE_RegisterServerSkin( const char *name ) {
qhandle_t r;
if (ri.Cvar_VariableIntegerValue( "cl_running" ) &&
ri.Com_TheHunkMarkHasBeenMade() &&
ShaderHashTableExists())
{ //If the client is running then we can go straight into the normal registerskin func
return RE_RegisterSkin(name);
}
gServerSkinHack = true;
r = RE_RegisterSkin(name);
gServerSkinHack = false;
return r;
}
/*
===============
R_InitSkins
===============
*/
void R_InitSkins( void ) {
skin_t *skin;
tr.numSkins = 1;
// make the default skin have all default shaders
skin = tr.skins[0] = (struct skin_s *)ri.Hunk_Alloc( sizeof( skin_t ), h_low );
Q_strncpyz( skin->name, "<default skin>", sizeof( skin->name ) );
skin->numSurfaces = 1;
skin->surfaces[0] = (_skinSurface_t *)ri.Hunk_Alloc( sizeof( skinSurface_t ), h_low );
skin->surfaces[0]->shader = tr.defaultShader;
}
/*
===============
R_GetSkinByHandle
===============
*/
skin_t *R_GetSkinByHandle( qhandle_t hSkin ) {
if ( hSkin < 1 || hSkin >= tr.numSkins ) {
return tr.skins[0];
}
return tr.skins[ hSkin ];
}
| Yberion/stats_mod | codemp/rd-dedicated/tr_skin.cpp | C++ | gpl-2.0 | 8,848 |
/**
* Copyright (c) 2012--2014 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.frontend.action.systems.sdc;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.redhat.rhn.common.db.datasource.DataResult;
import com.redhat.rhn.domain.rhnset.RhnSet;
import com.redhat.rhn.domain.server.Server;
import com.redhat.rhn.domain.user.User;
import com.redhat.rhn.frontend.dto.SystemPendingEventDto;
import com.redhat.rhn.frontend.struts.RequestContext;
import com.redhat.rhn.frontend.struts.RhnAction;
import com.redhat.rhn.frontend.struts.RhnHelper;
import com.redhat.rhn.frontend.struts.RhnListSetHelper;
import com.redhat.rhn.frontend.struts.StrutsDelegate;
import com.redhat.rhn.frontend.taglibs.list.ListTagHelper;
import com.redhat.rhn.frontend.taglibs.list.TagHelper;
import com.redhat.rhn.manager.rhnset.RhnSetDecl;
import com.redhat.rhn.manager.rhnset.RhnSetManager;
import com.redhat.rhn.manager.system.SystemManager;
/**
* SystemPendingEventsAction
* @version $Rev$
*/
public class SystemPendingEventsAction extends RhnAction {
/**
* {@inheritDoc}
*/
public ActionForward execute(ActionMapping mapping, ActionForm formIn,
HttpServletRequest request,
HttpServletResponse response) {
RequestContext context = new RequestContext(request);
Long sid = context.getRequiredParam("sid");
Server server = context.lookupAndBindServer();
User user = context.getCurrentUser();
Map<String, Object> params = makeParamMap(request);
params.put("sid", server.getId());
request.setAttribute(ListTagHelper.PARENT_URL, request.getRequestURI() +
"?sid=" + server.getId());
request.setAttribute("sid", sid);
RhnSet set = RhnSetDecl.PENDING_ACTIONS_TO_DELETE.get(user);
RhnListSetHelper helper = new RhnListSetHelper(request);
if (context.wasDispatched("system.event.pending.cancel")) {
helper.updateSet(set, RhnSetDecl.PENDING_ACTIONS_TO_DELETE.getLabel());
if (!set.isEmpty()) {
return getStrutsDelegate().forwardParams(
mapping.findForward("continue"), params);
}
RhnHelper.handleEmptySelection(request);
}
set.clear();
RhnSetManager.store(set);
DataResult<SystemPendingEventDto> result =
SystemManager.systemPendingEvents(sid, null);
if (ListTagHelper.getListAction(RequestContext.PAGE_LIST, request) != null) {
helper.execute(set, RequestContext.PAGE_LIST, result);
}
if (!set.isEmpty()) {
helper.syncSelections(set, result);
ListTagHelper.setSelectedAmount(RequestContext.PAGE_LIST,
set.size(), request);
}
ListTagHelper.bindSetDeclTo(RequestContext.PAGE_LIST,
RhnSetDecl.PENDING_ACTIONS_TO_DELETE, request);
TagHelper.bindElaboratorTo(RequestContext.PAGE_LIST,
result.getElaborator(), request);
params.put("isLocked", server.getLock() == null ? false : true);
request.setAttribute(RequestContext.PAGE_LIST, result);
return StrutsDelegate.getInstance().forwardParams(
mapping.findForward("default"), params);
}
}
| xkollar/spacewalk | java/code/src/com/redhat/rhn/frontend/action/systems/sdc/SystemPendingEventsAction.java | Java | gpl-2.0 | 4,067 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Checkout
* @copyright Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Multishipping checkout controller
*
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_Checkout_MultishippingController extends Mage_Checkout_Controller_Action
{
/**
* Retrieve checkout model
*
* @return Mage_Checkout_Model_Type_Multishipping
*/
protected function _getCheckout()
{
return Mage::getSingleton('checkout/type_multishipping');
}
/**
* Retrieve checkout state model
*
* @return Mage_Checkout_Model_Type_Multishipping_State
*/
protected function _getState()
{
return Mage::getSingleton('checkout/type_multishipping_state');
}
/**
* Retrieve checkout url heler
*
* @return Mage_Checkout_Helper_Url
*/
protected function _getHelper()
{
return Mage::helper('checkout/url');
}
/**
* Retrieve checkout session
*
* @return Mage_Checkout_Model_Session
*/
protected function _getCheckoutSession()
{
return Mage::getSingleton('checkout/session');
}
/**
* Action predispatch
*
* Check customer authentication for some actions
*
* @return Mage_Checkout_MultishippingController
*/
public function preDispatch()
{
parent::preDispatch();
if ($this->getFlag('', 'redirectLogin')) {
return $this;
}
$action = strtolower($this->getRequest()->getActionName());
$checkoutSessionQuote = $this->_getCheckoutSession()->getQuote();
/**
* Catch index action call to set some flags before checkout/type_multishipping model initialization
*/
if ($action == 'index') {
$checkoutSessionQuote->setIsMultiShipping(true);
$this->_getCheckoutSession()->setCheckoutState(
Mage_Checkout_Model_Session::CHECKOUT_STATE_BEGIN
);
} elseif (!$checkoutSessionQuote->getIsMultiShipping() &&
!in_array($action, array('login', 'register', 'success'))
) {
$this->_redirect('*/*/index');
$this->setFlag('', self::FLAG_NO_DISPATCH, true);
return $this;
}
if (!in_array($action, array('login', 'register'))) {
if (!Mage::getSingleton('customer/session')->authenticate($this, $this->_getHelper()->getMSLoginUrl())) {
$this->setFlag('', self::FLAG_NO_DISPATCH, true);
}
if (!Mage::helper('checkout')->isMultishippingCheckoutAvailable()) {
$error = $this->_getCheckout()->getMinimumAmountError();
$this->_getCheckoutSession()->addError($error);
$this->_redirectUrl($this->_getHelper()->getCartUrl());
$this->setFlag('', self::FLAG_NO_DISPATCH, true);
return $this;
}
}
if (!$this->_preDispatchValidateCustomer()) {
return $this;
}
if ($this->_getCheckoutSession()->getCartWasUpdated(true) &&
!in_array($action, array('index', 'login', 'register', 'addresses', 'success'))
) {
$this->_redirectUrl($this->_getHelper()->getCartUrl());
$this->setFlag('', self::FLAG_NO_DISPATCH, true);
}
if ($action == 'success' && $this->_getCheckout()->getCheckoutSession()->getDisplaySuccess(true)) {
return $this;
}
$quote = $this->_getCheckout()->getQuote();
if (!$quote->hasItems() || $quote->getHasError() || $quote->isVirtual()) {
$this->_redirectUrl($this->_getHelper()->getCartUrl());
$this->setFlag('', self::FLAG_NO_DISPATCH, true);
return;
}
return $this;
}
/**
* Index action of Multishipping checkout
*/
public function indexAction()
{
$this->_getCheckoutSession()->setCartWasUpdated(false);
$this->_redirect('*/*/addresses');
}
/**
* Multishipping checkout login page
*/
public function loginAction()
{
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
$this->_redirect('*/*/');
return;
}
$this->loadLayout();
$this->_initLayoutMessages('customer/session');
// set account create url
if ($loginForm = $this->getLayout()->getBlock('customer_form_login')) {
$loginForm->setCreateAccountUrl($this->_getHelper()->getMSRegisterUrl());
}
$this->renderLayout();
}
/**
* Multishipping checkout login page
*/
public function registerAction()
{
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
$this->_redirectUrl($this->_getHelper()->getMSCheckoutUrl());
return;
}
$this->loadLayout();
$this->_initLayoutMessages('customer/session');
if ($registerForm = $this->getLayout()->getBlock('customer_form_register')) {
$registerForm->setShowAddressFields(true)
->setBackUrl($this->_getHelper()->getMSLoginUrl())
->setSuccessUrl($this->_getHelper()->getMSShippingAddressSavedUrl())
->setErrorUrl($this->_getHelper()->getCurrentUrl());
}
$this->renderLayout();
}
/**
* Multishipping checkout select address page
*/
public function addressesAction()
{
// If customer do not have addresses
if (!$this->_getCheckout()->getCustomerDefaultShippingAddress()) {
$this->_redirect('*/multishipping_address/newShipping');
return;
}
$this->_getState()->unsCompleteStep(
Mage_Checkout_Model_Type_Multishipping_State::STEP_SHIPPING
);
$this->_getState()->setActiveStep(
Mage_Checkout_Model_Type_Multishipping_State::STEP_SELECT_ADDRESSES
);
if (!$this->_getCheckout()->validateMinimumAmount()) {
$message = $this->_getCheckout()->getMinimumAmountDescription();
$this->_getCheckout()->getCheckoutSession()->addNotice($message);
}
$this->loadLayout();
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('checkout/session');
$this->renderLayout();
}
/**
* Multishipping checkout process posted addresses
*/
public function addressesPostAction()
{
if (!$this->_getCheckout()->getCustomerDefaultShippingAddress()) {
$this->_redirect('*/multishipping_address/newShipping');
return;
}
try {
if ($this->getRequest()->getParam('continue', false)) {
$this->_getCheckout()->setCollectRatesFlag(true);
$this->_getState()->setActiveStep(
Mage_Checkout_Model_Type_Multishipping_State::STEP_SHIPPING
);
$this->_getState()->setCompleteStep(
Mage_Checkout_Model_Type_Multishipping_State::STEP_SELECT_ADDRESSES
);
$this->_redirect('*/*/shipping');
}
elseif ($this->getRequest()->getParam('new_address')) {
$this->_redirect('*/multishipping_address/newShipping');
}
else {
$this->_redirect('*/*/addresses');
}
if ($shipToInfo = $this->getRequest()->getPost('ship')) {
$this->_getCheckout()->setShippingItemsInformation($shipToInfo);
}
}
catch (Mage_Core_Exception $e) {
$this->_getCheckoutSession()->addError($e->getMessage());
$this->_redirect('*/*/addresses');
}
catch (Exception $e) {
$this->_getCheckoutSession()->addException(
$e,
Mage::helper('checkout')->__('Data saving problem')
);
$this->_redirect('*/*/addresses');
}
}
/**
* Multishipping checkout action to go back to addresses page
*/
public function backToAddressesAction()
{
$this->_getState()->setActiveStep(
Mage_Checkout_Model_Type_Multishipping_State::STEP_SELECT_ADDRESSES
);
$this->_getState()->unsCompleteStep(
Mage_Checkout_Model_Type_Multishipping_State::STEP_SHIPPING
);
$this->_redirect('*/*/addresses');
}
/**
* Multishipping checkout remove item action
*/
public function removeItemAction()
{
$itemId = $this->getRequest()->getParam('id');
$addressId = $this->getRequest()->getParam('address');
if ($addressId && $itemId) {
$this->_getCheckout()->setCollectRatesFlag(true);
$this->_getCheckout()->removeAddressItem($addressId, $itemId);
}
$this->_redirect('*/*/addresses');
}
/**
* Returns whether the minimum amount has been reached
*
* @return bool
*/
protected function _validateMinimumAmount()
{
if (!$this->_getCheckout()->validateMinimumAmount()) {
$error = $this->_getCheckout()->getMinimumAmountError();
$this->_getCheckout()->getCheckoutSession()->addError($error);
$this->_forward('backToAddresses');
return false;
}
return true;
}
/**
* Multishipping checkout shipping information page
*/
public function shippingAction()
{
if (!$this->_validateMinimumAmount()) {
return;
}
if (!$this->_getState()->getCompleteStep(Mage_Checkout_Model_Type_Multishipping_State::STEP_SELECT_ADDRESSES)) {
$this->_redirect('*/*/addresses');
return $this;
}
$this->_getState()->setActiveStep(
Mage_Checkout_Model_Type_Multishipping_State::STEP_SHIPPING
);
$this->loadLayout();
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('checkout/session');
$this->renderLayout();
}
/**
* Multishipping checkout action to go back to shipping
*/
public function backToShippingAction()
{
$this->_getState()->setActiveStep(
Mage_Checkout_Model_Type_Multishipping_State::STEP_SHIPPING
);
$this->_getState()->unsCompleteStep(
Mage_Checkout_Model_Type_Multishipping_State::STEP_BILLING
);
$this->_redirect('*/*/shipping');
}
/**
* Multishipping checkout after the shipping page
*/
public function shippingPostAction()
{
$shippingMethods = $this->getRequest()->getPost('shipping_method');
try {
Mage::dispatchEvent(
'checkout_controller_multishipping_shipping_post',
array('request'=>$this->getRequest(), 'quote'=>$this->_getCheckout()->getQuote())
);
$this->_getCheckout()->setShippingMethods($shippingMethods);
$this->_getState()->setActiveStep(
Mage_Checkout_Model_Type_Multishipping_State::STEP_BILLING
);
$this->_getState()->setCompleteStep(
Mage_Checkout_Model_Type_Multishipping_State::STEP_SHIPPING
);
$this->_redirect('*/*/billing');
}
catch (Exception $e) {
$this->_getCheckoutSession()->addError($e->getMessage());
$this->_redirect('*/*/shipping');
}
}
/**
* Multishipping checkout billing information page
*/
public function billingAction()
{
$collectTotals = false;
$quote = $this->_getCheckoutSession()->getQuote();
/**
* Reset customer balance
*/
if ($quote->getUseCustomerBalance()) {
$quote->setUseCustomerBalance(false);
$collectTotals = true;
}
/**
* Reset reward points
*/
if ($quote->getUseRewardPoints()) {
$quote->setUseRewardPoints(false);
$collectTotals = true;
}
if ($collectTotals) {
$quote->collectTotals()->save();
}
if (!$this->_validateBilling()) {
return;
}
if (!$this->_validateMinimumAmount()) {
return;
}
if (!$this->_getState()->getCompleteStep(Mage_Checkout_Model_Type_Multishipping_State::STEP_SHIPPING)) {
$this->_redirect('*/*/shipping');
return $this;
}
$this->_getState()->setActiveStep(
Mage_Checkout_Model_Type_Multishipping_State::STEP_BILLING
);
$this->loadLayout();
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('checkout/session');
$this->renderLayout();
}
/**
* Validation of selecting of billing address
*
* @return boolean
*/
protected function _validateBilling()
{
if(!$this->_getCheckout()->getQuote()->getBillingAddress()->getFirstname()) {
$this->_redirect('*/multishipping_address/selectBilling');
return false;
}
return true;
}
/**
* Multishipping checkout action to go back to billing
*/
public function backToBillingAction()
{
$this->_getState()->setActiveStep(
Mage_Checkout_Model_Type_Multishipping_State::STEP_BILLING
);
$this->_getState()->unsCompleteStep(
Mage_Checkout_Model_Type_Multishipping_State::STEP_OVERVIEW
);
$this->_redirect('*/*/billing');
}
/**
* Multishipping checkout place order page
*/
public function overviewAction()
{
if (!$this->_validateMinimumAmount()) {
return $this;
}
$this->_getState()->setActiveStep(Mage_Checkout_Model_Type_Multishipping_State::STEP_OVERVIEW);
try {
$payment = $this->getRequest()->getPost('payment', array());
$payment['checks'] = Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_MULTISHIPPING
| Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_COUNTRY
| Mage_Payment_Model_Method_Abstract::CHECK_USE_FOR_CURRENCY
| Mage_Payment_Model_Method_Abstract::CHECK_ORDER_TOTAL_MIN_MAX
| Mage_Payment_Model_Method_Abstract::CHECK_ZERO_TOTAL;
$this->_getCheckout()->setPaymentMethod($payment);
$this->_getState()->setCompleteStep(
Mage_Checkout_Model_Type_Multishipping_State::STEP_BILLING
);
$this->loadLayout();
$this->_initLayoutMessages('checkout/session');
$this->_initLayoutMessages('customer/session');
$this->renderLayout();
}
catch (Mage_Core_Exception $e) {
$this->_getCheckoutSession()->addError($e->getMessage());
$this->_redirect('*/*/billing');
}
catch (Exception $e) {
Mage::logException($e);
$this->_getCheckoutSession()->addException($e, $this->__('Cannot open the overview page'));
$this->_redirect('*/*/billing');
}
}
/**
* Multishipping checkout after the overview page
*/
public function overviewPostAction()
{
if (!$this->_validateFormKey()) {
$this->_forward('backToAddresses');
return;
}
if (!$this->_validateMinimumAmount()) {
return;
}
try {
if ($requiredAgreements = Mage::helper('checkout')->getRequiredAgreementIds()) {
$postedAgreements = array_keys($this->getRequest()->getPost('agreement', array()));
if ($diff = array_diff($requiredAgreements, $postedAgreements)) {
$this->_getCheckoutSession()->addError($this->__('Please agree to all Terms and Conditions before placing the order.'));
$this->_redirect('*/*/billing');
return;
}
}
$payment = $this->getRequest()->getPost('payment');
$paymentInstance = $this->_getCheckout()->getQuote()->getPayment();
if (isset($payment['cc_number'])) {
$paymentInstance->setCcNumber($payment['cc_number']);
}
if (isset($payment['cc_cid'])) {
$paymentInstance->setCcCid($payment['cc_cid']);
}
$this->_getCheckout()->createOrders();
$this->_getState()->setActiveStep(
Mage_Checkout_Model_Type_Multishipping_State::STEP_SUCCESS
);
$this->_getState()->setCompleteStep(
Mage_Checkout_Model_Type_Multishipping_State::STEP_OVERVIEW
);
$this->_getCheckout()->getCheckoutSession()->clear();
$this->_getCheckout()->getCheckoutSession()->setDisplaySuccess(true);
$this->_redirect('*/*/success');
} catch (Mage_Payment_Model_Info_Exception $e) {
$message = $e->getMessage();
if ( !empty($message) ) {
$this->_getCheckoutSession()->addError($message);
}
$this->_redirect('*/*/billing');
} catch (Mage_Checkout_Exception $e) {
Mage::helper('checkout')
->sendPaymentFailedEmail($this->_getCheckout()->getQuote(), $e->getMessage(), 'multi-shipping');
$this->_getCheckout()->getCheckoutSession()->clear();
$this->_getCheckoutSession()->addError($e->getMessage());
$this->_redirect('*/cart');
}
catch (Mage_Core_Exception $e) {
Mage::helper('checkout')
->sendPaymentFailedEmail($this->_getCheckout()->getQuote(), $e->getMessage(), 'multi-shipping');
$this->_getCheckoutSession()->addError($e->getMessage());
$this->_redirect('*/*/billing');
} catch (Exception $e) {
Mage::logException($e);
Mage::helper('checkout')
->sendPaymentFailedEmail($this->_getCheckout()->getQuote(), $e->getMessage(), 'multi-shipping');
$this->_getCheckoutSession()->addError($this->__('Order place error.'));
$this->_redirect('*/*/billing');
}
}
/**
* Multishipping checkout success page
*/
public function successAction()
{
if (!$this->_getState()->getCompleteStep(Mage_Checkout_Model_Type_Multishipping_State::STEP_OVERVIEW)) {
$this->_redirect('*/*/addresses');
return $this;
}
$this->loadLayout();
$this->_initLayoutMessages('checkout/session');
$ids = $this->_getCheckout()->getOrderIds();
Mage::dispatchEvent('checkout_multishipping_controller_success_action', array('order_ids' => $ids));
$this->renderLayout();
}
/**
* Redirect to login page
*/
public function redirectLogin()
{
$this->setFlag('', 'no-dispatch', true);
Mage::getSingleton('customer/session')->setBeforeAuthUrl(Mage::getUrl('*/*', array('_secure'=>true)));
$this->getResponse()->setRedirect(
Mage::helper('core/url')->addRequestParam(
$this->_getHelper()->getMSLoginUrl(),
array('context' => 'checkout')
)
);
$this->setFlag('', 'redirectLogin', true);
}
}
| dvh11er/mage-cheatcode | magento/app/code/core/Mage/Checkout/controllers/MultishippingController.php | PHP | gpl-2.0 | 20,321 |
//===================================================================================
//
// (C) COPYRIGHT International Business Machines Corp., 2002 All Rights Reserved
// Licensed Materials - Property of IBM
// US Government Users Restricted Rights - Use, duplication or
// disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
//
// IBM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
// ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL, INDIRECT OR
// CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
// USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
// OR PERFORMANCE OF THIS SOFTWARE.
//
// The program may be used, executed, copied, modified, and distributed
// without royalty for the purpose of developing, using, marketing, or distributing.
//
//=======================================================================================
// gSOAP v2 Interop test round 2 base
//#include "interoptA.h"
#include "soapH.h"
extern "C" void displayText(char *text);
extern "C" int interopA(const char *url);
struct Namespace namespacesA[] =
{ {"SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/"},
{"SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/"},
{"xsi", "http://www.w3.org/2001/XMLSchema-instance", "http://www.w3.org/*/XMLSchema-instance"},
{"xsd", "http://www.w3.org/2001/XMLSchema", "http://www.w3.org/*/XMLSchema"},
{"ns", "http://soapinterop.org/"},
{"s", "http://soapinterop.org/xsd"},
{"a", "http://xml.apache.org/xml-soap"},
{"h", "http://soapinterop.org/echoheader/"},
{NULL, NULL}
};
int interopA(const char *url)
{
struct soap *soap;
int i, g;
xsd__string so, si = "Hello World! <>&";
struct ArrayOfstring Asi, Aso;
xsd__int no, ni = 1234567890;
xsd__int n = 2147483647;
struct ArrayOfint Ani, Ano;
// xsd__float f1 = 3.40282e+38;
xsd__float f1 = 123.5678;
xsd__float f2 = 3.14;
xsd__float fo, fi = 123.456;
// xsd__float fo, fi = 3e2;
//#ifdef SYMBIAN
// const struct soap_double_nan { unsigned int n1, n2; } soap_double_nan;
//#endif
xsd__float nan = FLT_NAN, inf = FLT_PINFTY, ninf = FLT_NINFTY;
struct ArrayOffloat Afi, Afo;
struct s__SOAPStruct sti, *p;
struct ns__echoStructResponse sto;
struct ArrayOfSOAPStruct Asti, Asto;
struct ns__echoVoidResponse Rv;
struct xsd__base64Binary b64i, b64o;
xsd__dateTime dto, dti = "1967-12-29T01:02:03";
struct xsd__hexBinary hbi, hbo;
xsd__decimal Do, Di = "1234567890.123456789";
xsd__boolean bo, bi = true;
//struct a__Map mi, mo;
//struct ArrayOfMap Ami, Amo;
// char buff[100];
displayText("running test A on");
displayText((char*)url);
soap = soap_new();
soap->namespaces = (struct Namespace *)namespacesA;
// soap.send_timeout = 30;
// soap.recv_timeout = 30;
Asi.__size = 8;
Asi.__offset = 0;
Asi.__ptr = (xsd__string*)malloc(Asi.__size*sizeof(xsd__string));
Asi.__ptr[0] = NULL;
Asi.__ptr[1] = " Hello\tWorld";
Asi.__ptr[2] = NULL;
Asi.__ptr[3] = "! ";
Asi.__ptr[4] = NULL;
Asi.__ptr[5] = si;
Asi.__ptr[6] = NULL;
Asi.__ptr[7] = si;
Ani.__size = 0;
Ani.__offset = 0;
Ani.__ptr = NULL; // (xsd__int*)malloc(Ani.__size*sizeof(xsd__int));
Afi.__size = 5;
Afi.__offset = 0;
Afi.__ptr = (xsd__float**)malloc(Afi.__size*sizeof(xsd__float*));
Afi.__ptr[0] = &f1;
Afi.__ptr[1] = &nan; // FLT_NAN;
Afi.__ptr[2] = &inf; // FLT_PINFTY;
Afi.__ptr[3] = &ninf; // FLT_NINFTY;
Afi.__ptr[4] = &f2;
sti.varString = "Hello";
sti.varInt = &n;
sti.varFloat = &f1;
Asti.__size = 3;
Asti.__offset = 2;
Asti.__ptr = (struct s__SOAPStruct**)malloc((Asti.__size+1)*sizeof(struct s__SOAPStruct*));
p = (struct s__SOAPStruct*)malloc(Asti.__size*sizeof(struct s__SOAPStruct));
Asti.__ptr[0] = p;
Asti.__ptr[1] = p+1;
Asti.__ptr[2] = p+2;
Asti.__ptr[3] = p;
Asti.__ptr[0]->varString = "Hello";
Asti.__ptr[0]->varInt = &n;
Asti.__ptr[0]->varFloat = &f1;
Asti.__ptr[1]->varString = "World";
Asti.__ptr[1]->varInt = &n;
Asti.__ptr[1]->varFloat = &f2;
Asti.__ptr[2]->varString = "!";
Asti.__ptr[2]->varInt = &n;
Asti.__ptr[2]->varFloat = &f2;
// b64i.__ptr = (unsigned char*)"This is an example Base64 encoded string";
// b64i.__size = strlen((char*)b64i.__ptr)+1;
unsigned char b64data[4]={0x80, 0x81, 0x82, 0x83};
b64i.__ptr = b64data;
b64i.__size = 4;
hbi.__ptr = (unsigned char*)"This is an example HexBinary encoded string";
hbi.__size = strlen((char*)hbi.__ptr)+1;
/*
mi.__size = 2;
mi.__ptr = (struct _item*)malloc(mi.__size*sizeof(struct _item));
mi.__ptr[0].key = new xsd__string_("hello");
mi.__ptr[0].value = new xsd__string_("world");
mi.__ptr[1].key = new xsd__int_(2);
mi.__ptr[1].value = new xsd__boolean_(true);
Ami.__size = 2;
Ami.__ptr = (struct a__Map**)malloc(Ami.__size*sizeof(struct a__Map*));
Ami.__ptr[0] = &mi;
Ami.__ptr[1] = &mi; */
char *site=(char*)url;
// char* site ="http://websrv.cs.fsu.edu/~engelen/interop2.cgi";
// char* site = "http://nagoya.apache.org:5049/axis/services/echo ";
char* action = "http://soapinterop.org/";
bool ok=true;
if (soap_call_ns__echoString(soap, site, action, si, so))
{
displayText("echoString fail");
ok=false;
}
else if (!so || strcmp(si, so))
{
ok=false;
displayText("echoString mismatched");
}
else
displayText("echoString pass");
if (soap_call_ns__echoInteger(soap, site, "http://soapinterop.org/", ni, no))
{
ok=false;
displayText("echoInteger fail");
}
else if (ni != no)
{
ok=false;
displayText("echoInteger mismatched");
}
else
displayText("echoInteger pass");
if (soap_call_ns__echoFloat(soap, site, "http://soapinterop.org/", fi, fo))
{
ok=false;
displayText("echoFloat fail");
}
else if (fi != fo)
{
ok=false;
displayText("echoFloat mismatched");
}
else
displayText("echoFloat pass");
if (soap_call_ns__echoStruct(soap, site, "http://soapinterop.org/", sti, sto))
{
ok=false;
displayText("echoStruct fail");
}
else if (!sto._return.varString || strcmp(sti.varString, sto._return.varString)
|| !sto._return.varInt || *sti.varInt != *sto._return.varInt
|| !sto._return.varFloat || *sti.varFloat != *sto._return.varFloat)
{
ok=false;
displayText("echoStruct mismatch");
}
else
displayText("echoStruct pass");
if (soap_call_ns__echoStringArray(soap, site, "http://soapinterop.org/", Asi, Aso))
{
soap_set_fault(soap);
soap_faultdetail(soap);
ok=false;
displayText("echoStringArray fail");
}
else
{ g = 0;
if (Asi.__size != Aso.__size)
g = 1;
else
for (i = 0; i < Asi.__size; i++)
if (Asi.__ptr[i] && Aso.__ptr[i] && strcmp(Asi.__ptr[i], Aso.__ptr[i]))
g = 1;
else if (!Asi.__ptr[i])
;
else if (Asi.__ptr[i] && !Aso.__ptr[i])
g = 1;
if (g)
{
ok=false;
displayText("echoStringArray mismatch");
}
else
displayText("echoStringArray pass");
}
if (soap_call_ns__echoIntegerArray(soap, site, "http://soapinterop.org/", Ani, Ano))
{ displayText("echoIntegerArray fail");
ok=false;
}
else
{ g = 0;
if (Ani.__size != Ano.__size)
g = 1;
else
for (i = 0; i < Ani.__size; i++)
if (Ani.__ptr[i] && (!Ano.__ptr[i] || *Ani.__ptr[i] != *Ano.__ptr[i]))
g = 1;
if (g)
{ displayText("echoIntegerArray mismatch");
ok=false;
}
else
displayText("echoIntegerArray pass");
}
if (soap_call_ns__echoFloatArray(soap, site, "http://soapinterop.org/", Afi, Afo))
{ displayText("echoFloatArray fail");
ok=false;
}
else
{ g = 0;
if (Afi.__size != Afo.__size)
g = 1;
else
for (i = 0; i < Afi.__size; i++)
if (Afi.__ptr[i] && Afo.__ptr[i] && soap_isnan(*Afi.__ptr[i]) && soap_isnan(*Afo.__ptr[i]))
;
else if (Afi.__ptr[i] && (!Afo.__ptr[i] || *Afi.__ptr[i] != *Afo.__ptr[i]))
g = 1;
if (g)
{ displayText("echoFloatArray mismatch");
ok=false;
}
else
displayText("echoFloatArray pass");
}
if (soap_call_ns__echoStructArray(soap, site, "http://soapinterop.org/", Asti, Asto))
{ displayText("echoStructArray fail");
ok=false;
}
else
{ g = 0;
if (Asti.__size+Asti.__offset != Asto.__size+Asto.__offset)
g = 1;
else
for (i = Asti.__offset; i < Asti.__size+Asti.__offset; i++)
if (!Asto.__ptr[i-Asto.__offset] ||
!Asto.__ptr[i-Asto.__offset]->varString ||
strcmp(Asti.__ptr[i-Asti.__offset]->varString, Asto.__ptr[i-Asto.__offset]->varString) ||
!Asto.__ptr[i-Asto.__offset]->varInt ||
*Asti.__ptr[i-Asti.__offset]->varInt != *Asto.__ptr[i-Asto.__offset]->varInt ||
!Asto.__ptr[i-Asto.__offset]->varFloat ||
*Asti.__ptr[i-Asti.__offset]->varFloat != *Asto.__ptr[i-Asto.__offset]->varFloat)
g = 1;
if (g)
{ displayText("echoStructArray mismatch");
ok=false;
}
else
displayText("echoStructArray pass");
}
if (soap_call_ns__echoVoid(soap, site, "http://soapinterop.org/", Rv))
{ displayText("echoVoid fail");
ok=false;
}
else
displayText("echoVoid pass");
if (soap_call_ns__echoBase64(soap, site, "http://soapinterop.org/", b64i, b64o))
{ displayText("echoBase64 fail");
ok=false;
}
else if ((b64i.__size+2)/3 != (b64o.__size+2)/3 || strncmp((char*)b64i.__ptr, (char*)b64o.__ptr,b64i.__size))
{
displayText("echoBase64 mismatch");
ok=false;
}
else
displayText("echoBase64 pass");
if (soap_call_ns__echoDate(soap, site, "http://soapinterop.org/", dti, dto))
{
displayText("echoDate fail");
ok=false;
}
else if (!dto || strncmp(dti, dto, 19))
{
displayText("echoDate mismatch");
ok=false;
}
else
displayText("echoDate pass");
if (soap_call_ns__echoHexBinary(soap, site, "http://soapinterop.org/", hbi, hbo))
{
ok=false;
displayText("echoHexBinary fail");
}
else if (hbi.__size != hbo.__size || strcmp((char*)hbi.__ptr, (char*)hbo.__ptr))
{
ok=false;
displayText("echoHexBinary mismatch");
}
else
displayText("echoHexBinary pass");
if (soap_call_ns__echoDecimal(soap, site, "http://soapinterop.org/", Di, Do))
{
ok=false;
displayText("echoDecimal pass");
}
else if (strcmp(Di, Do))
{
ok=false;
displayText("echoDecimal mismatch");
}
else
displayText("echoDecimal pass");
if (soap_call_ns__echoBoolean(soap, site, "http://soapinterop.org/", bi, bo))
{
ok=false;
displayText("echoBoolean fail");
}
else if (bi != bo)
{
ok=false;
displayText("echoBoolean mismatch");
}
else
displayText("echoBoolean pass");
if (ok)
displayText("ALL PASS");
else
displayText("FAILURES");
return 0;
end:
return 1;
}
| cory-ko/KBWS | gsoap/Symbian/interop2test.cpp | C++ | gpl-2.0 | 11,395 |
/*
*
* Copyright 2003, 2004 Blur Studio Inc.
*
* This file is part of the Resin software package.
*
* Resin 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 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 Resin; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef COMMIT_CODE
#include <qdir.h>
#include <stdlib.h>
#include "shotgroup.h"
int ShotGroup::frameStart() const
{
return shots()[shots().count()-1].frameStart();
}
int ShotGroup::frameEnd() const
{
return shots()[0].frameEnd();
}
int ShotGroup::frameStartEDL() const
{
return shots()[shots().count()-1].frameStartEDL();
}
int ShotGroup::frameEndEDL() const
{
return shots()[0].frameEndEDL();
}
ShotList ShotGroup::shots() const
{
ShotList shots = children( Shot::type(), true );
return shots;
}
#endif
| perryjrandall/arsenalsuite | cpp/lib/classes/base/shotgroupbase.cpp | C++ | gpl-2.0 | 1,325 |
/*
* Copyright (c) 2002, 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.
*/
package nsk.jdi.VirtualMachine.redefineClasses;
import nsk.share.*;
import nsk.share.jpda.*;
import nsk.share.jdi.*;
/**
* <code>redefineclasses012b</code> is deugee's part of the redefineclasses012.
* adding new field
*/
public interface redefineclasses012b {
//new fields
static public final Object newField001 = null;
//preexisting fields
static public final Object field001 = null;
public final Object field002 = null;
final Object field003 = null;
Object field004 = null;
}
| md-5/jdk10 | test/hotspot/jtreg/vmTestbase/nsk/jdi/VirtualMachine/redefineClasses/redefineclasses012/newclass01/redefineclasses012b.java | Java | gpl-2.0 | 1,616 |
<?php
/**
* @file
* Contains \Drupal\Console\Command\Generate\PluginFieldWidgetCommand.
*/
namespace Drupal\Console\Command\Generate;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Drupal\Console\Generator\PluginFieldWidgetGenerator;
use Drupal\Console\Command\ModuleTrait;
use Drupal\Console\Command\ConfirmationTrait;
use Drupal\Console\Command\GeneratorCommand;
use Drupal\Console\Style\DrupalStyle;
class PluginFieldWidgetCommand extends GeneratorCommand
{
use ModuleTrait;
use ConfirmationTrait;
protected function configure()
{
$this
->setName('generate:plugin:fieldwidget')
->setDescription($this->trans('commands.generate.plugin.fieldwidget.description'))
->setHelp($this->trans('commands.generate.plugin.fieldwidget.help'))
->addOption('module', '', InputOption::VALUE_REQUIRED, $this->trans('commands.common.options.module'))
->addOption(
'class',
'',
InputOption::VALUE_REQUIRED,
$this->trans('commands.generate.plugin.fieldwidget.options.class')
)
->addOption(
'label',
'',
InputOption::VALUE_OPTIONAL,
$this->trans('commands.generate.plugin.fieldwidget.options.label')
)
->addOption(
'plugin-id',
'',
InputOption::VALUE_OPTIONAL,
$this->trans('commands.generate.plugin.fieldwidget.options.plugin-id')
)
->addOption(
'field-type',
'',
InputOption::VALUE_OPTIONAL,
$this->trans('commands.generate.plugin.fieldwidget.options.field-type')
);
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new DrupalStyle($input, $output);
// @see use Drupal\Console\Command\ConfirmationTrait::confirmGeneration
if (!$this->confirmGeneration($io)) {
return;
}
$module = $input->getOption('module');
$class_name = $input->getOption('class');
$label = $input->getOption('label');
$plugin_id = $input->getOption('plugin-id');
$field_type = $input->getOption('field-type');
$this
->getGenerator()
->generate($module, $class_name, $label, $plugin_id, $field_type);
$this->getChain()->addCommand('cache:rebuild', ['cache' => 'discovery']);
}
protected function interact(InputInterface $input, OutputInterface $output)
{
$io = new DrupalStyle($input, $output);
$fieldTypePluginManager = $this->getService('plugin.manager.field.field_type');
// --module option
$module = $input->getOption('module');
if (!$module) {
// @see Drupal\Console\Command\ModuleTrait::moduleQuestion
$module = $this->moduleQuestion($output);
$input->setOption('module', $module);
}
// --class option
$class_name = $input->getOption('class');
if (!$class_name) {
$class_name = $io->ask(
$this->trans('commands.generate.plugin.fieldwidget.questions.class'),
'ExampleFieldWidget'
);
$input->setOption('class', $class_name);
}
// --plugin label option
$label = $input->getOption('label');
if (!$label) {
$label = $io->ask(
$this->trans('commands.generate.plugin.fieldwidget.questions.label'),
$this->getStringHelper()->camelCaseToHuman($class_name)
);
$input->setOption('label', $label);
}
// --plugin-id option
$plugin_id = $input->getOption('plugin-id');
if (!$plugin_id) {
$plugin_id = $io->ask(
$this->trans('commands.generate.plugin.fieldwidget.questions.plugin-id'),
$this->getStringHelper()->camelCaseToUnderscore($class_name)
);
$input->setOption('plugin-id', $plugin_id);
}
// --field-type option
$field_type = $input->getOption('field-type');
if (!$field_type) {
// Gather valid field types.
$field_type_options = array();
foreach ($fieldTypePluginManager->getGroupedDefinitions($fieldTypePluginManager->getUiDefinitions()) as $category => $field_types) {
foreach ($field_types as $name => $field_type) {
$field_type_options[] = $name;
}
}
$field_type = $io->choice(
$this->trans('commands.generate.plugin.fieldwidget.questions.field-type'),
$field_type_options
);
$input->setOption('field-type', $field_type);
}
}
protected function createGenerator()
{
return new PluginFieldWidgetGenerator();
}
}
| sgrichards/BrightonDrupal | vendor/drupal/console/src/Command/Generate/PluginFieldWidgetCommand.php | PHP | gpl-2.0 | 5,154 |
/*
* Copyright (c) 2011, 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.net;
/**
* Choose a network inteface to be the default for
* outgoing IPv6 traffic that does not specify a scope_id (and which needs one).
* We choose the first interface that is up and is (in order of preference):
* 1. neither loopback nor point to point
* 2. point to point
* 3. loopback
* 4. none.
* Platforms that do not require a default interface implement a dummy
* that returns null.
*/
import java.util.Enumeration;
import java.io.IOException;
class DefaultInterface {
private final static NetworkInterface defaultInterface =
chooseDefaultInterface();
static NetworkInterface getDefault() {
return defaultInterface;
}
/**
* Choose a default interface. This method returns an interface that is
* both "up" and supports multicast. This method choses an interface in
* order of preference:
* 1. neither loopback nor point to point
* 2. point to point
* 3. loopback
*
* @return the chosen interface or {@code null} if there isn't a suitable
* default
*/
private static NetworkInterface chooseDefaultInterface() {
Enumeration<NetworkInterface> nifs;
try {
nifs = NetworkInterface.getNetworkInterfaces();
} catch (IOException ignore) {
// unable to enumate network interfaces
return null;
}
NetworkInterface ppp = null;
NetworkInterface loopback = null;
while (nifs.hasMoreElements()) {
NetworkInterface ni = nifs.nextElement();
try {
if (ni.isUp() && ni.supportsMulticast()) {
boolean isLoopback = ni.isLoopback();
boolean isPPP = ni.isPointToPoint();
if (!isLoopback && !isPPP) {
// found an interface that is not the loopback or a
// point-to-point interface
return ni;
}
if (ppp == null && isPPP)
ppp = ni;
if (loopback == null && isLoopback)
loopback = ni;
}
} catch (IOException skip) { }
}
return (ppp != null) ? ppp : loopback;
}
}
| greghaskins/openjdk-jdk7u-jdk | src/macosx/classes/java/net/DefaultInterface.java | Java | gpl-2.0 | 3,499 |
/*
Copyright (C) 2011-2012 de4dot@gmail.com
This file is part of de4dot.
de4dot 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.
de4dot 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 de4dot. If not, see <http://www.gnu.org/licenses/>.
*/
using de4dot.PE;
namespace de4dot.code.deobfuscators.MaxtoCode {
class DecrypterInfo {
public readonly MainType mainType;
public readonly PeImage peImage;
public readonly PeHeader peHeader;
public readonly McKey mcKey;
public readonly byte[] fileData;
public DecrypterInfo(MainType mainType, byte[] fileData) {
this.mainType = mainType;
this.peImage = new PeImage(fileData);
this.peHeader = new PeHeader(mainType, peImage);
this.mcKey = new McKey(peImage, peHeader);
this.fileData = fileData;
}
}
}
| hjlfmy/de4dot | de4dot.code/deobfuscators/MaxtoCode/DecrypterInfo.cs | C# | gpl-3.0 | 1,256 |
"""
Help has buttons and menu items to open help, blog and forum pages in your primary browser.
"""
from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
import __init__
from fabmetheus_utilities import archive
from fabmetheus_utilities import settings
from skeinforge_application.skeinforge_utilities import skeinforge_profile
__author__ = 'Enrique Perez (perez_enrique@yahoo.com)'
__date__ = '$Date: 2008/21/04 $'
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
def getNewRepository():
'Get new repository.'
return HelpRepository()
class HelpRepository:
"A class to handle the help settings."
def __init__(self):
"Set the default settings, execute title & settings fileName."
skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_utilities.skeinforge_help.html', self)
announcementsText = '- Announcements - '
announcementsLabel = settings.LabelDisplay().getFromName(announcementsText, self )
announcementsLabel.columnspan = 6
settings.LabelDisplay().getFromName('Fabmetheus Blog, Announcements & Questions:', self )
settings.HelpPage().getFromNameAfterHTTP('fabmetheus.blogspot.com/', 'Fabmetheus Blog', self )
settings.LabelSeparator().getFromRepository(self)
settings.LabelDisplay().getFromName('- Documentation -', self )
settings.LabelDisplay().getFromName('Local Documentation Table of Contents: ', self )
settings.HelpPage().getFromNameSubName('Contents', self, 'contents.html')
settings.LabelDisplay().getFromName('Wiki Manual with Pictures & Charts: ', self )
settings.HelpPage().getFromNameAfterHTTP('fabmetheus.crsndoo.com/wiki/index.php/Skeinforge', 'Wiki Manual', self )
settings.LabelDisplay().getFromName('Skeinforge Overview: ', self )
settings.HelpPage().getFromNameSubName('Skeinforge Overview', self, 'skeinforge_application.skeinforge.html')
settings.LabelSeparator().getFromRepository(self)
settings.LabelDisplay().getFromName('- Search -', self )
settings.LabelDisplay().getFromName('Reprap Search:', self )
settings.HelpPage().getFromNameAfterHTTP('members.axion.net/~enrique/search_reprap.html', 'Reprap Search', self )
settings.LabelDisplay().getFromName('Skeinforge Search:', self )
settings.HelpPage().getFromNameAfterHTTP('members.axion.net/~enrique/search_skeinforge.html', 'Skeinforge Search', self )
settings.LabelDisplay().getFromName('Web Search:', self )
settings.HelpPage().getFromNameAfterHTTP('members.axion.net/~enrique/search_web.html', 'Web Search', self )
settings.LabelSeparator().getFromRepository(self)
settings.LabelDisplay().getFromName('- Troubleshooting -', self )
settings.LabelDisplay().getFromName('Skeinforge Forum:', self)
settings.HelpPage().getFromNameAfterHTTP('forums.reprap.org/list.php?154', ' Skeinforge Forum ', self )
settings.LabelSeparator().getFromRepository(self)
self.version = settings.LabelDisplay().getFromName('Version: ' + archive.getFileText(archive.getVersionFileName()), self)
self.wikiManualPrimary = settings.BooleanSetting().getFromValue('Wiki Manual Primary', self, True )
self.wikiManualPrimary.setUpdateFunction( self.save )
def save(self):
"Write the entities."
settings.writeSettingsPrintMessage(self)
| nophead/Skeinforge50plus | skeinforge_application/skeinforge_utilities/skeinforge_help.py | Python | agpl-3.0 | 3,508 |
#!/usr/bin/env python
# Copyright (c) 2006-2007 XenSource, Inc.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# Simple example using the asynchronous version of the VM start method
# Assumes the presence of a VM called 'new'
import pprint, time, sys
import XenAPI
def main(session):
print "Listing all VM references:"
vms = session.xenapi.VM.get_all()
pprint.pprint(vms)
print "Dumping all VM records:"
for vm in vms:
pprint.pprint(session.xenapi.VM.get_record(vm))
print "Attempting to start a VM called 'new' (if it doesn't exist this will throw an exception)"
vm = session.xenapi.VM.get_by_name_label('new')[0]
session.xenapi.VM.start(vm, False, True)
print "Attempting to start the VM asynchronously"
task = session.xenapi.Async.VM.start(vm, False, True)
task_record = session.xenapi.task.get_record(task)
print "The initial contents of the task record:"
pprint.pprint(task_record)
print "Waiting for the task to complete"
while session.xenapi.task.get_status(task) == "pending": time.sleep(1)
task_record = session.xenapi.task.get_record(task)
print "The final contents of the task record:"
pprint.pprint(task_record)
if __name__ == "__main__":
if len(sys.argv) <> 4:
print "Usage:"
print sys.argv[0], " <url> <username> <password>"
sys.exit(1)
url = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]
# First acquire a valid session by logging in:
session = XenAPI.Session(url)
session.xenapi.login_with_password(username, password, "1.0", "xen-api-scripts-vm-start-async.py")
main(session)
| anoobs/xen-api | scripts/examples/python/vm_start_async.py | Python | lgpl-2.1 | 2,335 |
//Draw ellipses
//Author: Rene Brun
TCanvas *ellipse(){
TCanvas *c1 = new TCanvas("c1");
c1->Range(0,0,1,1);
TPaveLabel *pel = new TPaveLabel(0.1,0.8,0.9,0.95,"Examples of Ellipses");
pel->SetFillColor(42);
pel->Draw();
TEllipse *el1 = new TEllipse(0.25,0.25,.1,.2);
el1->Draw();
TEllipse *el2 = new TEllipse(0.25,0.6,.2,.1);
el2->SetFillColor(6);
el2->SetFillStyle(3008);
el2->Draw();
TEllipse *el3 = new TEllipse(0.75,0.6,.2,.1,45,315);
el3->SetFillColor(2);
el3->SetFillStyle(1001);
el3->SetLineColor(4);
el3->Draw();
TEllipse *el4 = new TEllipse(0.75,0.25,.2,.15,45,315,62);
el4->SetFillColor(5);
el4->SetFillStyle(1001);
el4->SetLineColor(4);
el4->SetLineWidth(6);
el4->Draw();
return c1;
}
| perovic/root | tutorials/graphics/ellipse.C | C++ | lgpl-2.1 | 765 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.crypto.key.kms;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Preconditions;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.hadoop.classification.InterfaceAudience;
/**
* A Utility class that maintains a Queue of entries for a given key. It tries
* to ensure that there is are always at-least <code>numValues</code> entries
* available for the client to consume for a particular key.
* It also uses an underlying Cache to evict queues for keys that have not been
* accessed for a configurable period of time.
* Implementing classes are required to implement the
* <code>QueueRefiller</code> interface that exposes a method to refill the
* queue, when empty
*/
@InterfaceAudience.Private
public class ValueQueue <E> {
/**
* QueueRefiller interface a client must implement to use this class
*/
public interface QueueRefiller <E> {
/**
* Method that has to be implemented by implementing classes to fill the
* Queue.
* @param keyName Key name
* @param keyQueue Queue that needs to be filled
* @param numValues number of Values to be added to the queue.
* @throws IOException
*/
public void fillQueueForKey(String keyName,
Queue<E> keyQueue, int numValues) throws IOException;
}
private static final String REFILL_THREAD =
ValueQueue.class.getName() + "_thread";
private final LoadingCache<String, LinkedBlockingQueue<E>> keyQueues;
private final ThreadPoolExecutor executor;
private final UniqueKeyBlockingQueue queue = new UniqueKeyBlockingQueue();
private final QueueRefiller<E> refiller;
private final SyncGenerationPolicy policy;
private final int numValues;
private final float lowWatermark;
private volatile boolean executorThreadsStarted = false;
/**
* A <code>Runnable</code> which takes a string name.
*/
private abstract static class NamedRunnable implements Runnable {
final String name;
private NamedRunnable(String keyName) {
this.name = keyName;
}
}
/**
* This backing blocking queue used in conjunction with the
* <code>ThreadPoolExecutor</code> used by the <code>ValueQueue</code>. This
* Queue accepts a task only if the task is not currently in the process
* of being run by a thread which is implied by the presence of the key
* in the <code>keysInProgress</code> set.
*
* NOTE: Only methods that ware explicitly called by the
* <code>ThreadPoolExecutor</code> need to be over-ridden.
*/
private static class UniqueKeyBlockingQueue extends
LinkedBlockingQueue<Runnable> {
private static final long serialVersionUID = -2152747693695890371L;
private HashSet<String> keysInProgress = new HashSet<String>();
@Override
public synchronized void put(Runnable e) throws InterruptedException {
if (keysInProgress.add(((NamedRunnable)e).name)) {
super.put(e);
}
}
@Override
public Runnable take() throws InterruptedException {
Runnable k = super.take();
if (k != null) {
keysInProgress.remove(((NamedRunnable)k).name);
}
return k;
}
@Override
public Runnable poll(long timeout, TimeUnit unit)
throws InterruptedException {
Runnable k = super.poll(timeout, unit);
if (k != null) {
keysInProgress.remove(((NamedRunnable)k).name);
}
return k;
}
}
/**
* Policy to decide how many values to return to client when client asks for
* "n" values and Queue is empty.
* This decides how many values to return when client calls "getAtMost"
*/
public static enum SyncGenerationPolicy {
ATLEAST_ONE, // Return atleast 1 value
LOW_WATERMARK, // Return min(n, lowWatermark * numValues) values
ALL // Return n values
}
/**
* Constructor takes the following tunable configuration parameters
* @param numValues The number of values cached in the Queue for a
* particular key.
* @param lowWatermark The ratio of (number of current entries/numValues)
* below which the <code>fillQueueForKey()</code> funciton will be
* invoked to fill the Queue.
* @param expiry Expiry time after which the Key and associated Queue are
* evicted from the cache.
* @param numFillerThreads Number of threads to use for the filler thread
* @param policy The SyncGenerationPolicy to use when client
* calls "getAtMost"
* @param refiller implementation of the QueueRefiller
*/
public ValueQueue(final int numValues, final float lowWatermark,
long expiry, int numFillerThreads, SyncGenerationPolicy policy,
final QueueRefiller<E> refiller) {
Preconditions.checkArgument(numValues > 0, "\"numValues\" must be > 0");
Preconditions.checkArgument(((lowWatermark > 0)&&(lowWatermark <= 1)),
"\"lowWatermark\" must be > 0 and <= 1");
Preconditions.checkArgument(expiry > 0, "\"expiry\" must be > 0");
Preconditions.checkArgument(numFillerThreads > 0,
"\"numFillerThreads\" must be > 0");
Preconditions.checkNotNull(policy, "\"policy\" must not be null");
this.refiller = refiller;
this.policy = policy;
this.numValues = numValues;
this.lowWatermark = lowWatermark;
keyQueues = CacheBuilder.newBuilder()
.expireAfterAccess(expiry, TimeUnit.MILLISECONDS)
.build(new CacheLoader<String, LinkedBlockingQueue<E>>() {
@Override
public LinkedBlockingQueue<E> load(String keyName)
throws Exception {
LinkedBlockingQueue<E> keyQueue =
new LinkedBlockingQueue<E>();
refiller.fillQueueForKey(keyName, keyQueue,
(int)(lowWatermark * numValues));
return keyQueue;
}
});
executor =
new ThreadPoolExecutor(numFillerThreads, numFillerThreads, 0L,
TimeUnit.MILLISECONDS, queue, new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(REFILL_THREAD).build());
}
public ValueQueue(final int numValues, final float lowWaterMark, long expiry,
int numFillerThreads, QueueRefiller<E> fetcher) {
this(numValues, lowWaterMark, expiry, numFillerThreads,
SyncGenerationPolicy.ALL, fetcher);
}
/**
* Initializes the Value Queues for the provided keys by calling the
* fill Method with "numInitValues" values
* @param keyNames Array of key Names
* @throws ExecutionException
*/
public void initializeQueuesForKeys(String... keyNames)
throws ExecutionException {
for (String keyName : keyNames) {
keyQueues.get(keyName);
}
}
/**
* This removes the value currently at the head of the Queue for the
* provided key. Will immediately fire the Queue filler function if key
* does not exist.
* If Queue exists but all values are drained, It will ask the generator
* function to add 1 value to Queue and then drain it.
* @param keyName String key name
* @return E the next value in the Queue
* @throws IOException
* @throws ExecutionException
*/
public E getNext(String keyName)
throws IOException, ExecutionException {
return getAtMost(keyName, 1).get(0);
}
/**
* Drains the Queue for the provided key.
*
* @param keyName the key to drain the Queue for
*/
public void drain(String keyName ) {
try {
keyQueues.get(keyName).clear();
} catch (ExecutionException ex) {
//NOP
}
}
/**
* This removes the "num" values currently at the head of the Queue for the
* provided key. Will immediately fire the Queue filler function if key
* does not exist
* How many values are actually returned is governed by the
* <code>SyncGenerationPolicy</code> specified by the user.
* @param keyName String key name
* @param num Minimum number of values to return.
* @return List<E> values returned
* @throws IOException
* @throws ExecutionException
*/
public List<E> getAtMost(String keyName, int num) throws IOException,
ExecutionException {
LinkedBlockingQueue<E> keyQueue = keyQueues.get(keyName);
// Using poll to avoid race condition..
LinkedList<E> ekvs = new LinkedList<E>();
try {
for (int i = 0; i < num; i++) {
E val = keyQueue.poll();
// If queue is empty now, Based on the provided SyncGenerationPolicy,
// figure out how many new values need to be generated synchronously
if (val == null) {
// Synchronous call to get remaining values
int numToFill = 0;
switch (policy) {
case ATLEAST_ONE:
numToFill = (ekvs.size() < 1) ? 1 : 0;
break;
case LOW_WATERMARK:
numToFill =
Math.min(num, (int) (lowWatermark * numValues)) - ekvs.size();
break;
case ALL:
numToFill = num - ekvs.size();
break;
}
// Synchronous fill if not enough values found
if (numToFill > 0) {
refiller.fillQueueForKey(keyName, ekvs, numToFill);
}
// Asynch task to fill > lowWatermark
if (i <= (int) (lowWatermark * numValues)) {
submitRefillTask(keyName, keyQueue);
}
return ekvs;
}
ekvs.add(val);
}
} catch (Exception e) {
throw new IOException("Exeption while contacting value generator ", e);
}
return ekvs;
}
private void submitRefillTask(final String keyName,
final Queue<E> keyQueue) throws InterruptedException {
if (!executorThreadsStarted) {
synchronized (this) {
// To ensure all requests are first queued, make coreThreads =
// maxThreads
// and pre-start all the Core Threads.
executor.prestartAllCoreThreads();
executorThreadsStarted = true;
}
}
// The submit/execute method of the ThreadPoolExecutor is bypassed and
// the Runnable is directly put in the backing BlockingQueue so that we
// can control exactly how the runnable is inserted into the queue.
queue.put(
new NamedRunnable(keyName) {
@Override
public void run() {
int cacheSize = numValues;
int threshold = (int) (lowWatermark * (float) cacheSize);
// Need to ensure that only one refill task per key is executed
try {
if (keyQueue.size() < threshold) {
refiller.fillQueueForKey(name, keyQueue,
cacheSize - keyQueue.size());
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
}
);
}
/**
* Cleanly shutdown
*/
public void shutdown() {
executor.shutdownNow();
}
}
| bruthe/hadoop-2.6.0r | src/common/org/apache/hadoop/crypto/key/kms/ValueQueue.java | Java | apache-2.0 | 12,143 |
package version
// 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.
// Number contains the semantic version of this SDK.
const Number = "v40.2.0"
| sethpollack/kubernetes | vendor/github.com/Azure/azure-sdk-for-go/version/version.go | GO | apache-2.0 | 865 |
/*
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 fake
import (
api "k8s.io/kubernetes/pkg/api"
unversioned "k8s.io/kubernetes/pkg/api/unversioned"
v1 "k8s.io/kubernetes/pkg/api/v1"
v1alpha1 "k8s.io/kubernetes/pkg/apis/rbac/v1alpha1"
core "k8s.io/kubernetes/pkg/client/testing/core"
labels "k8s.io/kubernetes/pkg/labels"
watch "k8s.io/kubernetes/pkg/watch"
)
// FakeClusterRoleBindings implements ClusterRoleBindingInterface
type FakeClusterRoleBindings struct {
Fake *FakeRbacV1alpha1
}
var clusterrolebindingsResource = unversioned.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1alpha1", Resource: "clusterrolebindings"}
func (c *FakeClusterRoleBindings) Create(clusterRoleBinding *v1alpha1.ClusterRoleBinding) (result *v1alpha1.ClusterRoleBinding, err error) {
obj, err := c.Fake.
Invokes(core.NewRootCreateAction(clusterrolebindingsResource, clusterRoleBinding), &v1alpha1.ClusterRoleBinding{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha1.ClusterRoleBinding), err
}
func (c *FakeClusterRoleBindings) Update(clusterRoleBinding *v1alpha1.ClusterRoleBinding) (result *v1alpha1.ClusterRoleBinding, err error) {
obj, err := c.Fake.
Invokes(core.NewRootUpdateAction(clusterrolebindingsResource, clusterRoleBinding), &v1alpha1.ClusterRoleBinding{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha1.ClusterRoleBinding), err
}
func (c *FakeClusterRoleBindings) Delete(name string, options *v1.DeleteOptions) error {
_, err := c.Fake.
Invokes(core.NewRootDeleteAction(clusterrolebindingsResource, name), &v1alpha1.ClusterRoleBinding{})
return err
}
func (c *FakeClusterRoleBindings) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
action := core.NewRootDeleteCollectionAction(clusterrolebindingsResource, listOptions)
_, err := c.Fake.Invokes(action, &v1alpha1.ClusterRoleBindingList{})
return err
}
func (c *FakeClusterRoleBindings) Get(name string) (result *v1alpha1.ClusterRoleBinding, err error) {
obj, err := c.Fake.
Invokes(core.NewRootGetAction(clusterrolebindingsResource, name), &v1alpha1.ClusterRoleBinding{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha1.ClusterRoleBinding), err
}
func (c *FakeClusterRoleBindings) List(opts v1.ListOptions) (result *v1alpha1.ClusterRoleBindingList, err error) {
obj, err := c.Fake.
Invokes(core.NewRootListAction(clusterrolebindingsResource, opts), &v1alpha1.ClusterRoleBindingList{})
if obj == nil {
return nil, err
}
label, _, _ := core.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
list := &v1alpha1.ClusterRoleBindingList{}
for _, item := range obj.(*v1alpha1.ClusterRoleBindingList).Items {
if label.Matches(labels.Set(item.Labels)) {
list.Items = append(list.Items, item)
}
}
return list, err
}
// Watch returns a watch.Interface that watches the requested clusterRoleBindings.
func (c *FakeClusterRoleBindings) Watch(opts v1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(core.NewRootWatchAction(clusterrolebindingsResource, opts))
}
// Patch applies the patch and returns the patched clusterRoleBinding.
func (c *FakeClusterRoleBindings) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterRoleBinding, err error) {
obj, err := c.Fake.
Invokes(core.NewRootPatchSubresourceAction(clusterrolebindingsResource, name, data, subresources...), &v1alpha1.ClusterRoleBinding{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha1.ClusterRoleBinding), err
}
| github-co/kubernetes | pkg/client/clientset_generated/release_1_5/typed/rbac/v1alpha1/fake/fake_clusterrolebinding.go | GO | apache-2.0 | 4,098 |
package datastore
import (
"fmt"
"log"
"reflect"
"strings"
"sync"
"time"
"github.com/docker/docker/libnetwork/discoverapi"
"github.com/docker/docker/libnetwork/types"
"github.com/docker/libkv"
"github.com/docker/libkv/store"
)
//DataStore exported
type DataStore interface {
// GetObject gets data from datastore and unmarshals to the specified object
GetObject(key string, o KVObject) error
// PutObject adds a new Record based on an object into the datastore
PutObject(kvObject KVObject) error
// PutObjectAtomic provides an atomic add and update operation for a Record
PutObjectAtomic(kvObject KVObject) error
// DeleteObject deletes a record
DeleteObject(kvObject KVObject) error
// DeleteObjectAtomic performs an atomic delete operation
DeleteObjectAtomic(kvObject KVObject) error
// DeleteTree deletes a record
DeleteTree(kvObject KVObject) error
// Watchable returns whether the store is watchable or not
Watchable() bool
// Watch for changes on a KVObject
Watch(kvObject KVObject, stopCh <-chan struct{}) (<-chan KVObject, error)
// RestartWatch retriggers stopped Watches
RestartWatch()
// Active returns if the store is active
Active() bool
// List returns of a list of KVObjects belonging to the parent
// key. The caller must pass a KVObject of the same type as
// the objects that need to be listed
List(string, KVObject) ([]KVObject, error)
// Map returns a Map of KVObjects
Map(key string, kvObject KVObject) (map[string]KVObject, error)
// Scope returns the scope of the store
Scope() string
// KVStore returns access to the KV Store
KVStore() store.Store
// Close closes the data store
Close()
}
// ErrKeyModified is raised for an atomic update when the update is working on a stale state
var (
ErrKeyModified = store.ErrKeyModified
ErrKeyNotFound = store.ErrKeyNotFound
)
type datastore struct {
scope string
store store.Store
cache *cache
watchCh chan struct{}
active bool
sequential bool
sync.Mutex
}
// KVObject is Key/Value interface used by objects to be part of the DataStore
type KVObject interface {
// Key method lets an object provide the Key to be used in KV Store
Key() []string
// KeyPrefix method lets an object return immediate parent key that can be used for tree walk
KeyPrefix() []string
// Value method lets an object marshal its content to be stored in the KV store
Value() []byte
// SetValue is used by the datastore to set the object's value when loaded from the data store.
SetValue([]byte) error
// Index method returns the latest DB Index as seen by the object
Index() uint64
// SetIndex method allows the datastore to store the latest DB Index into the object
SetIndex(uint64)
// True if the object exists in the datastore, false if it hasn't been stored yet.
// When SetIndex() is called, the object has been stored.
Exists() bool
// DataScope indicates the storage scope of the KV object
DataScope() string
// Skip provides a way for a KV Object to avoid persisting it in the KV Store
Skip() bool
}
// KVConstructor interface defines methods which can construct a KVObject from another.
type KVConstructor interface {
// New returns a new object which is created based on the
// source object
New() KVObject
// CopyTo deep copies the contents of the implementing object
// to the passed destination object
CopyTo(KVObject) error
}
// ScopeCfg represents Datastore configuration.
type ScopeCfg struct {
Client ScopeClientCfg
}
// ScopeClientCfg represents Datastore Client-only mode configuration
type ScopeClientCfg struct {
Provider string
Address string
Config *store.Config
}
const (
// LocalScope indicates to store the KV object in local datastore such as boltdb
LocalScope = "local"
// GlobalScope indicates to store the KV object in global datastore such as consul/etcd/zookeeper
GlobalScope = "global"
// SwarmScope is not indicating a datastore location. It is defined here
// along with the other two scopes just for consistency.
SwarmScope = "swarm"
defaultPrefix = "/var/lib/docker/network/files"
)
const (
// NetworkKeyPrefix is the prefix for network key in the kv store
NetworkKeyPrefix = "network"
// EndpointKeyPrefix is the prefix for endpoint key in the kv store
EndpointKeyPrefix = "endpoint"
)
var (
defaultScopes = makeDefaultScopes()
)
func makeDefaultScopes() map[string]*ScopeCfg {
def := make(map[string]*ScopeCfg)
def[LocalScope] = &ScopeCfg{
Client: ScopeClientCfg{
Provider: string(store.BOLTDB),
Address: defaultPrefix + "/local-kv.db",
Config: &store.Config{
Bucket: "libnetwork",
ConnectionTimeout: time.Minute,
},
},
}
return def
}
var defaultRootChain = []string{"docker", "network", "v1.0"}
var rootChain = defaultRootChain
// DefaultScopes returns a map of default scopes and its config for clients to use.
func DefaultScopes(dataDir string) map[string]*ScopeCfg {
if dataDir != "" {
defaultScopes[LocalScope].Client.Address = dataDir + "/network/files/local-kv.db"
return defaultScopes
}
defaultScopes[LocalScope].Client.Address = defaultPrefix + "/local-kv.db"
return defaultScopes
}
// IsValid checks if the scope config has valid configuration.
func (cfg *ScopeCfg) IsValid() bool {
if cfg == nil ||
strings.TrimSpace(cfg.Client.Provider) == "" ||
strings.TrimSpace(cfg.Client.Address) == "" {
return false
}
return true
}
//Key provides convenient method to create a Key
func Key(key ...string) string {
keychain := append(rootChain, key...)
str := strings.Join(keychain, "/")
return str + "/"
}
//ParseKey provides convenient method to unpack the key to complement the Key function
func ParseKey(key string) ([]string, error) {
chain := strings.Split(strings.Trim(key, "/"), "/")
// The key must at least be equal to the rootChain in order to be considered as valid
if len(chain) <= len(rootChain) || !reflect.DeepEqual(chain[0:len(rootChain)], rootChain) {
return nil, types.BadRequestErrorf("invalid Key : %s", key)
}
return chain[len(rootChain):], nil
}
// newClient used to connect to KV Store
func newClient(scope string, kv string, addr string, config *store.Config, cached bool) (DataStore, error) {
if cached && scope != LocalScope {
return nil, fmt.Errorf("caching supported only for scope %s", LocalScope)
}
sequential := false
if scope == LocalScope {
sequential = true
}
if config == nil {
config = &store.Config{}
}
var addrs []string
if kv == string(store.BOLTDB) {
// Parse file path
addrs = strings.Split(addr, ",")
} else {
// Parse URI
parts := strings.SplitN(addr, "/", 2)
addrs = strings.Split(parts[0], ",")
// Add the custom prefix to the root chain
if len(parts) == 2 {
rootChain = append([]string{parts[1]}, defaultRootChain...)
}
}
store, err := libkv.NewStore(store.Backend(kv), addrs, config)
if err != nil {
return nil, err
}
ds := &datastore{scope: scope, store: store, active: true, watchCh: make(chan struct{}), sequential: sequential}
if cached {
ds.cache = newCache(ds)
}
return ds, nil
}
// NewDataStore creates a new instance of LibKV data store
func NewDataStore(scope string, cfg *ScopeCfg) (DataStore, error) {
if cfg == nil || cfg.Client.Provider == "" || cfg.Client.Address == "" {
c, ok := defaultScopes[scope]
if !ok || c.Client.Provider == "" || c.Client.Address == "" {
return nil, fmt.Errorf("unexpected scope %s without configuration passed", scope)
}
cfg = c
}
var cached bool
if scope == LocalScope {
cached = true
}
return newClient(scope, cfg.Client.Provider, cfg.Client.Address, cfg.Client.Config, cached)
}
// NewDataStoreFromConfig creates a new instance of LibKV data store starting from the datastore config data
func NewDataStoreFromConfig(dsc discoverapi.DatastoreConfigData) (DataStore, error) {
var (
ok bool
sCfgP *store.Config
)
sCfgP, ok = dsc.Config.(*store.Config)
if !ok && dsc.Config != nil {
return nil, fmt.Errorf("cannot parse store configuration: %v", dsc.Config)
}
scopeCfg := &ScopeCfg{
Client: ScopeClientCfg{
Address: dsc.Address,
Provider: dsc.Provider,
Config: sCfgP,
},
}
ds, err := NewDataStore(dsc.Scope, scopeCfg)
if err != nil {
return nil, fmt.Errorf("failed to construct datastore client from datastore configuration %v: %v", dsc, err)
}
return ds, err
}
func (ds *datastore) Close() {
ds.store.Close()
}
func (ds *datastore) Scope() string {
return ds.scope
}
func (ds *datastore) Active() bool {
return ds.active
}
func (ds *datastore) Watchable() bool {
return ds.scope != LocalScope
}
func (ds *datastore) Watch(kvObject KVObject, stopCh <-chan struct{}) (<-chan KVObject, error) {
sCh := make(chan struct{})
ctor, ok := kvObject.(KVConstructor)
if !ok {
return nil, fmt.Errorf("error watching object type %T, object does not implement KVConstructor interface", kvObject)
}
kvpCh, err := ds.store.Watch(Key(kvObject.Key()...), sCh)
if err != nil {
return nil, err
}
kvoCh := make(chan KVObject)
go func() {
retry_watch:
var err error
// Make sure to get a new instance of watch channel
ds.Lock()
watchCh := ds.watchCh
ds.Unlock()
loop:
for {
select {
case <-stopCh:
close(sCh)
return
case kvPair := <-kvpCh:
// If the backend KV store gets reset libkv's go routine
// for the watch can exit resulting in a nil value in
// channel.
if kvPair == nil {
ds.Lock()
ds.active = false
ds.Unlock()
break loop
}
dstO := ctor.New()
if err = dstO.SetValue(kvPair.Value); err != nil {
log.Printf("Could not unmarshal kvpair value = %s", string(kvPair.Value))
break
}
dstO.SetIndex(kvPair.LastIndex)
kvoCh <- dstO
}
}
// Wait on watch channel for a re-trigger when datastore becomes active
<-watchCh
kvpCh, err = ds.store.Watch(Key(kvObject.Key()...), sCh)
if err != nil {
log.Printf("Could not watch the key %s in store: %v", Key(kvObject.Key()...), err)
}
goto retry_watch
}()
return kvoCh, nil
}
func (ds *datastore) RestartWatch() {
ds.Lock()
defer ds.Unlock()
ds.active = true
watchCh := ds.watchCh
ds.watchCh = make(chan struct{})
close(watchCh)
}
func (ds *datastore) KVStore() store.Store {
return ds.store
}
// PutObjectAtomic adds a new Record based on an object into the datastore
func (ds *datastore) PutObjectAtomic(kvObject KVObject) error {
var (
previous *store.KVPair
pair *store.KVPair
err error
)
if ds.sequential {
ds.Lock()
defer ds.Unlock()
}
if kvObject == nil {
return types.BadRequestErrorf("invalid KV Object : nil")
}
kvObjValue := kvObject.Value()
if kvObjValue == nil {
return types.BadRequestErrorf("invalid KV Object with a nil Value for key %s", Key(kvObject.Key()...))
}
if kvObject.Skip() {
goto add_cache
}
if kvObject.Exists() {
previous = &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()}
} else {
previous = nil
}
_, pair, err = ds.store.AtomicPut(Key(kvObject.Key()...), kvObjValue, previous, nil)
if err != nil {
if err == store.ErrKeyExists {
return ErrKeyModified
}
return err
}
kvObject.SetIndex(pair.LastIndex)
add_cache:
if ds.cache != nil {
// If persistent store is skipped, sequencing needs to
// happen in cache.
return ds.cache.add(kvObject, kvObject.Skip())
}
return nil
}
// PutObject adds a new Record based on an object into the datastore
func (ds *datastore) PutObject(kvObject KVObject) error {
if ds.sequential {
ds.Lock()
defer ds.Unlock()
}
if kvObject == nil {
return types.BadRequestErrorf("invalid KV Object : nil")
}
if kvObject.Skip() {
goto add_cache
}
if err := ds.putObjectWithKey(kvObject, kvObject.Key()...); err != nil {
return err
}
add_cache:
if ds.cache != nil {
// If persistent store is skipped, sequencing needs to
// happen in cache.
return ds.cache.add(kvObject, kvObject.Skip())
}
return nil
}
func (ds *datastore) putObjectWithKey(kvObject KVObject, key ...string) error {
kvObjValue := kvObject.Value()
if kvObjValue == nil {
return types.BadRequestErrorf("invalid KV Object with a nil Value for key %s", Key(kvObject.Key()...))
}
return ds.store.Put(Key(key...), kvObjValue, nil)
}
// GetObject returns a record matching the key
func (ds *datastore) GetObject(key string, o KVObject) error {
if ds.sequential {
ds.Lock()
defer ds.Unlock()
}
if ds.cache != nil {
return ds.cache.get(key, o)
}
kvPair, err := ds.store.Get(key)
if err != nil {
return err
}
if err := o.SetValue(kvPair.Value); err != nil {
return err
}
// Make sure the object has a correct view of the DB index in
// case we need to modify it and update the DB.
o.SetIndex(kvPair.LastIndex)
return nil
}
func (ds *datastore) ensureParent(parent string) error {
exists, err := ds.store.Exists(parent)
if err != nil {
return err
}
if exists {
return nil
}
return ds.store.Put(parent, []byte{}, &store.WriteOptions{IsDir: true})
}
func (ds *datastore) List(key string, kvObject KVObject) ([]KVObject, error) {
if ds.sequential {
ds.Lock()
defer ds.Unlock()
}
if ds.cache != nil {
return ds.cache.list(kvObject)
}
var kvol []KVObject
cb := func(key string, val KVObject) {
kvol = append(kvol, val)
}
err := ds.iterateKVPairsFromStore(key, kvObject, cb)
if err != nil {
return nil, err
}
return kvol, nil
}
func (ds *datastore) iterateKVPairsFromStore(key string, kvObject KVObject, callback func(string, KVObject)) error {
// Bail out right away if the kvObject does not implement KVConstructor
ctor, ok := kvObject.(KVConstructor)
if !ok {
return fmt.Errorf("error listing objects, object does not implement KVConstructor interface")
}
// Make sure the parent key exists
if err := ds.ensureParent(key); err != nil {
return err
}
kvList, err := ds.store.List(key)
if err != nil {
return err
}
for _, kvPair := range kvList {
if len(kvPair.Value) == 0 {
continue
}
dstO := ctor.New()
if err := dstO.SetValue(kvPair.Value); err != nil {
return err
}
// Make sure the object has a correct view of the DB index in
// case we need to modify it and update the DB.
dstO.SetIndex(kvPair.LastIndex)
callback(kvPair.Key, dstO)
}
return nil
}
func (ds *datastore) Map(key string, kvObject KVObject) (map[string]KVObject, error) {
if ds.sequential {
ds.Lock()
defer ds.Unlock()
}
kvol := make(map[string]KVObject)
cb := func(key string, val KVObject) {
// Trim the leading & trailing "/" to make it consistent across all stores
kvol[strings.Trim(key, "/")] = val
}
err := ds.iterateKVPairsFromStore(key, kvObject, cb)
if err != nil {
return nil, err
}
return kvol, nil
}
// DeleteObject unconditionally deletes a record from the store
func (ds *datastore) DeleteObject(kvObject KVObject) error {
if ds.sequential {
ds.Lock()
defer ds.Unlock()
}
// cleanup the cache first
if ds.cache != nil {
// If persistent store is skipped, sequencing needs to
// happen in cache.
ds.cache.del(kvObject, kvObject.Skip())
}
if kvObject.Skip() {
return nil
}
return ds.store.Delete(Key(kvObject.Key()...))
}
// DeleteObjectAtomic performs atomic delete on a record
func (ds *datastore) DeleteObjectAtomic(kvObject KVObject) error {
if ds.sequential {
ds.Lock()
defer ds.Unlock()
}
if kvObject == nil {
return types.BadRequestErrorf("invalid KV Object : nil")
}
previous := &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()}
if kvObject.Skip() {
goto del_cache
}
if _, err := ds.store.AtomicDelete(Key(kvObject.Key()...), previous); err != nil {
if err == store.ErrKeyExists {
return ErrKeyModified
}
return err
}
del_cache:
// cleanup the cache only if AtomicDelete went through successfully
if ds.cache != nil {
// If persistent store is skipped, sequencing needs to
// happen in cache.
return ds.cache.del(kvObject, kvObject.Skip())
}
return nil
}
// DeleteTree unconditionally deletes a record from the store
func (ds *datastore) DeleteTree(kvObject KVObject) error {
if ds.sequential {
ds.Lock()
defer ds.Unlock()
}
// cleanup the cache first
if ds.cache != nil {
// If persistent store is skipped, sequencing needs to
// happen in cache.
ds.cache.del(kvObject, kvObject.Skip())
}
if kvObject.Skip() {
return nil
}
return ds.store.DeleteTree(Key(kvObject.KeyPrefix()...))
}
| jthelin/docker | libnetwork/datastore/datastore.go | GO | apache-2.0 | 16,439 |
// Copyright 2013 The Go Circuit Project
// Use of this source code is governed by the license for
// The Go Circuit Project, found in the LICENSE file.
//
// Authors:
// 2013 Petar Maymounkov <p@gocircuit.org>
package tele
import (
"github.com/gocircuit/circuit/kit/tele/blend"
"github.com/gocircuit/circuit/use/n"
)
type Conn struct {
addr *Addr
sub *blend.Conn
}
func NewConn(sub *blend.Conn, addr *Addr) *Conn {
return &Conn{addr: addr, sub: sub}
}
func (c *Conn) Read() (v interface{}, err error) {
if v, err = c.sub.Read(); err != nil {
return nil, err
}
return
}
func (c *Conn) Write(v interface{}) (err error) {
if err = c.sub.Write(v); err != nil {
return err
}
return nil
}
func (c *Conn) Close() error {
return c.sub.Close()
}
func (c *Conn) Abort(reason error) {
c.sub.Abort(reason)
}
func (c *Conn) Addr() n.Addr {
return c.addr
}
| bzz/circuit | sys/tele/conn.go | GO | apache-2.0 | 874 |
/* Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/kernels/fuzzing/fuzz_session.h"
namespace tensorflow {
namespace fuzzing {
// Fuzz inputs to the example proto decoder.
// TODO(dga): Make this more comprehensive.
// Right now, it's just a quick PoC to show how to attach the
// plumbing, but it needs some real protos to chew on as a
// corpus, and the sparse/dense parts should be made more rich
// to achieve higher code coverage.
class FuzzExampleProtoFastParsing : public FuzzSession {
void BuildGraph(const Scope& scope) final {
using namespace ::tensorflow::ops; // NOLINT(build/namespaces)
// The serialized proto.
auto input = Placeholder(scope.WithOpName("input"), DT_STRING);
auto in_expanded = ExpandDims(scope, input, Const<int>(scope, 0));
auto names = Const(scope, {"noname"});
std::vector<Output> dense_keys = {Const(scope, {"a"})};
std::vector<Output> sparse_keys; // Empty.
std::vector<Output> dense_defaults = {Const(scope, {1.0f})};
DataTypeSlice sparse_types = {};
std::vector<PartialTensorShape> dense_shapes;
dense_shapes.push_back(PartialTensorShape());
(void)ParseExample(scope.WithOpName("output"), in_expanded, names,
sparse_keys, dense_keys, dense_defaults, sparse_types,
dense_shapes);
}
void FuzzImpl(const uint8_t* data, size_t size) final {
// TODO(dga): Test the batch case also.
Tensor input_tensor(tensorflow::DT_STRING, TensorShape({}));
input_tensor.scalar<string>()() =
string(reinterpret_cast<const char*>(data), size);
RunInputs({{"input", input_tensor}});
}
};
STANDARD_TF_FUZZ_FUNCTION(FuzzExampleProtoFastParsing);
} // end namespace fuzzing
} // end namespace tensorflow
| ghchinoy/tensorflow | tensorflow/core/kernels/fuzzing/example_proto_fast_parsing_fuzz.cc | C++ | apache-2.0 | 2,435 |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.core.database.map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.core.database.Database;
import org.pentaho.di.core.database.DatabaseTransactionListener;
/**
* This class contains a map between on the one hand
* <p/>
* the transformation name/thread the partition ID the connection group
* <p/>
* And on the other hand
* <p/>
* The database connection The number of times it was opened
*
* @author Matt
*/
public class DatabaseConnectionMap {
private final ConcurrentMap<String, Database> map;
private final AtomicInteger transactionId;
private final Map<String, List<DatabaseTransactionListener>> transactionListenersMap;
private static final DatabaseConnectionMap connectionMap = new DatabaseConnectionMap();
public static synchronized DatabaseConnectionMap getInstance() {
return connectionMap;
}
private DatabaseConnectionMap() {
map = new ConcurrentHashMap<String, Database>();
transactionId = new AtomicInteger( 0 );
transactionListenersMap = new HashMap<String, List<DatabaseTransactionListener>>();
}
/**
* Tries to obtain an existing <tt>Database</tt> instance for specified parameters. If none is found, then maps the
* key's value to <tt>database</tt>. Similarly to {@linkplain ConcurrentHashMap#putIfAbsent(Object, Object)} returns
* <tt>null</tt> if there was no value for the specified key and they mapped value otherwise.
*
* @param connectionGroup connection group
* @param partitionID partition's id
* @param database database
* @return <tt>null</tt> or previous value
*/
public Database getOrStoreIfAbsent( String connectionGroup, String partitionID, Database database ) {
String key = createEntryKey( connectionGroup, partitionID, database );
return map.putIfAbsent( key, database );
}
public void removeConnection( String connectionGroup, String partitionID, Database database ) {
String key = createEntryKey( connectionGroup, partitionID, database );
map.remove( key );
}
/**
* @deprecated use {@linkplain #getOrStoreIfAbsent(String, String, Database)} instead
*/
@Deprecated
public synchronized void storeDatabase( String connectionGroup, String partitionID, Database database ) {
String key = createEntryKey( connectionGroup, partitionID, database );
map.put( key, database );
}
/**
* @deprecated use {@linkplain #getOrStoreIfAbsent(String, String, Database)} instead
*/
@Deprecated
public synchronized Database getDatabase( String connectionGroup, String partitionID, Database database ) {
String key = createEntryKey( connectionGroup, partitionID, database );
return map.get( key );
}
public static String createEntryKey( String connectionGroup, String partitionID, Database database ) {
StringBuilder key = new StringBuilder( connectionGroup );
key.append( ':' ).append( database.getDatabaseMeta().getName() );
if ( !Utils.isEmpty( partitionID ) ) {
key.append( ':' ).append( partitionID );
}
return key.toString();
}
public Map<String, Database> getMap() {
return map;
}
public String getNextTransactionId() {
return Integer.toString( transactionId.incrementAndGet() );
}
public void addTransactionListener( String transactionId, DatabaseTransactionListener listener ) {
List<DatabaseTransactionListener> transactionListeners = getTransactionListeners( transactionId );
transactionListeners.add( listener );
}
public void removeTransactionListener( String transactionId, DatabaseTransactionListener listener ) {
List<DatabaseTransactionListener> transactionListeners = getTransactionListeners( transactionId );
transactionListeners.remove( listener );
}
public List<DatabaseTransactionListener> getTransactionListeners( String transactionId ) {
List<DatabaseTransactionListener> transactionListeners = transactionListenersMap.get( transactionId );
if ( transactionListeners == null ) {
transactionListeners = new ArrayList<DatabaseTransactionListener>();
transactionListenersMap.put( transactionId, transactionListeners );
}
return transactionListeners;
}
public void removeTransactionListeners( String transactionId ) {
transactionListenersMap.remove( transactionId );
}
}
| emartin-pentaho/pentaho-kettle | core/src/main/java/org/pentaho/di/core/database/map/DatabaseConnectionMap.java | Java | apache-2.0 | 5,471 |
//
// 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
namespace Microsoft.Azure.Management.HDInsight.Models
{
/// <summary>
/// The directory type.
/// </summary>
public enum DirectoryType
{
/// <summary>
/// active directory type.
/// </summary>
ActiveDirectory = 1,
}
}
| nemanja88/azure-sdk-for-net | src/ResourceManagement/HDInsight/HDInsight/Generated/Models/DirectoryType.cs | C# | apache-2.0 | 1,096 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony;
/**
* WapPushManager constant value definitions
*/
public class WapPushManagerParams {
/**
* Application type activity
*/
public static final int APP_TYPE_ACTIVITY = 0;
/**
* Application type service
*/
public static final int APP_TYPE_SERVICE = 1;
/**
* Process Message return value
* Message is handled
*/
public static final int MESSAGE_HANDLED = 0x1;
/**
* Process Message return value
* Application ID or content type was not found in the application ID table
*/
public static final int APP_QUERY_FAILED = 0x2;
/**
* Process Message return value
* Receiver application signature check failed
*/
public static final int SIGNATURE_NO_MATCH = 0x4;
/**
* Process Message return value
* Receiver application was not found
*/
public static final int INVALID_RECEIVER_NAME = 0x8;
/**
* Process Message return value
* Unknown exception
*/
public static final int EXCEPTION_CAUGHT = 0x10;
/**
* Process Message return value
* Need further processing after WapPushManager message processing
*/
public static final int FURTHER_PROCESSING = 0x8000;
}
| JSDemos/android-sdk-20 | src/com/android/internal/telephony/WapPushManagerParams.java | Java | apache-2.0 | 1,891 |
require 'test_helper'
class TraceSummariesHelperTest < ActionView::TestCase
end
| rodzyn0688/zipkin | zipkin-web/test/unit/helpers/trace_summaries_helper_test.rb | Ruby | apache-2.0 | 81 |
/*
* Copyright 2015 LG CNS.
*
* 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 scouter.client.maria.views;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.TreeColumnLayout;
import org.eclipse.jface.viewers.ColumnPixelData;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;
import scouter.client.Images;
import scouter.client.model.AgentDailyListProxy;
import scouter.client.model.DigestModel;
import scouter.client.model.RefreshThread;
import scouter.client.model.RefreshThread.Refreshable;
import scouter.client.model.TextProxy;
import scouter.client.net.INetReader;
import scouter.client.net.TcpProxy;
import scouter.client.popup.DigestDetailDialog;
import scouter.client.sorter.TreeLabelSorter;
import scouter.client.util.ConsoleProxy;
import scouter.client.util.ExUtil;
import scouter.client.util.ImageUtil;
import scouter.client.util.TimeUtil;
import scouter.io.DataInputX;
import scouter.lang.DigestKey;
import scouter.lang.counters.CounterConstants;
import scouter.lang.pack.MapPack;
import scouter.lang.pack.Pack;
import scouter.lang.pack.PackEnum;
import scouter.lang.pack.StatusPack;
import scouter.lang.value.ListValue;
import scouter.lang.value.MapValue;
import scouter.net.RequestCmd;
import scouter.util.CastUtil;
import scouter.util.DateUtil;
import scouter.util.FormatUtil;
public class DigestTableView extends ViewPart implements Refreshable {
public final static String ID = DigestTableView.class.getName();
double PICO = Math.pow(10, -12);
int serverId;
Composite parent;
TreeViewer viewer;
TreeColumnLayout columnLayout;
AgentDailyListProxy agentProxy = new AgentDailyListProxy();
RefreshThread thread;
boolean isAutoRefresh = false;
String date;
long stime, etime;
HashMap<Integer, DigestModel> root = new HashMap<Integer, DigestModel>();
public void init(IViewSite site) throws PartInitException {
super.init(site);
String secId = site.getSecondaryId();
this.serverId = CastUtil.cint(secId);
}
public void createPartControl(Composite parent) {
this.parent = parent;
GridLayout gridlayout = new GridLayout(1, false);
gridlayout.marginHeight = 0;
gridlayout.horizontalSpacing = 0;
gridlayout.marginWidth = 0;
parent.setLayout(gridlayout);
columnLayout = new TreeColumnLayout();
Composite mainComp = new Composite(parent, SWT.NONE);
mainComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
mainComp.setLayout(columnLayout);
viewer = new TreeViewer(mainComp, SWT.FULL_SELECTION | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
createColumns();
final Tree tree = viewer.getTree();
tree.setHeaderVisible(true);
tree.setLinesVisible(true);
viewer.setLabelProvider(new TreeLabelProvider());
viewer.setContentProvider(new TreeContentProvider());
viewer.setComparator(new TreeLabelSorter(viewer));
viewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
StructuredSelection sel = (StructuredSelection) event.getSelection();
Object o = sel.getFirstElement();
if (o instanceof DigestModel) {
DigestModel model = (DigestModel) o;
new DigestDetailDialog().show(model, stime, etime, serverId);
}
}
});
viewer.setInput(root);
IToolBarManager man = getViewSite().getActionBars().getToolBarManager();
Action actAutoRefresh = new Action("Auto Refresh in 10 sec.", IAction.AS_CHECK_BOX){
public void run() {
isAutoRefresh = isChecked();
if (isAutoRefresh) {
thread.interrupt();
}
}
};
actAutoRefresh.setImageDescriptor(ImageUtil.getImageDescriptor(Images.refresh_auto));
man.add(actAutoRefresh);
long now = TimeUtil.getCurrentTime(serverId);
date = DateUtil.yyyymmdd(now);
stime = now - DateUtil.MILLIS_PER_FIVE_MINUTE;
etime = now;
loadQueryJob.schedule(2000);
thread = new RefreshThread(this, 10000);
thread.start();
}
public void refresh() {
if (isAutoRefresh) {
root.clear();
long now = TimeUtil.getCurrentTime(serverId);
date = DateUtil.yyyymmdd(now);
stime = now - DateUtil.MILLIS_PER_FIVE_MINUTE;
etime = now;
loadQueryJob.schedule();
}
}
public void setInput(long stime, long etime) {
if (loadQueryJob.getState() == Job.WAITING || loadQueryJob.getState() == Job.RUNNING) {
MessageDialog.openInformation(null, "STOP", "Previous loading is not yet finished");
return;
}
if (etime - stime < DateUtil.MILLIS_PER_MINUTE) {
stime = etime - DateUtil.MILLIS_PER_MINUTE;
}
root.clear();
this.stime = stime;
this.etime = etime;
this.date = DateUtil.yyyymmdd(stime);
loadQueryJob.schedule();
}
ArrayList<DigestSchema> columnList = new ArrayList<DigestSchema>();
private void createColumns() {
columnList.clear();
for (DigestSchema column : DigestSchema.values()) {
createTreeViewerColumn(column.getTitle(), column.getWidth(), column.getAlignment(), true, true, column.isNumber());
columnList.add(column);
}
}
private TreeViewerColumn createTreeViewerColumn(String title, int width, int alignment, boolean resizable, boolean moveable, final boolean isNumber) {
final TreeViewerColumn viewerColumn = new TreeViewerColumn(viewer, SWT.NONE);
final TreeColumn column = viewerColumn.getColumn();
column.setText(title);
column.setAlignment(alignment);
column.setMoveable(moveable);
columnLayout.setColumnData(column, new ColumnPixelData(width, resizable));
column.setData("isNumber", isNumber);
column.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
TreeLabelSorter sorter = (TreeLabelSorter) viewer.getComparator();
TreeColumn selectedColumn = (TreeColumn) e.widget;
sorter.setColumn(selectedColumn);
}
});
return viewerColumn;
}
public void setFocus() {
}
Job loadQueryJob = new Job("Load Digest List...") {
HashMap<DigestKey, MapPack> summaryMap = new HashMap<DigestKey, MapPack>();
HashMap<Integer, StatusPack> firstStatusMap = new HashMap<Integer, StatusPack>();
HashMap<Integer, StatusPack> lastStatusMap = new HashMap<Integer, StatusPack>();
protected IStatus run(final IProgressMonitor monitor) {
summaryMap.clear();
firstStatusMap.clear();
lastStatusMap.clear();
monitor.beginTask(DateUtil.hhmmss(stime) + " ~ " + DateUtil.hhmmss(etime), 100);
TcpProxy tcp = TcpProxy.getTcpProxy(serverId);
try {
MapPack param = new MapPack();
ListValue objHashLv = agentProxy.getObjHashLv(date, serverId, CounterConstants.MARIA_PLUGIN);
if (objHashLv.size() > 0) {
param.put("objHash", objHashLv);
param.put("date", date);
param.put("time", stime);
List<Pack> firstList = tcp.process(RequestCmd.DB_LAST_DIGEST_TABLE, param);
for (Pack p : firstList) {
StatusPack s = (StatusPack) p;
firstStatusMap.put(s.objHash, s);
}
param.put("stime", stime);
param.put("etime", etime);
tcp.process(RequestCmd.DB_DIGEST_TABLE, param, new INetReader() {
public void process(DataInputX in) throws IOException {
Pack p = in.readPack();
switch (p.getPackType()) {
case PackEnum.MAP:
MapPack m = (MapPack) p;
if (m.containsKey("percent")) {
monitor.worked(m.getInt("percent"));
} else {
int objHash = m.getInt("objHash");
int digestHash = m.getInt("digestHash");
summaryMap.put(new DigestKey(objHash, digestHash), m);
}
break;
case PackEnum.PERF_STATUS:
StatusPack sp = (StatusPack) p;
lastStatusMap.put(sp.objHash, sp);
break;
}
}
});
}
} catch (Exception e) {
ConsoleProxy.errorSafe(e.toString());
} finally {
TcpProxy.putTcpProxy(tcp);
}
Iterator<Integer> itr = lastStatusMap.keySet().iterator();
while (itr.hasNext()) {
int objHash = itr.next();
StatusPack firstStatus = firstStatusMap.get(objHash);
StatusPack lastStatus = lastStatusMap.get(objHash);
HashMap<Integer, MapValue> firstMap = new HashMap<Integer, MapValue>();
if (firstStatus == null) {
// nothing
} else {
// index first values for delta
MapValue firstData = firstStatus.data;
ListValue firstDigestLv = firstData.getList("DIGEST_TEXT");
for (int i = 0; i < firstDigestLv.size(); i++) {
int digestHash = firstDigestLv.getInt(i);
MapValue valueMap = new MapValue();
Enumeration<String> keys = firstData.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
valueMap.put(key, firstData.getList(key).get(i));
}
firstMap.put(digestHash, valueMap);
}
}
MapValue data = lastStatus.data;
ListValue digestLv = data.getList("DIGEST_TEXT");
ListValue schemaNameLv = data.getList("SCHEMA_NAME");
ListValue executionLv = data.getList("COUNT_STAR");
ListValue timerWaitLv = data.getList("SUM_TIMER_WAIT");
ListValue lockTimeLv = data.getList("SUM_LOCK_TIME");
ListValue errorsLv = data.getList("SUM_ERRORS");
ListValue warnsLv = data.getList("SUM_WARNINGS");
ListValue rowsAffectedLv = data.getList("SUM_ROWS_AFFECTED");
ListValue rowsSentLv = data.getList("SUM_ROWS_SENT");
ListValue rowsExaminedLv = data.getList("SUM_ROWS_EXAMINED");
ListValue createdTmpDiskTablesLv = data.getList("SUM_CREATED_TMP_DISK_TABLES");
ListValue createdTmpTablesLv = data.getList("SUM_CREATED_TMP_TABLES");
ListValue selectFullJoin = data.getList("SUM_SELECT_FULL_JOIN");
ListValue selectFullRangeJoin = data.getList("SUM_SELECT_FULL_RANGE_JOIN");
ListValue selectRangeLv = data.getList("SUM_SELECT_RANGE");
ListValue selectRangeCheckLv = data.getList("SUM_SELECT_RANGE_CHECK");
ListValue selectScanLv = data.getList("SUM_SELECT_SCAN");
ListValue sortMergePassesLv = data.getList("SUM_SORT_MERGE_PASSES");
ListValue sortRangeLv = data.getList("SUM_SORT_RANGE");
ListValue sortRowsLv = data.getList("SUM_SORT_ROWS");
ListValue sortScanLv = data.getList("SUM_SORT_SCAN");
ListValue noIndexUsedLv = data.getList("SUM_NO_INDEX_USED");
ListValue noGoodIndexUsedLv = data.getList("SUM_NO_GOOD_INDEX_USED");
ListValue firstSeenLv = data.getList("FIRST_SEEN");
ListValue lastSeenLv = data.getList("LAST_SEEN");
for (int i = 0; i < digestLv.size(); i++) {
if (lastSeenLv.getLong(i) < stime || lastSeenLv.getLong(i) > etime) {
continue;
}
DigestModel model = new DigestModel();
int digestHash = digestLv.getInt(i);
MapPack m = summaryMap.get(new DigestKey(objHash, digestHash));
if (m == null) continue;
long maxTimerWait = m.getLong("MAX_TIMER_WAIT");
long minTimerWait = m.getLong("MIN_TIMER_WAIT");
long avgTimerWait = m.getLong("AVG_TIMER_WAIT");
int count = m.getInt("count");
model.objHash = objHash;
model.digestHash = digestHash;
model.name = TextProxy.object.getLoadText(date, objHash, serverId);
model.database = TextProxy.maria.getLoadText(date, schemaNameLv.getInt(i), serverId);
model.firstSeen = firstSeenLv.getLong(i);
model.lastSeen = lastSeenLv.getLong(i);
model.avgResponseTime = avgTimerWait / (double) count;
model.minResponseTime = minTimerWait;
model.maxResponseTime = maxTimerWait;
MapValue firstValue = firstMap.get(digestHash);
if (firstValue == null) {
firstValue = new MapValue();
}
model.execution = executionLv.getInt(i) - firstValue.getInt("COUNT_STAR");
if (model.execution < 1) {
System.out.println("first=>" + firstStatus);
System.out.println("last =>" + firstStatus);
}
model.errorCnt = errorsLv.getInt(i) - firstValue.getInt("SUM_ERRORS");
model.warnCnt = warnsLv.getInt(i) - firstValue.getInt("SUM_WARNINGS");
model.sumResponseTime = timerWaitLv.getLong(i) - firstValue.getLong("SUM_TIMER_WAIT");
model.lockTime = lockTimeLv.getLong(i) - firstValue.getLong("SUM_LOCK_TIME");
model.rowsAffected = rowsAffectedLv.getLong(i) - firstValue.getLong("SUM_ROWS_AFFECTED");
model.rowsSent = rowsSentLv.getLong(i) - firstValue.getLong("SUM_ROWS_SENT");
model.rowsExamined = rowsExaminedLv.getLong(i) - firstValue.getLong("SUM_ROWS_EXAMINED");
model.createdTmpDiskTables = createdTmpDiskTablesLv.getLong(i) - firstValue.getLong("SUM_CREATED_TMP_DISK_TABLES");
model.createdTmpTables = createdTmpTablesLv.getLong(i) - firstValue.getLong("SUM_CREATED_TMP_TABLES");
model.selectFullJoin = selectFullJoin.getLong(i) - firstValue.getLong("SUM_SELECT_FULL_JOIN");
model.selectFullRangeJoin = selectFullRangeJoin.getLong(i) - firstValue.getLong("SUM_SELECT_FULL_RANGE_JOIN");
model.selectRange = selectRangeLv.getLong(i) - firstValue.getLong("SUM_SELECT_RANGE");
model.selectRangeCheck = selectRangeCheckLv.getLong(i) - firstValue.getLong("SUM_SELECT_RANGE_CHECK");
model.selectScan = selectScanLv.getLong(i) - firstValue.getLong("SUM_SELECT_SCAN");
model.sortMergePasses = sortMergePassesLv.getLong(i) - firstValue.getLong("SUM_SORT_MERGE_PASSES");
model.sortRange =sortRangeLv.getLong(i) - firstValue.getLong("SUM_SORT_RANGE");
model.sortRows = sortRowsLv.getLong(i) - firstValue.getLong("SUM_SORT_ROWS");
model.sortScan = sortScanLv.getLong(i) - firstValue.getLong("SUM_SORT_SCAN");
model.noIndexUsed = noIndexUsedLv.getLong(i) - firstValue.getLong("SUM_NO_INDEX_USED");
model.noGoodIndexUsed = noGoodIndexUsedLv.getLong(i) - firstValue.getLong("SUM_NO_GOOD_INDEX_USED");
DigestModel parent = root.get(digestHash);
if (parent == null) {
parent = new DigestModel();
parent.digestHash = digestHash;
String digestTxt = TextProxy.maria.getLoadText(date, digestHash, serverId);
parent.name = digestTxt == null ? "unknown hash" : digestTxt;
root.put(digestHash, parent);
}
model.parent = parent;
parent.addChild(model);
}
}
Iterator<DigestModel> parents = root.values().iterator();
while (parents.hasNext()) {
DigestModel parent = parents.next();
DigestModel[] childs = parent.getChildArray();
if (childs != null) {
double sumAvg = 0.0d;
for (DigestModel child : childs) {
sumAvg += child.avgResponseTime;
}
parent.avgResponseTime = sumAvg / childs.length;
}
}
monitor.done();
ExUtil.exec(viewer.getTree(), new Runnable() {
public void run() {
DigestTableView.this.setContentDescription(DateUtil.format(stime, "MM-dd HH:mm:ss") + " ~ " + DateUtil.format(etime, "MM-dd HH:mm:ss") + " (" + root.size() + ")");
viewer.refresh();
}
});
return Status.OK_STATUS;
}
};
class TreeContentProvider implements ITreeContentProvider {
public void dispose() {
}
public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
}
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof DigestModel) {
DigestModel parent = (DigestModel) parentElement;
Object[] array = parent.getChildArray();
if(array != null) return array;
}
return new Object[0];
}
public Object[] getElements(Object inputElement) {
if (inputElement instanceof HashMap) {
HashMap map = (HashMap) inputElement;
Object[] objArray = new Object[map.size()];
Iterator itr = map.values().iterator();
int cnt = 0;
while (itr.hasNext()) {
objArray[cnt] = itr.next();
cnt++;
}
return objArray;
}
return new Object[0];
}
public Object getParent(Object element) {
if (element instanceof DigestModel) {
return ((DigestModel) element).parent;
}
return null;
}
public boolean hasChildren(Object element) {
if (element instanceof DigestModel) {
return ((DigestModel) element).getChildArray() != null;
}
return false;
}
}
class TreeLabelProvider implements ITableLabelProvider {
public void addListener(ILabelProviderListener listener) {
}
public void dispose() {
}
public boolean isLabelProperty(Object element, String property) {
return false;
}
public void removeListener(ILabelProviderListener listener) {
}
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
if (element instanceof DigestModel) {
DigestModel model = (DigestModel) element;
DigestSchema column = columnList.get(columnIndex);
switch (column) {
case DIGEST_TEXT:
return model.name;
case SCHEMA_NAME:
return model.database;
case COUNT_STAR:
return FormatUtil.print(model.execution, "#,##0");
case SUM_ERRORS:
return FormatUtil.print(model.errorCnt, "#,##0");
case SUM_WARNINGS:
return FormatUtil.print(model.warnCnt, "#,##0");
case SUM_TIMER_WAIT:
return FormatUtil.print(model.sumResponseTime * PICO, "#,##0.00#");
case AVG_TIMER_WAIT:
return FormatUtil.print(model.avgResponseTime * PICO, "#,##0.00#");
case MIN_TIMER_WAIT:
return FormatUtil.print(model.minResponseTime * PICO, "#,##0.00#");
case MAX_TIMER_WAIT:
return FormatUtil.print(model.maxResponseTime * PICO, "#,##0.00#");
case SUM_LOCK_TIME:
return FormatUtil.print(model.lockTime * PICO, "#,##0.00#");
case SUM_ROWS_AFFECTED:
return FormatUtil.print(model.rowsAffected, "#,##0");
case SUM_ROWS_SENT:
return FormatUtil.print(model.rowsSent, "#,##0");
case SUM_ROWS_EXAMINED:
return FormatUtil.print(model.rowsExamined, "#,##0");
case SUM_CREATED_TMP_DISK_TABLES:
return FormatUtil.print(model.createdTmpDiskTables, "#,##0");
case SUM_CREATED_TMP_TABLES:
return FormatUtil.print(model.createdTmpTables, "#,##0");
case SUM_SELECT_FULL_JOIN:
return FormatUtil.print(model.selectFullJoin, "#,##0");
case SUM_SELECT_FULL_RANGE_JOIN:
return FormatUtil.print(model.selectFullRangeJoin, "#,##0");
case SUM_SELECT_RANGE:
return FormatUtil.print(model.selectRange, "#,##0");
case SUM_SELECT_RANGE_CHECK:
return FormatUtil.print(model.selectRangeCheck, "#,##0");
case SUM_SELECT_SCAN:
return FormatUtil.print(model.selectScan, "#,##0");
case SUM_SORT_MERGE_PASSES:
return FormatUtil.print(model.sortMergePasses, "#,##0");
case SUM_SORT_RANGE:
return FormatUtil.print(model.sortRange, "#,##0");
case SUM_SORT_ROWS:
return FormatUtil.print(model.sortRows, "#,##0");
case SUM_SORT_SCAN:
return FormatUtil.print(model.sortScan, "#,##0");
case SUM_NO_INDEX_USED:
return FormatUtil.print(model.noIndexUsed, "#,##0");
case SUM_NO_GOOD_INDEX_USED:
return FormatUtil.print(model.noGoodIndexUsed, "#,##0");
case FIRST_SEEN:
return DateUtil.timestamp(model.firstSeen);
case LAST_SEEN:
return DateUtil.timestamp(model.lastSeen);
}
}
return null;
}
}
public void dispose() {
super.dispose();
if (loadQueryJob != null && (loadQueryJob.getState() == Job.WAITING || loadQueryJob.getState() == Job.RUNNING)) {
loadQueryJob.cancel();
}
}
public static void main(String[] args) {
System.out.println(139871834183L * Math.pow(10, -12));
}
}
| jahnaviancha/scouter | scouter.client/src/scouter/client/maria/views/DigestTableView.java | Java | apache-2.0 | 21,743 |
package org.zstack.sdk;
public class GetCandidateVmForAttachingIsoResult {
public java.util.List<VmInstanceInventory> inventories;
public void setInventories(java.util.List<VmInstanceInventory> inventories) {
this.inventories = inventories;
}
public java.util.List<VmInstanceInventory> getInventories() {
return this.inventories;
}
}
| Alvin-Lau/zstack | sdk/src/main/java/org/zstack/sdk/GetCandidateVmForAttachingIsoResult.java | Java | apache-2.0 | 372 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Remote;
namespace Microsoft.CodeAnalysis.FindSymbols
{
public static partial class SymbolFinder
{
/// <summary>
/// Callback object we pass to the OOP server to hear about the result
/// of the FindReferencesEngine as it executes there.
/// </summary>
internal sealed class FindReferencesServerCallback : IEqualityComparer<SerializableSymbolAndProjectId>
{
private readonly Solution _solution;
private readonly IStreamingFindReferencesProgress _progress;
private readonly CancellationToken _cancellationToken;
private readonly object _gate = new();
private readonly Dictionary<SerializableSymbolAndProjectId, ISymbol> _definitionMap;
public FindReferencesServerCallback(
Solution solution,
IStreamingFindReferencesProgress progress,
CancellationToken cancellationToken)
{
_solution = solution;
_progress = progress;
_cancellationToken = cancellationToken;
_definitionMap = new Dictionary<SerializableSymbolAndProjectId, ISymbol>(this);
}
public ValueTask AddItemsAsync(int count)
=> _progress.ProgressTracker.AddItemsAsync(count);
public ValueTask ItemCompletedAsync()
=> _progress.ProgressTracker.ItemCompletedAsync();
public ValueTask OnStartedAsync()
=> _progress.OnStartedAsync();
public ValueTask OnCompletedAsync()
=> _progress.OnCompletedAsync();
public ValueTask OnFindInDocumentStartedAsync(DocumentId documentId)
{
var document = _solution.GetDocument(documentId);
return _progress.OnFindInDocumentStartedAsync(document);
}
public ValueTask OnFindInDocumentCompletedAsync(DocumentId documentId)
{
var document = _solution.GetDocument(documentId);
return _progress.OnFindInDocumentCompletedAsync(document);
}
public async ValueTask OnDefinitionFoundAsync(SerializableSymbolAndProjectId definition)
{
var symbol = await definition.TryRehydrateAsync(
_solution, _cancellationToken).ConfigureAwait(false);
if (symbol == null)
return;
lock (_gate)
{
_definitionMap[definition] = symbol;
}
await _progress.OnDefinitionFoundAsync(symbol).ConfigureAwait(false);
}
public async ValueTask OnReferenceFoundAsync(
SerializableSymbolAndProjectId definition, SerializableReferenceLocation reference)
{
ISymbol symbol;
lock (_gate)
{
// The definition may not be in the map if we failed to map it over using TryRehydrateAsync in OnDefinitionFoundAsync.
// Just ignore this reference. Note: while this is a degraded experience:
//
// 1. TryRehydrateAsync logs an NFE so we can track down while we're failing to roundtrip the
// definition so we can track down that issue.
// 2. NFE'ing and failing to show a result, is much better than NFE'ing and then crashing
// immediately afterwards.
if (!_definitionMap.TryGetValue(definition, out symbol))
return;
}
var referenceLocation = await reference.RehydrateAsync(
_solution, _cancellationToken).ConfigureAwait(false);
await _progress.OnReferenceFoundAsync(symbol, referenceLocation).ConfigureAwait(false);
}
bool IEqualityComparer<SerializableSymbolAndProjectId>.Equals(SerializableSymbolAndProjectId x, SerializableSymbolAndProjectId y)
=> y.SymbolKeyData.Equals(x.SymbolKeyData);
int IEqualityComparer<SerializableSymbolAndProjectId>.GetHashCode(SerializableSymbolAndProjectId obj)
=> obj.SymbolKeyData.GetHashCode();
}
}
}
| ErikSchierboom/roslyn | src/Workspaces/Core/Portable/FindSymbols/SymbolFinder.FindReferencesServerCallback.cs | C# | apache-2.0 | 4,661 |
/// <reference path='fourslash.ts'/>
////var o = {
//// foo() { },
//// bar: 0,
//// "some other name": 1
////};
////
////o["/*1*/bar"];
////o["/*2*/
goTo.marker('1');
verify.completionListContains("foo");
verify.completionListAllowsNewIdentifier();
verify.completionListCount(3);
goTo.marker('2');
verify.completionListContains("some other name");
verify.completionListAllowsNewIdentifier();
verify.completionListCount(3);
| synaptek/TypeScript | tests/cases/fourslash/completionForStringLiteral2.ts | TypeScript | apache-2.0 | 456 |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Management.Automation;
using Microsoft.Azure.Commands.Sql.Common;
using Microsoft.Azure.Commands.Sql.ElasticPool.Model;
using Microsoft.Azure.Commands.Sql.ElasticPool.Services;
namespace Microsoft.Azure.Commands.Sql.ElasticPool.Cmdlet
{
public abstract class AzureSqlElasticPoolActivityCmdletBase : AzureSqlCmdletBase<IEnumerable<AzureSqlElasticPoolActivityModel>, AzureSqlElasticPoolAdapter>
{
/// <summary>
/// Gets or sets the name of the database server to use.
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
Position = 1,
HelpMessage = "The name of the Azure SQL Server the Elastic Pool is in.")]
[ValidateNotNullOrEmpty]
public string ServerName { get; set; }
/// <summary>
/// Gets or sets the name of the ElasticPool to use.
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
Position = 2,
HelpMessage = "The name of the Azure SQL Elastic Pool.")]
[ValidateNotNullOrEmpty]
public string ElasticPoolName { get; set; }
/// <summary>
/// Initializes the adapter
/// </summary>
/// <param name="subscription"></param>
/// <returns></returns>
protected override AzureSqlElasticPoolAdapter InitModelAdapter(Azure.Common.Authentication.Models.AzureSubscription subscription)
{
return new AzureSqlElasticPoolAdapter(DefaultProfile.Context);
}
}
}
| mayurid/azure-powershell | src/ResourceManager/Sql/Commands.Sql/Elastic Pools/Cmdlet/AzureSqlElasticPoolActivityCmdletBase.cs | C# | apache-2.0 | 2,382 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is part of dcm4che, an implementation of DICOM(TM) in
* Java(TM), hosted at http://sourceforge.net/projects/dcm4che.
*
* The Initial Developer of the Original Code is
* Agfa-Gevaert AG.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* See listed authors below.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.dcm4chee.usr.war.common;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.link.Link;
import org.dcm4chee.usr.war.pages.LoginPage;
/**
* @author Robert David <robert.david@agfa.com>
* @version $Revision$ $Date$
* @since 28.09.2009
*/
public class PageExpiredErrorPage extends WebPage {
public PageExpiredErrorPage() {
Link<?> backToLoginLink = new Link<Object>("back-to-login") {
private static final long serialVersionUID = 1L;
@Override
public void onClick() {
this.getSession().invalidateNow();
setResponsePage(LoginPage.class);
}
};
add(backToLoginLink);
}
}
| medicayun/medicayundicom | dcm4chee-usr/trunk/dcm4chee-usr-war/src/main/java/org/dcm4chee/usr/war/common/PageExpiredErrorPage.java | Java | apache-2.0 | 2,548 |
/*
* 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.logging.log4j.core.appender.mom;
import java.io.Serializable;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.naming.NamingException;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.appender.AbstractManager;
import org.apache.logging.log4j.core.appender.ManagerFactory;
import org.apache.logging.log4j.core.net.JndiManager;
import org.apache.logging.log4j.status.StatusLogger;
/**
* JMS connection and session manager. Can be used to access MessageProducer, MessageConsumer, and Message objects
* involving a configured ConnectionFactory and Destination.
*/
public class JmsManager extends AbstractManager {
private static final Logger LOGGER = StatusLogger.getLogger();
private static final JmsManagerFactory FACTORY = new JmsManagerFactory();
private final JndiManager jndiManager;
private final Connection connection;
private final Session session;
private final Destination destination;
private JmsManager(final String name, final JndiManager jndiManager, final String connectionFactoryName,
final String destinationName, final String username, final String password)
throws NamingException, JMSException {
super(name);
this.jndiManager = jndiManager;
final ConnectionFactory connectionFactory = this.jndiManager.lookup(connectionFactoryName);
if (username != null && password != null) {
this.connection = connectionFactory.createConnection(username, password);
} else {
this.connection = connectionFactory.createConnection();
}
this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
this.destination = this.jndiManager.lookup(destinationName);
this.connection.start();
}
/**
* Gets a JmsManager using the specified configuration parameters.
*
* @param name The name to use for this JmsManager.
* @param jndiManager The JndiManager to look up JMS information through.
* @param connectionFactoryName The binding name for the {@link javax.jms.ConnectionFactory}.
* @param destinationName The binding name for the {@link javax.jms.Destination}.
* @param username The username to connect with or {@code null} for no authentication.
* @param password The password to use with the given username or {@code null} for no authentication.
* @return The JmsManager as configured.
*/
public static JmsManager getJmsManager(final String name, final JndiManager jndiManager,
final String connectionFactoryName, final String destinationName,
final String username, final String password) {
final JmsConfiguration configuration = new JmsConfiguration(jndiManager, connectionFactoryName, destinationName,
username, password);
return FACTORY.createManager(name, configuration);
}
/**
* Creates a MessageConsumer on this Destination using the current Session.
*
* @return A MessageConsumer on this Destination.
* @throws JMSException
*/
public MessageConsumer createMessageConsumer() throws JMSException {
return this.session.createConsumer(this.destination);
}
/**
* Creates a MessageProducer on this Destination using the current Session.
*
* @return A MessageProducer on this Destination.
* @throws JMSException
*/
public MessageProducer createMessageProducer() throws JMSException {
return this.session.createProducer(this.destination);
}
/**
* Creates a TextMessage or ObjectMessage from a Serializable object. For instance, when using a text-based
* {@link org.apache.logging.log4j.core.Layout} such as {@link org.apache.logging.log4j.core.layout.PatternLayout},
* the {@link org.apache.logging.log4j.core.LogEvent} message will be serialized to a String. When using a
* layout such as {@link org.apache.logging.log4j.core.layout.SerializedLayout}, the LogEvent message will be
* serialized as a Java object.
*
* @param object The LogEvent or String message to wrap.
* @return A new JMS message containing the provided object.
* @throws JMSException
*/
public Message createMessage(final Serializable object) throws JMSException {
if (object instanceof String) {
return this.session.createTextMessage((String) object);
}
return this.session.createObjectMessage(object);
}
@Override
protected void releaseSub() {
try {
this.session.close();
} catch (final JMSException ignored) {
}
try {
this.connection.close();
} catch (final JMSException ignored) {
}
this.jndiManager.release();
}
private static class JmsConfiguration {
private final JndiManager jndiManager;
private final String connectionFactoryName;
private final String destinationName;
private final String username;
private final String password;
private JmsConfiguration(final JndiManager jndiManager, final String connectionFactoryName, final String destinationName,
final String username, final String password) {
this.jndiManager = jndiManager;
this.connectionFactoryName = connectionFactoryName;
this.destinationName = destinationName;
this.username = username;
this.password = password;
}
}
private static class JmsManagerFactory implements ManagerFactory<JmsManager, JmsConfiguration> {
@Override
public JmsManager createManager(final String name, final JmsConfiguration data) {
try {
return new JmsManager(name, data.jndiManager, data.connectionFactoryName, data.destinationName,
data.username, data.password);
} catch (final Exception e) {
LOGGER.error("Error creating JmsManager using ConnectionFactory [{}] and Destination [{}].",
data.connectionFactoryName, data.destinationName, e);
return null;
}
}
}
}
| SourceStudyNotes/log4j2 | src/main/java/org/apache/logging/log4j/core/appender/mom/JmsManager.java | Java | apache-2.0 | 7,359 |
// Copyright 2016 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.
// ============================================================================
#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/lib/core/errors.h"
using ::tensorflow::shape_inference::InferenceContext;
using ::tensorflow::shape_inference::ShapeAndType;
using ::tensorflow::shape_inference::ShapeHandle;
namespace tensorflow {
namespace {
Status ValidateVariableResourceHandle(InferenceContext* c,
ShapeAndType* shape_and_type) {
auto* handle_data = c->input_handle_shapes_and_types(0);
if (handle_data == nullptr || handle_data->empty()) {
shape_and_type->shape = c->UnknownShape();
shape_and_type->dtype = DT_INVALID;
} else {
*shape_and_type = (*handle_data)[0];
DataType value_dtype;
TF_RETURN_IF_ERROR(c->GetAttr("dtype", &value_dtype));
if (shape_and_type->dtype != value_dtype) {
return errors::InvalidArgument(
"Trying to read variable with wrong dtype. "
"Expected ",
DataTypeString(shape_and_type->dtype), " got ",
DataTypeString(value_dtype));
}
}
return Status::OK();
}
Status ReadVariableShapeFn(InferenceContext* c) {
ShapeAndType shape_and_type;
TF_RETURN_IF_ERROR(ValidateVariableResourceHandle(c, &shape_and_type));
c->set_output(0, shape_and_type.shape);
return Status::OK();
}
Status ReadVariablesShapeFn(InferenceContext* c) {
int n;
TF_RETURN_IF_ERROR(c->GetAttr("N", &n));
DataTypeVector value_dtypes;
TF_RETURN_IF_ERROR(c->GetAttr("dtypes", &value_dtypes));
if (n != value_dtypes.size()) {
return errors::InvalidArgument(
"Mismatched number of arguments to ReadVariablesOp");
}
for (int i = 0; i < n; ++i) {
ShapeAndType shape_and_type;
auto* handle_data = c->input_handle_shapes_and_types(i);
if (handle_data == nullptr || handle_data->empty()) {
shape_and_type.shape = c->UnknownShape();
shape_and_type.dtype = DT_INVALID;
} else {
shape_and_type = (*handle_data)[0];
if (shape_and_type.dtype != value_dtypes[i]) {
return errors::InvalidArgument(
"Trying to read variable with wrong dtype. "
"Expected ",
DataTypeString(shape_and_type.dtype), " got ",
DataTypeString(value_dtypes[i]));
}
}
c->set_output(i, shape_and_type.shape);
}
return Status::OK();
}
} // namespace
REGISTER_OP("VarHandleOp")
.Attr("container: string = ''")
.Attr("shared_name: string = ''")
.Attr("dtype: type")
.Attr("shape: shape")
.Output("resource: resource")
.SetIsStateful()
.SetShapeFn([](InferenceContext* c) {
c->set_output(0, c->Scalar());
DataType t;
TF_RETURN_IF_ERROR(c->GetAttr("dtype", &t));
PartialTensorShape p;
TF_RETURN_IF_ERROR(c->GetAttr("shape", &p));
ShapeHandle s;
TF_RETURN_IF_ERROR(c->MakeShapeFromPartialTensorShape(p, &s));
c->set_output_handle_shapes_and_types(0,
std::vector<ShapeAndType>{{s, t}});
return Status::OK();
});
REGISTER_OP("_VarHandlesOp")
.Attr("containers: list(string)")
.Attr("shared_names: list(string)")
.Attr("N: int >= 0")
.Attr("dtypes: list(type)")
.Attr("shapes: list(shape)")
.Output("resources: N * resource")
.SetIsStateful()
.SetShapeFn([](InferenceContext* c) {
int n;
TF_RETURN_IF_ERROR(c->GetAttr("N", &n));
DataTypeVector dtypes;
TF_RETURN_IF_ERROR(c->GetAttr("dtypes", &dtypes));
std::vector<PartialTensorShape> shapes;
TF_RETURN_IF_ERROR(c->GetAttr("shapes", &shapes));
if (dtypes.size() != n) {
return errors::InvalidArgument("Mismatched number of dtypes (n=", n,
", num dtypes=", dtypes.size(), ")");
}
if (shapes.size() != n) {
return errors::InvalidArgument("Mismatched number of shapes (n=", n,
", num shapes=", shapes.size(), ")");
}
for (int i = 0; i < n; ++i) {
c->set_output(i, c->Scalar());
ShapeHandle s;
TF_RETURN_IF_ERROR(c->MakeShapeFromPartialTensorShape(shapes[i], &s));
c->set_output_handle_shapes_and_types(
i, std::vector<ShapeAndType>{{s, dtypes[i]}});
}
return Status::OK();
});
REGISTER_OP("ReadVariableOp")
.Input("resource: resource")
.Output("value: dtype")
.Attr("dtype: type")
.SetShapeFn(ReadVariableShapeFn);
REGISTER_OP("_ReadVariablesOp")
.Attr("N: int >= 0")
.Input("resources: N * resource")
.Output("values: dtypes")
.Attr("dtypes: list(type)")
.SetShapeFn(ReadVariablesShapeFn);
Status ReadGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FunctionDefHelper::Define(
// Arg defs
{"x: resource", "dy: float"},
// Ret val defs
{"dy: float"},
// Attr defs
{},
// Nodes
{});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("ReadVariableOp", ReadGrad);
REGISTER_OP("DestroyResourceOp")
.Input("resource: resource")
.Attr("ignore_lookup_error: bool = true")
.SetIsStateful()
.SetShapeFn(shape_inference::NoOutputs);
Status CreateAssignShapeFn(InferenceContext* c) {
ShapeAndType handle_shape_and_type;
TF_RETURN_IF_ERROR(ValidateVariableResourceHandle(c, &handle_shape_and_type));
ShapeHandle value_shape = c->input(1);
ShapeHandle unused;
TF_RETURN_IF_ERROR(
c->Merge(handle_shape_and_type.shape, value_shape, &unused));
return Status::OK();
}
REGISTER_OP("AssignVariableOp")
.Input("resource: resource")
.Input("value: dtype")
.Attr("dtype: type")
.SetShapeFn(CreateAssignShapeFn);
REGISTER_OP("AssignAddVariableOp")
.Input("resource: resource")
.Input("value: dtype")
.Attr("dtype: type")
.SetShapeFn(CreateAssignShapeFn);
REGISTER_OP("AssignSubVariableOp")
.Input("resource: resource")
.Input("value: dtype")
.Attr("dtype: type")
.SetShapeFn(CreateAssignShapeFn);
REGISTER_OP("VarIsInitializedOp")
.Input("resource: resource")
.Output("is_initialized: bool")
.SetShapeFn(tensorflow::shape_inference::ScalarShape);
Status VariableShapeShapeFn(InferenceContext* c) {
auto* handle_data = c->input_handle_shapes_and_types(0);
if (handle_data == nullptr || handle_data->empty()) {
c->set_output(0, c->Vector(c->UnknownDim()));
return Status::OK();
}
ShapeHandle var_shape = (*handle_data)[0].shape;
int64 rank = c->RankKnown(var_shape) ? c->Rank(var_shape)
: InferenceContext::kUnknownDim;
c->set_output(0, c->Vector(rank));
return Status::OK();
}
REGISTER_OP("VariableShape")
.Input("input: resource")
.Output("output: out_type")
.Attr("out_type: {int32, int64} = DT_INT32")
.SetShapeFn(VariableShapeShapeFn);
REGISTER_OP("ResourceGather")
.Input("resource: resource")
.Input("indices: Tindices")
.Attr("validate_indices: bool = true")
.Output("output: dtype")
.Attr("dtype: type")
.Attr("Tindices: {int32,int64}")
.SetShapeFn([](InferenceContext* c) {
ShapeAndType handle_shape_and_type;
TF_RETURN_IF_ERROR(
ValidateVariableResourceHandle(c, &handle_shape_and_type));
ShapeHandle unused;
TF_RETURN_IF_ERROR(
c->WithRankAtLeast(handle_shape_and_type.shape, 1, &unused));
ShapeHandle params_subshape;
TF_RETURN_IF_ERROR(
c->Subshape(handle_shape_and_type.shape, 1, ¶ms_subshape));
ShapeHandle indices_shape = c->input(1);
ShapeHandle out;
TF_RETURN_IF_ERROR(c->Concatenate(indices_shape, params_subshape, &out));
c->set_output(0, out);
return Status::OK();
});
namespace {
Status ResourceScatterUpdateShape(InferenceContext* c) {
ShapeAndType handle_shape_and_type;
TF_RETURN_IF_ERROR(ValidateVariableResourceHandle(c, &handle_shape_and_type));
ShapeHandle var_shape = handle_shape_and_type.shape;
ShapeHandle indices_shape = c->input(1);
ShapeHandle unused_updates_shape;
ShapeHandle concat;
ShapeHandle var_subshape;
TF_RETURN_IF_ERROR(c->Subshape(var_shape, 1, &var_subshape));
TF_RETURN_IF_ERROR(c->Concatenate(indices_shape, var_subshape, &concat));
TF_RETURN_IF_ERROR(
InferenceContext::Rank(c->input(2)) == 0
? Status::OK()
: c->Merge(c->input(2), concat, &unused_updates_shape));
return Status::OK();
}
} // namespace
REGISTER_OP("ResourceScatterAdd")
.Input("resource: resource")
.Input("indices: Tindices")
.Input("updates: dtype")
.Attr("dtype: numbertype")
.Attr("Tindices: {int32, int64}")
.SetShapeFn(ResourceScatterUpdateShape);
REGISTER_OP("ResourceScatterSub")
.Input("resource: resource")
.Input("indices: Tindices")
.Input("updates: dtype")
.Attr("dtype: numbertype")
.Attr("Tindices: {int32, int64}")
.SetShapeFn(ResourceScatterUpdateShape);
REGISTER_OP("ResourceScatterMul")
.Input("resource: resource")
.Input("indices: Tindices")
.Input("updates: dtype")
.Attr("dtype: numbertype")
.Attr("Tindices: {int32, int64}")
.SetShapeFn(ResourceScatterUpdateShape);
REGISTER_OP("ResourceScatterDiv")
.Input("resource: resource")
.Input("indices: Tindices")
.Input("updates: dtype")
.Attr("dtype: numbertype")
.Attr("Tindices: {int32, int64}")
.SetShapeFn(ResourceScatterUpdateShape);
REGISTER_OP("ResourceScatterMin")
.Input("resource: resource")
.Input("indices: Tindices")
.Input("updates: dtype")
.Attr("dtype: numbertype")
.Attr("Tindices: {int32, int64}")
.SetShapeFn(ResourceScatterUpdateShape);
REGISTER_OP("ResourceScatterMax")
.Input("resource: resource")
.Input("indices: Tindices")
.Input("updates: dtype")
.Attr("dtype: numbertype")
.Attr("Tindices: {int32, int64}")
.SetShapeFn(ResourceScatterUpdateShape);
REGISTER_OP("ResourceScatterUpdate")
.Input("resource: resource")
.Input("indices: Tindices")
.Input("updates: dtype")
.Attr("dtype: type")
.Attr("Tindices: {int32, int64}")
.SetShapeFn(ResourceScatterUpdateShape);
REGISTER_OP("MutexV2")
.Attr("container: string = ''")
.Attr("shared_name: string = ''")
.Output("resource: resource")
.SetIsStateful()
.SetShapeFn([](InferenceContext* c) {
c->set_output(0, c->Scalar());
return Status::OK();
});
REGISTER_OP("MutexLock")
.Input("mutex: resource")
.Output("mutex_lock: variant")
.SetIsStateful()
.SetShapeFn([](InferenceContext* c) {
c->set_output(0, c->Scalar());
return Status::OK();
});
REGISTER_OP("ConsumeMutexLock")
.Input("mutex_lock: variant")
.SetIsStateful()
.SetShapeFn([](InferenceContext* c) { return Status::OK(); });
} // namespace tensorflow
| hfp/tensorflow-xsmm | tensorflow/core/ops/resource_variable_ops.cc | C++ | apache-2.0 | 11,757 |
require "formula"
class Libpng < Formula
homepage "http://www.libpng.org/pub/png/libpng.html"
url "https://downloads.sf.net/project/libpng/libpng16/1.6.13/libpng-1.6.13.tar.xz"
sha1 "5ae32b6b99cef6c5c85feab8edf9d619e1773b15"
bottle do
cellar :any
sha1 "c4c5f94b771ea53620d9b6c508b382b3a40d6c80" => :yosemite
sha1 "09af92d209c67dd0719d16866dc26c05bbbef77b" => :mavericks
sha1 "23812e76bf0e3f98603c6d22ab69258b219918ca" => :mountain_lion
sha1 "af1fe6844a0614652bbc9b60fd84c57e24da93ee" => :lion
end
keg_only :provided_pre_mountain_lion
option :universal
def install
ENV.universal_binary if build.universal?
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make install"
end
end
| 0xbb/homebrew | Library/Formula/libpng.rb | Ruby | bsd-2-clause | 844 |
/*global app: true, env: true */
/**
Define tags that are known in JSDoc.
@module jsdoc/tag/dictionary/definitions
@author Michael Mathews <micmath@gmail.com>
@license Apache License 2.0 - See file 'LICENSE.md' in this project.
*/
'use strict';
var logger = require('jsdoc/util/logger');
var path = require('jsdoc/path');
var Syntax = require('jsdoc/src/syntax').Syntax;
function getSourcePaths() {
var sourcePaths = env.sourceFiles.slice(0) || [];
if (env.opts._) {
env.opts._.forEach(function(sourcePath) {
var resolved = path.resolve(env.pwd, sourcePath);
if (sourcePaths.indexOf(resolved) === -1) {
sourcePaths.push(resolved);
}
});
}
return sourcePaths;
}
function filepathMinusPrefix(filepath) {
var sourcePaths = getSourcePaths();
var commonPrefix = path.commonPrefix(sourcePaths);
var result = '';
if (filepath) {
// always use forward slashes
result = (filepath + path.sep).replace(commonPrefix, '')
.replace(/\\/g, '/');
}
if (result.length > 0 && result[result.length - 1] !== '/') {
result += '/';
}
return result;
}
/** @private */
function setDocletKindToTitle(doclet, tag) {
doclet.addTag( 'kind', tag.title );
}
function setDocletScopeToTitle(doclet, tag) {
try {
doclet.setScope(tag.title);
}
catch(e) {
logger.error(e.message);
}
}
function setDocletNameToValue(doclet, tag) {
if (tag.value && tag.value.description) { // as in a long tag
doclet.addTag( 'name', tag.value.description);
}
else if (tag.text) { // or a short tag
doclet.addTag('name', tag.text);
}
}
function setDocletNameToValueName(doclet, tag) {
if (tag.value && tag.value.name) {
doclet.addTag('name', tag.value.name);
}
}
function setDocletDescriptionToValue(doclet, tag) {
if (tag.value) {
doclet.addTag( 'description', tag.value );
}
}
function setDocletTypeToValueType(doclet, tag) {
if (tag.value && tag.value.type) {
doclet.type = tag.value.type;
}
}
function setNameToFile(doclet, tag) {
var name;
if (doclet.meta.filename) {
name = filepathMinusPrefix(doclet.meta.path) + doclet.meta.filename;
doclet.addTag('name', name);
}
}
function setDocletMemberof(doclet, tag) {
if (tag.value && tag.value !== '<global>') {
doclet.setMemberof(tag.value);
}
}
function applyNamespace(docletOrNs, tag) {
if (typeof docletOrNs === 'string') { // ns
tag.value = app.jsdoc.name.applyNamespace(tag.value, docletOrNs);
}
else { // doclet
if (!docletOrNs.name) {
return; // error?
}
//doclet.displayname = doclet.name;
docletOrNs.longname = app.jsdoc.name.applyNamespace(docletOrNs.name, tag.title);
}
}
function setDocletNameToFilename(doclet, tag) {
var name = '';
if (doclet.meta.path) {
name = filepathMinusPrefix(doclet.meta.path);
}
name += doclet.meta.filename.replace(/\.js$/i, '');
doclet.name = name;
}
function parseBorrows(doclet, tag) {
var m = /^(\S+)(?:\s+as\s+(\S+))?$/.exec(tag.text);
if (m) {
if (m[1] && m[2]) {
return { target: m[1], source: m[2] };
}
else if (m[1]) {
return { target: m[1] };
}
} else {
return {};
}
}
function firstWordOf(string) {
var m = /^(\S+)/.exec(string);
if (m) { return m[1]; }
else { return ''; }
}
/** Populate the given dictionary with all known JSDoc tag definitions.
@param {module:jsdoc/tag/dictionary} dictionary
*/
exports.defineTags = function(dictionary) {
dictionary.defineTag('abstract', {
mustNotHaveValue: true,
onTagged: function(doclet, tag) {
// since "abstract" is reserved word in JavaScript let's use "virtual" in code
doclet.virtual = true;
}
})
.synonym('virtual');
dictionary.defineTag('access', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
// only valid values are private and protected, public is default
if ( /^(private|protected)$/i.test(tag.value) ) {
doclet.access = tag.value.toLowerCase();
}
else {
delete doclet.access;
}
}
});
dictionary.defineTag('alias', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
doclet.alias = tag.value;
}
});
// Special separator tag indicating that multiple doclets should be generated for the same
// comment. Used internally (and by some JSDoc users, although it's not officially supported).
//
// In the following example, the parser will replace `//**` with an `@also` tag:
//
// /**
// * Foo.
// *//**
// * Foo with a param.
// * @param {string} bar
// */
// function foo(bar) {}
dictionary.defineTag('also', {
onTagged: function(doclet, tag) {
// let the parser handle it; we define the tag here to avoid "not a known tag" errors
}
});
// this symbol inherits from the specified symbol
dictionary.defineTag('augments', {
mustHaveValue: true,
// Allow augments value to be specified as a normal type, e.g. {Type}
onTagText: function(text) {
var type = require('jsdoc/tag/type'),
tagType = type.parse(text, false, true);
return tagType.typeExpression || text;
},
onTagged: function(doclet, tag) {
doclet.augment( firstWordOf(tag.value) );
}
})
.synonym('extends');
dictionary.defineTag('author', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
if (!doclet.author) { doclet.author = []; }
doclet.author.push(tag.value);
}
});
// this symbol has a member that should use the same docs as another symbol
dictionary.defineTag('borrows', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
var borrows = parseBorrows(doclet, tag);
doclet.borrow(borrows.target, borrows.source);
}
});
dictionary.defineTag('class', {
onTagged: function(doclet, tag) {
doclet.addTag('kind', 'class');
// handle special case where both @class and @constructor tags exist in same doclet
if (tag.originalTitle === 'class') {
var looksLikeDesc = (tag.value || '').match(/\S+\s+\S+/); // multiple words after @class?
if ( looksLikeDesc || /@construct(s|or)\b/i.test(doclet.comment) ) {
doclet.classdesc = tag.value; // treat the @class tag as a @classdesc tag instead
return;
}
}
setDocletNameToValue(doclet, tag);
}
})
.synonym('constructor');
dictionary.defineTag('classdesc', {
onTagged: function(doclet, tag) {
doclet.classdesc = tag.value;
}
});
dictionary.defineTag('constant', {
canHaveType: true,
canHaveName: true,
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
setDocletNameToValueName(doclet, tag);
setDocletTypeToValueType(doclet, tag);
}
})
.synonym('const');
dictionary.defineTag('constructs', {
onTagged: function(doclet, tag) {
var ownerClassName;
if (!tag.value) {
ownerClassName = '{@thisClass}'; // this can be resolved later in the handlers
}
else {
ownerClassName = firstWordOf(tag.value);
}
doclet.addTag('alias', ownerClassName);
doclet.addTag('kind', 'class');
}
});
dictionary.defineTag('copyright', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
doclet.copyright = tag.value;
}
});
dictionary.defineTag('default', {
onTagged: function(doclet, tag) {
var type;
var value;
if (tag.value) {
doclet.defaultvalue = tag.value;
}
else if (doclet.meta && doclet.meta.code && doclet.meta.code.value) {
type = doclet.meta.code.type;
value = doclet.meta.code.value;
if (type === Syntax.Literal) {
doclet.defaultvalue = String(value);
}
// TODO: reenable the changes for https://github.com/jsdoc3/jsdoc/pull/419
/*
else if (doclet.meta.code.type === 'OBJECTLIT') {
doclet.defaultvalue = String(doclet.meta.code.node.toSource());
doclet.defaultvaluetype = 'object';
}
*/
}
}
})
.synonym('defaultvalue');
dictionary.defineTag('deprecated', {
// value is optional
onTagged: function(doclet, tag) {
doclet.deprecated = tag.value || true;
}
});
dictionary.defineTag('description', {
mustHaveValue: true
})
.synonym('desc');
dictionary.defineTag('enum', {
canHaveType: true,
onTagged: function(doclet, tag) {
doclet.kind = 'member';
doclet.isEnum = true;
setDocletTypeToValueType(doclet, tag);
}
});
dictionary.defineTag('event', {
isNamespace: true,
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
setDocletNameToValue(doclet, tag);
}
});
dictionary.defineTag('example', {
keepsWhitespace: true,
removesIndent: true,
mustHaveValue: true,
onTagged: function(doclet, tag) {
if (!doclet.examples) { doclet.examples = []; }
doclet.examples.push(tag.value);
}
});
dictionary.defineTag('exception', {
mustHaveValue: true,
canHaveType: true,
onTagged: function(doclet, tag) {
if (!doclet.exceptions) { doclet.exceptions = []; }
doclet.exceptions.push(tag.value);
setDocletTypeToValueType(doclet, tag);
}
})
.synonym('throws');
dictionary.defineTag('exports', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
var modName = firstWordOf(tag.value);
doclet.addTag('alias', modName);
doclet.addTag('kind', 'module');
}
});
dictionary.defineTag('external', {
canHaveType: true,
isNamespace: true,
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
if (tag.value && tag.value.type) {
setDocletTypeToValueType(doclet, tag);
doclet.addTag('name', doclet.type.names[0]);
}
}
})
.synonym('host');
dictionary.defineTag('file', {
onTagged: function(doclet, tag) {
setNameToFile(doclet, tag);
setDocletKindToTitle(doclet, tag);
setDocletDescriptionToValue(doclet, tag);
doclet.preserveName = true;
}
})
.synonym('fileoverview')
.synonym('overview');
dictionary.defineTag('fires', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
if (!doclet.fires) { doclet.fires = []; }
applyNamespace('event', tag);
doclet.fires.push(tag.value);
}
})
.synonym('emits');
dictionary.defineTag('function', {
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
setDocletNameToValue(doclet, tag);
}
})
.synonym('func')
.synonym('method');
dictionary.defineTag('global', {
mustNotHaveValue: true,
onTagged: function(doclet, tag) {
doclet.scope = 'global';
delete doclet.memberof;
}
});
dictionary.defineTag('ignore', {
mustNotHaveValue: true,
onTagged: function(doclet, tag) {
doclet.ignore = true;
}
});
dictionary.defineTag('inner', {
onTagged: function(doclet, tag) {
setDocletScopeToTitle(doclet, tag);
}
});
dictionary.defineTag('instance', {
onTagged: function(doclet, tag) {
setDocletScopeToTitle(doclet, tag);
}
});
dictionary.defineTag('kind', {
mustHaveValue: true
});
dictionary.defineTag('lends', {
onTagged: function(doclet, tag) {
var GLOBAL_LONGNAME = require('jsdoc/doclet').GLOBAL_LONGNAME;
doclet.alias = tag.value || GLOBAL_LONGNAME;
doclet.addTag('undocumented');
}
});
dictionary.defineTag('license', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
doclet.license = tag.value;
}
});
dictionary.defineTag('listens', {
mustHaveValue: true,
onTagged: function (doclet, tag) {
if (!doclet.listens) { doclet.listens = []; }
applyNamespace('event', tag);
doclet.listens.push(tag.value);
// TODO: verify that parameters match the event parameters?
}
});
dictionary.defineTag('member', {
canHaveType: true,
canHaveName: true,
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
setDocletNameToValueName(doclet, tag);
setDocletTypeToValueType(doclet, tag);
}
})
.synonym('var');
dictionary.defineTag('memberof', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
var GLOBAL_LONGNAME = require('jsdoc/doclet').GLOBAL_LONGNAME;
if (tag.originalTitle === 'memberof!') {
doclet.forceMemberof = true;
if (tag.value === GLOBAL_LONGNAME) {
doclet.addTag('global');
delete doclet.memberof;
}
}
setDocletMemberof(doclet, tag);
}
})
.synonym('memberof!');
// this symbol mixes in all of the specified object's members
dictionary.defineTag('mixes', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
var source = firstWordOf(tag.value);
doclet.mix(source);
}
});
dictionary.defineTag('mixin', {
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
setDocletNameToValue(doclet, tag);
}
});
dictionary.defineTag('module', {
canHaveType: true,
isNamespace: true,
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
setDocletNameToValue(doclet, tag);
if (!doclet.name) {
setDocletNameToFilename(doclet, tag);
}
setDocletTypeToValueType(doclet, tag);
}
});
dictionary.defineTag('name', {
mustHaveValue: true
});
dictionary.defineTag('namespace', {
canHaveType: true,
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
setDocletNameToValue(doclet, tag);
setDocletTypeToValueType(doclet, tag);
}
});
dictionary.defineTag('param', {
//mustHaveValue: true, // param name can be found in the source code if not provided
canHaveType: true,
canHaveName: true,
onTagged: function(doclet, tag) {
if (!doclet.params) { doclet.params = []; }
doclet.params.push(tag.value||{});
}
})
.synonym('argument')
.synonym('arg');
dictionary.defineTag('private', {
mustNotHaveValue: true,
onTagged: function(doclet, tag) {
doclet.access = 'private';
}
});
dictionary.defineTag('property', {
mustHaveValue: true,
canHaveType: true,
canHaveName: true,
onTagged: function(doclet, tag) {
if (!doclet.properties) { doclet.properties = []; }
doclet.properties.push(tag.value);
}
})
.synonym('prop');
dictionary.defineTag('protected', {
mustNotHaveValue: true,
onTagged: function(doclet, tag) {
doclet.access = 'protected';
}
});
dictionary.defineTag('public', {
mustNotHaveValue: true,
onTagged: function(doclet, tag) {
delete doclet.access; // public is default
}
});
// use this instead of old deprecated @final tag
dictionary.defineTag('readonly', {
mustNotHaveValue: true,
onTagged: function(doclet, tag) {
doclet.readonly = true;
}
});
dictionary.defineTag('requires', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
var requiresName;
var MODULE_PREFIX = require('jsdoc/name').MODULE_PREFIX;
// inline link tags are passed through as-is so that `@requires {@link foo}` works
if ( require('jsdoc/tag/inline').isInlineTag(tag.value, 'link\\S*') ) {
requiresName = tag.value;
}
// otherwise, assume it's a module
else {
requiresName = firstWordOf(tag.value);
if (requiresName.indexOf(MODULE_PREFIX) !== 0) {
requiresName = MODULE_PREFIX + requiresName;
}
}
if (!doclet.requires) { doclet.requires = []; }
doclet.requires.push(requiresName);
}
});
dictionary.defineTag('returns', {
mustHaveValue: true,
canHaveType: true,
onTagged: function(doclet, tag) {
if (!doclet.returns) { doclet.returns = []; }
doclet.returns.push(tag.value);
}
})
.synonym('return');
dictionary.defineTag('see', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
if (!doclet.see) { doclet.see = []; }
doclet.see.push(tag.value);
}
});
dictionary.defineTag('since', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
doclet.since = tag.value;
}
});
dictionary.defineTag('static', {
onTagged: function(doclet, tag) {
setDocletScopeToTitle(doclet, tag);
}
});
dictionary.defineTag('summary', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
doclet.summary = tag.value;
}
});
dictionary.defineTag('this', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
doclet['this'] = firstWordOf(tag.value);
}
});
dictionary.defineTag('todo', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
if (!doclet.todo) { doclet.todo = []; }
doclet.todo.push(tag.value);
}
});
dictionary.defineTag('tutorial', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
if (!doclet.tutorials) { doclet.tutorials = []; }
doclet.tutorials.push(tag.value);
}
});
dictionary.defineTag('type', {
mustHaveValue: true,
canHaveType: true,
onTagText: function(text) {
// remove line breaks so we can parse the type expression correctly
text = text.replace(/[\n\r]/g, '');
// any text must be formatted as a type, but for back compat braces are optional
if ( !/^\{[\s\S]+\}$/.test(text) ) {
text = '{' + text + '}';
}
return text;
},
onTagged: function(doclet, tag) {
if (tag.value && tag.value.type) {
setDocletTypeToValueType(doclet, tag);
// for backwards compatibility, we allow @type for functions to imply return type
if (doclet.kind === 'function') {
doclet.addTag('returns', tag.text);
}
}
}
});
dictionary.defineTag('typedef', {
canHaveType: true,
canHaveName: true,
onTagged: function(doclet, tag) {
setDocletKindToTitle(doclet, tag);
if (tag.value) {
setDocletNameToValueName(doclet, tag);
// callbacks are always type {function}
if (tag.originalTitle === 'callback') {
doclet.type = {
names: [
'function'
]
};
}
else {
setDocletTypeToValueType(doclet, tag);
}
}
}
})
.synonym('callback');
dictionary.defineTag('undocumented', {
mustNotHaveValue: true,
onTagged: function(doclet, tag) {
doclet.undocumented = true;
doclet.comment = '';
}
});
dictionary.defineTag('variation', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
doclet.variation = tag.value;
}
});
dictionary.defineTag('version', {
mustHaveValue: true,
onTagged: function(doclet, tag) {
doclet.version = tag.value;
}
});
};
| ad-l/djcl | tools/jsdoc/lib/jsdoc/tag/dictionary/definitions.js | JavaScript | bsd-2-clause | 21,625 |
--TEST--
Bug #43483 (get_class_methods() does not list all visible methods)
--FILE--
<?php
class C {
public static function test() {
D::prot();
print_r(get_class_methods("D"));
}
}
class D extends C {
protected static function prot() {
echo "Successfully called D::prot().\n";
}
}
D::test();
?>
--EXPECT--
Successfully called D::prot().
Array
(
[0] => prot
[1] => test
)
| glayzzle/tests | zend/bug43483.phpt | PHP | bsd-3-clause | 389 |
// Copyright (C) 2001, 2004, 2005 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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 library 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 library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
// 23.2.2.1 list constructors, copy, and assignment
#include <list>
#include <testsuite_hooks.h>
bool test __attribute__((unused)) = true;
// Range constructor
//
// This test verifies the following.
// 23.2.2.1 template list(InputIterator f, InputIterator l, const Allocator& a = Allocator())
// 23.2.2 const_iterator begin() const
// 23.2.2 const_iterator end() const
// 23.2.2 size_type size() const
//
void
test03()
{
const int A[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17};
const std::size_t N = sizeof(A) / sizeof(int);
std::size_t count;
std::list<int>::const_iterator i;
// construct from a dissimilar range
std::list<int> list0301(A, A + N);
for (i = list0301.begin(), count = 0;
i != list0301.end();
++i, ++count)
VERIFY(*i == A[count]);
VERIFY(count == N);
VERIFY(list0301.size() == N);
// construct from a similar range
std::list<int> list0302(list0301.begin(), list0301.end());
for (i = list0302.begin(), count = 0;
i != list0302.end();
++i, ++count)
VERIFY(*i == A[count]);
VERIFY(count == N);
VERIFY(list0302.size() == N);
}
int main()
{
test03();
return 0;
}
| shaotuanchen/sunflower_exp | tools/source/gcc-4.2.4/libstdc++-v3/testsuite/23_containers/list/cons/4.cc | C++ | bsd-3-clause | 2,030 |
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
* @emails oncall+javascript_foundation
*/
'use strict';
jest.mock('fs');
const getProjectConfig = require('../../ios').projectConfig;
const fs = require('fs');
const projects = require('../../__fixtures__/projects');
describe('ios::getProjectConfig', () => {
const userConfig = {};
beforeEach(() => {
fs.__setMockFilesystem({testDir: projects});
});
it('returns an object with ios project configuration', () => {
const folder = '/testDir/nested';
expect(getProjectConfig(folder, userConfig)).not.toBeNull();
expect(typeof getProjectConfig(folder, userConfig)).toBe('object');
});
it('returns `null` if ios project was not found', () => {
const folder = '/testDir/empty';
expect(getProjectConfig(folder, userConfig)).toBeNull();
});
it('returns normalized shared library names', () => {
const projectConfig = getProjectConfig('/testDir/nested', {
sharedLibraries: ['libc++', 'libz.tbd', 'HealthKit', 'HomeKit.framework'],
});
expect(projectConfig.sharedLibraries).toEqual([
'libc++.tbd',
'libz.tbd',
'HealthKit.framework',
'HomeKit.framework',
]);
});
});
| Bhullnatik/react-native | local-cli/core/__tests__/ios/getProjectConfig.spec.js | JavaScript | bsd-3-clause | 1,475 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is JavaScript Engine testing utilities.
*
* The Initial Developer of the Original Code is
* Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2007
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Norris Boyd
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
//-----------------------------------------------------------------------------
var BUGNUMBER = 392308;
var summary = 'StopIteration should be catchable';
var actual = '';
var expect = '';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
function testStop() {
function yielder() {
actual += 'before, ';
yield;
actual += 'after, ';
}
expect = 'before, after, iteration terminated normally';
try {
var gen = yielder();
result = gen.next();
gen.send(result);
} catch (x if x instanceof StopIteration) {
actual += 'iteration terminated normally';
} catch (x2) {
actual += 'unexpected throw: ' + x2;
}
}
testStop();
reportCompare(expect, actual, summary);
exitFunc ('test');
}
| darkrsw/safe | tests/browser_extensions/js1_7/extensions/XXXregress-392308.js | JavaScript | bsd-3-clause | 2,774 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>PayPal Merchant SDK - MassPay</title>
<link rel="stylesheet" href="../Common/sdk.css"/>
<script type="text/javascript" src="../Common/sdk.js"></script>
</head>
<body>
<div id="wrapper">
<img src="https://devtools-paypal.com/image/bdg_payments_by_pp_2line.png">
<div id="header">
<h3>MassPay</h3>
<div id="apidetails">MassPay API operation makes a payment to one or
more PayPal account holders.</div>
</div>
<form method="POST" action="MassPay.php">
<div id="request_form">
<div class="params">
<div class="param_name">Receiver Info Code Type</div>
<div class="param_value">
<select name=receiverInfoCode>
<option value=EmailAddress>Email</option>
<option value=UserID>UserID</option>
<option value=PhoneNumber>Phone</option>
</select>
</div>
</div>
<table class="params">
<tr>
<th class="param_name">Mail</th>
<th class="param_name">UserID</th>
<th class="param_name">Phone Number</th>
<th class="param_name">Amount</th>
<th class="param_name">Currency Code</th>
</tr>
<tr>
<td class="param_value"><input type="text" name="mail[]"
value="enduser_biz@gmail.com" size="25" maxlength="260" /></td>
<td class="param_value"><input type="text" name="id[]" value=""
size="25" maxlength="260" /></td>
<td class="param_value"><input type="text" name="phone[]" value=""
size="25" maxlength="260" /></td>
<td class="param_value"><input type="text" name="amount[]"
value="3.00" size="25" maxlength="260" /></td>
<td class="param_value"><input type="text" name="currencyCode[]"
value="USD" size="25" maxlength="260" /></td>
</tr>
<tr>
<td class="param_value"><input type="text" name="mail[]"
value="sdk-three@paypal.com" size="25" maxlength="260" /></td>
<td class="param_value"><input type="text" name="id[]" value=""
size="25" maxlength="260" /></td>
<td class="param_value"><input type="text" name="phone[]" value=""
size="25" maxlength="260" /></td>
<td class="param_value"><input type="text" name="amount[]"
value="3.00" size="25" maxlength="260" /></td>
<td class="param_value"><input type="text" name="currencyCode[]"
value="USD" size="25" maxlength="260" /></td>
</tr>
<tr>
<td class="param_value"><input type="text" name="mail[]"
value="jb-us-seller@paypal.com" size="25" maxlength="260" /></td>
<td class="param_value"><input type="text" name="id[]" value=""
size="25" maxlength="260" /></td>
<td class="param_value"><input type="text" name="phone[]" value=""
size="25" maxlength="260" /></td>
<td class="param_value"><input type="text" name="amount[]"
value="3.00" size="25" maxlength="260" /></td>
<td class="param_value"><input type="text" name="currencyCode[]"
value="USD" size="25" maxlength="260" /></td>
</tr>
</table>
<?php
include('../Permissions/Permission.html.php');
?>
<input type="submit" name="MassPayBtn" value="MassPay" /><br />
</div>
<a href="../index.php">Home</a>
</form>
</div>
</body>
</html>
| olegkaliuga/yii | vendor/paypal/work/merchant-sdk-php/samples/MassPay/MassPay.html.php | PHP | bsd-3-clause | 3,396 |
// 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.
package org.chromium.media;
import android.content.Context;
import android.graphics.ImageFormat;
import android.hardware.display.DisplayManager;
import android.view.Display;
import android.view.Surface;
import org.chromium.base.ContextUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Video Capture Device base class, defines a set of methods that native code
* needs to use to configure, start capture, and to be reached by callbacks and
* provides some necessary data type(s) with accessors.
**/
@JNINamespace("media")
public abstract class VideoCapture {
/**
* Common class for storing a framerate range. Values should be multiplied by 1000.
*/
protected static class FramerateRange {
public int min;
public int max;
public FramerateRange(int min, int max) {
this.min = min;
this.max = max;
}
}
// The angle (0, 90, 180, 270) that the image needs to be rotated to show in
// the display's native orientation.
protected int mCameraNativeOrientation;
// In some occasions we need to invert the device rotation readings, see the
// individual implementations.
protected boolean mInvertDeviceOrientationReadings;
protected VideoCaptureFormat mCaptureFormat;
protected final int mId;
// Native callback context variable.
protected final long mNativeVideoCaptureDeviceAndroid;
protected boolean mUseBackgroundThreadForTesting;
VideoCapture(int id, long nativeVideoCaptureDeviceAndroid) {
mId = id;
mNativeVideoCaptureDeviceAndroid = nativeVideoCaptureDeviceAndroid;
}
// Allocate necessary resources for capture.
@CalledByNative
public abstract boolean allocate(
int width, int height, int frameRate, boolean enableFaceDetection);
// Success is indicated by returning true and a callback to
// VideoCaptureJni.get().onStarted(, VideoCapture.this), which may occur synchronously or
// asynchronously. Failure can be indicated by one of the following:
// * Returning false. In this case no callback to VideoCaptureJni.get().onStarted() is made.
// * Returning true, and asynchronously invoking VideoCaptureJni.get().onError. In this case
// also no callback to VideoCaptureJni.get().onStarted() is made.
@CalledByNative
public abstract boolean startCaptureMaybeAsync();
// Blocks until it is guaranteed that no more frames are sent.
@CalledByNative
public abstract boolean stopCaptureAndBlockUntilStopped();
// Replies by calling VideoCaptureJni.get().onGetPhotoCapabilitiesReply(). Will pass |null|
// for parameter |result| to indicate failure.
@CalledByNative
public abstract void getPhotoCapabilitiesAsync(long callbackId);
/**
* @param zoom Zoom level, should be ignored if 0.
* @param focusMode Focus mode following AndroidMeteringMode enum.
* @param focusDistance Desired distance to plane of sharpest focus.
* @param exposureMode Exposure mode following AndroidMeteringMode enum.
* @param pointsOfInterest2D 2D normalized points of interest, marshalled with
* x coordinate first followed by the y coordinate.
* @param hasExposureCompensation Indicates if |exposureCompensation| is set.
* @param exposureCompensation Adjustment to auto exposure. 0 means not adjusted.
* @param exposureTime Duration each pixel is exposed to light (in nanoseconds).
* @param whiteBalanceMode White Balance mode following AndroidMeteringMode enum.
* @param iso Sensitivity to light. 0, which would be invalid, means ignore.
* @param hasRedEyeReduction Indicates if |redEyeReduction| is set.
* @param redEyeReduction Value of red eye reduction for the auto flash setting.
* @param fillLightMode Flash setting, following AndroidFillLightMode enum.
* @param colorTemperature White Balance reference temperature, valid if whiteBalanceMode is
* manual, and its value is larger than 0.
* @param torch Torch setting, true meaning on.
*/
@CalledByNative
public abstract void setPhotoOptions(double zoom, int focusMode, double focusDistance,
int exposureMode, double width, double height, double[] pointsOfInterest2D,
boolean hasExposureCompensation, double exposureCompensation, double exposureTime,
int whiteBalanceMode, double iso, boolean hasRedEyeReduction, boolean redEyeReduction,
int fillLightMode, boolean hasTorch, boolean torch, double colorTemperature);
// Replies by calling VideoCaptureJni.get().onPhotoTaken().
@CalledByNative
public abstract void takePhotoAsync(long callbackId);
@CalledByNative
public abstract void deallocate();
@CalledByNative
public final int queryWidth() {
return mCaptureFormat.mWidth;
}
@CalledByNative
public final int queryHeight() {
return mCaptureFormat.mHeight;
}
@CalledByNative
public final int queryFrameRate() {
return mCaptureFormat.mFramerate;
}
@CalledByNative
public final int getColorspace() {
switch (mCaptureFormat.mPixelFormat) {
case ImageFormat.YV12:
return AndroidImageFormat.YV12;
case ImageFormat.YUV_420_888:
return AndroidImageFormat.YUV_420_888;
case ImageFormat.NV21:
return AndroidImageFormat.NV21;
case ImageFormat.UNKNOWN:
default:
return AndroidImageFormat.UNKNOWN;
}
}
@CalledByNative
public final void setTestMode() {
mUseBackgroundThreadForTesting = true;
}
protected final int getCameraRotation() {
int rotation = mInvertDeviceOrientationReadings ? (360 - getDeviceRotation())
: getDeviceRotation();
return (mCameraNativeOrientation + rotation) % 360;
}
protected final int getDeviceRotation() {
final int orientation;
DisplayManager dm = (DisplayManager) ContextUtils.getApplicationContext().getSystemService(
Context.DISPLAY_SERVICE);
switch (dm.getDisplay(Display.DEFAULT_DISPLAY).getRotation()) {
case Surface.ROTATION_90:
orientation = 90;
break;
case Surface.ROTATION_180:
orientation = 180;
break;
case Surface.ROTATION_270:
orientation = 270;
break;
case Surface.ROTATION_0:
default:
orientation = 0;
break;
}
return orientation;
}
// {@link VideoCaptureJni.get().onPhotoTaken()} needs to be called back if there's any
// problem after {@link takePhotoAsync()} has returned true.
protected void notifyTakePhotoError(long callbackId) {
VideoCaptureJni.get().onPhotoTaken(
mNativeVideoCaptureDeviceAndroid, VideoCapture.this, callbackId, null);
}
/**
* Finds the framerate range matching |targetFramerate|. Tries to find a range with as low of a
* minimum value as possible to allow the camera adjust based on the lighting conditions.
* Assumes that all framerate values are multiplied by 1000.
*
* This code is mostly copied from WebRTC:
* CameraEnumerationAndroid.getClosestSupportedFramerateRange
* in webrtc/api/android/java/src/org/webrtc/CameraEnumerationAndroid.java
*/
protected static FramerateRange getClosestFramerateRange(
final List<FramerateRange> framerateRanges, final int targetFramerate) {
return Collections.min(framerateRanges, new Comparator<FramerateRange>() {
// Threshold and penalty weights if the upper bound is further away than
// |MAX_FPS_DIFF_THRESHOLD| from requested.
private static final int MAX_FPS_DIFF_THRESHOLD = 5000;
private static final int MAX_FPS_LOW_DIFF_WEIGHT = 1;
private static final int MAX_FPS_HIGH_DIFF_WEIGHT = 3;
// Threshold and penalty weights if the lower bound is bigger than |MIN_FPS_THRESHOLD|.
private static final int MIN_FPS_THRESHOLD = 8000;
private static final int MIN_FPS_LOW_VALUE_WEIGHT = 1;
private static final int MIN_FPS_HIGH_VALUE_WEIGHT = 4;
// Use one weight for small |value| less than |threshold|, and another weight above.
private int progressivePenalty(
int value, int threshold, int lowWeight, int highWeight) {
return (value < threshold)
? value * lowWeight
: threshold * lowWeight + (value - threshold) * highWeight;
}
int diff(FramerateRange range) {
final int minFpsError = progressivePenalty(range.min, MIN_FPS_THRESHOLD,
MIN_FPS_LOW_VALUE_WEIGHT, MIN_FPS_HIGH_VALUE_WEIGHT);
final int maxFpsError = progressivePenalty(Math.abs(targetFramerate - range.max),
MAX_FPS_DIFF_THRESHOLD, MAX_FPS_LOW_DIFF_WEIGHT, MAX_FPS_HIGH_DIFF_WEIGHT);
return minFpsError + maxFpsError;
}
@Override
public int compare(FramerateRange range1, FramerateRange range2) {
return diff(range1) - diff(range2);
}
});
}
protected static int[] integerArrayListToArray(ArrayList<Integer> intArrayList) {
int[] intArray = new int[intArrayList.size()];
for (int i = 0; i < intArrayList.size(); i++) {
intArray[i] = intArrayList.get(i).intValue();
}
return intArray;
}
@NativeMethods
interface Natives {
// Method for VideoCapture implementations to call back native code.
void onFrameAvailable(long nativeVideoCaptureDeviceAndroid, VideoCapture caller,
byte[] data, int length, int rotation);
void onI420FrameAvailable(long nativeVideoCaptureDeviceAndroid, VideoCapture caller,
ByteBuffer yBuffer, int yStride, ByteBuffer uBuffer, ByteBuffer vBuffer,
int uvRowStride, int uvPixelStride, int width, int height, int rotation,
long timestamp);
// Method for VideoCapture implementations to signal an asynchronous error.
void onError(long nativeVideoCaptureDeviceAndroid, VideoCapture caller,
int androidVideoCaptureError, String message);
// Method for VideoCapture implementations to signal that a frame was dropped.
void onFrameDropped(long nativeVideoCaptureDeviceAndroid, VideoCapture caller,
int androidVideoCaptureFrameDropReason);
void onGetPhotoCapabilitiesReply(long nativeVideoCaptureDeviceAndroid, VideoCapture caller,
long callbackId, PhotoCapabilities result);
// Callback for calls to takePhoto(). This can indicate both success and
// failure. Failure is indicated by |data| being null.
void onPhotoTaken(long nativeVideoCaptureDeviceAndroid, VideoCapture caller,
long callbackId, byte[] data);
// Method for VideoCapture implementations to report device started event.
void onStarted(long nativeVideoCaptureDeviceAndroid, VideoCapture caller);
void dCheckCurrentlyOnIncomingTaskRunner(
long nativeVideoCaptureDeviceAndroid, VideoCapture caller);
}
}
| youtube/cobalt | third_party/chromium/media/capture/video/android/java/src/org/chromium/media/VideoCapture.java | Java | bsd-3-clause | 11,938 |
// 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 "ui/app_list/search/history.h"
#include <stddef.h>
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "ui/app_list/search/history_data.h"
#include "ui/app_list/search/history_data_store.h"
#include "ui/app_list/search/tokenized_string.h"
namespace app_list {
namespace {
// Normalize the given string by joining all its tokens with a space.
std::string NormalizeString(const std::string& utf8) {
TokenizedString tokenized(base::UTF8ToUTF16(utf8));
return base::UTF16ToUTF8(
base::JoinString(tokenized.tokens(), base::ASCIIToUTF16(" ")));
}
} // namespace
History::History(scoped_refptr<HistoryDataStore> store)
: store_(store), data_loaded_(false) {
const size_t kMaxQueryEntries = 1000;
const size_t kMaxSecondaryQueries = 5;
data_.reset(
new HistoryData(store_.get(), kMaxQueryEntries, kMaxSecondaryQueries));
data_->AddObserver(this);
}
History::~History() {
data_->RemoveObserver(this);
}
bool History::IsReady() const {
return data_loaded_;
}
void History::AddLaunchEvent(const std::string& query,
const std::string& result_id) {
DCHECK(IsReady());
data_->Add(NormalizeString(query), result_id);
}
scoped_ptr<KnownResults> History::GetKnownResults(
const std::string& query) const {
DCHECK(IsReady());
return data_->GetKnownResults(NormalizeString(query));
}
void History::OnHistoryDataLoadedFromStore() {
data_loaded_ = true;
}
} // namespace app_list
| hujiajie/chromium-crosswalk | ui/app_list/search/history.cc | C++ | bsd-3-clause | 1,669 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.admin.indices.rollover;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.IndicesRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.master.AcknowledgedRequest;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.ParseFieldMatcherSupplier;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import static org.elasticsearch.action.ValidateActions.addValidationError;
/**
* Request class to swap index under an alias upon satisfying conditions
*/
public class RolloverRequest extends AcknowledgedRequest<RolloverRequest> implements IndicesRequest {
public static ObjectParser<RolloverRequest, ParseFieldMatcherSupplier> PARSER =
new ObjectParser<>("conditions", null);
static {
PARSER.declareField((parser, request, parseFieldMatcherSupplier) ->
Condition.PARSER.parse(parser, request.conditions, parseFieldMatcherSupplier),
new ParseField("conditions"), ObjectParser.ValueType.OBJECT);
PARSER.declareField((parser, request, parseFieldMatcherSupplier) ->
request.createIndexRequest.settings(parser.map()),
new ParseField("settings"), ObjectParser.ValueType.OBJECT);
PARSER.declareField((parser, request, parseFieldMatcherSupplier) -> {
for (Map.Entry<String, Object> mappingsEntry : parser.map().entrySet()) {
request.createIndexRequest.mapping(mappingsEntry.getKey(),
(Map<String, Object>) mappingsEntry.getValue());
}
}, new ParseField("mappings"), ObjectParser.ValueType.OBJECT);
PARSER.declareField((parser, request, parseFieldMatcherSupplier) ->
request.createIndexRequest.aliases(parser.map()),
new ParseField("aliases"), ObjectParser.ValueType.OBJECT);
}
private String alias;
private String newIndexName;
private boolean dryRun;
private Set<Condition> conditions = new HashSet<>(2);
private CreateIndexRequest createIndexRequest = new CreateIndexRequest("_na_");
RolloverRequest() {}
public RolloverRequest(String alias, String newIndexName) {
this.alias = alias;
this.newIndexName = newIndexName;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = createIndexRequest == null ? null : createIndexRequest.validate();
if (alias == null) {
validationException = addValidationError("index alias is missing", validationException);
}
if (createIndexRequest == null) {
validationException = addValidationError("create index request is missing", validationException);
}
return validationException;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
alias = in.readString();
newIndexName = in.readOptionalString();
dryRun = in.readBoolean();
int size = in.readVInt();
for (int i = 0; i < size; i++) {
this.conditions.add(in.readNamedWriteable(Condition.class));
}
createIndexRequest = new CreateIndexRequest();
createIndexRequest.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(alias);
out.writeOptionalString(newIndexName);
out.writeBoolean(dryRun);
out.writeVInt(conditions.size());
for (Condition condition : conditions) {
out.writeNamedWriteable(condition);
}
createIndexRequest.writeTo(out);
}
@Override
public String[] indices() {
return new String[] {alias};
}
@Override
public IndicesOptions indicesOptions() {
return IndicesOptions.strictSingleIndexNoExpandForbidClosed();
}
/**
* Sets the alias to rollover to another index
*/
public void setAlias(String alias) {
this.alias = alias;
}
/**
* Sets the alias to rollover to another index
*/
public void setNewIndexName(String newIndexName) {
this.newIndexName = newIndexName;
}
/**
* Sets if the rollover should not be executed when conditions are met
*/
public void dryRun(boolean dryRun) {
this.dryRun = dryRun;
}
/**
* Adds condition to check if the index is at least <code>age</code> old
*/
public void addMaxIndexAgeCondition(TimeValue age) {
this.conditions.add(new MaxAgeCondition(age));
}
/**
* Adds condition to check if the index has at least <code>numDocs</code>
*/
public void addMaxIndexDocsCondition(long numDocs) {
this.conditions.add(new MaxDocsCondition(numDocs));
}
/**
* Sets rollover index creation request to override index settings when
* the rolled over index has to be created
*/
public void setCreateIndexRequest(CreateIndexRequest createIndexRequest) {
this.createIndexRequest = Objects.requireNonNull(createIndexRequest, "create index request must not be null");;
}
boolean isDryRun() {
return dryRun;
}
Set<Condition> getConditions() {
return conditions;
}
String getAlias() {
return alias;
}
String getNewIndexName() {
return newIndexName;
}
CreateIndexRequest getCreateIndexRequest() {
return createIndexRequest;
}
public void source(BytesReference source) {
XContentType xContentType = XContentFactory.xContentType(source);
if (xContentType != null) {
try (XContentParser parser = XContentFactory.xContent(xContentType).createParser(source)) {
PARSER.parse(parser, this, () -> ParseFieldMatcher.EMPTY);
} catch (IOException e) {
throw new ElasticsearchParseException("failed to parse source for rollover index", e);
}
} else {
throw new ElasticsearchParseException("failed to parse content type for rollover index source");
}
}
/**
* Sets the number of shard copies that should be active for creation of the
* new rollover index to return. Defaults to {@link ActiveShardCount#DEFAULT}, which will
* wait for one shard copy (the primary) to become active. Set this value to
* {@link ActiveShardCount#ALL} to wait for all shards (primary and all replicas) to be active
* before returning. Otherwise, use {@link ActiveShardCount#from(int)} to set this value to any
* non-negative integer, up to the number of copies per shard (number of replicas + 1),
* to wait for the desired amount of shard copies to become active before returning.
* Index creation will only wait up until the timeout value for the number of shard copies
* to be active before returning. Check {@link RolloverResponse#isShardsAcked()} to
* determine if the requisite shard copies were all started before returning or timing out.
*
* @param waitForActiveShards number of active shard copies to wait on
*/
public void setWaitForActiveShards(ActiveShardCount waitForActiveShards) {
this.createIndexRequest.waitForActiveShards(waitForActiveShards);
}
/**
* A shortcut for {@link #setWaitForActiveShards(ActiveShardCount)} where the numerical
* shard count is passed in, instead of having to first call {@link ActiveShardCount#from(int)}
* to get the ActiveShardCount.
*/
public void setWaitForActiveShards(final int waitForActiveShards) {
setWaitForActiveShards(ActiveShardCount.from(waitForActiveShards));
}
}
| strahanjen/strahanjen.github.io | elasticsearch-master/core/src/main/java/org/elasticsearch/action/admin/indices/rollover/RolloverRequest.java | Java | bsd-3-clause | 9,336 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
using Microsoft.AzureStack.Management.Compute.Admin;
using Microsoft.AzureStack.Management.Compute.Admin.Models;
using System.Linq;
using System.Net;
using Xunit;
namespace Compute.Tests
{
public class QuotaTests : ComputeTestBase
{
// Helper
private Quota Create(int asc, int cl, int vssc, int vmc, int smds, int pmds) {
var newQuota = new Quota()
{
AvailabilitySetCount = asc,
CoresLimit = cl,
VmScaleSetCount = vssc,
VirtualMachineCount = vmc,
MaxAllocationStandardManagedDisksAndSnapshots =smds,
MaxAllocationPremiumManagedDisksAndSnapshots = pmds
};
return newQuota;
}
private void ValidateQuota(Quota quota) {
AssertValidResource(quota);
Assert.NotNull(quota);
Assert.NotNull(quota.AvailabilitySetCount);
Assert.NotNull(quota.CoresLimit);
Assert.NotNull(quota.VirtualMachineCount);
Assert.NotNull(quota.VmScaleSetCount);
Assert.NotNull(quota.MaxAllocationStandardManagedDisksAndSnapshots);
Assert.NotNull(quota.MaxAllocationPremiumManagedDisksAndSnapshots);
}
private void AssertSame(Quota expected, Quota given, bool resourceToo = true) {
if (resourceToo)
{
AssertSameResource(expected, given);
}
if (expected == null)
{
Assert.Null(given);
}
else
{
Assert.NotNull(given);
Assert.Equal(expected.AvailabilitySetCount, given.AvailabilitySetCount);
Assert.Equal(expected.CoresLimit, given.CoresLimit);
Assert.Equal(expected.VirtualMachineCount, given.VirtualMachineCount);
Assert.Equal(expected.VmScaleSetCount, given.VmScaleSetCount);
Assert.Equal(expected.MaxAllocationStandardManagedDisksAndSnapshots, given.MaxAllocationStandardManagedDisksAndSnapshots);
Assert.Equal(expected.MaxAllocationPremiumManagedDisksAndSnapshots, given.MaxAllocationPremiumManagedDisksAndSnapshots);
}
}
[Fact]
public void TestListQuotas() {
RunTest((client) => {
var quotas = client.Quotas.List("local");
Assert.NotNull(quotas);
quotas.ForEach(ValidateQuota);
});
}
[Fact]
public void TestGetQuota() {
RunTest((client) => {
var quota = client.Quotas.List("local").FirstOrDefault();
var result = client.Quotas.Get("local", quota.Name);
AssertSame(quota, result);
});
}
[Fact]
public void TestGetAllQuotas() {
RunTest((client) => {
var quotas = client.Quotas.List("local");
quotas.ForEach((quota) => {
var result = client.Quotas.Get("local", quota.Name);
AssertSame(quota, result);
});
});
}
private void ValidateAgainstData(Quota q, int[] d) {
Assert.Equal(q.AvailabilitySetCount, d[0]);
Assert.Equal(q.CoresLimit, d[1]);
Assert.Equal(q.VmScaleSetCount, d[2]);
Assert.Equal(q.VirtualMachineCount, d[3]);
Assert.Equal(q.MaxAllocationStandardManagedDisksAndSnapshots, d[4]);
Assert.Equal(q.MaxAllocationPremiumManagedDisksAndSnapshots, d[5]);
}
[Fact]
public void CreateUpdateDeleteQuota() {
RunTest((client) => {
var location = "local";
var name = "testQuotaCreateUpdateDelete";
var data = new int[]{1,1,1,1,1,1 };
var newQuota = Create(data[0], data[1], data[2], data[3], data[4], data[5]);
var quota = client.Quotas.CreateOrUpdate(location, name, newQuota);
ValidateAgainstData(quota, data);
AssertSame(newQuota, quota, false);
quota.VirtualMachineCount += 1;
quota = client.Quotas.CreateOrUpdate(location, name, quota);
data[3] += 1;
ValidateAgainstData(quota, data);
quota.AvailabilitySetCount += 1;
quota = client.Quotas.CreateOrUpdate(location, name, quota);
data[0] += 1;
ValidateAgainstData(quota, data);
quota.VmScaleSetCount += 1;
quota = client.Quotas.CreateOrUpdate(location, name, quota);
data[2] += 1;
ValidateAgainstData(quota, data);
quota.CoresLimit+= 1;
quota = client.Quotas.CreateOrUpdate(location, name, quota);
data[1] += 1;
ValidateAgainstData(quota, data);
quota.MaxAllocationStandardManagedDisksAndSnapshots+= 1;
quota = client.Quotas.CreateOrUpdate(location, name, quota);
data[4] += 1;
ValidateAgainstData(quota, data);
quota.MaxAllocationPremiumManagedDisksAndSnapshots += 1;
quota = client.Quotas.CreateOrUpdate(location, name, quota);
data[5] += 1;
ValidateAgainstData(quota, data);
client.Quotas.Delete(location, name);
});
}
[Fact]
public void TestCreateQuota() {
RunTest((client) => {
var location = "local";
var quotaNamePrefix = "testQuota";
var data = new System.Collections.Generic.List<int[]> {
new [] { 0, 0, 0, 0, 0, 0, 0 },
new [] { 1, 0, 0, 0, 0, 0, 1 },
new [] { 0, 1, 0, 0, 0, 0, 2 },
new [] { 0, 0, 1, 0, 0, 0, 3 },
new [] { 0, 0, 0, 1, 0, 0, 4 },
new [] { 0, 0, 0, 0, 1, 0, 5 },
new [] { 0, 0, 0, 0, 0, 1, 6 },
new [] { 100, 100, 100, 100 ,100, 100, 7 },
new [] { 1000, 1000, 1000, 1000, 1000, 1000, 8 }
};
data.ForEach((d) => {
var name = quotaNamePrefix + d[6];
var newQuota = Create(d[0], d[1], d[2], d[3], d[4], d[5]);
var quota = client.Quotas.CreateOrUpdate(location, name, newQuota);
ValidateAgainstData(quota, d);
var result = client.Quotas.Get(location, name);
AssertSame(quota, result, false);
});
data.ForEach((d) => {
var name = quotaNamePrefix + d[6];
var list = client.Quotas.List(location);
Assert.Equal(1, list.Count((q) => q.Name.Equals(name)));
});
data.ForEach((d) => {
var name = quotaNamePrefix + d[6];
client.Quotas.Delete(location, name);
ValidateExpectedReturnCode(
() => client.Quotas.Get(location, name),
HttpStatusCode.NotFound
);
});
});
}
#region Test With Invalid data
[Fact]
public void TestCreateInvalidQuota() {
RunTest((client) => {
var name = "myQuota";
Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(-1, 1, 1, 1, 1, 1)));
Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(1, -1, 1, 1, 1, 1)));
Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(1, 1, -1, 1, 1, 1)));
Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(1, 1, 1, -1, 1, 1)));
Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(1, 1, 1, 1, -1, 1)));
Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(1, 1, 1, 1, 1, -1)));
Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(-1, 0, 0, 0, 0, 0)));
Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(0, -1, 0, 0, 0, 0)));
Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(0, 0, -1, 0, 0, 0)));
Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(0, 0, 0, -1, 0, 0)));
Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(0, 0, 0, 0, -1, 0)));
Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(0, 0, 0, 0, 0, -1)));
Assert.ThrowsAny<System.Exception>(() => client.Quotas.CreateOrUpdate("local", name, Create(-1, -1, -1, -1, -1, -1)));
});
}
// Invalid Locations
[Fact(Skip = "CRP does not handle invalid locations correctly.")]
public void TestListInvalidLocation() {
RunTest((client) => {
var list = client.Quotas.List("thisisnotarealplace");
Assert.Empty(list);
});
}
[Fact]
public void TestDeleteNonExistingQuota() {
RunTest((client) => {
ValidateExpectedReturnCode(
() => client.Quotas.Delete("local", "thisdoesnotexistandifitdoesoops"),
HttpStatusCode.NotFound
);
});
}
[Fact(Skip = "CRP does not handle invalid locations correctly.")]
public void TestCreateQuotaOnInvalidLocation() {
RunTest((client) => {
var location = "thislocationdoesnotexist";
var quotaNamePrefix = "testQuota";
var data = new System.Collections.Generic.List<int[]> {
new [] { 0, 0, 0, 0, 0, 0, 0 },
new [] { 1, 0, 0, 0, 0, 0, 1 },
new [] { 0, 1, 0, 0, 0, 0, 2 },
new [] { 0, 0, 1, 0, 0, 0, 3 },
new [] { 0, 0, 0, 1, 0, 0, 4 },
new [] { 0, 0, 0, 0, 1, 0, 5 },
new [] { 0, 0, 0, 0, 0, 1, 6 },
new [] { 100, 100, 100, 100 ,100, 100, 7 },
new [] { 1000, 1000, 1000, 1000, 1000, 1000, 8 }
};
data.ForEach((d) => {
var name = quotaNamePrefix + d[6];
var newQuota = Create(d[0], d[1], d[2], d[3], d[4], d[5]);
var quota = client.Quotas.CreateOrUpdate(location, name, newQuota);
var result = client.Quotas.Get(location, name);
Assert.Null(quota);
Assert.Null(result);
});
data.ForEach((d) => {
var name = quotaNamePrefix + d[6];
var list = client.Quotas.List(location);
Assert.Equal(0, list.Count((q) => q.Name.Equals(name)));
});
});
}
#endregion
}
}
| shahabhijeet/azure-sdk-for-net | src/AzureStack/Admin/ComputeAdmin/Compute.Admin.Tests/src/QuotaTests.cs | C# | mit | 11,692 |
<?php
namespace SMW\Tests\DataValues;
use SMW\DataValues\ImportValue;
/**
* @covers \SMW\DataValues\ImportValue
*
* @group semantic-mediawiki
*
* @license GNU GPL v2+
* @since 2.2
*
* @author mwjames
*/
class ImportValueTest extends \PHPUnit_Framework_TestCase {
public function testCanConstruct() {
$this->assertInstanceOf(
'\SMW\DataValues\ImportValue',
new ImportValue( '__imp' )
);
// FIXME Legacy naming remove in 3.x
$this->assertInstanceOf(
'\SMWImportValue',
new ImportValue( '__imp' )
);
}
public function testErrorForInvalidUserValue() {
$instance = new ImportValue( '__imp' );
$instance->setUserValue( 'FooBar' );
$this->assertEquals(
'FooBar',
$instance->getWikiValue()
);
$this->assertNotEmpty(
$instance->getErrors()
);
}
}
| owen-kellie-smith/mediawiki | wiki/extensions/SemanticMediaWiki/tests/phpunit/includes/DataValues/ImportValueTest.php | PHP | mit | 805 |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// 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.
// File System.Security.Policy.Hash.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Security.Policy
{
sealed public partial class Hash : EvidenceBase, System.Runtime.Serialization.ISerializable
{
#region Methods and constructors
public override EvidenceBase Clone()
{
return default(EvidenceBase);
}
public static System.Security.Policy.Hash CreateMD5(byte[] md5)
{
Contract.Ensures(Contract.Result<System.Security.Policy.Hash>() != null);
return default(System.Security.Policy.Hash);
}
public static System.Security.Policy.Hash CreateSHA1(byte[] sha1)
{
Contract.Ensures(Contract.Result<System.Security.Policy.Hash>() != null);
return default(System.Security.Policy.Hash);
}
public static System.Security.Policy.Hash CreateSHA256(byte[] sha256)
{
Contract.Ensures(Contract.Result<System.Security.Policy.Hash>() != null);
return default(System.Security.Policy.Hash);
}
public byte[] GenerateHash(System.Security.Cryptography.HashAlgorithm hashAlg)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
return default(byte[]);
}
public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
}
public Hash(System.Reflection.Assembly assembly)
{
Contract.Ensures(!assembly.IsDynamic);
}
public override string ToString()
{
return default(string);
}
#endregion
#region Properties and indexers
public byte[] MD5
{
get
{
Contract.Ensures(Contract.Result<byte[]>() != null);
return default(byte[]);
}
}
public byte[] SHA1
{
get
{
Contract.Ensures(Contract.Result<byte[]>() != null);
return default(byte[]);
}
}
public byte[] SHA256
{
get
{
Contract.Ensures(Contract.Result<byte[]>() != null);
return default(byte[]);
}
}
#endregion
}
}
| ndykman/CodeContracts | Microsoft.Research/Contracts/MsCorlib/Sources/System.Security.Policy.Hash.cs | C# | mit | 3,951 |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// 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.
// File System.ComponentModel.SingleConverter.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.ComponentModel
{
public partial class SingleConverter : BaseNumberConverter
{
#region Methods and constructors
public SingleConverter()
{
}
#endregion
}
}
| ndykman/CodeContracts | Microsoft.Research/Contracts/System/Sources/System.ComponentModel.SingleConverter.cs | C# | mit | 2,183 |
// Type definitions for angular-file-upload 2.5
// Project: https://github.com/nervgh/angular-file-upload
// Definitions by: Cyril Gandon <https://github.com/cyrilgandon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
import * as angular from 'angular';
export interface FileUploaderFactory {
new(options?: Partial<FileUploaderOptions>): FileUploader;
}
export interface FileUploaderOptions {
/**
* Path on the server to upload files
* @default /
*/
url: string;
/**
* Name of the field which will contain the file, default is file
* @default file
*/
alias: string;
/**
* Headers to be sent along with the files. HTML5 browsers only.
* @default {}
*/
headers: Headers;
/**
* Items to be uploaded
* @default []
*/
queue: FileItem[];
/**
* Automatically upload files after adding them to the queue
* @default false
*/
autoUpload: boolean;
/**
* Remove files from the queue after uploading
* @default false
*/
removeAfterUpload: boolean;
/**
* It's a request method. HTML5 browsers only.
* @default POST
*/
method: string;
/**
* Filters to be applied to the files before adding them to the queue. If the filter returns true the file will be added to the queue
* @default [folderFilter, queueLimitFilter]
*/
filters: Filter[];
/**
* Data to be sent along with the files
* @default []
*/
formData: FormData[];
/**
* Maximum count of files.
* @default Number.MAX_VALUE
*/
queueLimit: number;
/**
* enable CORS. HTML5 browsers only.
* @default false
*/
withCredentials: boolean;
/**
* Disable multipart.
* @default false
*/
disableMultipart: boolean;
}
export interface FileUploader extends FileUploaderOptions {
/**
* Upload queue progress percentage. Read only.
*/
progress: number;
/**
* true if uploader is html5-uploader. Read only.
*/
isHTML5: boolean;
/**
* true if an upload is in progress. Read only.
*/
isUploading: boolean;
// **Methods**
/**
* Add items to the queue
*/
addToQueue(files: File | HTMLInputElement | object | FileList | object[], options: object, filters: Filter[] | string): void;
/**
* Remove an item from the queue, where value is {FileItem} or index of item.
*/
removeFromQueue(value: FileItem | number): void;
/**
* Removes all elements from the queue.
*/
clearQueue(): void;
/**
* Uploads an item, where value is {FileItem} or index of item.
*/
uploadItem(value: FileItem | number): void;
/**
* Cancels uploading of item, where value is {FileItem} or index of item.
*/
cancelItem(value: FileItem | number): void;
/**
* Upload all pending items on the queue.
*/
uploadAll(): void;
/**
* Cancels all current uploads.
*/
cancelAll(): void;
/**
* Destroys a uploader.
*/
destroy(): void;
/**
* Returns true if value is {File}.
*/
isFile(value: any): boolean;
/**
* Returns true if value is {FileLikeObject}.
*/
isFileLikeObject(value: any): boolean;
/**
* Returns the index of the {FileItem} queue element.
*/
getIndexOfItem(fileItem: FileItem): number;
/**
* Return items are ready to upload.
*/
getReadyItems(): FileItem[];
/**
* Return an array of all pending items on the queue
*/
getNotUploadedItems(): FileItem[];
// **Callbacks**
/**
* Fires after adding all the dragged or selected files to the queue.
*/
onAfterAddingAll(addedItems: FileItem[]): void;
/**
* When adding a file failed
*/
onWhenAddingFileFailed(item: FileItem, filter: Filter, options: object): void;
/**
* Fires after adding a single file to the queue.
*/
onAfterAddingFile(item: FileItem): void;
/**
* Fires before uploading an item.
*/
onBeforeUploadItem(item: FileItem): void;
/**
* On file upload progress.
*/
onProgressItem(item: FileItem, progress: number): void;
/**
* On file successfully uploaded
*/
onSuccessItem(item: FileItem, response: Response, status: number, headers: Headers): void;
/**
* On upload error
*/
onErrorItem(item: FileItem, response: Response, status: number, headers: Headers): void;
/**
* On cancel uploading
*/
onCancelItem(item: FileItem, response: Response, status: number, headers: Headers): void;
/**
* On file upload complete (independently of the sucess of the operation)
*/
onCompleteItem(item: FileItem, response: Response, status: number, headers: Headers): void;
/**
* On upload queue progress
*/
onProgressAll(progress: number): void;
/**
* On all loaded when uploading an entire queue, or on file loaded when uploading a single independent file
*/
onCompleteAll(): void;
}
export interface FileLikeObject {
/**
* Equals File.lastModifiedDate
*/
lastModifiedDate: any;
/**
* Equals File.name
*/
name: string;
/**
* Equals Blob.size, in octet
*/
size: number;
/**
* Equals Blob.type, in octet
*/
type: string;
}
export interface FileItem {
// **Properties**
file: FileLikeObject;
/**
* Path on the server in which this file will be uploaded
*/
url: string;
/**
* Name of the field which will contain the file, default is file
*/
alias: string;
/**
* Headers to be sent along with this file. HTML5 browsers only.
*/
headers: Headers;
/**
* Data to be sent along with this file
*/
formData: FormData[];
/**
* It's a request method. By default POST. HTML5 browsers only.
*/
method: string;
/**
* enable CORS. HTML5 browsers only.
*/
withCredentials: boolean;
/**
* Remove this file from the queue after uploading
*/
removeAfterUpload: boolean;
/**
* A sequence number upload. Read only.
*/
index: number;
/**
* File upload progress percentage. Read only.
*/
progress: number;
/**
* File is ready to upload. Read only.
*/
isReady: boolean;
/**
* true if the file is being uploaded. Read only.
*/
isUploading: boolean;
/**
* true if the file was uploaded. Read only.
*/
isUploaded: boolean;
/**
* true if the file was uploaded successfully. Read only.
*/
isSuccess: boolean;
/**
* true if uploading was canceled. Read only.
*/
isCancel: boolean;
/**
* true if occurred error while file uploading. Read only.
*/
isError: boolean;
/**
* Reference to the parent Uploader object for this file. Read only.
*/
uploader: FileUploader;
// **Methods**
/**
* Cancels uploading of this file
*/
cancel(): void;
/**
* Remove this file from the queue
*/
remove(): void;
/**
* Upload this file
*/
upload(): void;
// **Callbacks**
/**
* Fires before uploading an item.
*/
onBeforeUpload(): void;
/**
* On file upload progress.
*/
onProgress(progress: number): void;
/**
* On file successfully uploaded
*/
onSuccess(response: Response, status: number, headers: Headers): void;
/**
* On upload error
*/
onError(response: Response, status: number, headers: Headers): void;
/**
* On cancel uploading
*/
onCancel(response: Response, status: number, headers: Headers): void;
/**
* On file upload complete (independently of the sucess of the operation)
*/
onComplete(response: Response, status: number, headers: Headers): void;
}
export type SyncFilter = (item: File | FileLikeObject, options?: object) => boolean;
export type AsyncFilter = (item: File | FileLikeObject, options: object | undefined, deferred: angular.IDeferred<any>) => void;
export interface Filter {
name: string;
fn: SyncFilter | AsyncFilter;
}
| benishouga/DefinitelyTyped | types/angular-file-upload/index.d.ts | TypeScript | mit | 8,307 |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Product\Resolver;
use Doctrine\Common\Collections\Collection;
use Sylius\Component\Product\Model\ProductInterface;
use Sylius\Component\Product\Model\ProductOptionInterface;
use Sylius\Component\Product\Model\ProductOptionValueInterface;
final class AvailableProductOptionValuesResolver implements AvailableProductOptionValuesResolverInterface
{
public function resolve(ProductInterface $product, ProductOptionInterface $productOption): Collection
{
if (!$product->hasOption($productOption)) {
throw new \InvalidArgumentException(
sprintf(
'Cannot resolve available product option values. Option "%s" does not belong to product "%s".',
$product->getCode(),
$productOption->getCode()
)
);
}
return $productOption->getValues()->filter(
static function (ProductOptionValueInterface $productOptionValue) use ($product) {
foreach ($product->getEnabledVariants() as $productVariant) {
if ($productVariant->hasOptionValue($productOptionValue)) {
return true;
}
}
return false;
}
);
}
}
| loic425/Sylius | src/Sylius/Component/Product/Resolver/AvailableProductOptionValuesResolver.php | PHP | mit | 1,552 |
package polyfill
import (
"os"
"path/filepath"
"github.com/go-git/go-billy/v5"
)
// Polyfill is a helper that implements all missing method from billy.Filesystem.
type Polyfill struct {
billy.Basic
c capabilities
}
type capabilities struct{ tempfile, dir, symlink, chroot bool }
// New creates a new filesystem wrapping up 'fs' the intercepts all the calls
// made and errors if fs doesn't implement any of the billy interfaces.
func New(fs billy.Basic) billy.Filesystem {
if original, ok := fs.(billy.Filesystem); ok {
return original
}
h := &Polyfill{Basic: fs}
_, h.c.tempfile = h.Basic.(billy.TempFile)
_, h.c.dir = h.Basic.(billy.Dir)
_, h.c.symlink = h.Basic.(billy.Symlink)
_, h.c.chroot = h.Basic.(billy.Chroot)
return h
}
func (h *Polyfill) TempFile(dir, prefix string) (billy.File, error) {
if !h.c.tempfile {
return nil, billy.ErrNotSupported
}
return h.Basic.(billy.TempFile).TempFile(dir, prefix)
}
func (h *Polyfill) ReadDir(path string) ([]os.FileInfo, error) {
if !h.c.dir {
return nil, billy.ErrNotSupported
}
return h.Basic.(billy.Dir).ReadDir(path)
}
func (h *Polyfill) MkdirAll(filename string, perm os.FileMode) error {
if !h.c.dir {
return billy.ErrNotSupported
}
return h.Basic.(billy.Dir).MkdirAll(filename, perm)
}
func (h *Polyfill) Symlink(target, link string) error {
if !h.c.symlink {
return billy.ErrNotSupported
}
return h.Basic.(billy.Symlink).Symlink(target, link)
}
func (h *Polyfill) Readlink(link string) (string, error) {
if !h.c.symlink {
return "", billy.ErrNotSupported
}
return h.Basic.(billy.Symlink).Readlink(link)
}
func (h *Polyfill) Lstat(path string) (os.FileInfo, error) {
if !h.c.symlink {
return nil, billy.ErrNotSupported
}
return h.Basic.(billy.Symlink).Lstat(path)
}
func (h *Polyfill) Chroot(path string) (billy.Filesystem, error) {
if !h.c.chroot {
return nil, billy.ErrNotSupported
}
return h.Basic.(billy.Chroot).Chroot(path)
}
func (h *Polyfill) Root() string {
if !h.c.chroot {
return string(filepath.Separator)
}
return h.Basic.(billy.Chroot).Root()
}
func (h *Polyfill) Underlying() billy.Basic {
return h.Basic
}
// Capabilities implements the Capable interface.
func (h *Polyfill) Capabilities() billy.Capability {
return billy.Capabilities(h.Basic)
}
| cez81/gitea | vendor/github.com/go-git/go-billy/v5/helper/polyfill/polyfill.go | GO | mit | 2,297 |
require 'webrat/core/elements/form'
require 'action_dispatch/testing/integration'
module Webrat
Form.class_eval do
def self.parse_rails_request_params(params)
Rack::Utils.parse_nested_query(params)
end
end
module Logging
# Avoid RAILS_DEFAULT_LOGGER deprecation warning
def logger # :nodoc:
::Rails.logger
end
end
class RailsAdapter
protected
def do_request(http_method, url, data, headers)
update_protocol(url)
integration_session.send(http_method, normalize_url(url), params: data, headers: headers)
end
end
end
module ActionDispatch #:nodoc:
IntegrationTest.class_eval do
include Webrat::Methods
include Webrat::Matchers
end
end
| lrosskamp/makealist-public | vendor/cache/ruby/2.3.0/gems/devise-4.3.0/test/support/webrat/integrations/rails.rb | Ruby | mit | 717 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Reflection.Metadata.Ecma335
{
internal class NamespaceCache
{
private readonly MetadataReader _metadataReader;
private readonly object _namespaceTableAndListLock = new object();
private Dictionary<NamespaceDefinitionHandle, NamespaceData> _namespaceTable;
private NamespaceData _rootNamespace;
private ImmutableArray<NamespaceDefinitionHandle> _namespaceList;
private uint _virtualNamespaceCounter;
internal NamespaceCache(MetadataReader reader)
{
Debug.Assert(reader != null);
_metadataReader = reader;
}
/// <summary>
/// Returns whether the namespaceTable has been created. If it hasn't, calling a GetXXX method
/// on this will probably have a very high amount of overhead.
/// </summary>
internal bool CacheIsRealized
{
get { return _namespaceTable != null; }
}
internal string GetFullName(NamespaceDefinitionHandle handle)
{
Debug.Assert(!handle.HasFullName); // we should not hit the cache in this case.
NamespaceData data = GetNamespaceData(handle);
return data.FullName;
}
internal NamespaceData GetRootNamespace()
{
EnsureNamespaceTableIsPopulated();
Debug.Assert(_rootNamespace != null);
return _rootNamespace;
}
internal NamespaceData GetNamespaceData(NamespaceDefinitionHandle handle)
{
EnsureNamespaceTableIsPopulated();
NamespaceData result;
if (!_namespaceTable.TryGetValue(handle, out result))
{
Throw.InvalidHandle();
}
return result;
}
/// <summary>
/// This will return a StringHandle for the simple name of a namespace name at the given segment index.
/// If no segment index is passed explicitly or the "segment" index is greater than or equal to the number
/// of segments, then the last segment is used. "Segment" in this context refers to part of a namespace
/// name between dots.
///
/// Example: Given a NamespaceDefinitionHandle to "System.Collections.Generic.Test" called 'handle':
///
/// reader.GetString(GetSimpleName(handle)) == "Test"
/// reader.GetString(GetSimpleName(handle, 0)) == "System"
/// reader.GetString(GetSimpleName(handle, 1)) == "Collections"
/// reader.GetString(GetSimpleName(handle, 2)) == "Generic"
/// reader.GetString(GetSimpleName(handle, 3)) == "Test"
/// reader.GetString(GetSimpleName(handle, 1000)) == "Test"
/// </summary>
private StringHandle GetSimpleName(NamespaceDefinitionHandle fullNamespaceHandle, int segmentIndex = Int32.MaxValue)
{
StringHandle handleContainingSegment = fullNamespaceHandle.GetFullName();
Debug.Assert(!handleContainingSegment.IsVirtual);
int lastFoundIndex = fullNamespaceHandle.GetHeapOffset() - 1;
int currentSegment = 0;
while (currentSegment < segmentIndex)
{
int currentIndex = _metadataReader.StringHeap.IndexOfRaw(lastFoundIndex + 1, '.');
if (currentIndex == -1)
{
break;
}
lastFoundIndex = currentIndex;
++currentSegment;
}
Debug.Assert(lastFoundIndex >= 0 || currentSegment == 0);
// + 1 because lastFoundIndex will either "point" to a '.', or will be -1. Either way,
// we want the next char.
int resultIndex = lastFoundIndex + 1;
return StringHandle.FromOffset(resultIndex).WithDotTermination();
}
/// <summary>
/// Two distinct namespace handles represent the same namespace if their full names are the same. This
/// method merges builders corresponding to such namespace handles.
/// </summary>
private void PopulateNamespaceTable()
{
lock (_namespaceTableAndListLock)
{
if (_namespaceTable != null)
{
return;
}
var namespaceBuilderTable = new Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder>();
// Make sure to add entry for root namespace. The root namespace is special in that even
// though it might not have types of its own it always has an equivalent representation
// as a nil handle and we don't want to handle it below as dot-terminated virtual namespace.
// We use NamespaceDefinitionHandle.FromIndexOfFullName(0) instead of default(NamespaceDefinitionHandle) so
// that we never hand back a handle to the user that doesn't have a typeid as that prevents
// round-trip conversion to Handle and back. (We may discover other handle aliases for the
// root namespace (any nil/empty string will do), but we need this one to always be there.
NamespaceDefinitionHandle rootNamespace = NamespaceDefinitionHandle.FromFullNameOffset(0);
namespaceBuilderTable.Add(
rootNamespace,
new NamespaceDataBuilder(
rootNamespace,
rootNamespace.GetFullName(),
String.Empty));
PopulateTableWithTypeDefinitions(namespaceBuilderTable);
PopulateTableWithExportedTypes(namespaceBuilderTable);
Dictionary<string, NamespaceDataBuilder> stringTable;
MergeDuplicateNamespaces(namespaceBuilderTable, out stringTable);
List<NamespaceDataBuilder> virtualNamespaces;
ResolveParentChildRelationships(stringTable, out virtualNamespaces);
var namespaceTable = new Dictionary<NamespaceDefinitionHandle, NamespaceData>();
foreach (var group in namespaceBuilderTable)
{
// Freeze() caches the result, so any many-to-one relationships
// between keys and values will be preserved and efficiently handled.
namespaceTable.Add(group.Key, group.Value.Freeze());
}
if (virtualNamespaces != null)
{
foreach (var virtualNamespace in virtualNamespaces)
{
namespaceTable.Add(virtualNamespace.Handle, virtualNamespace.Freeze());
}
}
_namespaceTable = namespaceTable;
_rootNamespace = namespaceTable[rootNamespace];
}
}
/// <summary>
/// This will take 'table' and merge all of the NamespaceData instances that point to the same
/// namespace. It has to create 'stringTable' as an intermediate dictionary, so it will hand it
/// back to the caller should the caller want to use it.
/// </summary>
private void MergeDuplicateNamespaces(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table, out Dictionary<string, NamespaceDataBuilder> stringTable)
{
var namespaces = new Dictionary<string, NamespaceDataBuilder>();
List<KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>> remaps = null;
foreach (var group in table)
{
NamespaceDataBuilder data = group.Value;
NamespaceDataBuilder existingRecord;
if (namespaces.TryGetValue(data.FullName, out existingRecord))
{
// Children should not exist until the next step.
Debug.Assert(data.Namespaces.Count == 0);
data.MergeInto(existingRecord);
if (remaps == null)
{
remaps = new List<KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>>();
}
remaps.Add(new KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>(group.Key, existingRecord));
}
else
{
namespaces.Add(data.FullName, data);
}
}
// Needs to be done outside of foreach (var group in table) to avoid modifying the dictionary while foreach'ing over it.
if (remaps != null)
{
foreach (var tuple in remaps)
{
table[tuple.Key] = tuple.Value;
}
}
stringTable = namespaces;
}
/// <summary>
/// Creates a NamespaceDataBuilder instance that contains a synthesized NamespaceDefinitionHandle,
/// as well as the name provided.
/// </summary>
private NamespaceDataBuilder SynthesizeNamespaceData(string fullName, NamespaceDefinitionHandle realChild)
{
Debug.Assert(realChild.HasFullName);
int numberOfSegments = 0;
foreach (char c in fullName)
{
if (c == '.')
{
numberOfSegments++;
}
}
StringHandle simpleName = GetSimpleName(realChild, numberOfSegments);
var namespaceHandle = NamespaceDefinitionHandle.FromVirtualIndex(++_virtualNamespaceCounter);
return new NamespaceDataBuilder(namespaceHandle, simpleName, fullName);
}
/// <summary>
/// Quick convenience method that handles linking together child + parent
/// </summary>
private void LinkChildDataToParentData(NamespaceDataBuilder child, NamespaceDataBuilder parent)
{
Debug.Assert(child != null && parent != null);
Debug.Assert(!child.Handle.IsNil);
child.Parent = parent.Handle;
parent.Namespaces.Add(child.Handle);
}
/// <summary>
/// Links a child to its parent namespace. If the parent namespace doesn't exist, this will create a
/// virtual one. This will automatically link any virtual namespaces it creates up to its parents.
/// </summary>
private void LinkChildToParentNamespace(Dictionary<string, NamespaceDataBuilder> existingNamespaces,
NamespaceDataBuilder realChild,
ref List<NamespaceDataBuilder> virtualNamespaces)
{
Debug.Assert(realChild.Handle.HasFullName);
string childName = realChild.FullName;
var child = realChild;
// The condition for this loop is very complex -- essentially, we keep going
// until we:
// A. Encounter the root namespace as 'child'
// B. Find a preexisting namespace as 'parent'
while (true)
{
int lastIndex = childName.LastIndexOf('.');
string parentName;
if (lastIndex == -1)
{
if (childName.Length == 0)
{
return;
}
else
{
parentName = String.Empty;
}
}
else
{
parentName = childName.Substring(0, lastIndex);
}
NamespaceDataBuilder parentData;
if (existingNamespaces.TryGetValue(parentName, out parentData))
{
LinkChildDataToParentData(child, parentData);
return;
}
if (virtualNamespaces != null)
{
foreach (var data in virtualNamespaces)
{
if (data.FullName == parentName)
{
LinkChildDataToParentData(child, data);
return;
}
}
}
else
{
virtualNamespaces = new List<NamespaceDataBuilder>();
}
var virtualParent = SynthesizeNamespaceData(parentName, realChild.Handle);
LinkChildDataToParentData(child, virtualParent);
virtualNamespaces.Add(virtualParent);
childName = virtualParent.FullName;
child = virtualParent;
}
}
/// <summary>
/// This will link all parents/children in the given namespaces dictionary up to each other.
///
/// In some cases, we need to synthesize namespaces that do not have any type definitions or forwarders
/// of their own, but do have child namespaces. These are returned via the virtualNamespaces out
/// parameter.
/// </summary>
private void ResolveParentChildRelationships(Dictionary<string, NamespaceDataBuilder> namespaces, out List<NamespaceDataBuilder> virtualNamespaces)
{
virtualNamespaces = null;
foreach (var namespaceData in namespaces.Values)
{
LinkChildToParentNamespace(namespaces, namespaceData, ref virtualNamespaces);
}
}
/// <summary>
/// Loops through all type definitions in metadata, adding them to the given table
/// </summary>
private void PopulateTableWithTypeDefinitions(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table)
{
Debug.Assert(table != null);
foreach (var typeHandle in _metadataReader.TypeDefinitions)
{
TypeDefinition type = _metadataReader.GetTypeDefinition(typeHandle);
if (type.Attributes.IsNested())
{
continue;
}
NamespaceDefinitionHandle namespaceHandle = _metadataReader.TypeDefTable.GetNamespaceDefinition(typeHandle);
NamespaceDataBuilder builder;
if (table.TryGetValue(namespaceHandle, out builder))
{
builder.TypeDefinitions.Add(typeHandle);
}
else
{
StringHandle name = GetSimpleName(namespaceHandle);
string fullName = _metadataReader.GetString(namespaceHandle);
var newData = new NamespaceDataBuilder(namespaceHandle, name, fullName);
newData.TypeDefinitions.Add(typeHandle);
table.Add(namespaceHandle, newData);
}
}
}
/// <summary>
/// Loops through all type forwarders in metadata, adding them to the given table
/// </summary>
private void PopulateTableWithExportedTypes(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table)
{
Debug.Assert(table != null);
foreach (var exportedTypeHandle in _metadataReader.ExportedTypes)
{
ExportedType exportedType = _metadataReader.GetExportedType(exportedTypeHandle);
if (exportedType.Implementation.Kind == HandleKind.ExportedType)
{
continue; // skip nested exported types.
}
NamespaceDefinitionHandle namespaceHandle = exportedType.NamespaceDefinition;
NamespaceDataBuilder builder;
if (table.TryGetValue(namespaceHandle, out builder))
{
builder.ExportedTypes.Add(exportedTypeHandle);
}
else
{
Debug.Assert(namespaceHandle.HasFullName);
StringHandle simpleName = GetSimpleName(namespaceHandle);
string fullName = _metadataReader.GetString(namespaceHandle);
var newData = new NamespaceDataBuilder(namespaceHandle, simpleName, fullName);
newData.ExportedTypes.Add(exportedTypeHandle);
table.Add(namespaceHandle, newData);
}
}
}
/// <summary>
/// Populates namespaceList with distinct namespaces. No ordering is guaranteed.
/// </summary>
private void PopulateNamespaceList()
{
lock (_namespaceTableAndListLock)
{
if (_namespaceList != null)
{
return;
}
Debug.Assert(_namespaceTable != null);
var namespaceNameSet = new HashSet<string>();
var namespaceListBuilder = ImmutableArray.CreateBuilder<NamespaceDefinitionHandle>();
foreach (var group in _namespaceTable)
{
var data = group.Value;
if (namespaceNameSet.Add(data.FullName))
{
namespaceListBuilder.Add(group.Key);
}
}
_namespaceList = namespaceListBuilder.ToImmutable();
}
}
/// <summary>
/// If the namespace table doesn't exist, populates it!
/// </summary>
private void EnsureNamespaceTableIsPopulated()
{
// PERF: Branch will rarely be taken; do work in PopulateNamespaceList() so this can be inlined easily.
if (_namespaceTable == null)
{
PopulateNamespaceTable();
}
Debug.Assert(_namespaceTable != null);
}
/// <summary>
/// If the namespace list doesn't exist, populates it!
/// </summary>
private void EnsureNamespaceListIsPopulated()
{
if (_namespaceList == null)
{
PopulateNamespaceList();
}
Debug.Assert(_namespaceList != null);
}
/// <summary>
/// An intermediate class used to build NamespaceData instances. This was created because we wanted to
/// use ImmutableArrays in NamespaceData, but having ArrayBuilders and ImmutableArrays that served the
/// same purpose in NamespaceData got ugly. With the current design of how we create our Namespace
/// dictionary, this needs to be a class because we have a many-to-one mapping between NamespaceHandles
/// and NamespaceData. So, the pointer semantics must be preserved.
///
/// This class assumes that the builders will not be modified in any way after the first call to
/// Freeze().
/// </summary>
private class NamespaceDataBuilder
{
public readonly NamespaceDefinitionHandle Handle;
public readonly StringHandle Name;
public readonly string FullName;
public NamespaceDefinitionHandle Parent;
public ImmutableArray<NamespaceDefinitionHandle>.Builder Namespaces;
public ImmutableArray<TypeDefinitionHandle>.Builder TypeDefinitions;
public ImmutableArray<ExportedTypeHandle>.Builder ExportedTypes;
private NamespaceData _frozen;
public NamespaceDataBuilder(NamespaceDefinitionHandle handle, StringHandle name, string fullName)
{
Handle = handle;
Name = name;
FullName = fullName;
Namespaces = ImmutableArray.CreateBuilder<NamespaceDefinitionHandle>();
TypeDefinitions = ImmutableArray.CreateBuilder<TypeDefinitionHandle>();
ExportedTypes = ImmutableArray.CreateBuilder<ExportedTypeHandle>();
}
/// <summary>
/// Returns a NamespaceData that represents this NamespaceDataBuilder instance. After calling
/// this method, it is an error to use any methods or fields except Freeze() on the target
/// NamespaceDataBuilder.
/// </summary>
public NamespaceData Freeze()
{
// It is not an error to call this function multiple times. We cache the result
// because it's immutable.
if (_frozen == null)
{
var namespaces = Namespaces.ToImmutable();
Namespaces = null;
var typeDefinitions = TypeDefinitions.ToImmutable();
TypeDefinitions = null;
var exportedTypes = ExportedTypes.ToImmutable();
ExportedTypes = null;
_frozen = new NamespaceData(Name, FullName, Parent, namespaces, typeDefinitions, exportedTypes);
}
return _frozen;
}
public void MergeInto(NamespaceDataBuilder other)
{
Parent = default(NamespaceDefinitionHandle);
other.Namespaces.AddRange(this.Namespaces);
other.TypeDefinitions.AddRange(this.TypeDefinitions);
other.ExportedTypes.AddRange(this.ExportedTypes);
}
}
}
}
| alphonsekurian/corefx | src/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/NamespaceCache.cs | C# | mit | 21,688 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
namespace PowerBIRestDemo.Results
{
public class ChallengeResult : IHttpActionResult
{
public ChallengeResult(string loginProvider, ApiController controller)
{
LoginProvider = loginProvider;
Request = controller.Request;
}
public string LoginProvider { get; set; }
public HttpRequestMessage Request { get; set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
Request.GetOwinContext().Authentication.Challenge(LoginProvider);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
response.RequestMessage = Request;
return Task.FromResult(response);
}
}
}
| ericleigh007/azure-stream-analytics | Samples/SensorDataAnalytics/SourceCode/Archived/PowerBIRestDemo-master/PowerBIRestDemo/Results/ChallengeResult.cs | C# | mit | 964 |
<?php
/**
* EMongoGridFS.php
*
* PHP version 5.2+
*
* @author Jose Martinez <jmartinez@ibitux.com>
* @author Philippe Gaultier <pgaultier@ibitux.com>
* @copyright 2010 Ibitux
* @license http://www.yiiframework.com/license/ BSD license
* @version SVN: $Revision: $
* @category ext
* @package ext.YiiMongoDbSuite
*/
/**
* EMongoGridFS
*
* Authorization management, dispatches actions and views on the system
*
* @author Jose Martinez <jmartinez@ibitux.com>
* @author Philippe Gaultier <pgaultier@ibitux.com>
* @copyright 2010 Ibitux
* @license http://www.yiiframework.com/license/ BSD license
* @version SVN: $Revision: $
* @category ext
* @package ext.YiiMongoDbSuite
*
*/
class MongoImage extends EMongoGridFS
{
public $metadata;
/**
* this is similar to the get tableName() method. this returns tha name of the
* document for this class. this should be in all lowercase.
*/
public function getCollectionName()
{
return 'images';
}
/**
* Returns the static model of the specified AR class.
*
* @param string $className class name
*
* @return CompaniesDb the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function rules()
{
return array(
array('filename, metadata','safe'),
array('filename','required'),
);
}
} | vishin-pavel/quick-app | www/protected/extensions/YiiMongoDbSuite/examples/MongoImage.php | PHP | mit | 1,364 |
<?php
/**
* This file is part of the Nette Framework (http://nette.org)
* Copyright (c) 2004 David Grudl (http://davidgrudl.com)
*/
namespace Nette\Reflection;
use Nette,
Nette\Utils\ObjectMixin;
/**
* Reports information about a classes variable.
*
* @author David Grudl
* @property-read ClassType $declaringClass
* @property-read IAnnotation[][] $annotations
* @property-read string $description
* @property-read string $name
* @property mixed $value
* @property-read bool $public
* @property-read bool $private
* @property-read bool $protected
* @property-read bool $static
* @property-read bool $default
* @property-read int $modifiers
* @property-read string $docComment
* @property-write bool $accessible
*/
class Property extends \ReflectionProperty
{
public function __toString()
{
return parent::getDeclaringClass()->getName() . '::$' . $this->getName();
}
/********************* Reflection layer ****************d*g**/
/**
* @return ClassType
*/
public function getDeclaringClass()
{
return new ClassType(parent::getDeclaringClass()->getName());
}
/********************* Nette\Annotations support ****************d*g**/
/**
* Has property specified annotation?
* @param string
* @return bool
*/
public function hasAnnotation($name)
{
$res = AnnotationsParser::getAll($this);
return !empty($res[$name]);
}
/**
* Returns an annotation value.
* @param string
* @return IAnnotation
*/
public function getAnnotation($name)
{
$res = AnnotationsParser::getAll($this);
return isset($res[$name]) ? end($res[$name]) : NULL;
}
/**
* Returns all annotations.
* @return IAnnotation[][]
*/
public function getAnnotations()
{
return AnnotationsParser::getAll($this);
}
/**
* Returns value of annotation 'description'.
* @return string
*/
public function getDescription()
{
return $this->getAnnotation('description');
}
/********************* Nette\Object behaviour ****************d*g**/
public function __call($name, $args)
{
return ObjectMixin::call($this, $name, $args);
}
public function &__get($name)
{
return ObjectMixin::get($this, $name);
}
public function __set($name, $value)
{
ObjectMixin::set($this, $name, $value);
}
public function __isset($name)
{
return ObjectMixin::has($this, $name);
}
public function __unset($name)
{
ObjectMixin::remove($this, $name);
}
}
| xvadur01/BPIS | vendor/nette/reflection/src/Reflection/Property.php | PHP | mit | 2,431 |
import Mmenu from '../../core/oncanvas/mmenu.oncanvas';
import * as DOM from '../../core/_dom';
// DEPRECATED
// Will be removed in version 8.2
export default function (navbar) {
// Add content
var next = DOM.create('a.mm-btn.mm-btn_next.mm-navbar__btn');
navbar.append(next);
// Update to opened panel
var org;
var _url, _txt;
this.bind('openPanel:start', (panel) => {
org = panel.querySelector('.' + this.conf.classNames.navbars.panelNext);
_url = org ? org.getAttribute('href') : '';
_txt = org ? org.innerHTML : '';
if (_url) {
next.setAttribute('href', _url);
}
else {
next.removeAttribute('href');
}
next.classList[_url || _txt ? 'remove' : 'add']('mm-hidden');
next.innerHTML = _txt;
});
// Add screenreader / aria support
this.bind('openPanel:start:sr-aria', (panel) => {
Mmenu.sr_aria(next, 'hidden', next.matches('mm-hidden'));
Mmenu.sr_aria(next, 'owns', (next.getAttribute('href') || '').slice(1));
});
}
| extend1994/cdnjs | ajax/libs/jQuery.mmenu/8.2.3/addons/navbars/_navbar.next.js | JavaScript | mit | 1,073 |
/**
* Copyright (c) 2010-2016, openHAB.org and others.
*
* 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.io.caldav.internal;
import static org.quartz.impl.matchers.GroupMatcher.jobGroupEquals;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import org.apache.commons.lang3.BooleanUtils;
import org.joda.time.DateTimeZone;
import org.openhab.core.service.AbstractActiveService;
import org.openhab.io.caldav.CalDavEvent;
import org.openhab.io.caldav.CalDavLoader;
import org.openhab.io.caldav.CalDavQuery;
import org.openhab.io.caldav.EventNotifier;
import org.openhab.io.caldav.internal.EventStorage.CalendarRuntime;
import org.openhab.io.caldav.internal.EventStorage.EventContainer;
import org.openhab.io.caldav.internal.job.EventJob;
import org.openhab.io.caldav.internal.job.EventJob.EventTrigger;
import org.openhab.io.caldav.internal.job.EventReloaderJob;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.quartz.DateBuilder;
import org.quartz.DateBuilder.IntervalUnit;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.sardine.Sardine;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.util.CompatibilityHints;
/**
* Loads all events from the configured calDAV servers. This is done with an
* interval. All interesting events are hold in memory.
*
* @author Robert Delbrück
* @since 1.8.0
*
*/
public class CalDavLoaderImpl extends AbstractActiveService implements ManagedService, CalDavLoader {
private static final String JOB_NAME_EVENT_RELOADER = "event-reloader";
public static final String JOB_NAME_EVENT_START = "event-start";
public static final String JOB_NAME_EVENT_END = "event-end";
private static final String PROP_RELOAD_INTERVAL = "reloadInterval";
private static final String PROP_PRELOAD_TIME = "preloadTime";
private static final String PROP_HISTORIC_LOAD_TIME = "historicLoadTime";
private static final String PROP_URL = "url";
private static final String PROP_PASSWORD = "password";
private static final String PROP_USERNAME = "username";
private static final String PROP_TIMEZONE = "timeZone";
public static final String PROP_DISABLE_CERTIFICATE_VERIFICATION = "disableCertificateVerification";
private static final String PROP_LAST_MODIFIED_TIMESTAMP_VALID = "lastModifiedFileTimeStampValid";
public static DateTimeZone defaultTimeZone = DateTimeZone.getDefault();
private static final Logger log = LoggerFactory.getLogger(CalDavLoaderImpl.class);
public static final String CACHE_PATH = "etc/caldav";
private ScheduledExecutorService execService;
private List<EventNotifier> eventListenerList = new ArrayList<EventNotifier>();
private Scheduler scheduler;
public static CalDavLoaderImpl instance;
public CalDavLoaderImpl() {
if (instance != null) {
throw new IllegalStateException("something went wrong, the loader service should be singleton");
}
instance = this;
}
@Override
public void start() {
super.start();
if (this.isProperlyConfigured()) {
try {
scheduler = new StdSchedulerFactory().getScheduler();
this.removeAllJobs();
} catch (SchedulerException e) {
log.error("cannot get job-scheduler", e);
throw new IllegalStateException("cannot get job-scheduler", e);
}
this.startLoading();
}
}
private void removeAllJobs() throws SchedulerException {
scheduler.deleteJobs(new ArrayList<JobKey>(scheduler.getJobKeys(jobGroupEquals(JOB_NAME_EVENT_RELOADER))));
scheduler.deleteJobs(new ArrayList<JobKey>(scheduler.getJobKeys(jobGroupEquals(JOB_NAME_EVENT_START))));
scheduler.deleteJobs(new ArrayList<JobKey>(scheduler.getJobKeys(jobGroupEquals(JOB_NAME_EVENT_END))));
}
@Override
public void shutdown() {
super.shutdown();
try {
this.removeAllJobs();
} catch (SchedulerException e) {
log.error("cannot remove jobs: " + e.getMessage(), e);
}
}
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
if (config != null) {
CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);
// just temporary
Map<String, CalDavConfig> configMap = new HashMap<String, CalDavConfig>();
Enumeration<String> iter = config.keys();
while (iter.hasMoreElements()) {
String key = iter.nextElement();
log.trace("configuration parameter: " + key);
if (key.equals("service.pid")) {
continue;
} else if (key.equals(PROP_TIMEZONE)) {
log.debug("overriding default timezone {} with {}", defaultTimeZone, config.get(key));
defaultTimeZone = DateTimeZone.forID(config.get(key) + "");
if (defaultTimeZone == null) {
throw new ConfigurationException(PROP_TIMEZONE, "invalid timezone value: " + config.get(key));
}
log.debug("found timeZone: {}", defaultTimeZone);
continue;
}
String[] keys = key.split(":");
if (keys.length != 2) {
throw new ConfigurationException(key, "unknown identifier");
}
String id = keys[0];
String paramKey = keys[1];
CalDavConfig calDavConfig = configMap.get(id);
if (calDavConfig == null) {
calDavConfig = new CalDavConfig();
configMap.put(id, calDavConfig);
}
String value = config.get(key) + "";
calDavConfig.setKey(id);
if (paramKey.equals(PROP_USERNAME)) {
calDavConfig.setUsername(value);
} else if (paramKey.equals(PROP_PASSWORD)) {
calDavConfig.setPassword(value);
} else if (paramKey.equals(PROP_URL)) {
calDavConfig.setUrl(value);
} else if (paramKey.equals(PROP_RELOAD_INTERVAL)) {
calDavConfig.setReloadMinutes(Integer.parseInt(value));
} else if (paramKey.equals(PROP_PRELOAD_TIME)) {
calDavConfig.setPreloadMinutes(Integer.parseInt(value));
} else if (paramKey.equals(PROP_HISTORIC_LOAD_TIME)) {
calDavConfig.setHistoricLoadMinutes(Integer.parseInt(value));
} else if (paramKey.equals(PROP_LAST_MODIFIED_TIMESTAMP_VALID)) {
calDavConfig.setLastModifiedFileTimeStampValid(BooleanUtils.toBoolean(value));
} else if (paramKey.equals(PROP_DISABLE_CERTIFICATE_VERIFICATION)) {
calDavConfig.setDisableCertificateVerification(BooleanUtils.toBoolean(value));
}
}
// verify if all required parameters are set
for (String id : configMap.keySet()) {
if (configMap.get(id).getUrl() == null) {
throw new ConfigurationException(PROP_URL, PROP_URL + " must be set");
}
if (configMap.get(id).getUsername() == null) {
throw new ConfigurationException(PROP_USERNAME, PROP_USERNAME + " must be set");
}
if (configMap.get(id).getPassword() == null) {
throw new ConfigurationException(PROP_PASSWORD, PROP_PASSWORD + " must be set");
}
log.trace("config for id '{}': {}", id, configMap.get(id));
}
// initialize event cache
for (CalDavConfig calDavConfig : configMap.values()) {
final CalendarRuntime eventRuntime = new CalendarRuntime();
eventRuntime.setConfig(calDavConfig);
File cachePath = Util.getCachePath(calDavConfig.getKey());
if (!cachePath.exists() && !cachePath.mkdirs()) {
log.error("cannot create directory ({}) for calendar caching (missing rights?)",
cachePath.getAbsoluteFile());
continue;
}
EventStorage.getInstance().getEventCache().put(calDavConfig.getKey(), eventRuntime);
}
setProperlyConfigured(true);
}
}
public List<EventNotifier> getEventListenerList() {
return eventListenerList;
}
public Scheduler getScheduler() {
return scheduler;
}
@Override
public void addListener(EventNotifier notifier) {
this.eventListenerList.add(notifier);
// notify for missing changes
for (CalendarRuntime calendarRuntime : EventStorage.getInstance().getEventCache().values()) {
for (EventContainer eventContainer : calendarRuntime.getEventMap().values()) {
for (CalDavEvent event : eventContainer.getEventList()) {
notifier.eventLoaded(event);
}
}
}
}
@Override
public void removeListener(EventNotifier notifier) {
this.eventListenerList.remove(notifier);
}
public synchronized void addEventToMap(EventContainer eventContainer, boolean createTimer) {
CalendarRuntime calendarRuntime = EventStorage.getInstance().getEventCache()
.get(eventContainer.getCalendarId());
ConcurrentHashMap<String, EventContainer> eventContainerMap = calendarRuntime.getEventMap();
if (eventContainerMap.containsKey(eventContainer.getEventId())) {
EventContainer eventContainerOld = eventContainerMap.get(eventContainer.getEventId());
// event is already in map
if (eventContainer.getLastChanged().isAfter(eventContainerOld.getLastChanged())) {
log.debug("event is already in event map and newer -> delete the old one, reschedule timer");
// cancel old jobs
for (String timerKey : eventContainerOld.getTimerMap()) {
try {
this.scheduler.deleteJob(JobKey.jobKey(timerKey));
} catch (SchedulerException e) {
log.error("cannot cancel event with job-id: " + timerKey, e);
}
}
eventContainerOld.getTimerMap().clear();
// override event
eventContainerMap.put(eventContainer.getEventId(), eventContainer);
for (EventNotifier notifier : eventListenerList) {
for (CalDavEvent event : eventContainerOld.getEventList()) {
log.trace("notify listener... {}", notifier);
try {
notifier.eventRemoved(event);
} catch (Exception e) {
log.error("error while invoking listener", e);
}
}
}
for (EventNotifier notifier : eventListenerList) {
for (CalDavEvent event : eventContainer.getEventList()) {
log.trace("notify listener... {}", notifier);
try {
notifier.eventLoaded(event);
} catch (Exception e) {
log.error("error while invoking listener", e);
}
}
}
if (createTimer) {
int index = 0;
for (CalDavEvent event : eventContainer.getEventList()) {
if (event.getEnd().isAfterNow()) {
try {
createJob(eventContainer, event, index);
} catch (SchedulerException e) {
log.error("cannot create jobs for event '{}': ", event.getShortName(), e.getMessage());
}
}
index++;
}
}
} else {
// event is already in map and not updated, ignoring
}
} else {
// event is new
eventContainerMap.put(eventContainer.getEventId(), eventContainer);
log.trace("listeners for events: {}", eventListenerList.size());
for (EventNotifier notifier : eventListenerList) {
for (CalDavEvent event : eventContainer.getEventList()) {
log.trace("notify listener... {}", notifier);
try {
notifier.eventLoaded(event);
} catch (Exception e) {
log.error("error while invoking listener", e);
}
}
}
if (createTimer) {
int index = 0;
for (CalDavEvent event : eventContainer.getEventList()) {
if (event.getEnd().isAfterNow()) {
try {
createJob(eventContainer, event, index);
} catch (SchedulerException e) {
log.error("cannot create jobs for event: " + event.getShortName());
}
}
index++;
}
}
}
}
private synchronized void createJob(final EventContainer eventContainer, final CalDavEvent event, final int index)
throws SchedulerException {
final String triggerStart = JOB_NAME_EVENT_START + "-" + event.getShortName() + "-" + index;
final boolean startJobTriggerDeleted = this.scheduler
.unscheduleJob(TriggerKey.triggerKey(triggerStart, JOB_NAME_EVENT_START));
final boolean startJobDeleted = this.scheduler.deleteJob(JobKey.jobKey(triggerStart, JOB_NAME_EVENT_START));
log.trace("old start job ({}) deleted? {}/{}", triggerStart, startJobDeleted, startJobTriggerDeleted);
Date startDate = event.getStart().toDate();
JobDetail jobStart = JobBuilder.newJob().ofType(EventJob.class)
.usingJobData(EventJob.KEY_CONFIG, eventContainer.getCalendarId())
.usingJobData(EventJob.KEY_EVENT, eventContainer.getEventId())
.usingJobData(EventJob.KEY_REC_INDEX, index)
.usingJobData(EventJob.KEY_EVENT_TRIGGER, EventTrigger.BEGIN.name()).storeDurably(false)
.withIdentity(triggerStart, JOB_NAME_EVENT_START).build();
Trigger jobTriggerStart = TriggerBuilder.newTrigger().withIdentity(triggerStart, JOB_NAME_EVENT_START)
.startAt(startDate).build();
this.scheduler.scheduleJob(jobStart, jobTriggerStart);
eventContainer.getTimerMap().add(triggerStart);
log.debug("begin timer scheduled for event '{}' @ {}", event.getShortName(), startDate);
final String triggerEnd = JOB_NAME_EVENT_END + "-" + event.getShortName() + "-" + index;
final boolean endJobTriggerDeleted = this.scheduler
.unscheduleJob(TriggerKey.triggerKey(triggerEnd, JOB_NAME_EVENT_END));
final boolean endJobDeleted = this.scheduler.deleteJob(JobKey.jobKey(triggerEnd, JOB_NAME_EVENT_END));
log.trace("old end job ({}) deleted? {}/{}", triggerEnd, endJobDeleted, endJobTriggerDeleted);
Date endDate = event.getEnd().toDate();
JobDetail jobEnd = JobBuilder.newJob().ofType(EventJob.class)
.usingJobData(EventJob.KEY_CONFIG, eventContainer.getCalendarId())
.usingJobData(EventJob.KEY_EVENT, eventContainer.getEventId())
.usingJobData(EventJob.KEY_REC_INDEX, index)
.usingJobData(EventJob.KEY_EVENT_TRIGGER, EventTrigger.END.name()).storeDurably(false)
.withIdentity(triggerEnd, JOB_NAME_EVENT_END).build();
Trigger jobTriggerEnd = TriggerBuilder.newTrigger().withIdentity(triggerEnd, JOB_NAME_EVENT_END)
.startAt(endDate).build();
this.scheduler.scheduleJob(jobEnd, jobTriggerEnd);
eventContainer.getTimerMap().add(triggerEnd);
log.debug("end timer scheduled for event '{}' @ {}", event.getShortName(), endDate);
}
public void startLoading() {
if (execService != null) {
return;
}
log.trace("starting execution...");
int i = 0;
for (final CalendarRuntime eventRuntime : EventStorage.getInstance().getEventCache().values()) {
try {
JobDetail job = JobBuilder.newJob().ofType(EventReloaderJob.class)
.usingJobData(EventReloaderJob.KEY_CONFIG, eventRuntime.getConfig().getKey())
.withIdentity(eventRuntime.getConfig().getKey(), JOB_NAME_EVENT_RELOADER).storeDurably()
.build();
this.scheduler.addJob(job, false);
SimpleTrigger jobTrigger = TriggerBuilder.newTrigger().forJob(job)
.withIdentity(eventRuntime.getConfig().getKey(), JOB_NAME_EVENT_RELOADER)
.startAt(DateBuilder.futureDate(10 + i, IntervalUnit.SECOND)).withSchedule(SimpleScheduleBuilder
.repeatMinutelyForever(eventRuntime.getConfig().getReloadMinutes()))
.build();
this.scheduler.scheduleJob(jobTrigger);
log.info("reload job scheduled for: {}", eventRuntime.getConfig().getKey());
} catch (SchedulerException e) {
log.error("cannot schedule calendar-reloader", e);
}
// next event 10 seconds later
i += 10;
}
}
@Override
protected void execute() {
}
@Override
protected long getRefreshInterval() {
return 1000;
}
@Override
protected String getName() {
return "CalDav Loader";
}
@Override
public void addEvent(CalDavEvent calDavEvent) {
final CalendarRuntime calendarRuntime = EventStorage.getInstance().getEventCache()
.get(calDavEvent.getCalendarId());
CalDavConfig config = calendarRuntime.getConfig();
if (config == null) {
log.error("cannot find config for calendar id: {}", calDavEvent.getCalendarId());
}
Sardine sardine = Util.getConnection(config);
Calendar calendar = Util.createCalendar(calDavEvent, defaultTimeZone);
try {
final String fullIcsFile = config.getUrl() + "/" + calDavEvent.getFilename() + ".ics";
if (calendarRuntime.getEventContainerByFilename(calDavEvent.getFilename()) != null) {
log.debug("event will be updated: {}", fullIcsFile);
try {
sardine.delete(fullIcsFile);
} catch (IOException e) {
log.error("cannot remove old ics file: {}", fullIcsFile);
}
} else {
log.debug("event is new: {}", fullIcsFile);
}
sardine.put(fullIcsFile, calendar.toString().getBytes("UTF-8"));
EventContainer eventContainer = new EventContainer(calDavEvent.getCalendarId());
eventContainer.setEventId(calDavEvent.getId());
eventContainer.setFilename(Util.getFilename(calDavEvent.getFilename()));
eventContainer.getEventList().add(calDavEvent);
eventContainer.setLastChanged(calDavEvent.getLastChanged());
this.addEventToMap(eventContainer, false);
} catch (UnsupportedEncodingException e) {
log.error("cannot write event", e);
} catch (IOException e) {
log.error("cannot write event", e);
}
}
@Override
public List<CalDavEvent> getEvents(final CalDavQuery query) {
log.trace("quering events for filter: {}", query);
final ArrayList<CalDavEvent> eventList = new ArrayList<CalDavEvent>();
if (query.getCalendarIds() != null) {
for (String calendarId : query.getCalendarIds()) {
final CalendarRuntime eventRuntime = EventStorage.getInstance().getEventCache().get(calendarId);
if (eventRuntime == null) {
log.debug("calendar id {} not found", calendarId);
continue;
}
for (EventContainer eventContainer : eventRuntime.getEventMap().values()) {
for (CalDavEvent calDavEvent : eventContainer.getEventList()) {
if (query.getFrom() != null) {
if (calDavEvent.getEnd().isBefore(query.getFrom())) {
continue;
}
}
if (query.getTo() != null) {
if (calDavEvent.getStart().isAfter(query.getTo())) {
continue;
}
}
eventList.add(calDavEvent);
}
}
}
}
if (query.getSort() != null) {
Collections.sort(eventList, new Comparator<CalDavEvent>() {
@Override
public int compare(CalDavEvent arg0, CalDavEvent arg1) {
if (query.getSort().equals(CalDavQuery.Sort.ASCENDING)) {
return (arg0.getStart().compareTo(arg1.getStart()));
} else if (query.getSort().equals(CalDavQuery.Sort.DESCENDING)) {
return (arg1.getStart().compareTo(arg0.getStart()));
} else {
return 0;
}
}
});
}
log.debug("return event list for {} with {} entries", query, eventList.size());
return eventList;
}
}
| paolodenti/openhab | bundles/io/org.openhab.io.caldav/src/main/java/org/openhab/io/caldav/internal/CalDavLoaderImpl.java | Java | epl-1.0 | 23,171 |
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Curl based implementation of apiIO.
*
* @author Chris Chabot <chabotc@google.com>
* @author Chirag Shah <chirags@google.com>
*/
require_once 'apiCacheParser.php';
class apiCurlIO implements apiIO {
const CONNECTION_ESTABLISHED = "HTTP/1.0 200 Connection established\r\n\r\n";
const FORM_URLENCODED = 'application/x-www-form-urlencoded';
private static $ENTITY_HTTP_METHODS = array("POST" => null, "PUT" => null);
private static $HOP_BY_HOP = array(
'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
'te', 'trailers', 'transfer-encoding', 'upgrade');
private static $DEFAULT_CURL_PARAMS = array (
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => 0,
CURLOPT_FAILONERROR => false,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_HEADER => true,
CURLOPT_VERBOSE => false,
);
/**
* Perform an authenticated / signed apiHttpRequest.
* This function takes the apiHttpRequest, calls apiAuth->sign on it
* (which can modify the request in what ever way fits the auth mechanism)
* and then calls apiCurlIO::makeRequest on the signed request
*
* @param apiHttpRequest $request
* @return apiHttpRequest The resulting HTTP response including the
* responseHttpCode, responseHeaders and responseBody.
*/
public function authenticatedRequest(apiHttpRequest $request) {
$request = apiClient::$auth->sign($request);
return $this->makeRequest($request);
}
/**
* Execute a apiHttpRequest
*
* @param apiHttpRequest $request the http request to be executed
* @return apiHttpRequest http request with the response http code, response
* headers and response body filled in
* @throws apiIOException on curl or IO error
*/
public function makeRequest(apiHttpRequest $request) {
// First, check to see if we have a valid cached version.
$cached = $this->getCachedRequest($request);
if ($cached !== false) {
if (apiCacheParser::mustRevalidate($cached)) {
$addHeaders = array();
if ($cached->getResponseHeader('etag')) {
// [13.3.4] If an entity tag has been provided by the origin server,
// we must use that entity tag in any cache-conditional request.
$addHeaders['If-None-Match'] = $cached->getResponseHeader('etag');
} elseif ($cached->getResponseHeader('date')) {
$addHeaders['If-Modified-Since'] = $cached->getResponseHeader('date');
}
$request->setRequestHeaders($addHeaders);
} else {
// No need to revalidate the request, return it directly
return $cached;
}
}
if (array_key_exists($request->getRequestMethod(),
self::$ENTITY_HTTP_METHODS)) {
$request = $this->processEntityRequest($request);
}
$ch = curl_init();
curl_setopt_array($ch, self::$DEFAULT_CURL_PARAMS);
curl_setopt($ch, CURLOPT_URL, $request->getUrl());
if ($request->getPostBody()) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getPostBody());
}
$requestHeaders = $request->getRequestHeaders();
if ($requestHeaders && is_array($requestHeaders)) {
$parsed = array();
foreach ($requestHeaders as $k => $v) {
$parsed[] = "$k: $v";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $parsed);
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request->getRequestMethod());
curl_setopt($ch, CURLOPT_USERAGENT, $request->getUserAgent());
$respData = curl_exec($ch);
// Retry if certificates are missing.
if (curl_errno($ch) == CURLE_SSL_CACERT) {
error_log('SSL certificate problem, verify that the CA cert is OK.'
. ' Retrying with the CA cert bundle from google-api-php-client.');
curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacerts.pem');
$respData = curl_exec($ch);
}
$respHeaderSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$respHttpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErrorNum = curl_errno($ch);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlErrorNum != CURLE_OK) {
throw new apiIOException("HTTP Error: ($respHttpCode) $curlError");
}
// Parse out the raw response into usable bits
list($responseHeaders, $responseBody) =
self::parseHttpResponse($respData, $respHeaderSize);
if ($respHttpCode == 304 && $cached) {
// If the server responded NOT_MODIFIED, return the cached request.
if (isset($responseHeaders['connection'])) {
$hopByHop = array_merge(
self::$HOP_BY_HOP,
explode(',', $responseHeaders['connection'])
);
$endToEnd = array();
foreach($hopByHop as $key) {
if (isset($responseHeaders[$key])) {
$endToEnd[$key] = $responseHeaders[$key];
}
}
$cached->setResponseHeaders($endToEnd);
}
return $cached;
}
// Fill in the apiHttpRequest with the response values
$request->setResponseHttpCode($respHttpCode);
$request->setResponseHeaders($responseHeaders);
$request->setResponseBody($responseBody);
// Store the request in cache (the function checks to see if the request
// can actually be cached)
$this->setCachedRequest($request);
// And finally return it
return $request;
}
/**
* @visible for testing.
* Cache the response to an HTTP request if it is cacheable.
* @param apiHttpRequest $request
* @return bool Returns true if the insertion was successful.
* Otherwise, return false.
*/
public function setCachedRequest(apiHttpRequest $request) {
// Determine if the request is cacheable.
if (apiCacheParser::isResponseCacheable($request)) {
apiClient::$cache->set($request->getCacheKey(), $request);
return true;
}
return false;
}
/**
* @visible for testing.
* @param apiHttpRequest $request
* @return apiHttpRequest|bool Returns the cached object or
* false if the operation was unsuccessful.
*/
public function getCachedRequest(apiHttpRequest $request) {
if (false == apiCacheParser::isRequestCacheable($request)) {
false;
}
return apiClient::$cache->get($request->getCacheKey());
}
/**
* @param $respData
* @param $headerSize
* @return array
*/
public static function parseHttpResponse($respData, $headerSize) {
if (stripos($respData, self::CONNECTION_ESTABLISHED) !== false) {
$respData = str_ireplace(self::CONNECTION_ESTABLISHED, '', $respData);
}
if ($headerSize) {
$responseBody = substr($respData, $headerSize);
$responseHeaders = substr($respData, 0, $headerSize);
} else {
list($responseHeaders, $responseBody) = explode("\r\n\r\n", $respData, 2);
}
$responseHeaders = self::parseResponseHeaders($responseHeaders);
return array($responseHeaders, $responseBody);
}
public static function parseResponseHeaders($rawHeaders) {
$responseHeaders = array();
$responseHeaderLines = explode("\r\n", $rawHeaders);
foreach ($responseHeaderLines as $headerLine) {
if ($headerLine && strpos($headerLine, ':') !== false) {
list($header, $value) = explode(': ', $headerLine, 2);
$header = strtolower($header);
if (isset($responseHeaders[$header])) {
$responseHeaders[$header] .= "\n" . $value;
} else {
$responseHeaders[$header] = $value;
}
}
}
return $responseHeaders;
}
/**
* @visible for testing
* Process an http request that contains an enclosed entity.
* @param apiHttpRequest $request
* @return apiHttpRequest Processed request with the enclosed entity.
*/
public function processEntityRequest(apiHttpRequest $request) {
$postBody = $request->getPostBody();
$contentType = $request->getRequestHeader("content-type");
// Set the default content-type as application/x-www-form-urlencoded.
if (false == $contentType) {
$contentType = self::FORM_URLENCODED;
$request->setRequestHeaders(array('content-type' => $contentType));
}
// Force the payload to match the content-type asserted in the header.
if ($contentType == self::FORM_URLENCODED && is_array($postBody)) {
$postBody = http_build_query($postBody, '', '&');
$request->setPostBody($postBody);
}
// Make sure the content-length header is set.
if (!$postBody || is_string($postBody)) {
$postsLength = strlen($postBody);
$request->setRequestHeaders(array('content-length' => $postsLength));
}
return $request;
}
} | mpranivong/golf-phpnuke | wp/wp-content/plugins/wordcents/src/io/apiCurlIO.php | PHP | gpl-2.0 | 9,202 |
/***************************************************************************
* Copyright (C) 2007 by Tarek Saidi *
* tarek.saidi@arcor.de *
* *
* 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; version 2 of the License. *
* *
* 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., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <QTreeWidget>
#include <QPainter>
#include <QPaintEvent>
#include <QResizeEvent>
#include "main.h"
#include "TrashCanDlg.h"
TrashCanDialog::TrashCanDialog(QWidget* parent,IDatabase* database,const QList<IEntryHandle*>& TrashItems):QDialog(parent){
setupUi(this);
Entries=TrashItems;
for(int i=0;i<Entries.size();i++){
QTreeWidgetItem* item=new QTreeWidgetItem(treeWidget);
item->setData(0,Qt::UserRole,i);
item->setText(0,Entries[i]->group()->title());
item->setText(1,Entries[i]->title());
item->setText(2,Entries[i]->username());
item->setText(3,Entries[i]->expire().dateToString(Qt::LocalDate));
item->setIcon(0,database->icon(Entries[i]->group()->image()));
item->setIcon(1,database->icon(Entries[i]->image()));
}
connect(treeWidget,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this,SLOT(OnItemDoubleClicked(QTreeWidgetItem*)));
connect(treeWidget,SIGNAL(customContextMenuRequested(const QPoint&)),this,SLOT(OnContextMenu(const QPoint&)));
ContextMenu=new QMenu(this);
ContextMenu->addAction(getIcon("restore"),"Restore");
ContextMenu->addAction(getIcon("deleteentry"),"Delete");
}
void TrashCanDialog::paintEvent(QPaintEvent* event){
QDialog::paintEvent(event);
QPainter painter(this);
painter.setClipRegion(event->region());
painter.drawPixmap(QPoint(0,0),BannerPixmap);
}
void TrashCanDialog::resizeEvent(QResizeEvent* event){
createBanner(&BannerPixmap,getPixmap("trashcan"),tr("Recycle Bin"),width());
QDialog::resizeEvent(event);
}
void TrashCanDialog::OnItemDoubleClicked(QTreeWidgetItem* item){
SelectedEntry=Entries[item->data(0,Qt::UserRole).toInt()];
accept();
}
void TrashCanDialog::OnContextMenu(const QPoint& pos){
if(treeWidget->itemAt(pos)){
QTreeWidgetItem* item=treeWidget->itemAt(pos);
if(treeWidget->selectedItems().size()==0){
treeWidget->setItemSelected(item,true);
}
else{
if(!treeWidget->isItemSelected(item)){
while(treeWidget->selectedItems().size()){
treeWidget->setItemSelected(treeWidget->selectedItems()[0],false);
}
treeWidget->setItemSelected(item,true);
}
}
}
else
{
while(treeWidget->selectedItems().size())
treeWidget->setItemSelected(treeWidget->selectedItems()[0],false);
}
ContextMenu->popup(treeWidget->viewport()->mapToGlobal(pos));
}
///TODO 0.2.3 locale aware string/date compare for correct sorting
| dwihn0r/keepassx | src/dialogs/TrashCanDlg.cpp | C++ | gpl-2.0 | 3,752 |
// Copyright 2013 Dolphin Emulator Project
// Licensed under GPLv2
// Refer to the license.txt file included.
#include "Core/ConfigManager.h"
#include "Core/HW/Sram.h"
// english
SRAM sram_dump = {{
0xFF, 0x6B,
0x00, 0x91,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0x40,
0x00,
0x00,
0x00,
0x2C,
0x44, 0x4F, 0x4C, 0x50, 0x48, 0x49, 0x4E, 0x53, 0x4C, 0x4F, 0x54, 0x41,
0x44, 0x4F, 0x4C, 0x50, 0x48, 0x49, 0x4E, 0x53, 0x4C, 0x4F, 0x54, 0x42,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00,
0x00, 0x00,
0x00, 0x00,
0x00, 0x00,
0x00,
0x00,
0x6E, 0x6D,
0x00, 0x00,
0x00, 0x00
}};
#if 0
// german
SRAM sram_dump_german = {{
0x1F, 0x66,
0xE0, 0x96,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x04, 0xEA, 0x19, 0x40,
0x00,
0x00,
0x01,
0x3C,
0x12, 0xD5, 0xEA, 0xD3, 0x00, 0xFA, 0x2D, 0x33, 0x13, 0x41, 0x26, 0x03,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00,
0x00, 0x00,
0x00, 0x00,
0x00, 0x00,
0x00,
0x00,
0x84, 0xFF,
0x00, 0x00,
0x00, 0x00
}};
#endif
void InitSRAM()
{
File::IOFile file(SConfig::GetInstance().m_LocalCoreStartupParameter.m_strSRAM, "rb");
if (file)
{
if (!file.ReadArray(&g_SRAM, 1))
{
ERROR_LOG(EXPANSIONINTERFACE, "EXI IPL-DEV: Could not read all of SRAM");
g_SRAM = sram_dump;
}
}
else
{
g_SRAM = sram_dump;
}
}
void SetCardFlashID(u8* buffer, u8 card_index)
{
u64 rand = Common::swap64( *(u64*)&(buffer[12]));
u8 csum=0;
for (int i = 0; i < 12; i++)
{
rand = (((rand * (u64)0x0000000041c64e6dULL) + (u64)0x0000000000003039ULL) >> 16);
csum += g_SRAM.flash_id[card_index][i] = buffer[i] - ((u8)rand&0xff);
rand = (((rand * (u64)0x0000000041c64e6dULL) + (u64)0x0000000000003039ULL) >> 16);
rand &= (u64)0x0000000000007fffULL;
}
g_SRAM.flashID_chksum[card_index] = csum^0xFF;
}
| zhuowei/dolphin | Source/Core/Core/HW/Sram.cpp | C++ | gpl-2.0 | 1,852 |
/* 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 "engines/wintermute/debugger.h"
#include "engines/wintermute/wintermute.h"
#include "engines/wintermute/base/base_engine.h"
#include "engines/wintermute/base/base_file_manager.h"
#include "engines/wintermute/base/base_game.h"
namespace Wintermute {
Console::Console(WintermuteEngine *vm) : GUI::Debugger(), _engineRef(vm) {
registerCmd("show_fps", WRAP_METHOD(Console, Cmd_ShowFps));
registerCmd("dump_file", WRAP_METHOD(Console, Cmd_DumpFile));
}
Console::~Console(void) {
}
bool Console::Cmd_ShowFps(int argc, const char **argv) {
if (argc > 1) {
if (Common::String(argv[1]) == "true") {
_engineRef->_game->setShowFPS(true);
} else if (Common::String(argv[1]) == "false") {
_engineRef->_game->setShowFPS(false);
}
}
return true;
}
bool Console::Cmd_DumpFile(int argc, const char **argv) {
if (argc != 3) {
debugPrintf("Usage: %s <file path> <output file name>\n", argv[0]);
return true;
}
Common::String filePath = argv[1];
Common::String outFileName = argv[2];
BaseFileManager *fileManager = BaseEngine::instance().getFileManager();
Common::SeekableReadStream *inFile = fileManager->openFile(filePath);
if (!inFile) {
debugPrintf("File '%s' not found\n", argv[1]);
return true;
}
Common::DumpFile *outFile = new Common::DumpFile();
outFile->open(outFileName);
byte *data = new byte[inFile->size()];
inFile->read(data, inFile->size());
outFile->write(data, inFile->size());
outFile->finalize();
outFile->close();
delete[] data;
delete outFile;
delete inFile;
debugPrintf("Resource file '%s' dumped to file '%s'\n", argv[1], argv[2]);
return true;
}
} // End of namespace Wintermute
| clone2727/cabal | engines/wintermute/debugger.cpp | C++ | gpl-2.0 | 2,600 |
// 2005-12-01 Paolo Carlini <pcarlini@suse.de>
// Copyright (C) 2005, 2009 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option)
// any later version.
// This library 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 library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// { dg-do compile }
#include <vector>
namespace N
{
struct X { };
template<typename T>
X operator+(T, std::size_t)
{ return X(); }
template<typename T>
X operator-(T, T)
{ return X(); }
}
int main()
{
std::vector<N::X> v(5);
const std::vector<N::X> w(1);
v[0];
w[0];
v.size();
v.capacity();
v.resize(1);
v.insert(v.begin(), N::X());
v.insert(v.begin(), 1, N::X());
v.insert(v.begin(), w.begin(), w.end());
v = w;
return 0;
}
| embecosm/avr32-gcc | libstdc++-v3/testsuite/23_containers/vector/types/1.cc | C++ | gpl-2.0 | 1,294 |
<?php
/*
+---------------------------------------------------------------------------+
| Revive Adserver |
| http://www.revive-adserver.com |
| |
| Copyright: See the COPYRIGHT.txt file. |
| License: GPLv2 or later, see the LICENSE.txt file. |
+---------------------------------------------------------------------------+
*/
// Meta information
$translation_readable = "Bulgarian";
$translation_maintainer = "Revive Adserver Team";
$translation_contact = "noreply@revive-adserver.com";
| Tate-ad/revive-adserver | lib/max/language/bg/index.lang.php | PHP | gpl-2.0 | 723 |
require "mysql2"
require File.expand_path(File.dirname(__FILE__) + "/base.rb")
class ImportScripts::Kunena < ImportScripts::Base
KUNENA_DB = "kunena"
def initialize
super
@users = {}
@client = Mysql2::Client.new(
host: "localhost",
username: "root",
#password: "password",
database: KUNENA_DB
)
end
def execute
parse_users
puts "creating users"
create_users(@users) do |id, user|
{ id: id,
email: user[:email],
username: user[:username],
created_at: user[:created_at],
bio_raw: user[:bio],
moderator: user[:moderator] ? true : false,
admin: user[:admin] ? true : false,
suspended_at: user[:suspended] ? Time.zone.now : nil,
suspended_till: user[:suspended] ? 100.years.from_now : nil }
end
@users = nil
create_categories(@client.query("SELECT id, parent, name, description, ordering FROM jos_kunena_categories ORDER BY parent, id;")) do |c|
h = { id: c['id'], name: c['name'], description: c['description'], position: c['ordering'].to_i }
if c['parent'].to_i > 0
h[:parent_category_id] = category_id_from_imported_category_id(c['parent'])
end
h
end
import_posts
begin
create_admin(email: 'neil.lalonde@discourse.org', username: UserNameSuggester.suggest('neil'))
rescue => e
puts '', "Failed to create admin user"
puts e.message
end
end
def parse_users
# Need to merge data from joomla with kunena
puts "fetching Joomla users data from mysql"
results = @client.query("SELECT id, username, email, registerDate FROM jos_users;", cache_rows: false)
results.each do |u|
next unless u['id'].to_i > (0) && u['username'].present? && u['email'].present?
username = u['username'].gsub(' ', '_').gsub(/[^A-Za-z0-9_]/, '')[0, User.username_length.end]
if username.length < User.username_length.first
username = username * User.username_length.first
end
@users[u['id'].to_i] = { id: u['id'].to_i, username: username, email: u['email'], created_at: u['registerDate'] }
end
puts "fetching Kunena user data from mysql"
results = @client.query("SELECT userid, signature, moderator, banned FROM jos_kunena_users;", cache_rows: false)
results.each do |u|
next unless u['userid'].to_i > 0
user = @users[u['userid'].to_i]
if user
user[:bio] = u['signature']
user[:moderator] = (u['moderator'].to_i == 1)
user[:suspended] = u['banned'].present?
end
end
end
def import_posts
puts '', "creating topics and posts"
total_count = @client.query("SELECT COUNT(*) count FROM jos_kunena_messages m;").first['count']
batch_size = 1000
batches(batch_size) do |offset|
results = @client.query("
SELECT m.id id,
m.thread thread,
m.parent parent,
m.catid catid,
m.userid userid,
m.subject subject,
m.time time,
t.message message
FROM jos_kunena_messages m,
jos_kunena_messages_text t
WHERE m.id = t.mesid
ORDER BY m.id
LIMIT #{batch_size}
OFFSET #{offset};
", cache_rows: false)
break if results.size < 1
next if all_records_exist? :posts, results.map { |p| p['id'].to_i }
create_posts(results, total: total_count, offset: offset) do |m|
skip = false
mapped = {}
mapped[:id] = m['id']
mapped[:user_id] = user_id_from_imported_user_id(m['userid']) || -1
mapped[:raw] = m["message"]
mapped[:created_at] = Time.zone.at(m['time'])
if m['id'] == m['thread']
mapped[:category] = category_id_from_imported_category_id(m['catid'])
mapped[:title] = m['subject']
else
parent = topic_lookup_from_imported_post_id(m['parent'])
if parent
mapped[:topic_id] = parent[:topic_id]
mapped[:reply_to_post_number] = parent[:post_number] if parent[:post_number] > 1
else
puts "Parent post #{m['parent']} doesn't exist. Skipping #{m["id"]}: #{m["subject"][0..40]}"
skip = true
end
end
skip ? nil : mapped
end
end
end
end
ImportScripts::Kunena.new.perform
| fabianoleittes/discourse | script/import_scripts/kunena.rb | Ruby | gpl-2.0 | 4,377 |
/*
* This file is part of the cSploit.
*
* Copyleft of Massimo Dragano aka tux_mind <tux_mind@csploit.org>
*
* cSploit 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.
*
* cSploit 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 cSploit. If not, see <http://www.gnu.org/licenses/>.
*/
package org.csploit.android.tools;
import org.csploit.android.core.ChildManager;
import org.csploit.android.core.System;
import org.csploit.android.core.Child;
import org.csploit.android.core.Logger;
import org.csploit.android.events.Event;
import org.csploit.android.events.Host;
import org.csploit.android.events.HostLost;
import java.net.InetAddress;
public class NetworkRadar extends Tool {
public NetworkRadar() {
mHandler = "network-radar";
mCmdPrefix = null;
}
public static abstract class HostReceiver extends Child.EventReceiver {
public abstract void onHostFound(byte[] macAddress, InetAddress ipAddress, String name);
public abstract void onHostLost(InetAddress ipAddress);
public void onEvent(Event e) {
if ( e instanceof Host ) {
Host h = (Host)e;
onHostFound(h.ethAddress, h.ipAddress, h.name);
} else if ( e instanceof HostLost ) {
onHostLost(((HostLost)e).ipAddress);
} else {
Logger.error("Unknown event: " + e);
}
}
}
public Child start(HostReceiver receiver) throws ChildManager.ChildNotStartedException {
String ifName;
ifName = System.getNetwork().getInterface().getDisplayName();
return async(ifName, receiver);
}
}
| odin1314/android | cSploit/src/org/csploit/android/tools/NetworkRadar.java | Java | gpl-3.0 | 2,001 |
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* 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 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 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, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.function.pattern;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BaseBlock;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A pattern that returns the same {@link BaseBlock} each time.
*/
public class BlockPattern extends AbstractPattern {
private BaseBlock block;
/**
* Create a new pattern with the given block.
*
* @param block the block
*/
public BlockPattern(BaseBlock block) {
setBlock(block);
}
/**
* Get the block.
*
* @return the block that is always returned
*/
public BaseBlock getBlock() {
return block;
}
/**
* Set the block that is returned.
*
* @param block the block
*/
public void setBlock(BaseBlock block) {
checkNotNull(block);
this.block = block;
}
@Override
public BaseBlock apply(Vector position) {
return block;
}
}
| UnlimitedFreedom/UF-WorldEdit | worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/BlockPattern.java | Java | gpl-3.0 | 1,799 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
# ----------------------------------------------------------------------------
#
# This file is automatically generated by Magic Modules and manual
# changes will be clobbered when the file is regenerated.
#
# Please read more about how to change this file at
# https://www.github.com/GoogleCloudPlatform/magic-modules
#
# ----------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function
__metaclass__ = type
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'}
DOCUMENTATION = '''
---
module: gcp_sql_user_info
description:
- Gather info for GCP User
short_description: Gather info for GCP User
version_added: '2.8'
author: Google Inc. (@googlecloudplatform)
requirements:
- python >= 2.6
- requests >= 2.18.4
- google-auth >= 1.3.0
options:
instance:
description:
- The name of the Cloud SQL instance. This does not include the project ID.
- 'This field represents a link to a Instance resource in GCP. It can be specified
in two ways. First, you can place a dictionary with key ''name'' and value of
your resource''s name Alternatively, you can add `register: name-of-resource`
to a gcp_sql_instance task and then set this instance field to "{{ name-of-resource
}}"'
required: true
type: dict
project:
description:
- The Google Cloud Platform project to use.
type: str
auth_kind:
description:
- The type of credential used.
type: str
required: true
choices:
- application
- machineaccount
- serviceaccount
service_account_contents:
description:
- The contents of a Service Account JSON file, either in a dictionary or as a
JSON string that represents it.
type: jsonarg
service_account_file:
description:
- The path of a Service Account JSON file if serviceaccount is selected as type.
type: path
service_account_email:
description:
- An optional service account email address if machineaccount is selected and
the user does not wish to use the default email.
type: str
scopes:
description:
- Array of scopes to be used
type: list
env_type:
description:
- Specifies which Ansible environment you're running this module within.
- This should not be set unless you know what you're doing.
- This only alters the User Agent string for any API requests.
type: str
notes:
- for authentication, you can set service_account_file using the C(gcp_service_account_file)
env variable.
- for authentication, you can set service_account_contents using the C(GCP_SERVICE_ACCOUNT_CONTENTS)
env variable.
- For authentication, you can set service_account_email using the C(GCP_SERVICE_ACCOUNT_EMAIL)
env variable.
- For authentication, you can set auth_kind using the C(GCP_AUTH_KIND) env variable.
- For authentication, you can set scopes using the C(GCP_SCOPES) env variable.
- Environment variables values will only be used if the playbook values are not set.
- The I(service_account_email) and I(service_account_file) options are mutually exclusive.
'''
EXAMPLES = '''
- name: get info on a user
gcp_sql_user_info:
instance: "{{ instance }}"
project: test_project
auth_kind: serviceaccount
service_account_file: "/tmp/auth.pem"
'''
RETURN = '''
resources:
description: List of resources
returned: always
type: complex
contains:
host:
description:
- The host name from which the user can connect. For insert operations, host
defaults to an empty string. For update operations, host is specified as part
of the request URL. The host name cannot be updated after insertion.
returned: success
type: str
name:
description:
- The name of the user in the Cloud SQL instance.
returned: success
type: str
instance:
description:
- The name of the Cloud SQL instance. This does not include the project ID.
returned: success
type: dict
password:
description:
- The password for the user.
returned: success
type: str
'''
################################################################################
# Imports
################################################################################
from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest, replace_resource_dict
import json
################################################################################
# Main
################################################################################
def main():
module = GcpModule(argument_spec=dict(instance=dict(required=True, type='dict')))
if not module.params['scopes']:
module.params['scopes'] = ['https://www.googleapis.com/auth/sqlservice.admin']
return_value = {'resources': fetch_list(module, collection(module))}
module.exit_json(**return_value)
def collection(module):
res = {'project': module.params['project'], 'instance': replace_resource_dict(module.params['instance'], 'name')}
return "https://www.googleapis.com/sql/v1beta4/projects/{project}/instances/{instance}/users".format(**res)
def fetch_list(module, link):
auth = GcpSession(module, 'sql')
return auth.list(link, return_if_object, array_name='items')
def return_if_object(module, response):
# If not found, return nothing.
if response.status_code == 404:
return None
# If no content, return nothing.
if response.status_code == 204:
return None
try:
module.raise_for_status(response)
result = response.json()
except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst:
module.fail_json(msg="Invalid JSON response with error: %s" % inst)
if navigate_hash(result, ['error', 'errors']):
module.fail_json(msg=navigate_hash(result, ['error', 'errors']))
return result
if __name__ == "__main__":
main()
| anryko/ansible | lib/ansible/modules/cloud/google/gcp_sql_user_info.py | Python | gpl-3.0 | 6,527 |
var searchData=
[
['print',['PRINT',['../_m_d___parola__lib_8h.html#a1696fc35fb931f8c876786fbc1078ac4',1,'MD_Parola_lib.h']]],
['print_5fstate',['PRINT_STATE',['../_m_d___parola__lib_8h.html#a3fda4e1a5122a16a21bd96ae5217402c',1,'MD_Parola_lib.h']]],
['prints',['PRINTS',['../_m_d___parola__lib_8h.html#ad68f35c3cfe67be8d09d1cea8e788e13',1,'MD_Parola_lib.h']]],
['printx',['PRINTX',['../_m_d___parola__lib_8h.html#abf55b44e8497cbc3addccdeb294138cc',1,'MD_Parola_lib.h']]]
];
| javastraat/arduino | libraries/MD_Parola/doc/html/search/defines_70.js | JavaScript | gpl-3.0 | 482 |
/* 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/. */
const mapValuesByKeys = require('../../../js/lib/functional').mapValuesByKeys
const _ = null
const ExtensionConstants = {
BROWSER_ACTION_REGISTERED: _,
BROWSER_ACTION_UPDATED: _,
EXTENSION_INSTALLED: _,
EXTENSION_UNINSTALLED: _,
EXTENSION_ENABLED: _,
EXTENSION_DISABLED: _,
CONTEXT_MENU_CREATED: _,
CONTEXT_MENU_ALL_REMOVED: _,
CONTEXT_MENU_CLICKED: _
}
module.exports = mapValuesByKeys(ExtensionConstants)
| timborden/browser-laptop | app/common/constants/extensionConstants.js | JavaScript | mpl-2.0 | 633 |
<?php
$children = $main_article->getChildArticles();
$is_parent = in_array($main_article->getID(), $parents);
$is_selected = $main_article->getID() == $article->getID() || ($main_article->isRedirect() && $main_article->getRedirectArticleName() == $article->getTitle());
$is_first = $first;
$first = false;
$project_key = (\thebuggenie\core\framework\Context::isProjectContext()) ? \thebuggenie\core\framework\Context::getCurrentProject()->getKey() . ':' : '';
// $article_name = (strpos(mb_strtolower($main_article->getTitle()), 'category:') !== false) ? substr($main_article->getTitle(), 9+mb_strlen($project_key)) : substr($main_article->getTitle(), mb_strlen($project_key));
?>
<li class="<?php echo (isset($level) && $level >= 1) ? 'child' : 'parent'; ?> <?php if ($is_parent && !$is_selected) echo 'parent'; ?> <?php if ($is_selected) echo 'selected'; ?> level_<?php echo $level; ?>" id="article_sidebar_link_<?php echo $article->getID(); ?>">
<?php if (isset($level) && $level >= 1) echo image_tag('icon_tree_child.png', array('class' => 'branch')); ?>
<?php if ($is_first && $main_article->getArticleType() == \thebuggenie\modules\publish\entities\Article::TYPE_MANUAL): ?>
<?php echo image_tag('icon-article-type-manual.small.png'); ?>
<?php else: ?>
<?php echo (!empty($children)) ? image_tag('icon_folder.png', array(), false, 'publish') : image_tag('icon_article.png', array(), false, 'publish'); ?>
<?php endif; ?>
<?php echo link_tag(make_url('publish_article', array('article_name' => $main_article->getName())), $main_article->getManualName()); ?>
<?php if ($is_parent || $is_selected): ?>
<ul>
<?php foreach ($children as $child_article): ?>
<?php include_component('publish/manualsidebarlink', array('parents' => $parents, 'first' => $first, 'article' => $article, 'main_article' => $child_article, 'level' => $level + 1)); ?>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li>
| hurie/thebuggenie | modules/publish/templates/_manualsidebarlink.inc.php | PHP | mpl-2.0 | 2,024 |
/*
* Copyright 2008, 2009 Google Inc.
* Copyright 2006, 2007 Nintendo Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string.h>
#include <es/any.h>
#include <es/endian.h>
#include <es/formatter.h>
#include <es/interfaceData.h>
#include <es/object.h>
#include <es/base/IProcess.h>
#include <es/hashtable.h>
#include <es/reflect.h>
// TODO use proper name prefix or namespace
namespace es
{
Reflect::Interface& getInterface(const char* iid);
Object* getConstructor(const char* iid);
extern unsigned char* defaultInterfaceInfo[];
extern size_t defaultInterfaceCount;
} // namespace es
#ifndef VERBOSE
#define PRINTF(...) (__VA_ARGS__)
#else
#define PRINTF(...) report(__VA_ARGS__)
#endif
class ObjectValue;
#include "interface.h"
extern es::CurrentProcess* System();
namespace
{
const int GuidStringLength = 37; // Including terminating zero
}
//
// invoke
//
typedef long long (*InterfaceMethod)(void* self, ...);
static char heap[64*1024];
static Value* invoke(const char* iid, int number, InterfaceMethod** self, ListValue* list)
{
if (!self)
{
throw getErrorInstance("TypeError");
}
Reflect::Interface interface = es::getInterface(iid);
Reflect::Method method(interface.getMethod(number));
PRINTF("invoke %s.%s(%p)\n", interface.getName().c_str(), method.getName().c_str(), self);
// Set up parameters
Any argv[9];
Any* argp = argv;
int ext = 0; // extra parameter count
// Set this
*argp++ = Any(reinterpret_cast<intptr_t>(self));
// In the following implementation, we assume no out nor inout attribute is
// used for parameters.
Reflect::Type returnType = method.getReturnType();
switch (returnType.getType())
{
case Reflect::kAny:
// Any op(void* buf, int len, ...);
// FALL THROUGH
case Reflect::kString:
// const char* op(xxx* buf, int len, ...);
*argp++ = Any(reinterpret_cast<intptr_t>(heap));
*argp++ = Any(sizeof(heap));
break;
case Reflect::kSequence:
// int op(xxx* buf, int len, ...);
*argp++ = Any(reinterpret_cast<intptr_t>(heap));
++ext;
*argp++ = Any(static_cast<int32_t>(((*list)[0])->toNumber()));
break;
case Reflect::kArray:
// void op(xxx[x] buf, ...);
*argp++ = Any(reinterpret_cast<intptr_t>(heap));
break;
}
Reflect::Parameter param = method.listParameter();
for (int i = ext; param.next(); ++i, ++argp)
{
Reflect::Type type(param.getType());
Value* value = (*list)[i];
switch (type.getType())
{
case Reflect::kAny:
// Any variant, ...
switch (value->getType()) {
case Value::BoolType:
*argp = Any(static_cast<bool>(value->toBoolean()));
break;
case Value::StringType:
*argp = Any(value->toString().c_str());
break;
case Value::NumberType:
*argp = Any(static_cast<double>(value->toNumber()));
break;
case Value::ObjectType:
if (InterfacePointerValue* unknown = dynamic_cast<InterfacePointerValue*>(value))
{
*argp = Any(unknown->getObject());
}
else
{
// XXX expose ECMAScript object
*argp = Any(static_cast<Object*>(0));
}
break;
default:
*argp = Any();
break;
}
argp->makeVariant();
break;
case Reflect::kSequence:
// xxx* buf, int len, ...
// XXX Assume sequence<octet> now...
*argp++ = Any(reinterpret_cast<intptr_t>(value->toString().c_str()));
value = (*list)[++i];
*argp = Any(static_cast<int32_t>(value->toNumber()));
break;
case Reflect::kString:
*argp = Any(value->toString().c_str());
break;
case Reflect::kArray:
// void op(xxx[x] buf, ...);
// XXX expand data
break;
case Reflect::kObject:
if (InterfacePointerValue* unknown = dynamic_cast<InterfacePointerValue*>(value))
{
*argp = Any(unknown->getObject());
}
else
{
*argp = Any(static_cast<Object*>(0));
}
break;
case Reflect::kBoolean:
*argp = Any(static_cast<bool>(value->toBoolean()));
break;
case Reflect::kPointer:
*argp = Any(static_cast<intptr_t>(value->toNumber()));
break;
case Reflect::kShort:
*argp = Any(static_cast<int16_t>(value->toNumber()));
break;
case Reflect::kLong:
*argp = Any(static_cast<int32_t>(value->toNumber()));
break;
case Reflect::kOctet:
*argp = Any(static_cast<uint8_t>(value->toNumber()));
break;
case Reflect::kUnsignedShort:
*argp = Any(static_cast<uint16_t>(value->toNumber()));
break;
case Reflect::kUnsignedLong:
*argp = Any(static_cast<uint32_t>(value->toNumber()));
break;
case Reflect::kLongLong:
*argp = Any(static_cast<int64_t>(value->toNumber()));
break;
case Reflect::kUnsignedLongLong:
*argp = Any(static_cast<uint64_t>(value->toNumber()));
break;
case Reflect::kFloat:
*argp = Any(static_cast<float>(value->toNumber()));
break;
case Reflect::kDouble:
*argp = Any(static_cast<double>(value->toNumber()));
break;
default:
break;
}
}
// Invoke method
Register<Value> value;
unsigned methodNumber = interface.getInheritedMethodCount() + number;
int argc = argp - argv;
switch (returnType.getType())
{
case Reflect::kAny:
{
Any result = apply(argc, argv, (Any (*)()) ((*self)[methodNumber]));
switch (result.getType())
{
case Any::TypeVoid:
value = NullValue::getInstance();
break;
case Any::TypeBool:
value = BoolValue::getInstance(static_cast<bool>(result));
break;
case Any::TypeOctet:
value = new NumberValue(static_cast<uint8_t>(result));
break;
case Any::TypeShort:
value = new NumberValue(static_cast<int16_t>(result));
break;
case Any::TypeUnsignedShort:
value = new NumberValue(static_cast<uint16_t>(result));
break;
case Any::TypeLong:
value = new NumberValue(static_cast<int32_t>(result));
break;
case Any::TypeUnsignedLong:
value = new NumberValue(static_cast<uint32_t>(result));
break;
case Any::TypeLongLong:
value = new NumberValue(static_cast<int64_t>(result));
break;
case Any::TypeUnsignedLongLong:
value = new NumberValue(static_cast<uint64_t>(result));
break;
case Any::TypeFloat:
value = new NumberValue(static_cast<float>(result));
break;
case Any::TypeDouble:
value = new NumberValue(static_cast<double>(result));
break;
case Any::TypeString:
if (const char* string = static_cast<const char*>(result))
{
value = new StringValue(string);
}
else
{
value = NullValue::getInstance();
}
break;
case Any::TypeObject:
if (Object* unknown = static_cast<Object*>(result))
{
ObjectValue* instance = new InterfacePointerValue(unknown);
instance->setPrototype(getGlobal()->get(es::getInterface(Object::iid()).getName())->get("prototype")); // XXX Should use IID
value = instance;
}
else
{
value = NullValue::getInstance();
}
break;
default:
value = NullValue::getInstance();
break;
}
}
break;
case Reflect::kBoolean:
value = BoolValue::getInstance(static_cast<bool>(apply(argc, argv, (bool (*)()) ((*self)[methodNumber]))));
break;
case Reflect::kOctet:
value = new NumberValue(static_cast<uint8_t>(apply(argc, argv, (uint8_t (*)()) ((*self)[methodNumber]))));
break;
case Reflect::kShort:
value = new NumberValue(static_cast<int16_t>(apply(argc, argv, (int16_t (*)()) ((*self)[methodNumber]))));
break;
case Reflect::kUnsignedShort:
value = new NumberValue(static_cast<uint16_t>(apply(argc, argv, (uint16_t (*)()) ((*self)[methodNumber]))));
break;
case Reflect::kLong:
value = new NumberValue(static_cast<int32_t>(apply(argc, argv, (int32_t (*)()) ((*self)[methodNumber]))));
break;
case Reflect::kUnsignedLong:
value = new NumberValue(static_cast<uint32_t>(apply(argc, argv, (uint32_t (*)()) ((*self)[methodNumber]))));
break;
case Reflect::kLongLong:
value = new NumberValue(static_cast<int64_t>(apply(argc, argv, (int64_t (*)()) ((*self)[methodNumber]))));
break;
case Reflect::kUnsignedLongLong:
value = new NumberValue(static_cast<uint64_t>(apply(argc, argv, (uint64_t (*)()) ((*self)[methodNumber]))));
break;
case Reflect::kFloat:
value = new NumberValue(static_cast<float>(apply(argc, argv, (float (*)()) ((*self)[methodNumber]))));
break;
case Reflect::kDouble:
value = new NumberValue(apply(argc, argv, (double (*)()) ((*self)[methodNumber])));
break;
case Reflect::kPointer:
value = new NumberValue(static_cast<intptr_t>(apply(argc, argv, (intptr_t (*)()) ((*self)[methodNumber]))));
break;
case Reflect::kString:
{
heap[0] = '\0';
Any result = apply(argc, argv, (const char* (*)()) ((*self)[methodNumber]));
if (const char* string = static_cast<const char*>(result))
{
value = new StringValue(string);
}
else
{
value = NullValue::getInstance();
}
}
break;
case Reflect::kSequence:
{
// XXX Assume sequence<octet> now...
int32_t count = apply(argc, argv, (int32_t (*)()) ((*self)[methodNumber]));
if (count < 0)
{
count = 0;
}
heap[count] = '\0';
value = new StringValue(heap);
}
break;
case Reflect::kObject:
if (Object* unknown = apply(argc, argv, (Object* (*)()) ((*self)[methodNumber])))
{
ObjectValue* instance = new InterfacePointerValue(unknown);
// TODO: check Object and others
instance->setPrototype(getGlobal()->get(es::getInterface(returnType.getQualifiedName().c_str()).getName())->get("prototype")); // XXX Should use IID
value = instance;
}
else
{
value = NullValue::getInstance();
}
break;
case Reflect::kVoid:
apply(argc, argv, (int32_t (*)()) ((*self)[methodNumber]));
value = NullValue::getInstance();
break;
}
return value;
}
static Value* invoke(const char* iid, int number, InterfacePointerValue* object, ListValue* list)
{
InterfaceMethod** self = reinterpret_cast<InterfaceMethod**>(object->getObject());
if (!self)
{
throw getErrorInstance("TypeError");
}
Value* value = invoke(iid, number, self, list);
if (strcmp(iid, Object::iid()) == 0 && number == 2) // Object::release()
{
object->clearObject();
}
return value;
}
//
// AttributeValue
//
class AttributeValue : public ObjectValue
{
bool readOnly;
const char* iid;
int getter; // Method number
int setter; // Method number
public:
AttributeValue(const char* iid) :
readOnly(true),
iid(iid),
getter(0),
setter(0)
{
}
~AttributeValue()
{
}
void addSetter(int number)
{
readOnly = false;
setter = number;
}
void addGetter(int number)
{
getter = number;
}
// Getter
virtual Value* get(Value* self)
{
if (dynamic_cast<InterfacePointerValue*>(self))
{
Register<ListValue> list = new ListValue;
return invoke(iid, getter, static_cast<InterfacePointerValue*>(self), list);
}
else
{
return this;
}
}
// Setter
virtual bool put(Value* self, Value* value)
{
if (dynamic_cast<InterfacePointerValue*>(self) && !readOnly)
{
Register<ListValue> list = new ListValue;
list->push(value);
invoke(iid, setter, static_cast<InterfacePointerValue*>(self), list);
}
return true;
}
};
//
// InterfaceMethodCode
//
class InterfaceMethodCode : public Code
{
FormalParameterList* arguments;
ObjectValue* prototype;
const char* iid;
int number; // Method number
public:
InterfaceMethodCode(ObjectValue* object, const char* iid, int number) :
arguments(new FormalParameterList),
prototype(new ObjectValue),
iid(iid),
number(number)
{
Reflect::Interface interface = es::getInterface(iid);
Reflect::Method method(interface.getMethod(number));
#if 0
// Add as many arguments as required.
for (int i = 0; i < method.getParameterCount(); ++i)
{
Reflect::Parameter param(method.getParameter(i));
if (param.isInput())
{
// Note the name "arguments" is reserved in a ECMAScript function.
ASSERT(strcmp(param.getName(), "arguments") != 0);
arguments->add(new Identifier(param.getName()));
}
}
#endif
object->setParameterList(arguments);
object->setScope(getGlobal());
// Create Interface.prototype
prototype->put("constructor", object);
object->put("prototype", prototype);
}
~InterfaceMethodCode()
{
delete arguments;
}
CompletionType evaluate()
{
InterfacePointerValue* object = dynamic_cast<InterfacePointerValue*>(getThis());
if (!object)
{
throw getErrorInstance("TypeError");
}
ListValue* list = static_cast<ListValue*>(getScopeChain()->get("arguments"));
Register<Value> value = invoke(iid, number, object, list);
return CompletionType(CompletionType::Return, value, "");
}
};
//
// AttributeSetterValue
//
class AttributeSetterValue : public ObjectValue
{
const char* iid;
int number; // Method number
public:
AttributeSetterValue(const char* iid, int number) :
iid(iid),
number(number)
{
}
~AttributeSetterValue()
{
}
void put(Value* self, const std::string& name, Value* value)
{
Register<ListValue> list = new ListValue;
Register<StringValue> ident = new StringValue(name);
list->push(ident);
list->push(value);
invoke(iid, number, static_cast<InterfacePointerValue*>(self), list);
return;
}
};
//
// AttributeGetterValue
//
class AttributeGetterValue : public ObjectValue
{
const char* iid;
int number; // Method number
public:
AttributeGetterValue(const char* iid, int number) :
iid(iid),
number(number)
{
}
~AttributeGetterValue()
{
}
Value* get(Value* self, const std::string& name)
{
Register<ListValue> list = new ListValue;
Register<StringValue> ident = new StringValue(name);
list->push(ident);
return invoke(iid, number, static_cast<InterfacePointerValue*>(self), list);
}
};
//
// InterfacePrototypeValue
//
class InterfacePrototypeValue : public ObjectValue
{
enum OpObject {
IndexGetter,
IndexSetter,
NameGetter,
NameSetter,
ObjectCount
};
ObjectValue* opObjects[ObjectCount];
public:
InterfacePrototypeValue()
{
for (int i = 0; i < ObjectCount; ++i)
{
opObjects[i] = 0;
}
}
~InterfacePrototypeValue()
{
}
void setOpObject(int op, ObjectValue* object)
{
ASSERT(op >= 0 && op < ObjectCount);
opObjects[op] = object;
}
ObjectValue* getOpObject(int op)
{
ASSERT(op >= 0 && op < ObjectCount);
return opObjects[op];
}
friend class InterfaceConstructor;
friend class InterfacePointerValue;
};
//
// InterfaceConstructor
//
class InterfaceConstructor : public Code
{
ObjectValue* constructor;
FormalParameterList* arguments;
InterfacePrototypeValue* prototype;
std::string iid;
public:
InterfaceConstructor(ObjectValue* object, std::string iid) :
constructor(object),
arguments(new FormalParameterList),
prototype(new InterfacePrototypeValue),
iid(iid)
{
arguments->add(new Identifier("object"));
object->setParameterList(arguments);
object->setScope(getGlobal());
Reflect::Interface interface = es::getInterface(iid.c_str());
// PRINTF("interface: %s\n", interface.getName().c_str());
for (int i = 0; i < interface.getMethodCount(); ++i)
{
// Construct Method object
Reflect::Method method(interface.getMethod(i));
if (prototype->hasProperty(method.getName()))
{
if (method.isOperation())
{
// XXX Currently overloaded functions are just ignored.
}
else
{
AttributeValue* attribute = static_cast<AttributeValue*>(prototype->get(method.getName()));
if (method.isGetter())
{
attribute->addGetter(i);
}
else
{
attribute->addSetter(i);
}
}
}
else
{
if (method.isOperation())
{
ObjectValue* function = new ObjectValue;
function->setCode(new InterfaceMethodCode(function, iid.c_str(), i));
prototype->put(method.getName(), function);
#if 0
if (method.isIndexGetter())
{
AttributeGetterValue* getter = new AttributeGetterValue(iid, i);
prototype->setOpObject(InterfacePrototypeValue::IndexGetter, getter);
}
else if (method.isIndexSetter())
{
AttributeSetterValue* setter = new AttributeSetterValue(iid, i);
prototype->setOpObject(InterfacePrototypeValue::IndexSetter, setter);
}
else if (method.isNameGetter())
{
AttributeGetterValue* getter = new AttributeGetterValue(iid, i);
prototype->setOpObject(InterfacePrototypeValue::NameGetter, getter);
}
else if (method.isNameSetter())
{
AttributeSetterValue* setter = new AttributeSetterValue(iid, i);
prototype->setOpObject(InterfacePrototypeValue::NameSetter, setter);
}
#endif
}
else
{
// method is an attribute
AttributeValue* attribute = new AttributeValue(iid.c_str());
if (method.isGetter())
{
attribute->addGetter(i);
}
else
{
attribute->addSetter(i);
}
prototype->put(method.getName(), attribute);
}
}
}
if (interface.getQualifiedSuperName() == "")
{
prototype->setPrototype(getGlobal()->get("InterfaceStore")->getPrototype()->getPrototype());
}
else
{
Reflect::Interface super = es::getInterface(interface.getQualifiedSuperName().c_str());
prototype->setPrototype(getGlobal()->get(super.getName())->get("prototype"));
}
// Create Interface.prototype
prototype->put("constructor", object);
object->put("prototype", prototype);
}
~InterfaceConstructor()
{
delete arguments;
}
// Query interface for this interface.
CompletionType evaluate()
{
if (constructor->hasInstance(getThis()))
{
// Constructor
Object* constructor = es::getConstructor(iid.c_str());
if (!constructor)
{
throw getErrorInstance("TypeError");
}
// TODO: Currently only the default constructor is supported
std::string ciid = iid;
ciid += "::Constructor";
Value* value = invoke(ciid.c_str(), 0, reinterpret_cast<InterfaceMethod**>(constructor), 0);
return CompletionType(CompletionType::Return, value, "");
}
else
{
// Cast
InterfacePointerValue* self = dynamic_cast<InterfacePointerValue*>(getScopeChain()->get("object"));
if (!self)
{
throw getErrorInstance("TypeError");
}
Object* object;
object = self->getObject();
if (!object || !(object = reinterpret_cast<Object*>(object->queryInterface(iid.c_str()))))
{
// We should throw an error in case called by a new expression.
throw getErrorInstance("TypeError");
}
ObjectValue* value = new InterfacePointerValue(object);
value->setPrototype(prototype);
return CompletionType(CompletionType::Return, value, "");
}
}
};
//
// InterfaceStoreConstructor
//
class InterfaceStoreConstructor : public Code
{
FormalParameterList* arguments;
ObjectValue* prototype; // Interface.prototype
public:
InterfaceStoreConstructor(ObjectValue* object) :
arguments(new FormalParameterList),
prototype(new ObjectValue)
{
ObjectValue* function = static_cast<ObjectValue*>(getGlobal()->get("Function"));
arguments->add(new Identifier("iid"));
object->setParameterList(arguments);
object->setScope(getGlobal());
// Create Interface.prototype
prototype->setPrototype(function->getPrototype()->getPrototype());
prototype->put("constructor", object);
object->put("prototype", prototype);
object->setPrototype(function->getPrototype());
}
~InterfaceStoreConstructor()
{
delete arguments;
}
CompletionType evaluate()
{
Value* value = getScopeChain()->get("iid");
if (!value->isString())
{
throw getErrorInstance("TypeError");
}
const char* iid = value->toString().c_str();
Reflect::Interface interface;
try
{
interface = es::getInterface(iid);
}
catch (...)
{
throw getErrorInstance("TypeError");
}
// Construct Interface Object
ObjectValue* object = new ObjectValue;
object->setCode(new InterfaceConstructor(object, iid));
object->setPrototype(prototype);
return CompletionType(CompletionType::Return, object, "");
}
};
static bool isIndexAccessor(const std::string& name)
{
const char* ptr = name.c_str();
bool hex = false;
if (strncasecmp(ptr, "0x", 2) == 0)
{
ptr += 2;
hex = true;
}
while(*ptr)
{
if (hex)
{
if (!isxdigit(*ptr))
{
return false;
}
}
else
{
if (!isdigit(*ptr))
{
return false;
}
}
ptr++;
}
return true;
}
Value* InterfacePointerValue::get(const std::string& name)
{
InterfacePrototypeValue* proto = static_cast<InterfacePrototypeValue*>(prototype);
AttributeGetterValue* getter;
if (hasProperty(name))
{
return ObjectValue::get(name);
}
else if ((getter = static_cast<AttributeGetterValue*>(proto->getOpObject(InterfacePrototypeValue::IndexGetter)))
&& isIndexAccessor(name))
{
return getter->get(this, name);
}
else if ((getter = static_cast<AttributeGetterValue*>(proto->getOpObject(InterfacePrototypeValue::NameGetter))))
{
return getter->get(this, name);
}
else {
return ObjectValue::get(name);
}
}
void InterfacePointerValue::put(const std::string& name, Value* value, int attributes)
{
InterfacePrototypeValue* proto = static_cast<InterfacePrototypeValue*>(prototype);
AttributeSetterValue* setter;
if (!canPut(name))
{
return;
}
if (hasProperty(name))
{
ObjectValue::put(name, value, attributes);
}
else if ((setter = static_cast<AttributeSetterValue*>(proto->getOpObject(InterfacePrototypeValue::IndexSetter)))
&& isIndexAccessor(name))
{
setter->put(this, name, value);
}
else if ((setter = static_cast<AttributeSetterValue*>(proto->getOpObject(InterfacePrototypeValue::NameSetter))))
{
setter->put(this, name, value);
}
else
{
ObjectValue::put(name, value, attributes);
}
}
ObjectValue* constructInterfaceObject()
{
ObjectValue* object = new ObjectValue;
object->setCode(new InterfaceStoreConstructor(object));
return object;
}
ObjectValue* constructSystemObject(void* system)
{
for (es::InterfaceData* data = es::interfaceData; data->iid; ++data)
{
// Construct Default Interface Object
Reflect::Interface interface = es::getInterface(data->iid());
PRINTF("%s\n", interface.getName().c_str());
ObjectValue* object = new ObjectValue;
object->setCode(new InterfaceConstructor(object, interface.getQualifiedName()));
object->setPrototype(getGlobal()->get("InterfaceStore")->getPrototype());
getGlobal()->put(interface.getName(), object);
}
System()->addRef();
ObjectValue* object = new InterfacePointerValue(System());
object->setPrototype(getGlobal()->get("CurrentProcess")->get("prototype"));
return object;
}
| LambdaLord/es-operating-system | esjs/src/interface.cpp | C++ | apache-2.0 | 28,073 |
/*
Copyright IBM Corp. 2016 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"fmt"
"testing"
"github.com/hyperledger/fabric/core/chaincode/shim"
ex02 "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02"
)
// chaincode_example02's hash is used here and must be updated if the example is changed
var example02Url = "github.com/hyperledger/fabric/core/example/chaincode/chaincode_example02"
// chaincode_example05 looks like it wanted to return a JSON response to Query()
// it doesn't actually do this though, it just returns the sum value
func jsonResponse(name string, value string) string {
return fmt.Sprintf("jsonResponse = \"{\"Name\":\"%v\",\"Value\":\"%v\"}", name, value)
}
func checkInit(t *testing.T, stub *shim.MockStub, args []string) {
_, err := stub.MockInit("1", "init", args)
if err != nil {
fmt.Println("Init failed", err)
t.FailNow()
}
}
func checkState(t *testing.T, stub *shim.MockStub, name string, expect string) {
bytes := stub.State[name]
if bytes == nil {
fmt.Println("State", name, "failed to get value")
t.FailNow()
}
if string(bytes) != expect {
fmt.Println("State value", name, "was not", expect, "as expected")
t.FailNow()
}
}
func checkQuery(t *testing.T, stub *shim.MockStub, args []string, expect string) {
bytes, err := stub.MockQuery("query", args)
if err != nil {
fmt.Println("Query", args, "failed", err)
t.FailNow()
}
if bytes == nil {
fmt.Println("Query", args, "failed to get result")
t.FailNow()
}
if string(bytes) != expect {
fmt.Println("Query result ", string(bytes), "was not", expect, "as expected")
t.FailNow()
}
}
func checkInvoke(t *testing.T, stub *shim.MockStub, args []string) {
_, err := stub.MockInvoke("1", "query", args)
if err != nil {
fmt.Println("Invoke", args, "failed", err)
t.FailNow()
}
}
func TestExample04_Init(t *testing.T) {
scc := new(SimpleChaincode)
stub := shim.NewMockStub("ex05", scc)
// Init A=123 B=234
checkInit(t, stub, []string{"sumStoreName", "432"})
checkState(t, stub, "sumStoreName", "432")
}
func TestExample04_Query(t *testing.T) {
scc := new(SimpleChaincode)
stub := shim.NewMockStub("ex05", scc)
ccEx2 := new(ex02.SimpleChaincode)
stubEx2 := shim.NewMockStub("ex02", ccEx2)
checkInit(t, stubEx2, []string{"a", "111", "b", "222"})
stub.MockPeerChaincode(example02Url, stubEx2)
checkInit(t, stub, []string{"sumStoreName", "0"})
// a + b = 111 + 222 = 333
checkQuery(t, stub, []string{example02Url, "sumStoreName"}, "333") // example05 doesn't return JSON?
}
func TestExample04_Invoke(t *testing.T) {
scc := new(SimpleChaincode)
stub := shim.NewMockStub("ex05", scc)
ccEx2 := new(ex02.SimpleChaincode)
stubEx2 := shim.NewMockStub("ex02", ccEx2)
checkInit(t, stubEx2, []string{"a", "222", "b", "333"})
stub.MockPeerChaincode(example02Url, stubEx2)
checkInit(t, stub, []string{"sumStoreName", "0"})
// a + b = 222 + 333 = 555
checkInvoke(t, stub, []string{example02Url, "sumStoreName"})
checkQuery(t, stub, []string{example02Url, "sumStoreName"}, "555") // example05 doesn't return JSON?
checkQuery(t, stubEx2, []string{"a"}, "222")
checkQuery(t, stubEx2, []string{"b"}, "333")
// update A-=10 and B+=10
checkInvoke(t, stubEx2, []string{"a", "b", "10"})
// a + b = 212 + 343 = 555
checkInvoke(t, stub, []string{example02Url, "sumStoreName"})
checkQuery(t, stub, []string{example02Url, "sumStoreName"}, "555") // example05 doesn't return JSON?
checkQuery(t, stubEx2, []string{"a"}, "212")
checkQuery(t, stubEx2, []string{"b"}, "343")
}
| narayan2903/cc-commercialpaper | vendor/github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example05/chaincode_example05_test.go | GO | apache-2.0 | 4,062 |
/*
* Copyright 2013 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:
*
* 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.netty.buffer;
import io.netty.util.Recycler;
import io.netty.util.internal.PlatformDependent;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.ScatteringByteChannel;
final class PooledUnsafeDirectByteBuf extends PooledByteBuf<ByteBuffer> {
private static final Recycler<PooledUnsafeDirectByteBuf> RECYCLER = new Recycler<PooledUnsafeDirectByteBuf>() {
@Override
protected PooledUnsafeDirectByteBuf newObject(Handle<PooledUnsafeDirectByteBuf> handle) {
return new PooledUnsafeDirectByteBuf(handle, 0);
}
};
static PooledUnsafeDirectByteBuf newInstance(int maxCapacity) {
PooledUnsafeDirectByteBuf buf = RECYCLER.get();
buf.reuse(maxCapacity);
return buf;
}
private long memoryAddress;
private PooledUnsafeDirectByteBuf(Recycler.Handle<PooledUnsafeDirectByteBuf> recyclerHandle, int maxCapacity) {
super(recyclerHandle, maxCapacity);
}
@Override
void init(PoolChunk<ByteBuffer> chunk, long handle, int offset, int length, int maxLength,
PoolThreadCache cache) {
super.init(chunk, handle, offset, length, maxLength, cache);
initMemoryAddress();
}
@Override
void initUnpooled(PoolChunk<ByteBuffer> chunk, int length) {
super.initUnpooled(chunk, length);
initMemoryAddress();
}
private void initMemoryAddress() {
memoryAddress = PlatformDependent.directBufferAddress(memory) + offset;
}
@Override
protected ByteBuffer newInternalNioBuffer(ByteBuffer memory) {
return memory.duplicate();
}
@Override
public boolean isDirect() {
return true;
}
@Override
protected byte _getByte(int index) {
return UnsafeByteBufUtil.getByte(addr(index));
}
@Override
protected short _getShort(int index) {
return UnsafeByteBufUtil.getShort(addr(index));
}
@Override
protected short _getShortLE(int index) {
return UnsafeByteBufUtil.getShortLE(addr(index));
}
@Override
protected int _getUnsignedMedium(int index) {
return UnsafeByteBufUtil.getUnsignedMedium(addr(index));
}
@Override
protected int _getUnsignedMediumLE(int index) {
return UnsafeByteBufUtil.getUnsignedMediumLE(addr(index));
}
@Override
protected int _getInt(int index) {
return UnsafeByteBufUtil.getInt(addr(index));
}
@Override
protected int _getIntLE(int index) {
return UnsafeByteBufUtil.getIntLE(addr(index));
}
@Override
protected long _getLong(int index) {
return UnsafeByteBufUtil.getLong(addr(index));
}
@Override
protected long _getLongLE(int index) {
return UnsafeByteBufUtil.getLongLE(addr(index));
}
@Override
public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) {
UnsafeByteBufUtil.getBytes(this, addr(index), index, dst, dstIndex, length);
return this;
}
@Override
public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) {
UnsafeByteBufUtil.getBytes(this, addr(index), index, dst, dstIndex, length);
return this;
}
@Override
public ByteBuf getBytes(int index, ByteBuffer dst) {
UnsafeByteBufUtil.getBytes(this, addr(index), index, dst);
return this;
}
@Override
public ByteBuf readBytes(ByteBuffer dst) {
int length = dst.remaining();
checkReadableBytes(length);
getBytes(readerIndex, dst);
readerIndex += length;
return this;
}
@Override
public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException {
UnsafeByteBufUtil.getBytes(this, addr(index), index, out, length);
return this;
}
@Override
public int getBytes(int index, GatheringByteChannel out, int length) throws IOException {
return getBytes(index, out, length, false);
}
private int getBytes(int index, GatheringByteChannel out, int length, boolean internal) throws IOException {
checkIndex(index, length);
if (length == 0) {
return 0;
}
ByteBuffer tmpBuf;
if (internal) {
tmpBuf = internalNioBuffer();
} else {
tmpBuf = memory.duplicate();
}
index = idx(index);
tmpBuf.clear().position(index).limit(index + length);
return out.write(tmpBuf);
}
@Override
public int getBytes(int index, FileChannel out, long position, int length) throws IOException {
return getBytes(index, out, position, length, false);
}
private int getBytes(int index, FileChannel out, long position, int length, boolean internal) throws IOException {
checkIndex(index, length);
if (length == 0) {
return 0;
}
ByteBuffer tmpBuf = internal ? internalNioBuffer() : memory.duplicate();
index = idx(index);
tmpBuf.clear().position(index).limit(index + length);
return out.write(tmpBuf, position);
}
@Override
public int readBytes(GatheringByteChannel out, int length)
throws IOException {
checkReadableBytes(length);
int readBytes = getBytes(readerIndex, out, length, true);
readerIndex += readBytes;
return readBytes;
}
@Override
public int readBytes(FileChannel out, long position, int length)
throws IOException {
checkReadableBytes(length);
int readBytes = getBytes(readerIndex, out, position, length, true);
readerIndex += readBytes;
return readBytes;
}
@Override
protected void _setByte(int index, int value) {
UnsafeByteBufUtil.setByte(addr(index), (byte) value);
}
@Override
protected void _setShort(int index, int value) {
UnsafeByteBufUtil.setShort(addr(index), value);
}
@Override
protected void _setShortLE(int index, int value) {
UnsafeByteBufUtil.setShortLE(addr(index), value);
}
@Override
protected void _setMedium(int index, int value) {
UnsafeByteBufUtil.setMedium(addr(index), value);
}
@Override
protected void _setMediumLE(int index, int value) {
UnsafeByteBufUtil.setMediumLE(addr(index), value);
}
@Override
protected void _setInt(int index, int value) {
UnsafeByteBufUtil.setInt(addr(index), value);
}
@Override
protected void _setIntLE(int index, int value) {
UnsafeByteBufUtil.setIntLE(addr(index), value);
}
@Override
protected void _setLong(int index, long value) {
UnsafeByteBufUtil.setLong(addr(index), value);
}
@Override
protected void _setLongLE(int index, long value) {
UnsafeByteBufUtil.setLongLE(addr(index), value);
}
@Override
public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) {
UnsafeByteBufUtil.setBytes(this, addr(index), index, src, srcIndex, length);
return this;
}
@Override
public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) {
UnsafeByteBufUtil.setBytes(this, addr(index), index, src, srcIndex, length);
return this;
}
@Override
public ByteBuf setBytes(int index, ByteBuffer src) {
UnsafeByteBufUtil.setBytes(this, addr(index), index, src);
return this;
}
@Override
public int setBytes(int index, InputStream in, int length) throws IOException {
return UnsafeByteBufUtil.setBytes(this, addr(index), index, in, length);
}
@Override
public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException {
checkIndex(index, length);
ByteBuffer tmpBuf = internalNioBuffer();
index = idx(index);
tmpBuf.clear().position(index).limit(index + length);
try {
return in.read(tmpBuf);
} catch (ClosedChannelException ignored) {
return -1;
}
}
@Override
public int setBytes(int index, FileChannel in, long position, int length) throws IOException {
checkIndex(index, length);
ByteBuffer tmpBuf = internalNioBuffer();
index = idx(index);
tmpBuf.clear().position(index).limit(index + length);
try {
return in.read(tmpBuf, position);
} catch (ClosedChannelException ignored) {
return -1;
}
}
@Override
public ByteBuf copy(int index, int length) {
return UnsafeByteBufUtil.copy(this, addr(index), index, length);
}
@Override
public int nioBufferCount() {
return 1;
}
@Override
public ByteBuffer[] nioBuffers(int index, int length) {
return new ByteBuffer[] { nioBuffer(index, length) };
}
@Override
public ByteBuffer nioBuffer(int index, int length) {
checkIndex(index, length);
index = idx(index);
return ((ByteBuffer) memory.duplicate().position(index).limit(index + length)).slice();
}
@Override
public ByteBuffer internalNioBuffer(int index, int length) {
checkIndex(index, length);
index = idx(index);
return (ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length);
}
@Override
public boolean hasArray() {
return false;
}
@Override
public byte[] array() {
throw new UnsupportedOperationException("direct buffer");
}
@Override
public int arrayOffset() {
throw new UnsupportedOperationException("direct buffer");
}
@Override
public boolean hasMemoryAddress() {
return true;
}
@Override
public long memoryAddress() {
ensureAccessible();
return memoryAddress;
}
private long addr(int index) {
return memoryAddress + index;
}
@Override
protected SwappedByteBuf newSwappedByteBuf() {
if (PlatformDependent.isUnaligned()) {
// Only use if unaligned access is supported otherwise there is no gain.
return new UnsafeDirectSwappedByteBuf(this);
}
return super.newSwappedByteBuf();
}
@Override
public ByteBuf setZero(int index, int length) {
UnsafeByteBufUtil.setZero(this, addr(index), index, length);
return this;
}
@Override
public ByteBuf writeZero(int length) {
ensureWritable(length);
int wIndex = writerIndex;
setZero(wIndex, length);
writerIndex = wIndex + length;
return this;
}
}
| mcobrien/netty | buffer/src/main/java/io/netty/buffer/PooledUnsafeDirectByteBuf.java | Java | apache-2.0 | 11,458 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.ha;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.HadoopIllegalArgumentException;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.util.ZKUtil.ZKAuthInfo;
import org.apache.hadoop.util.StringUtils;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher.Event;
import org.apache.zookeeper.ZKUtil;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.AsyncCallback.*;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.KeeperException.Code;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
/**
*
* This class implements a simple library to perform leader election on top of
* Apache Zookeeper. Using Zookeeper as a coordination service, leader election
* can be performed by atomically creating an ephemeral lock file (znode) on
* Zookeeper. The service instance that successfully creates the znode becomes
* active and the rest become standbys. <br/>
* This election mechanism is only efficient for small number of election
* candidates (order of 10's) because contention on single znode by a large
* number of candidates can result in Zookeeper overload. <br/>
* The elector does not guarantee fencing (protection of shared resources) among
* service instances. After it has notified an instance about becoming a leader,
* then that instance must ensure that it meets the service consistency
* requirements. If it cannot do so, then it is recommended to quit the
* election. The application implements the {@link ActiveStandbyElectorCallback}
* to interact with the elector
*/
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class ActiveStandbyElector implements StatCallback, StringCallback {
/**
* Callback interface to interact with the ActiveStandbyElector object. <br/>
* The application will be notified with a callback only on state changes
* (i.e. there will never be successive calls to becomeActive without an
* intermediate call to enterNeutralMode). <br/>
* The callbacks will be running on Zookeeper client library threads. The
* application should return from these callbacks quickly so as not to impede
* Zookeeper client library performance and notifications. The app will
* typically remember the state change and return from the callback. It will
* then proceed with implementing actions around that state change. It is
* possible to be called back again while these actions are in flight and the
* app should handle this scenario.
*/
public interface ActiveStandbyElectorCallback {
/**
* This method is called when the app becomes the active leader.
* If the service fails to become active, it should throw
* ServiceFailedException. This will cause the elector to
* sleep for a short period, then re-join the election.
*
* Callback implementations are expected to manage their own
* timeouts (e.g. when making an RPC to a remote node).
*/
void becomeActive() throws ServiceFailedException;
/**
* This method is called when the app becomes a standby
*/
void becomeStandby();
/**
* If the elector gets disconnected from Zookeeper and does not know about
* the lock state, then it will notify the service via the enterNeutralMode
* interface. The service may choose to ignore this or stop doing state
* changing operations. Upon reconnection, the elector verifies the leader
* status and calls back on the becomeActive and becomeStandby app
* interfaces. <br/>
* Zookeeper disconnects can happen due to network issues or loss of
* Zookeeper quorum. Thus enterNeutralMode can be used to guard against
* split-brain issues. In such situations it might be prudent to call
* becomeStandby too. However, such state change operations might be
* expensive and enterNeutralMode can help guard against doing that for
* transient issues.
*/
void enterNeutralMode();
/**
* If there is any fatal error (e.g. wrong ACL's, unexpected Zookeeper
* errors or Zookeeper persistent unavailability) then notifyFatalError is
* called to notify the app about it.
*/
void notifyFatalError(String errorMessage);
/**
* If an old active has failed, rather than exited gracefully, then
* the new active may need to take some fencing actions against it
* before proceeding with failover.
*
* @param oldActiveData the application data provided by the prior active
*/
void fenceOldActive(byte[] oldActiveData);
}
/**
* Name of the lock znode used by the library. Protected for access in test
* classes
*/
@VisibleForTesting
protected static final String LOCK_FILENAME = "ActiveStandbyElectorLock";
@VisibleForTesting
protected static final String BREADCRUMB_FILENAME = "ActiveBreadCrumb";
public static final Log LOG = LogFactory.getLog(ActiveStandbyElector.class);
private static final int SLEEP_AFTER_FAILURE_TO_BECOME_ACTIVE = 1000;
private static enum ConnectionState {
DISCONNECTED, CONNECTED, TERMINATED
};
static enum State {
INIT, ACTIVE, STANDBY, NEUTRAL
};
private State state = State.INIT;
private int createRetryCount = 0;
private int statRetryCount = 0;
private ZooKeeper zkClient;
private WatcherWithClientRef watcher;
private ConnectionState zkConnectionState = ConnectionState.TERMINATED;
private final ActiveStandbyElectorCallback appClient;
private final String zkHostPort;
private final int zkSessionTimeout;
private final List<ACL> zkAcl;
private final List<ZKAuthInfo> zkAuthInfo;
private byte[] appData;
private final String zkLockFilePath;
private final String zkBreadCrumbPath;
private final String znodeWorkingDir;
private final int maxRetryNum;
private Lock sessionReestablishLockForTests = new ReentrantLock();
private boolean wantToBeInElection;
/**
* Create a new ActiveStandbyElector object <br/>
* The elector is created by providing to it the Zookeeper configuration, the
* parent znode under which to create the znode and a reference to the
* callback interface. <br/>
* The parent znode name must be the same for all service instances and
* different across services. <br/>
* After the leader has been lost, a new leader will be elected after the
* session timeout expires. Hence, the app must set this parameter based on
* its needs for failure response time. The session timeout must be greater
* than the Zookeeper disconnect timeout and is recommended to be 3X that
* value to enable Zookeeper to retry transient disconnections. Setting a very
* short session timeout may result in frequent transitions between active and
* standby states during issues like network outages/GS pauses.
*
* @param zookeeperHostPorts
* ZooKeeper hostPort for all ZooKeeper servers
* @param zookeeperSessionTimeout
* ZooKeeper session timeout
* @param parentZnodeName
* znode under which to create the lock
* @param acl
* ZooKeeper ACL's
* @param authInfo a list of authentication credentials to add to the
* ZK connection
* @param app
* reference to callback interface object
* @throws IOException
* @throws HadoopIllegalArgumentException
*/
public ActiveStandbyElector(String zookeeperHostPorts,
int zookeeperSessionTimeout, String parentZnodeName, List<ACL> acl,
List<ZKAuthInfo> authInfo,
ActiveStandbyElectorCallback app, int maxRetryNum) throws IOException,
HadoopIllegalArgumentException, KeeperException {
if (app == null || acl == null || parentZnodeName == null
|| zookeeperHostPorts == null || zookeeperSessionTimeout <= 0) {
throw new HadoopIllegalArgumentException("Invalid argument");
}
zkHostPort = zookeeperHostPorts;
zkSessionTimeout = zookeeperSessionTimeout;
zkAcl = acl;
zkAuthInfo = authInfo;
appClient = app;
znodeWorkingDir = parentZnodeName;
zkLockFilePath = znodeWorkingDir + "/" + LOCK_FILENAME;
zkBreadCrumbPath = znodeWorkingDir + "/" + BREADCRUMB_FILENAME;
this.maxRetryNum = maxRetryNum;
// createConnection for future API calls
createConnection();
}
/**
* To participate in election, the app will call joinElection. The result will
* be notified by a callback on either the becomeActive or becomeStandby app
* interfaces. <br/>
* After this the elector will automatically monitor the leader status and
* perform re-election if necessary<br/>
* The app could potentially start off in standby mode and ignore the
* becomeStandby call.
*
* @param data
* to be set by the app. non-null data must be set.
* @throws HadoopIllegalArgumentException
* if valid data is not supplied
*/
public synchronized void joinElection(byte[] data)
throws HadoopIllegalArgumentException {
if (data == null) {
throw new HadoopIllegalArgumentException("data cannot be null");
}
if (wantToBeInElection) {
LOG.info("Already in election. Not re-connecting.");
return;
}
appData = new byte[data.length];
System.arraycopy(data, 0, appData, 0, data.length);
LOG.debug("Attempting active election for " + this);
joinElectionInternal();
}
/**
* @return true if the configured parent znode exists
*/
public synchronized boolean parentZNodeExists()
throws IOException, InterruptedException {
Preconditions.checkState(zkClient != null);
try {
return zkClient.exists(znodeWorkingDir, false) != null;
} catch (KeeperException e) {
throw new IOException("Couldn't determine existence of znode '" +
znodeWorkingDir + "'", e);
}
}
/**
* Utility function to ensure that the configured base znode exists.
* This recursively creates the znode as well as all of its parents.
*/
public synchronized void ensureParentZNode()
throws IOException, InterruptedException {
Preconditions.checkState(!wantToBeInElection,
"ensureParentZNode() may not be called while in the election");
String pathParts[] = znodeWorkingDir.split("/");
Preconditions.checkArgument(pathParts.length >= 1 &&
pathParts[0].isEmpty(),
"Invalid path: %s", znodeWorkingDir);
StringBuilder sb = new StringBuilder();
for (int i = 1; i < pathParts.length; i++) {
sb.append("/").append(pathParts[i]);
String prefixPath = sb.toString();
LOG.debug("Ensuring existence of " + prefixPath);
try {
createWithRetries(prefixPath, new byte[]{}, zkAcl, CreateMode.PERSISTENT);
} catch (KeeperException e) {
if (isNodeExists(e.code())) {
// This is OK - just ensuring existence.
continue;
} else {
throw new IOException("Couldn't create " + prefixPath, e);
}
}
}
LOG.info("Successfully created " + znodeWorkingDir + " in ZK.");
}
/**
* Clear all of the state held within the parent ZNode.
* This recursively deletes everything within the znode as well as the
* parent znode itself. It should only be used when it's certain that
* no electors are currently participating in the election.
*/
public synchronized void clearParentZNode()
throws IOException, InterruptedException {
Preconditions.checkState(!wantToBeInElection,
"clearParentZNode() may not be called while in the election");
try {
LOG.info("Recursively deleting " + znodeWorkingDir + " from ZK...");
zkDoWithRetries(new ZKAction<Void>() {
@Override
public Void run() throws KeeperException, InterruptedException {
ZKUtil.deleteRecursive(zkClient, znodeWorkingDir);
return null;
}
});
} catch (KeeperException e) {
throw new IOException("Couldn't clear parent znode " + znodeWorkingDir,
e);
}
LOG.info("Successfully deleted " + znodeWorkingDir + " from ZK.");
}
/**
* Any service instance can drop out of the election by calling quitElection.
* <br/>
* This will lose any leader status, if held, and stop monitoring of the lock
* node. <br/>
* If the instance wants to participate in election again, then it needs to
* call joinElection(). <br/>
* This allows service instances to take themselves out of rotation for known
* impending unavailable states (e.g. long GC pause or software upgrade).
*
* @param needFence true if the underlying daemon may need to be fenced
* if a failover occurs due to dropping out of the election.
*/
public synchronized void quitElection(boolean needFence) {
LOG.info("Yielding from election");
if (!needFence && state == State.ACTIVE) {
// If active is gracefully going back to standby mode, remove
// our permanent znode so no one fences us.
tryDeleteOwnBreadCrumbNode();
}
reset();
wantToBeInElection = false;
}
/**
* Exception thrown when there is no active leader
*/
public static class ActiveNotFoundException extends Exception {
private static final long serialVersionUID = 3505396722342846462L;
}
/**
* get data set by the active leader
*
* @return data set by the active instance
* @throws ActiveNotFoundException
* when there is no active leader
* @throws KeeperException
* other zookeeper operation errors
* @throws InterruptedException
* @throws IOException
* when ZooKeeper connection could not be established
*/
public synchronized byte[] getActiveData() throws ActiveNotFoundException,
KeeperException, InterruptedException, IOException {
try {
if (zkClient == null) {
createConnection();
}
Stat stat = new Stat();
return getDataWithRetries(zkLockFilePath, false, stat);
} catch(KeeperException e) {
Code code = e.code();
if (isNodeDoesNotExist(code)) {
// handle the commonly expected cases that make sense for us
throw new ActiveNotFoundException();
} else {
throw e;
}
}
}
/**
* interface implementation of Zookeeper callback for create
*/
@Override
public synchronized void processResult(int rc, String path, Object ctx,
String name) {
if (isStaleClient(ctx)) return;
LOG.debug("CreateNode result: " + rc + " for path: " + path
+ " connectionState: " + zkConnectionState +
" for " + this);
Code code = Code.get(rc);
if (isSuccess(code)) {
// we successfully created the znode. we are the leader. start monitoring
if (becomeActive()) {
monitorActiveStatus();
} else {
reJoinElectionAfterFailureToBecomeActive();
}
return;
}
if (isNodeExists(code)) {
if (createRetryCount == 0) {
// znode exists and we did not retry the operation. so a different
// instance has created it. become standby and monitor lock.
becomeStandby();
}
// if we had retried then the znode could have been created by our first
// attempt to the server (that we lost) and this node exists response is
// for the second attempt. verify this case via ephemeral node owner. this
// will happen on the callback for monitoring the lock.
monitorActiveStatus();
return;
}
String errorMessage = "Received create error from Zookeeper. code:"
+ code.toString() + " for path " + path;
LOG.debug(errorMessage);
if (shouldRetry(code)) {
if (createRetryCount < maxRetryNum) {
LOG.debug("Retrying createNode createRetryCount: " + createRetryCount);
++createRetryCount;
createLockNodeAsync();
return;
}
errorMessage = errorMessage
+ ". Not retrying further znode create connection errors.";
} else if (isSessionExpired(code)) {
// This isn't fatal - the client Watcher will re-join the election
LOG.warn("Lock acquisition failed because session was lost");
return;
}
fatalError(errorMessage);
}
/**
* interface implementation of Zookeeper callback for monitor (exists)
*/
@Override
public synchronized void processResult(int rc, String path, Object ctx,
Stat stat) {
if (isStaleClient(ctx)) return;
assert wantToBeInElection :
"Got a StatNode result after quitting election";
LOG.debug("StatNode result: " + rc + " for path: " + path
+ " connectionState: " + zkConnectionState + " for " + this);
Code code = Code.get(rc);
if (isSuccess(code)) {
// the following owner check completes verification in case the lock znode
// creation was retried
if (stat.getEphemeralOwner() == zkClient.getSessionId()) {
// we own the lock znode. so we are the leader
if (!becomeActive()) {
reJoinElectionAfterFailureToBecomeActive();
}
} else {
// we dont own the lock znode. so we are a standby.
becomeStandby();
}
// the watch set by us will notify about changes
return;
}
if (isNodeDoesNotExist(code)) {
// the lock znode disappeared before we started monitoring it
enterNeutralMode();
joinElectionInternal();
return;
}
String errorMessage = "Received stat error from Zookeeper. code:"
+ code.toString();
LOG.debug(errorMessage);
if (shouldRetry(code)) {
if (statRetryCount < maxRetryNum) {
++statRetryCount;
monitorLockNodeAsync();
return;
}
errorMessage = errorMessage
+ ". Not retrying further znode monitoring connection errors.";
} else if (isSessionExpired(code)) {
// This isn't fatal - the client Watcher will re-join the election
LOG.warn("Lock monitoring failed because session was lost");
return;
}
fatalError(errorMessage);
}
/**
* We failed to become active. Re-join the election, but
* sleep for a few seconds after terminating our existing
* session, so that other nodes have a chance to become active.
* The failure to become active is already logged inside
* becomeActive().
*/
private void reJoinElectionAfterFailureToBecomeActive() {
reJoinElection(SLEEP_AFTER_FAILURE_TO_BECOME_ACTIVE);
}
/**
* interface implementation of Zookeeper watch events (connection and node),
* proxied by {@link WatcherWithClientRef}.
*/
synchronized void processWatchEvent(ZooKeeper zk, WatchedEvent event) {
Event.EventType eventType = event.getType();
if (isStaleClient(zk)) return;
LOG.debug("Watcher event type: " + eventType + " with state:"
+ event.getState() + " for path:" + event.getPath()
+ " connectionState: " + zkConnectionState
+ " for " + this);
if (eventType == Event.EventType.None) {
// the connection state has changed
switch (event.getState()) {
case SyncConnected:
LOG.info("Session connected.");
// if the listener was asked to move to safe state then it needs to
// be undone
ConnectionState prevConnectionState = zkConnectionState;
zkConnectionState = ConnectionState.CONNECTED;
if (prevConnectionState == ConnectionState.DISCONNECTED &&
wantToBeInElection) {
monitorActiveStatus();
}
break;
case Disconnected:
LOG.info("Session disconnected. Entering neutral mode...");
// ask the app to move to safe state because zookeeper connection
// is not active and we dont know our state
zkConnectionState = ConnectionState.DISCONNECTED;
enterNeutralMode();
break;
case Expired:
// the connection got terminated because of session timeout
// call listener to reconnect
LOG.info("Session expired. Entering neutral mode and rejoining...");
enterNeutralMode();
reJoinElection(0);
break;
case SaslAuthenticated:
LOG.info("Successfully authenticated to ZooKeeper using SASL.");
break;
default:
fatalError("Unexpected Zookeeper watch event state: "
+ event.getState());
break;
}
return;
}
// a watch on lock path in zookeeper has fired. so something has changed on
// the lock. ideally we should check that the path is the same as the lock
// path but trusting zookeeper for now
String path = event.getPath();
if (path != null) {
switch (eventType) {
case NodeDeleted:
if (state == State.ACTIVE) {
enterNeutralMode();
}
joinElectionInternal();
break;
case NodeDataChanged:
monitorActiveStatus();
break;
default:
LOG.debug("Unexpected node event: " + eventType + " for path: " + path);
monitorActiveStatus();
}
return;
}
// some unexpected error has occurred
fatalError("Unexpected watch error from Zookeeper");
}
/**
* Get a new zookeeper client instance. protected so that test class can
* inherit and pass in a mock object for zookeeper
*
* @return new zookeeper client instance
* @throws IOException
* @throws KeeperException zookeeper connectionloss exception
*/
protected synchronized ZooKeeper getNewZooKeeper() throws IOException,
KeeperException {
// Unfortunately, the ZooKeeper constructor connects to ZooKeeper and
// may trigger the Connected event immediately. So, if we register the
// watcher after constructing ZooKeeper, we may miss that event. Instead,
// we construct the watcher first, and have it block any events it receives
// before we can set its ZooKeeper reference.
watcher = new WatcherWithClientRef();
ZooKeeper zk = new ZooKeeper(zkHostPort, zkSessionTimeout, watcher);
watcher.setZooKeeperRef(zk);
// Wait for the asynchronous success/failure. This may throw an exception
// if we don't connect within the session timeout.
watcher.waitForZKConnectionEvent(zkSessionTimeout);
for (ZKAuthInfo auth : zkAuthInfo) {
zk.addAuthInfo(auth.getScheme(), auth.getAuth());
}
return zk;
}
private void fatalError(String errorMessage) {
LOG.fatal(errorMessage);
reset();
appClient.notifyFatalError(errorMessage);
}
private void monitorActiveStatus() {
assert wantToBeInElection;
LOG.debug("Monitoring active leader for " + this);
statRetryCount = 0;
monitorLockNodeAsync();
}
private void joinElectionInternal() {
Preconditions.checkState(appData != null,
"trying to join election without any app data");
if (zkClient == null) {
if (!reEstablishSession()) {
fatalError("Failed to reEstablish connection with ZooKeeper");
return;
}
}
createRetryCount = 0;
wantToBeInElection = true;
createLockNodeAsync();
}
private void reJoinElection(int sleepTime) {
LOG.info("Trying to re-establish ZK session");
// Some of the test cases rely on expiring the ZK sessions and
// ensuring that the other node takes over. But, there's a race
// where the original lease holder could reconnect faster than the other
// thread manages to take the lock itself. This lock allows the
// tests to block the reconnection. It's a shame that this leaked
// into non-test code, but the lock is only acquired here so will never
// be contended.
sessionReestablishLockForTests.lock();
try {
terminateConnection();
sleepFor(sleepTime);
// Should not join election even before the SERVICE is reported
// as HEALTHY from ZKFC monitoring.
if (appData != null) {
joinElectionInternal();
} else {
LOG.info("Not joining election since service has not yet been " +
"reported as healthy.");
}
} finally {
sessionReestablishLockForTests.unlock();
}
}
/**
* Sleep for the given number of milliseconds.
* This is non-static, and separated out, so that unit tests
* can override the behavior not to sleep.
*/
@VisibleForTesting
protected void sleepFor(int sleepMs) {
if (sleepMs > 0) {
try {
Thread.sleep(sleepMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
@VisibleForTesting
void preventSessionReestablishmentForTests() {
sessionReestablishLockForTests.lock();
}
@VisibleForTesting
void allowSessionReestablishmentForTests() {
sessionReestablishLockForTests.unlock();
}
@VisibleForTesting
synchronized long getZKSessionIdForTests() {
if (zkClient != null) {
return zkClient.getSessionId();
} else {
return -1;
}
}
@VisibleForTesting
synchronized State getStateForTests() {
return state;
}
private boolean reEstablishSession() {
int connectionRetryCount = 0;
boolean success = false;
while(!success && connectionRetryCount < maxRetryNum) {
LOG.debug("Establishing zookeeper connection for " + this);
try {
createConnection();
success = true;
} catch(IOException e) {
LOG.warn(e);
sleepFor(5000);
} catch(KeeperException e) {
LOG.warn(e);
sleepFor(5000);
}
++connectionRetryCount;
}
return success;
}
private void createConnection() throws IOException, KeeperException {
if (zkClient != null) {
try {
zkClient.close();
} catch (InterruptedException e) {
throw new IOException("Interrupted while closing ZK",
e);
}
zkClient = null;
watcher = null;
}
zkClient = getNewZooKeeper();
LOG.debug("Created new connection for " + this);
}
@InterfaceAudience.Private
public synchronized void terminateConnection() {
if (zkClient == null) {
return;
}
LOG.debug("Terminating ZK connection for " + this);
ZooKeeper tempZk = zkClient;
zkClient = null;
watcher = null;
try {
tempZk.close();
} catch(InterruptedException e) {
LOG.warn(e);
}
zkConnectionState = ConnectionState.TERMINATED;
wantToBeInElection = false;
}
private void reset() {
state = State.INIT;
terminateConnection();
}
private boolean becomeActive() {
assert wantToBeInElection;
if (state == State.ACTIVE) {
// already active
return true;
}
try {
Stat oldBreadcrumbStat = fenceOldActive();
writeBreadCrumbNode(oldBreadcrumbStat);
LOG.debug("Becoming active for " + this);
appClient.becomeActive();
state = State.ACTIVE;
return true;
} catch (Exception e) {
LOG.warn("Exception handling the winning of election", e);
// Caller will handle quitting and rejoining the election.
return false;
}
}
/**
* Write the "ActiveBreadCrumb" node, indicating that this node may need
* to be fenced on failover.
* @param oldBreadcrumbStat
*/
private void writeBreadCrumbNode(Stat oldBreadcrumbStat)
throws KeeperException, InterruptedException {
Preconditions.checkState(appData != null, "no appdata");
LOG.info("Writing znode " + zkBreadCrumbPath +
" to indicate that the local node is the most recent active...");
if (oldBreadcrumbStat == null) {
// No previous active, just create the node
createWithRetries(zkBreadCrumbPath, appData, zkAcl,
CreateMode.PERSISTENT);
} else {
// There was a previous active, update the node
setDataWithRetries(zkBreadCrumbPath, appData, oldBreadcrumbStat.getVersion());
}
}
/**
* Try to delete the "ActiveBreadCrumb" node when gracefully giving up
* active status.
* If this fails, it will simply warn, since the graceful release behavior
* is only an optimization.
*/
private void tryDeleteOwnBreadCrumbNode() {
assert state == State.ACTIVE;
LOG.info("Deleting bread-crumb of active node...");
// Sanity check the data. This shouldn't be strictly necessary,
// but better to play it safe.
Stat stat = new Stat();
byte[] data = null;
try {
data = zkClient.getData(zkBreadCrumbPath, false, stat);
if (!Arrays.equals(data, appData)) {
throw new IllegalStateException(
"We thought we were active, but in fact " +
"the active znode had the wrong data: " +
StringUtils.byteToHexString(data) + " (stat=" + stat + ")");
}
deleteWithRetries(zkBreadCrumbPath, stat.getVersion());
} catch (Exception e) {
LOG.warn("Unable to delete our own bread-crumb of being active at " +
zkBreadCrumbPath + ": " + e.getLocalizedMessage() + ". " +
"Expecting to be fenced by the next active.");
}
}
/**
* If there is a breadcrumb node indicating that another node may need
* fencing, try to fence that node.
* @return the Stat of the breadcrumb node that was read, or null
* if no breadcrumb node existed
*/
private Stat fenceOldActive() throws InterruptedException, KeeperException {
final Stat stat = new Stat();
byte[] data;
LOG.info("Checking for any old active which needs to be fenced...");
try {
data = zkDoWithRetries(new ZKAction<byte[]>() {
@Override
public byte[] run() throws KeeperException, InterruptedException {
return zkClient.getData(zkBreadCrumbPath, false, stat);
}
});
} catch (KeeperException ke) {
if (isNodeDoesNotExist(ke.code())) {
LOG.info("No old node to fence");
return null;
}
// If we failed to read for any other reason, then likely we lost
// our session, or we don't have permissions, etc. In any case,
// we probably shouldn't become active, and failing the whole
// thing is the best bet.
throw ke;
}
LOG.info("Old node exists: " + StringUtils.byteToHexString(data));
if (Arrays.equals(data, appData)) {
LOG.info("But old node has our own data, so don't need to fence it.");
} else {
appClient.fenceOldActive(data);
}
return stat;
}
private void becomeStandby() {
if (state != State.STANDBY) {
LOG.debug("Becoming standby for " + this);
state = State.STANDBY;
appClient.becomeStandby();
}
}
private void enterNeutralMode() {
if (state != State.NEUTRAL) {
LOG.debug("Entering neutral mode for " + this);
state = State.NEUTRAL;
appClient.enterNeutralMode();
}
}
private void createLockNodeAsync() {
zkClient.create(zkLockFilePath, appData, zkAcl, CreateMode.EPHEMERAL,
this, zkClient);
}
private void monitorLockNodeAsync() {
zkClient.exists(zkLockFilePath,
watcher, this,
zkClient);
}
private String createWithRetries(final String path, final byte[] data,
final List<ACL> acl, final CreateMode mode)
throws InterruptedException, KeeperException {
return zkDoWithRetries(new ZKAction<String>() {
@Override
public String run() throws KeeperException, InterruptedException {
return zkClient.create(path, data, acl, mode);
}
});
}
private byte[] getDataWithRetries(final String path, final boolean watch,
final Stat stat) throws InterruptedException, KeeperException {
return zkDoWithRetries(new ZKAction<byte[]>() {
@Override
public byte[] run() throws KeeperException, InterruptedException {
return zkClient.getData(path, watch, stat);
}
});
}
private Stat setDataWithRetries(final String path, final byte[] data,
final int version) throws InterruptedException, KeeperException {
return zkDoWithRetries(new ZKAction<Stat>() {
@Override
public Stat run() throws KeeperException, InterruptedException {
return zkClient.setData(path, data, version);
}
});
}
private void deleteWithRetries(final String path, final int version)
throws KeeperException, InterruptedException {
zkDoWithRetries(new ZKAction<Void>() {
@Override
public Void run() throws KeeperException, InterruptedException {
zkClient.delete(path, version);
return null;
}
});
}
private <T> T zkDoWithRetries(ZKAction<T> action) throws KeeperException,
InterruptedException {
int retry = 0;
while (true) {
try {
return action.run();
} catch (KeeperException ke) {
if (shouldRetry(ke.code()) && ++retry < maxRetryNum) {
continue;
}
throw ke;
}
}
}
private interface ZKAction<T> {
T run() throws KeeperException, InterruptedException;
}
/**
* The callbacks and watchers pass a reference to the ZK client
* which made the original call. We don't want to take action
* based on any callbacks from prior clients after we quit
* the election.
* @param ctx the ZK client passed into the watcher
* @return true if it matches the current client
*/
private synchronized boolean isStaleClient(Object ctx) {
Preconditions.checkNotNull(ctx);
if (zkClient != (ZooKeeper)ctx) {
LOG.warn("Ignoring stale result from old client with sessionId " +
String.format("0x%08x", ((ZooKeeper)ctx).getSessionId()));
return true;
}
return false;
}
/**
* Watcher implementation which keeps a reference around to the
* original ZK connection, and passes it back along with any
* events.
*/
private final class WatcherWithClientRef implements Watcher {
private ZooKeeper zk;
/**
* Latch fired whenever any event arrives. This is used in order
* to wait for the Connected event when the client is first created.
*/
private CountDownLatch hasReceivedEvent = new CountDownLatch(1);
/**
* Latch used to wait until the reference to ZooKeeper is set.
*/
private CountDownLatch hasSetZooKeeper = new CountDownLatch(1);
/**
* Waits for the next event from ZooKeeper to arrive.
*
* @param connectionTimeoutMs zookeeper connection timeout in milliseconds
* @throws KeeperException if the connection attempt times out. This will
* be a ZooKeeper ConnectionLoss exception code.
* @throws IOException if interrupted while connecting to ZooKeeper
*/
private void waitForZKConnectionEvent(int connectionTimeoutMs)
throws KeeperException, IOException {
try {
if (!hasReceivedEvent.await(connectionTimeoutMs, TimeUnit.MILLISECONDS)) {
LOG.error("Connection timed out: couldn't connect to ZooKeeper in "
+ connectionTimeoutMs + " milliseconds");
zk.close();
throw KeeperException.create(Code.CONNECTIONLOSS);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException(
"Interrupted when connecting to zookeeper server", e);
}
}
private void setZooKeeperRef(ZooKeeper zk) {
Preconditions.checkState(this.zk == null,
"zk already set -- must be set exactly once");
this.zk = zk;
hasSetZooKeeper.countDown();
}
@Override
public void process(WatchedEvent event) {
hasReceivedEvent.countDown();
try {
if (!hasSetZooKeeper.await(zkSessionTimeout, TimeUnit.MILLISECONDS)) {
LOG.debug("Event received with stale zk");
}
ActiveStandbyElector.this.processWatchEvent(
zk, event);
} catch (Throwable t) {
fatalError(
"Failed to process watcher event " + event + ": " +
StringUtils.stringifyException(t));
}
}
}
private static boolean isSuccess(Code code) {
return (code == Code.OK);
}
private static boolean isNodeExists(Code code) {
return (code == Code.NODEEXISTS);
}
private static boolean isNodeDoesNotExist(Code code) {
return (code == Code.NONODE);
}
private static boolean isSessionExpired(Code code) {
return (code == Code.SESSIONEXPIRED);
}
private static boolean shouldRetry(Code code) {
return code == Code.CONNECTIONLOSS || code == Code.OPERATIONTIMEOUT;
}
@Override
public String toString() {
return "elector id=" + System.identityHashCode(this) +
" appData=" +
((appData == null) ? "null" : StringUtils.byteToHexString(appData)) +
" cb=" + appClient;
}
}
| JoeChien23/hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ha/ActiveStandbyElector.java | Java | apache-2.0 | 38,058 |
/*
Copyright 2014 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 cmd
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/spf13/cobra"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/kubernetes/pkg/kubectl"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/resource"
"k8s.io/kubernetes/pkg/kubectl/util/i18n"
)
var (
replaceLong = templates.LongDesc(i18n.T(`
Replace a resource by filename or stdin.
JSON and YAML formats are accepted. If replacing an existing resource, the
complete resource spec must be provided. This can be obtained by
$ kubectl get TYPE NAME -o yaml
Please refer to the models in https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/docs/api-reference/v1/definitions.html to find if a field is mutable.`))
replaceExample = templates.Examples(i18n.T(`
# Replace a pod using the data in pod.json.
kubectl replace -f ./pod.json
# Replace a pod based on the JSON passed into stdin.
cat pod.json | kubectl replace -f -
# Update a single-container pod's image version (tag) to v4
kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -
# Force replace, delete and then re-create the resource
kubectl replace --force -f ./pod.json`))
)
func NewCmdReplace(f cmdutil.Factory, out io.Writer) *cobra.Command {
options := &resource.FilenameOptions{}
cmd := &cobra.Command{
Use: "replace -f FILENAME",
DisableFlagsInUseLine: true,
Short: i18n.T("Replace a resource by filename or stdin"),
Long: replaceLong,
Example: replaceExample,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd))
err := RunReplace(f, out, cmd, args, options)
cmdutil.CheckErr(err)
},
}
usage := "to use to replace the resource."
cmdutil.AddFilenameOptionFlags(cmd, options, usage)
cmd.MarkFlagRequired("filename")
cmd.Flags().Bool("force", false, "Delete and re-create the specified resource")
cmd.Flags().Bool("cascade", false, "Only relevant during a force replace. If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController).")
cmd.Flags().Int("grace-period", -1, "Only relevant during a force replace. Period of time in seconds given to the old resource to terminate gracefully. Ignored if negative.")
cmd.Flags().Duration("timeout", 0, "Only relevant during a force replace. The length of time to wait before giving up on a delete of the old resource, zero means determine a timeout from the size of the object. Any other values should contain a corresponding time unit (e.g. 1s, 2m, 3h).")
cmdutil.AddValidateFlags(cmd)
cmdutil.AddOutputFlagsForMutation(cmd)
cmdutil.AddApplyAnnotationFlags(cmd)
cmdutil.AddRecordFlag(cmd)
cmdutil.AddInclude3rdPartyFlags(cmd)
return cmd
}
func RunReplace(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *resource.FilenameOptions) error {
schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"))
if err != nil {
return err
}
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
force := cmdutil.GetFlagBool(cmd, "force")
if cmdutil.IsFilenameSliceEmpty(options.Filenames) {
return cmdutil.UsageErrorf(cmd, "Must specify --filename to replace")
}
shortOutput := cmdutil.GetFlagString(cmd, "output") == "name"
if force {
return forceReplace(f, out, cmd, args, shortOutput, options)
}
if cmdutil.GetFlagInt(cmd, "grace-period") >= 0 {
return fmt.Errorf("--grace-period must have --force specified")
}
if cmdutil.GetFlagDuration(cmd, "timeout") != 0 {
return fmt.Errorf("--timeout must have --force specified")
}
r := f.NewBuilder().
Unstructured().
Schema(schema).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, options).
Flatten().
Do()
if err := r.Err(); err != nil {
return err
}
return r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, f.JSONEncoder()); err != nil {
return cmdutil.AddSourceToErr("replacing", info.Source, err)
}
if cmdutil.ShouldRecord(cmd, info) {
if err := cmdutil.RecordChangeCause(info.Object, f.Command(cmd, false)); err != nil {
return cmdutil.AddSourceToErr("replacing", info.Source, err)
}
}
// Serialize the object with the annotation applied.
obj, err := resource.NewHelper(info.Client, info.Mapping).Replace(info.Namespace, info.Name, true, info.Object)
if err != nil {
return cmdutil.AddSourceToErr("replacing", info.Source, err)
}
info.Refresh(obj, true)
f.PrintObjectSpecificMessage(obj, out)
f.PrintSuccess(shortOutput, out, info.Mapping.Resource, info.Name, false, "replaced")
return nil
})
}
func forceReplace(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, shortOutput bool, options *resource.FilenameOptions) error {
schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"))
if err != nil {
return err
}
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
for i, filename := range options.Filenames {
if filename == "-" {
tempDir, err := ioutil.TempDir("", "kubectl_replace_")
if err != nil {
return err
}
defer os.RemoveAll(tempDir)
tempFilename := filepath.Join(tempDir, "resource.stdin")
err = cmdutil.DumpReaderToFile(os.Stdin, tempFilename)
if err != nil {
return err
}
options.Filenames[i] = tempFilename
}
}
r := f.NewBuilder().
Unstructured().
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, options).
ResourceTypeOrNameArgs(false, args...).RequireObject(false).
Flatten().
Do()
if err := r.Err(); err != nil {
return err
}
mapper := r.Mapper().RESTMapper
//Replace will create a resource if it doesn't exist already, so ignore not found error
ignoreNotFound := true
timeout := cmdutil.GetFlagDuration(cmd, "timeout")
gracePeriod := cmdutil.GetFlagInt(cmd, "grace-period")
waitForDeletion := false
if gracePeriod == 0 {
// To preserve backwards compatibility, but prevent accidental data loss, we convert --grace-period=0
// into --grace-period=1 and wait until the object is successfully deleted.
gracePeriod = 1
waitForDeletion = true
}
// By default use a reaper to delete all related resources.
if cmdutil.GetFlagBool(cmd, "cascade") {
glog.Warningf("\"cascade\" is set, kubectl will delete and re-create all resources managed by this resource (e.g. Pods created by a ReplicationController). Consider using \"kubectl rolling-update\" if you want to update a ReplicationController together with its Pods.")
err = ReapResult(r, f, out, cmdutil.GetFlagBool(cmd, "cascade"), ignoreNotFound, timeout, gracePeriod, waitForDeletion, shortOutput, mapper, false)
} else {
err = DeleteResult(r, f, out, ignoreNotFound, gracePeriod, shortOutput, mapper)
}
if err != nil {
return err
}
if timeout == 0 {
timeout = kubectl.Timeout
}
err = r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
return wait.PollImmediate(kubectl.Interval, timeout, func() (bool, error) {
if err := info.Get(); !errors.IsNotFound(err) {
return false, err
}
return true, nil
})
})
if err != nil {
return err
}
r = f.NewBuilder().
Unstructured().
Schema(schema).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, options).
Flatten().
Do()
err = r.Err()
if err != nil {
return err
}
count := 0
err = r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, f.JSONEncoder()); err != nil {
return err
}
if cmdutil.ShouldRecord(cmd, info) {
if err := cmdutil.RecordChangeCause(info.Object, f.Command(cmd, false)); err != nil {
return cmdutil.AddSourceToErr("replacing", info.Source, err)
}
}
obj, err := resource.NewHelper(info.Client, info.Mapping).Create(info.Namespace, true, info.Object)
if err != nil {
return err
}
count++
info.Refresh(obj, true)
f.PrintObjectSpecificMessage(obj, out)
f.PrintSuccess(shortOutput, out, info.Mapping.Resource, info.Name, false, "replaced")
return nil
})
if err != nil {
return err
}
if count == 0 {
return fmt.Errorf("no objects passed to replace")
}
return nil
}
| humblec/external-storage | vendor/k8s.io/kubernetes/pkg/kubectl/cmd/replace.go | GO | apache-2.0 | 9,290 |
/*
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 plugins
import (
"fmt"
"k8s.io/test-infra/velodrome/sql"
"github.com/spf13/cobra"
)
// TypeFilterWrapperPlugin allows ignoring either PR or issues from processing
type TypeFilterWrapperPlugin struct {
pullRequests bool
issues bool
plugin Plugin
// List of issues that we should ignore
pass map[string]bool
}
var _ Plugin = &TypeFilterWrapperPlugin{}
// NewTypeFilterWrapperPlugin is the constructor of TypeFilterWrapperPlugin
func NewTypeFilterWrapperPlugin(plugin Plugin) *TypeFilterWrapperPlugin {
return &TypeFilterWrapperPlugin{
plugin: plugin,
pass: map[string]bool{},
}
}
// AddFlags adds "no-pull-requests" and "no-issues" to the command help
func (t *TypeFilterWrapperPlugin) AddFlags(cmd *cobra.Command) {
cmd.Flags().BoolVar(&t.pullRequests, "no-pull-requests", false, "Ignore pull-requests")
cmd.Flags().BoolVar(&t.issues, "no-issues", false, "Ignore issues")
}
// CheckFlags makes sure not both PR and issues are ignored
func (t *TypeFilterWrapperPlugin) CheckFlags() error {
if t.pullRequests && t.issues {
return fmt.Errorf(
"you can't ignore both pull-requests and issues")
}
return nil
}
// ReceiveIssue calls plugin.ReceiveIssue() if issues are not ignored
func (t *TypeFilterWrapperPlugin) ReceiveIssue(issue sql.Issue) []Point {
if issue.IsPR && t.pullRequests {
return nil
} else if !issue.IsPR && t.issues {
return nil
} else {
t.pass[issue.ID] = true
return t.plugin.ReceiveIssue(issue)
}
}
// ReceiveIssueEvent calls plugin.ReceiveIssueEvent() if issues are not ignored
func (t *TypeFilterWrapperPlugin) ReceiveIssueEvent(event sql.IssueEvent) []Point {
if !t.pass[event.IssueID] {
return nil
}
return t.plugin.ReceiveIssueEvent(event)
}
// ReceiveComment calls plugin.ReceiveComment() if issues are not ignored
func (t *TypeFilterWrapperPlugin) ReceiveComment(comment sql.Comment) []Point {
if !t.pass[comment.IssueID] {
return nil
}
return t.plugin.ReceiveComment(comment)
}
| lavalamp/test-infra | velodrome/transform/plugins/type_filter_wrapper.go | GO | apache-2.0 | 2,546 |
/**
* Copyright 2009-2015 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.apache.ibatis.domain.misc.generics;
public abstract class GenericSubclass extends GenericAbstract<Long> {
@Override
public abstract Long getId();
}
| macs524/mybatis_learn | src/test/java/org/apache/ibatis/domain/misc/generics/GenericSubclass.java | Java | apache-2.0 | 819 |
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
using namespace cv;
using namespace cv::cuda;
#if !defined (HAVE_CUDA) || defined (CUDA_DISABLER)
Ptr<cv::cuda::DescriptorMatcher> cv::cuda::DescriptorMatcher::createBFMatcher(int) { throw_no_cuda(); return Ptr<cv::cuda::DescriptorMatcher>(); }
#else /* !defined (HAVE_CUDA) */
namespace cv { namespace cuda { namespace device
{
namespace bf_match
{
template <typename T> void matchL1_gpu(const PtrStepSzb& query, const PtrStepSzb& train, const PtrStepSzb& mask,
const PtrStepSzi& trainIdx, const PtrStepSzf& distance,
cudaStream_t stream);
template <typename T> void matchL2_gpu(const PtrStepSzb& query, const PtrStepSzb& train, const PtrStepSzb& mask,
const PtrStepSzi& trainIdx, const PtrStepSzf& distance,
cudaStream_t stream);
template <typename T> void matchHamming_gpu(const PtrStepSzb& query, const PtrStepSzb& train, const PtrStepSzb& mask,
const PtrStepSzi& trainIdx, const PtrStepSzf& distance,
cudaStream_t stream);
template <typename T> void matchL1_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks,
const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance,
cudaStream_t stream);
template <typename T> void matchL2_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks,
const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance,
cudaStream_t stream);
template <typename T> void matchHamming_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks,
const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance,
cudaStream_t stream);
}
namespace bf_knnmatch
{
template <typename T> void matchL1_gpu(const PtrStepSzb& query, const PtrStepSzb& train, int k, const PtrStepSzb& mask,
const PtrStepSzb& trainIdx, const PtrStepSzb& distance, const PtrStepSzf& allDist,
cudaStream_t stream);
template <typename T> void matchL2_gpu(const PtrStepSzb& query, const PtrStepSzb& train, int k, const PtrStepSzb& mask,
const PtrStepSzb& trainIdx, const PtrStepSzb& distance, const PtrStepSzf& allDist,
cudaStream_t stream);
template <typename T> void matchHamming_gpu(const PtrStepSzb& query, const PtrStepSzb& train, int k, const PtrStepSzb& mask,
const PtrStepSzb& trainIdx, const PtrStepSzb& distance, const PtrStepSzf& allDist,
cudaStream_t stream);
template <typename T> void match2L1_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks,
const PtrStepSzb& trainIdx, const PtrStepSzb& imgIdx, const PtrStepSzb& distance,
cudaStream_t stream);
template <typename T> void match2L2_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks,
const PtrStepSzb& trainIdx, const PtrStepSzb& imgIdx, const PtrStepSzb& distance,
cudaStream_t stream);
template <typename T> void match2Hamming_gpu(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks,
const PtrStepSzb& trainIdx, const PtrStepSzb& imgIdx, const PtrStepSzb& distance,
cudaStream_t stream);
}
namespace bf_radius_match
{
template <typename T> void matchL1_gpu(const PtrStepSzb& query, const PtrStepSzb& train, float maxDistance, const PtrStepSzb& mask,
const PtrStepSzi& trainIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches,
cudaStream_t stream);
template <typename T> void matchL2_gpu(const PtrStepSzb& query, const PtrStepSzb& train, float maxDistance, const PtrStepSzb& mask,
const PtrStepSzi& trainIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches,
cudaStream_t stream);
template <typename T> void matchHamming_gpu(const PtrStepSzb& query, const PtrStepSzb& train, float maxDistance, const PtrStepSzb& mask,
const PtrStepSzi& trainIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches,
cudaStream_t stream);
template <typename T> void matchL1_gpu(const PtrStepSzb& query, const PtrStepSzb* trains, int n, float maxDistance, const PtrStepSzb* masks,
const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches,
cudaStream_t stream);
template <typename T> void matchL2_gpu(const PtrStepSzb& query, const PtrStepSzb* trains, int n, float maxDistance, const PtrStepSzb* masks,
const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches,
cudaStream_t stream);
template <typename T> void matchHamming_gpu(const PtrStepSzb& query, const PtrStepSzb* trains, int n, float maxDistance, const PtrStepSzb* masks,
const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches,
cudaStream_t stream);
}
}}}
namespace
{
static void makeGpuCollection(const std::vector<GpuMat>& trainDescCollection,
const std::vector<GpuMat>& masks,
GpuMat& trainCollection,
GpuMat& maskCollection)
{
if (trainDescCollection.empty())
return;
if (masks.empty())
{
Mat trainCollectionCPU(1, static_cast<int>(trainDescCollection.size()), CV_8UC(sizeof(PtrStepSzb)));
PtrStepSzb* trainCollectionCPU_ptr = trainCollectionCPU.ptr<PtrStepSzb>();
for (size_t i = 0, size = trainDescCollection.size(); i < size; ++i, ++trainCollectionCPU_ptr)
*trainCollectionCPU_ptr = trainDescCollection[i];
trainCollection.upload(trainCollectionCPU);
maskCollection.release();
}
else
{
CV_Assert( masks.size() == trainDescCollection.size() );
Mat trainCollectionCPU(1, static_cast<int>(trainDescCollection.size()), CV_8UC(sizeof(PtrStepSzb)));
Mat maskCollectionCPU(1, static_cast<int>(trainDescCollection.size()), CV_8UC(sizeof(PtrStepb)));
PtrStepSzb* trainCollectionCPU_ptr = trainCollectionCPU.ptr<PtrStepSzb>();
PtrStepb* maskCollectionCPU_ptr = maskCollectionCPU.ptr<PtrStepb>();
for (size_t i = 0, size = trainDescCollection.size(); i < size; ++i, ++trainCollectionCPU_ptr, ++maskCollectionCPU_ptr)
{
const GpuMat& train = trainDescCollection[i];
const GpuMat& mask = masks[i];
CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.cols == train.rows) );
*trainCollectionCPU_ptr = train;
*maskCollectionCPU_ptr = mask;
}
trainCollection.upload(trainCollectionCPU);
maskCollection.upload(maskCollectionCPU);
}
}
class BFMatcher_Impl : public cv::cuda::DescriptorMatcher
{
public:
explicit BFMatcher_Impl(int norm) : norm_(norm)
{
CV_Assert( norm == NORM_L1 || norm == NORM_L2 || norm == NORM_HAMMING );
}
virtual bool isMaskSupported() const { return true; }
virtual void add(const std::vector<GpuMat>& descriptors)
{
trainDescCollection_.insert(trainDescCollection_.end(), descriptors.begin(), descriptors.end());
}
virtual const std::vector<GpuMat>& getTrainDescriptors() const
{
return trainDescCollection_;
}
virtual void clear()
{
trainDescCollection_.clear();
}
virtual bool empty() const
{
return trainDescCollection_.empty();
}
virtual void train()
{
}
virtual void match(InputArray queryDescriptors, InputArray trainDescriptors,
std::vector<DMatch>& matches,
InputArray mask = noArray());
virtual void match(InputArray queryDescriptors,
std::vector<DMatch>& matches,
const std::vector<GpuMat>& masks = std::vector<GpuMat>());
virtual void matchAsync(InputArray queryDescriptors, InputArray trainDescriptors,
OutputArray matches,
InputArray mask = noArray(),
Stream& stream = Stream::Null());
virtual void matchAsync(InputArray queryDescriptors,
OutputArray matches,
const std::vector<GpuMat>& masks = std::vector<GpuMat>(),
Stream& stream = Stream::Null());
virtual void matchConvert(InputArray gpu_matches,
std::vector<DMatch>& matches);
virtual void knnMatch(InputArray queryDescriptors, InputArray trainDescriptors,
std::vector<std::vector<DMatch> >& matches,
int k,
InputArray mask = noArray(),
bool compactResult = false);
virtual void knnMatch(InputArray queryDescriptors,
std::vector<std::vector<DMatch> >& matches,
int k,
const std::vector<GpuMat>& masks = std::vector<GpuMat>(),
bool compactResult = false);
virtual void knnMatchAsync(InputArray queryDescriptors, InputArray trainDescriptors,
OutputArray matches,
int k,
InputArray mask = noArray(),
Stream& stream = Stream::Null());
virtual void knnMatchAsync(InputArray queryDescriptors,
OutputArray matches,
int k,
const std::vector<GpuMat>& masks = std::vector<GpuMat>(),
Stream& stream = Stream::Null());
virtual void knnMatchConvert(InputArray gpu_matches,
std::vector< std::vector<DMatch> >& matches,
bool compactResult = false);
virtual void radiusMatch(InputArray queryDescriptors, InputArray trainDescriptors,
std::vector<std::vector<DMatch> >& matches,
float maxDistance,
InputArray mask = noArray(),
bool compactResult = false);
virtual void radiusMatch(InputArray queryDescriptors,
std::vector<std::vector<DMatch> >& matches,
float maxDistance,
const std::vector<GpuMat>& masks = std::vector<GpuMat>(),
bool compactResult = false);
virtual void radiusMatchAsync(InputArray queryDescriptors, InputArray trainDescriptors,
OutputArray matches,
float maxDistance,
InputArray mask = noArray(),
Stream& stream = Stream::Null());
virtual void radiusMatchAsync(InputArray queryDescriptors,
OutputArray matches,
float maxDistance,
const std::vector<GpuMat>& masks = std::vector<GpuMat>(),
Stream& stream = Stream::Null());
virtual void radiusMatchConvert(InputArray gpu_matches,
std::vector< std::vector<DMatch> >& matches,
bool compactResult = false);
private:
int norm_;
std::vector<GpuMat> trainDescCollection_;
};
//
// 1 to 1 match
//
void BFMatcher_Impl::match(InputArray _queryDescriptors, InputArray _trainDescriptors,
std::vector<DMatch>& matches,
InputArray _mask)
{
GpuMat d_matches;
matchAsync(_queryDescriptors, _trainDescriptors, d_matches, _mask);
matchConvert(d_matches, matches);
}
void BFMatcher_Impl::match(InputArray _queryDescriptors,
std::vector<DMatch>& matches,
const std::vector<GpuMat>& masks)
{
GpuMat d_matches;
matchAsync(_queryDescriptors, d_matches, masks);
matchConvert(d_matches, matches);
}
void BFMatcher_Impl::matchAsync(InputArray _queryDescriptors, InputArray _trainDescriptors,
OutputArray _matches,
InputArray _mask,
Stream& stream)
{
using namespace cv::cuda::device::bf_match;
const GpuMat query = _queryDescriptors.getGpuMat();
const GpuMat train = _trainDescriptors.getGpuMat();
const GpuMat mask = _mask.getGpuMat();
if (query.empty() || train.empty())
{
_matches.release();
return;
}
CV_Assert( query.channels() == 1 && query.depth() < CV_64F );
CV_Assert( train.cols == query.cols && train.type() == query.type() );
CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.rows == query.rows && mask.cols == train.rows) );
typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb& train, const PtrStepSzb& mask,
const PtrStepSzi& trainIdx, const PtrStepSzf& distance,
cudaStream_t stream);
static const caller_t callersL1[] =
{
matchL1_gpu<unsigned char>, 0/*matchL1_gpu<signed char>*/,
matchL1_gpu<unsigned short>, matchL1_gpu<short>,
matchL1_gpu<int>, matchL1_gpu<float>
};
static const caller_t callersL2[] =
{
0/*matchL2_gpu<unsigned char>*/, 0/*matchL2_gpu<signed char>*/,
0/*matchL2_gpu<unsigned short>*/, 0/*matchL2_gpu<short>*/,
0/*matchL2_gpu<int>*/, matchL2_gpu<float>
};
static const caller_t callersHamming[] =
{
matchHamming_gpu<unsigned char>, 0/*matchHamming_gpu<signed char>*/,
matchHamming_gpu<unsigned short>, 0/*matchHamming_gpu<short>*/,
matchHamming_gpu<int>, 0/*matchHamming_gpu<float>*/
};
const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming;
const caller_t func = callers[query.depth()];
if (func == 0)
{
CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm");
}
const int nQuery = query.rows;
_matches.create(2, nQuery, CV_32SC1);
GpuMat matches = _matches.getGpuMat();
GpuMat trainIdx(1, nQuery, CV_32SC1, matches.ptr(0));
GpuMat distance(1, nQuery, CV_32FC1, matches.ptr(1));
func(query, train, mask, trainIdx, distance, StreamAccessor::getStream(stream));
}
void BFMatcher_Impl::matchAsync(InputArray _queryDescriptors,
OutputArray _matches,
const std::vector<GpuMat>& masks,
Stream& stream)
{
using namespace cv::cuda::device::bf_match;
const GpuMat query = _queryDescriptors.getGpuMat();
if (query.empty() || trainDescCollection_.empty())
{
_matches.release();
return;
}
CV_Assert( query.channels() == 1 && query.depth() < CV_64F );
GpuMat trainCollection, maskCollection;
makeGpuCollection(trainDescCollection_, masks, trainCollection, maskCollection);
typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks,
const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance,
cudaStream_t stream);
static const caller_t callersL1[] =
{
matchL1_gpu<unsigned char>, 0/*matchL1_gpu<signed char>*/,
matchL1_gpu<unsigned short>, matchL1_gpu<short>,
matchL1_gpu<int>, matchL1_gpu<float>
};
static const caller_t callersL2[] =
{
0/*matchL2_gpu<unsigned char>*/, 0/*matchL2_gpu<signed char>*/,
0/*matchL2_gpu<unsigned short>*/, 0/*matchL2_gpu<short>*/,
0/*matchL2_gpu<int>*/, matchL2_gpu<float>
};
static const caller_t callersHamming[] =
{
matchHamming_gpu<unsigned char>, 0/*matchHamming_gpu<signed char>*/,
matchHamming_gpu<unsigned short>, 0/*matchHamming_gpu<short>*/,
matchHamming_gpu<int>, 0/*matchHamming_gpu<float>*/
};
const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming;
const caller_t func = callers[query.depth()];
if (func == 0)
{
CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm");
}
const int nQuery = query.rows;
_matches.create(3, nQuery, CV_32SC1);
GpuMat matches = _matches.getGpuMat();
GpuMat trainIdx(1, nQuery, CV_32SC1, matches.ptr(0));
GpuMat imgIdx(1, nQuery, CV_32SC1, matches.ptr(1));
GpuMat distance(1, nQuery, CV_32FC1, matches.ptr(2));
func(query, trainCollection, maskCollection, trainIdx, imgIdx, distance, StreamAccessor::getStream(stream));
}
void BFMatcher_Impl::matchConvert(InputArray _gpu_matches,
std::vector<DMatch>& matches)
{
Mat gpu_matches;
if (_gpu_matches.kind() == _InputArray::CUDA_GPU_MAT)
{
_gpu_matches.getGpuMat().download(gpu_matches);
}
else
{
gpu_matches = _gpu_matches.getMat();
}
if (gpu_matches.empty())
{
matches.clear();
return;
}
CV_Assert( (gpu_matches.type() == CV_32SC1) && (gpu_matches.rows == 2 || gpu_matches.rows == 3) );
const int nQuery = gpu_matches.cols;
matches.clear();
matches.reserve(nQuery);
const int* trainIdxPtr = NULL;
const int* imgIdxPtr = NULL;
const float* distancePtr = NULL;
if (gpu_matches.rows == 2)
{
trainIdxPtr = gpu_matches.ptr<int>(0);
distancePtr = gpu_matches.ptr<float>(1);
}
else
{
trainIdxPtr = gpu_matches.ptr<int>(0);
imgIdxPtr = gpu_matches.ptr<int>(1);
distancePtr = gpu_matches.ptr<float>(2);
}
for (int queryIdx = 0; queryIdx < nQuery; ++queryIdx)
{
const int trainIdx = trainIdxPtr[queryIdx];
if (trainIdx == -1)
continue;
const int imgIdx = imgIdxPtr ? imgIdxPtr[queryIdx] : 0;
const float distance = distancePtr[queryIdx];
DMatch m(queryIdx, trainIdx, imgIdx, distance);
matches.push_back(m);
}
}
//
// knn match
//
void BFMatcher_Impl::knnMatch(InputArray _queryDescriptors, InputArray _trainDescriptors,
std::vector<std::vector<DMatch> >& matches,
int k,
InputArray _mask,
bool compactResult)
{
GpuMat d_matches;
knnMatchAsync(_queryDescriptors, _trainDescriptors, d_matches, k, _mask);
knnMatchConvert(d_matches, matches, compactResult);
}
void BFMatcher_Impl::knnMatch(InputArray _queryDescriptors,
std::vector<std::vector<DMatch> >& matches,
int k,
const std::vector<GpuMat>& masks,
bool compactResult)
{
if (k == 2)
{
GpuMat d_matches;
knnMatchAsync(_queryDescriptors, d_matches, k, masks);
knnMatchConvert(d_matches, matches, compactResult);
}
else
{
const GpuMat query = _queryDescriptors.getGpuMat();
if (query.empty() || trainDescCollection_.empty())
{
matches.clear();
return;
}
CV_Assert( query.channels() == 1 && query.depth() < CV_64F );
std::vector< std::vector<DMatch> > curMatches;
std::vector<DMatch> temp;
temp.reserve(2 * k);
matches.resize(query.rows);
for (size_t i = 0; i < matches.size(); ++i)
matches[i].reserve(k);
for (size_t imgIdx = 0; imgIdx < trainDescCollection_.size(); ++imgIdx)
{
knnMatch(query, trainDescCollection_[imgIdx], curMatches, k, masks.empty() ? GpuMat() : masks[imgIdx]);
for (int queryIdx = 0; queryIdx < query.rows; ++queryIdx)
{
std::vector<DMatch>& localMatch = curMatches[queryIdx];
std::vector<DMatch>& globalMatch = matches[queryIdx];
for (size_t i = 0; i < localMatch.size(); ++i)
localMatch[i].imgIdx = imgIdx;
temp.clear();
std::merge(globalMatch.begin(), globalMatch.end(), localMatch.begin(), localMatch.end(), std::back_inserter(temp));
globalMatch.clear();
const size_t count = std::min(static_cast<size_t>(k), temp.size());
std::copy(temp.begin(), temp.begin() + count, std::back_inserter(globalMatch));
}
}
if (compactResult)
{
std::vector< std::vector<DMatch> >::iterator new_end = std::remove_if(matches.begin(), matches.end(), std::mem_fun_ref(&std::vector<DMatch>::empty));
matches.erase(new_end, matches.end());
}
}
}
void BFMatcher_Impl::knnMatchAsync(InputArray _queryDescriptors, InputArray _trainDescriptors,
OutputArray _matches,
int k,
InputArray _mask,
Stream& stream)
{
using namespace cv::cuda::device::bf_knnmatch;
const GpuMat query = _queryDescriptors.getGpuMat();
const GpuMat train = _trainDescriptors.getGpuMat();
const GpuMat mask = _mask.getGpuMat();
if (query.empty() || train.empty())
{
_matches.release();
return;
}
CV_Assert( query.channels() == 1 && query.depth() < CV_64F );
CV_Assert( train.cols == query.cols && train.type() == query.type() );
CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.rows == query.rows && mask.cols == train.rows) );
typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb& train, int k, const PtrStepSzb& mask,
const PtrStepSzb& trainIdx, const PtrStepSzb& distance, const PtrStepSzf& allDist,
cudaStream_t stream);
static const caller_t callersL1[] =
{
matchL1_gpu<unsigned char>, 0/*matchL1_gpu<signed char>*/,
matchL1_gpu<unsigned short>, matchL1_gpu<short>,
matchL1_gpu<int>, matchL1_gpu<float>
};
static const caller_t callersL2[] =
{
0/*matchL2_gpu<unsigned char>*/, 0/*matchL2_gpu<signed char>*/,
0/*matchL2_gpu<unsigned short>*/, 0/*matchL2_gpu<short>*/,
0/*matchL2_gpu<int>*/, matchL2_gpu<float>
};
static const caller_t callersHamming[] =
{
matchHamming_gpu<unsigned char>, 0/*matchHamming_gpu<signed char>*/,
matchHamming_gpu<unsigned short>, 0/*matchHamming_gpu<short>*/,
matchHamming_gpu<int>, 0/*matchHamming_gpu<float>*/
};
const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming;
const caller_t func = callers[query.depth()];
if (func == 0)
{
CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm");
}
const int nQuery = query.rows;
const int nTrain = train.rows;
GpuMat trainIdx, distance, allDist;
if (k == 2)
{
_matches.create(2, nQuery, CV_32SC2);
GpuMat matches = _matches.getGpuMat();
trainIdx = GpuMat(1, nQuery, CV_32SC2, matches.ptr(0));
distance = GpuMat(1, nQuery, CV_32FC2, matches.ptr(1));
}
else
{
_matches.create(2 * nQuery, k, CV_32SC1);
GpuMat matches = _matches.getGpuMat();
trainIdx = GpuMat(nQuery, k, CV_32SC1, matches.ptr(0), matches.step);
distance = GpuMat(nQuery, k, CV_32FC1, matches.ptr(nQuery), matches.step);
BufferPool pool(stream);
allDist = pool.getBuffer(nQuery, nTrain, CV_32FC1);
}
trainIdx.setTo(Scalar::all(-1), stream);
func(query, train, k, mask, trainIdx, distance, allDist, StreamAccessor::getStream(stream));
}
void BFMatcher_Impl::knnMatchAsync(InputArray _queryDescriptors,
OutputArray _matches,
int k,
const std::vector<GpuMat>& masks,
Stream& stream)
{
using namespace cv::cuda::device::bf_knnmatch;
if (k != 2)
{
CV_Error(Error::StsNotImplemented, "only k=2 mode is supported for now");
}
const GpuMat query = _queryDescriptors.getGpuMat();
if (query.empty() || trainDescCollection_.empty())
{
_matches.release();
return;
}
CV_Assert( query.channels() == 1 && query.depth() < CV_64F );
GpuMat trainCollection, maskCollection;
makeGpuCollection(trainDescCollection_, masks, trainCollection, maskCollection);
typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb& trains, const PtrStepSz<PtrStepb>& masks,
const PtrStepSzb& trainIdx, const PtrStepSzb& imgIdx, const PtrStepSzb& distance,
cudaStream_t stream);
static const caller_t callersL1[] =
{
match2L1_gpu<unsigned char>, 0/*match2L1_gpu<signed char>*/,
match2L1_gpu<unsigned short>, match2L1_gpu<short>,
match2L1_gpu<int>, match2L1_gpu<float>
};
static const caller_t callersL2[] =
{
0/*match2L2_gpu<unsigned char>*/, 0/*match2L2_gpu<signed char>*/,
0/*match2L2_gpu<unsigned short>*/, 0/*match2L2_gpu<short>*/,
0/*match2L2_gpu<int>*/, match2L2_gpu<float>
};
static const caller_t callersHamming[] =
{
match2Hamming_gpu<unsigned char>, 0/*match2Hamming_gpu<signed char>*/,
match2Hamming_gpu<unsigned short>, 0/*match2Hamming_gpu<short>*/,
match2Hamming_gpu<int>, 0/*match2Hamming_gpu<float>*/
};
const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming;
const caller_t func = callers[query.depth()];
if (func == 0)
{
CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm");
}
const int nQuery = query.rows;
_matches.create(3, nQuery, CV_32SC2);
GpuMat matches = _matches.getGpuMat();
GpuMat trainIdx(1, nQuery, CV_32SC2, matches.ptr(0));
GpuMat imgIdx(1, nQuery, CV_32SC2, matches.ptr(1));
GpuMat distance(1, nQuery, CV_32FC2, matches.ptr(2));
trainIdx.setTo(Scalar::all(-1), stream);
func(query, trainCollection, maskCollection, trainIdx, imgIdx, distance, StreamAccessor::getStream(stream));
}
void BFMatcher_Impl::knnMatchConvert(InputArray _gpu_matches,
std::vector< std::vector<DMatch> >& matches,
bool compactResult)
{
Mat gpu_matches;
if (_gpu_matches.kind() == _InputArray::CUDA_GPU_MAT)
{
_gpu_matches.getGpuMat().download(gpu_matches);
}
else
{
gpu_matches = _gpu_matches.getMat();
}
if (gpu_matches.empty())
{
matches.clear();
return;
}
CV_Assert( ((gpu_matches.type() == CV_32SC2) && (gpu_matches.rows == 2 || gpu_matches.rows == 3)) ||
(gpu_matches.type() == CV_32SC1) );
int nQuery = -1, k = -1;
const int* trainIdxPtr = NULL;
const int* imgIdxPtr = NULL;
const float* distancePtr = NULL;
if (gpu_matches.type() == CV_32SC2)
{
nQuery = gpu_matches.cols;
k = 2;
if (gpu_matches.rows == 2)
{
trainIdxPtr = gpu_matches.ptr<int>(0);
distancePtr = gpu_matches.ptr<float>(1);
}
else
{
trainIdxPtr = gpu_matches.ptr<int>(0);
imgIdxPtr = gpu_matches.ptr<int>(1);
distancePtr = gpu_matches.ptr<float>(2);
}
}
else
{
nQuery = gpu_matches.rows / 2;
k = gpu_matches.cols;
trainIdxPtr = gpu_matches.ptr<int>(0);
distancePtr = gpu_matches.ptr<float>(nQuery);
}
matches.clear();
matches.reserve(nQuery);
for (int queryIdx = 0; queryIdx < nQuery; ++queryIdx)
{
matches.push_back(std::vector<DMatch>());
std::vector<DMatch>& curMatches = matches.back();
curMatches.reserve(k);
for (int i = 0; i < k; ++i)
{
const int trainIdx = *trainIdxPtr;
if (trainIdx == -1)
continue;
const int imgIdx = imgIdxPtr ? *imgIdxPtr : 0;
const float distance = *distancePtr;
DMatch m(queryIdx, trainIdx, imgIdx, distance);
curMatches.push_back(m);
++trainIdxPtr;
++distancePtr;
if (imgIdxPtr)
++imgIdxPtr;
}
if (compactResult && curMatches.empty())
{
matches.pop_back();
}
}
}
//
// radius match
//
void BFMatcher_Impl::radiusMatch(InputArray _queryDescriptors, InputArray _trainDescriptors,
std::vector<std::vector<DMatch> >& matches,
float maxDistance,
InputArray _mask,
bool compactResult)
{
GpuMat d_matches;
radiusMatchAsync(_queryDescriptors, _trainDescriptors, d_matches, maxDistance, _mask);
radiusMatchConvert(d_matches, matches, compactResult);
}
void BFMatcher_Impl::radiusMatch(InputArray _queryDescriptors,
std::vector<std::vector<DMatch> >& matches,
float maxDistance,
const std::vector<GpuMat>& masks,
bool compactResult)
{
GpuMat d_matches;
radiusMatchAsync(_queryDescriptors, d_matches, maxDistance, masks);
radiusMatchConvert(d_matches, matches, compactResult);
}
void BFMatcher_Impl::radiusMatchAsync(InputArray _queryDescriptors, InputArray _trainDescriptors,
OutputArray _matches,
float maxDistance,
InputArray _mask,
Stream& stream)
{
using namespace cv::cuda::device::bf_radius_match;
const GpuMat query = _queryDescriptors.getGpuMat();
const GpuMat train = _trainDescriptors.getGpuMat();
const GpuMat mask = _mask.getGpuMat();
if (query.empty() || train.empty())
{
_matches.release();
return;
}
CV_Assert( query.channels() == 1 && query.depth() < CV_64F );
CV_Assert( train.cols == query.cols && train.type() == query.type() );
CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.rows == query.rows && mask.cols == train.rows) );
typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb& train, float maxDistance, const PtrStepSzb& mask,
const PtrStepSzi& trainIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches,
cudaStream_t stream);
static const caller_t callersL1[] =
{
matchL1_gpu<unsigned char>, 0/*matchL1_gpu<signed char>*/,
matchL1_gpu<unsigned short>, matchL1_gpu<short>,
matchL1_gpu<int>, matchL1_gpu<float>
};
static const caller_t callersL2[] =
{
0/*matchL2_gpu<unsigned char>*/, 0/*matchL2_gpu<signed char>*/,
0/*matchL2_gpu<unsigned short>*/, 0/*matchL2_gpu<short>*/,
0/*matchL2_gpu<int>*/, matchL2_gpu<float>
};
static const caller_t callersHamming[] =
{
matchHamming_gpu<unsigned char>, 0/*matchHamming_gpu<signed char>*/,
matchHamming_gpu<unsigned short>, 0/*matchHamming_gpu<short>*/,
matchHamming_gpu<int>, 0/*matchHamming_gpu<float>*/
};
const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming;
const caller_t func = callers[query.depth()];
if (func == 0)
{
CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm");
}
const int nQuery = query.rows;
const int nTrain = train.rows;
const int cols = std::max((nTrain / 100), nQuery);
_matches.create(2 * nQuery + 1, cols, CV_32SC1);
GpuMat matches = _matches.getGpuMat();
GpuMat trainIdx(nQuery, cols, CV_32SC1, matches.ptr(0), matches.step);
GpuMat distance(nQuery, cols, CV_32FC1, matches.ptr(nQuery), matches.step);
GpuMat nMatches(1, nQuery, CV_32SC1, matches.ptr(2 * nQuery));
nMatches.setTo(Scalar::all(0), stream);
func(query, train, maxDistance, mask, trainIdx, distance, nMatches, StreamAccessor::getStream(stream));
}
void BFMatcher_Impl::radiusMatchAsync(InputArray _queryDescriptors,
OutputArray _matches,
float maxDistance,
const std::vector<GpuMat>& masks,
Stream& stream)
{
using namespace cv::cuda::device::bf_radius_match;
const GpuMat query = _queryDescriptors.getGpuMat();
if (query.empty() || trainDescCollection_.empty())
{
_matches.release();
return;
}
CV_Assert( query.channels() == 1 && query.depth() < CV_64F );
GpuMat trainCollection, maskCollection;
makeGpuCollection(trainDescCollection_, masks, trainCollection, maskCollection);
typedef void (*caller_t)(const PtrStepSzb& query, const PtrStepSzb* trains, int n, float maxDistance, const PtrStepSzb* masks,
const PtrStepSzi& trainIdx, const PtrStepSzi& imgIdx, const PtrStepSzf& distance, const PtrStepSz<unsigned int>& nMatches,
cudaStream_t stream);
static const caller_t callersL1[] =
{
matchL1_gpu<unsigned char>, 0/*matchL1_gpu<signed char>*/,
matchL1_gpu<unsigned short>, matchL1_gpu<short>,
matchL1_gpu<int>, matchL1_gpu<float>
};
static const caller_t callersL2[] =
{
0/*matchL2_gpu<unsigned char>*/, 0/*matchL2_gpu<signed char>*/,
0/*matchL2_gpu<unsigned short>*/, 0/*matchL2_gpu<short>*/,
0/*matchL2_gpu<int>*/, matchL2_gpu<float>
};
static const caller_t callersHamming[] =
{
matchHamming_gpu<unsigned char>, 0/*matchHamming_gpu<signed char>*/,
matchHamming_gpu<unsigned short>, 0/*matchHamming_gpu<short>*/,
matchHamming_gpu<int>, 0/*matchHamming_gpu<float>*/
};
const caller_t* callers = norm_ == NORM_L1 ? callersL1 : norm_ == NORM_L2 ? callersL2 : callersHamming;
const caller_t func = callers[query.depth()];
if (func == 0)
{
CV_Error(Error::StsUnsupportedFormat, "unsupported combination of query.depth() and norm");
}
const int nQuery = query.rows;
_matches.create(3 * nQuery + 1, nQuery, CV_32FC1);
GpuMat matches = _matches.getGpuMat();
GpuMat trainIdx(nQuery, nQuery, CV_32SC1, matches.ptr(0), matches.step);
GpuMat imgIdx(nQuery, nQuery, CV_32SC1, matches.ptr(nQuery), matches.step);
GpuMat distance(nQuery, nQuery, CV_32FC1, matches.ptr(2 * nQuery), matches.step);
GpuMat nMatches(1, nQuery, CV_32SC1, matches.ptr(3 * nQuery));
nMatches.setTo(Scalar::all(0), stream);
std::vector<PtrStepSzb> trains_(trainDescCollection_.begin(), trainDescCollection_.end());
std::vector<PtrStepSzb> masks_(masks.begin(), masks.end());
func(query, &trains_[0], static_cast<int>(trains_.size()), maxDistance, masks_.size() == 0 ? 0 : &masks_[0],
trainIdx, imgIdx, distance, nMatches, StreamAccessor::getStream(stream));
}
void BFMatcher_Impl::radiusMatchConvert(InputArray _gpu_matches,
std::vector< std::vector<DMatch> >& matches,
bool compactResult)
{
Mat gpu_matches;
if (_gpu_matches.kind() == _InputArray::CUDA_GPU_MAT)
{
_gpu_matches.getGpuMat().download(gpu_matches);
}
else
{
gpu_matches = _gpu_matches.getMat();
}
if (gpu_matches.empty())
{
matches.clear();
return;
}
CV_Assert( gpu_matches.type() == CV_32SC1 || gpu_matches.type() == CV_32FC1 );
int nQuery = -1;
const int* trainIdxPtr = NULL;
const int* imgIdxPtr = NULL;
const float* distancePtr = NULL;
const int* nMatchesPtr = NULL;
if (gpu_matches.type() == CV_32SC1)
{
nQuery = (gpu_matches.rows - 1) / 2;
trainIdxPtr = gpu_matches.ptr<int>(0);
distancePtr = gpu_matches.ptr<float>(nQuery);
nMatchesPtr = gpu_matches.ptr<int>(2 * nQuery);
}
else
{
nQuery = (gpu_matches.rows - 1) / 3;
trainIdxPtr = gpu_matches.ptr<int>(0);
imgIdxPtr = gpu_matches.ptr<int>(nQuery);
distancePtr = gpu_matches.ptr<float>(2 * nQuery);
nMatchesPtr = gpu_matches.ptr<int>(3 * nQuery);
}
matches.clear();
matches.reserve(nQuery);
for (int queryIdx = 0; queryIdx < nQuery; ++queryIdx)
{
const int nMatched = std::min(nMatchesPtr[queryIdx], gpu_matches.cols);
if (nMatched == 0)
{
if (!compactResult)
{
matches.push_back(std::vector<DMatch>());
}
}
else
{
matches.push_back(std::vector<DMatch>(nMatched));
std::vector<DMatch>& curMatches = matches.back();
for (int i = 0; i < nMatched; ++i)
{
const int trainIdx = trainIdxPtr[i];
const int imgIdx = imgIdxPtr ? imgIdxPtr[i] : 0;
const float distance = distancePtr[i];
DMatch m(queryIdx, trainIdx, imgIdx, distance);
curMatches[i] = m;
}
std::sort(curMatches.begin(), curMatches.end());
}
trainIdxPtr += gpu_matches.cols;
distancePtr += gpu_matches.cols;
if (imgIdxPtr)
imgIdxPtr += gpu_matches.cols;
}
}
}
Ptr<cv::cuda::DescriptorMatcher> cv::cuda::DescriptorMatcher::createBFMatcher(int norm)
{
return makePtr<BFMatcher_Impl>(norm);
}
#endif /* !defined (HAVE_CUDA) */
| DamianPilot382/Rubiks-Cube-Solver | opencv/sources/modules/cudafeatures2d/src/brute_force_matcher.cpp | C++ | apache-2.0 | 43,804 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.aggregation;
import com.facebook.presto.ExceededMemoryLimitException;
import com.facebook.presto.bytecode.DynamicClassLoader;
import com.facebook.presto.metadata.BoundVariables;
import com.facebook.presto.metadata.FunctionRegistry;
import com.facebook.presto.metadata.SqlAggregationFunction;
import com.facebook.presto.operator.aggregation.state.KeyValuePairStateSerializer;
import com.facebook.presto.operator.aggregation.state.KeyValuePairsState;
import com.facebook.presto.operator.aggregation.state.KeyValuePairsStateFactory;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spi.type.TypeManager;
import com.facebook.presto.type.ArrayType;
import com.facebook.presto.type.MapType;
import com.google.common.collect.ImmutableList;
import java.lang.invoke.MethodHandle;
import java.util.List;
import static com.facebook.presto.metadata.Signature.comparableTypeParameter;
import static com.facebook.presto.metadata.Signature.typeVariable;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.BLOCK_INDEX;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.BLOCK_INPUT_CHANNEL;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.NULLABLE_BLOCK_INPUT_CHANNEL;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.STATE;
import static com.facebook.presto.operator.aggregation.AggregationUtils.generateAggregationName;
import static com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT;
import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature;
import static com.facebook.presto.util.ImmutableCollectors.toImmutableList;
import static com.facebook.presto.util.Reflection.methodHandle;
import static java.lang.String.format;
public class MultimapAggregationFunction
extends SqlAggregationFunction
{
public static final MultimapAggregationFunction MULTIMAP_AGG = new MultimapAggregationFunction();
public static final String NAME = "multimap_agg";
private static final MethodHandle OUTPUT_FUNCTION = methodHandle(MultimapAggregationFunction.class, "output", KeyValuePairsState.class, BlockBuilder.class);
private static final MethodHandle INPUT_FUNCTION = methodHandle(MultimapAggregationFunction.class, "input", KeyValuePairsState.class, Block.class, Block.class, int.class);
private static final MethodHandle COMBINE_FUNCTION = methodHandle(MultimapAggregationFunction.class, "combine", KeyValuePairsState.class, KeyValuePairsState.class);
public MultimapAggregationFunction()
{
super(NAME,
ImmutableList.of(comparableTypeParameter("K"), typeVariable("V")),
ImmutableList.of(),
parseTypeSignature("map(K,array(V))"),
ImmutableList.of(parseTypeSignature("K"), parseTypeSignature("V")));
}
@Override
public String getDescription()
{
return "Aggregates all the rows (key/value pairs) into a single multimap";
}
@Override
public InternalAggregationFunction specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry)
{
Type keyType = boundVariables.getTypeVariable("K");
Type valueType = boundVariables.getTypeVariable("V");
return generateAggregation(keyType, valueType);
}
private static InternalAggregationFunction generateAggregation(Type keyType, Type valueType)
{
DynamicClassLoader classLoader = new DynamicClassLoader(MultimapAggregationFunction.class.getClassLoader());
List<Type> inputTypes = ImmutableList.of(keyType, valueType);
Type outputType = new MapType(keyType, new ArrayType(valueType));
KeyValuePairStateSerializer stateSerializer = new KeyValuePairStateSerializer(keyType, valueType, true);
Type intermediateType = stateSerializer.getSerializedType();
AggregationMetadata metadata = new AggregationMetadata(
generateAggregationName(NAME, outputType.getTypeSignature(), inputTypes.stream().map(Type::getTypeSignature).collect(toImmutableList())),
createInputParameterMetadata(keyType, valueType),
INPUT_FUNCTION,
COMBINE_FUNCTION,
OUTPUT_FUNCTION,
KeyValuePairsState.class,
stateSerializer,
new KeyValuePairsStateFactory(keyType, valueType),
outputType);
GenericAccumulatorFactoryBinder factory = AccumulatorCompiler.generateAccumulatorFactoryBinder(metadata, classLoader);
return new InternalAggregationFunction(NAME, inputTypes, intermediateType, outputType, true, factory);
}
private static List<ParameterMetadata> createInputParameterMetadata(Type keyType, Type valueType)
{
return ImmutableList.of(new ParameterMetadata(STATE),
new ParameterMetadata(BLOCK_INPUT_CHANNEL, keyType),
new ParameterMetadata(NULLABLE_BLOCK_INPUT_CHANNEL, valueType),
new ParameterMetadata(BLOCK_INDEX));
}
public static void input(KeyValuePairsState state, Block key, Block value, int position)
{
KeyValuePairs pairs = state.get();
if (pairs == null) {
pairs = new KeyValuePairs(state.getKeyType(), state.getValueType(), true);
state.set(pairs);
}
long startSize = pairs.estimatedInMemorySize();
try {
pairs.add(key, value, position, position);
}
catch (ExceededMemoryLimitException e) {
throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("The result of map_agg may not exceed %s", e.getMaxMemory()));
}
state.addMemoryUsage(pairs.estimatedInMemorySize() - startSize);
}
public static void combine(KeyValuePairsState state, KeyValuePairsState otherState)
{
if (state.get() != null && otherState.get() != null) {
Block keys = otherState.get().getKeys();
Block values = otherState.get().getValues();
KeyValuePairs pairs = state.get();
long startSize = pairs.estimatedInMemorySize();
for (int i = 0; i < keys.getPositionCount(); i++) {
try {
pairs.add(keys, values, i, i);
}
catch (ExceededMemoryLimitException e) {
throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("The result of map_agg may not exceed %s", e.getMaxMemory()));
}
}
state.addMemoryUsage(pairs.estimatedInMemorySize() - startSize);
}
else if (state.get() == null) {
state.set(otherState.get());
}
}
public static void output(KeyValuePairsState state, BlockBuilder out)
{
KeyValuePairs pairs = state.get();
if (pairs == null) {
out.appendNull();
}
else {
Block block = pairs.toMultimapNativeEncoding();
out.writeObject(block);
out.closeEntry();
}
}
}
| marsorp/blog | presto166/presto-main/src/main/java/com/facebook/presto/operator/aggregation/MultimapAggregationFunction.java | Java | apache-2.0 | 8,045 |
import { __platform_browser_private__ as r } from '@angular/platform-browser';
export var getDOM = r.getDOM;
//# sourceMappingURL=platform_browser_private.js.map | evandor/skysail-webconsole | webconsole.client/client/dist/lib/@angular/platform-browser-dynamic/esm/platform_browser_private.js | JavaScript | apache-2.0 | 161 |
/**
* Copyright 2005-2015 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.krad.devtools.datadictionary;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
/**
* This is a description of what this class does - gilesp don't forget to fill this in.
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*
*/
public class URLMonitor {
private static final Log LOG = LogFactory.getLog(URLMonitor.class);
private final LinkedList<URLContentChangedListener> listeners = new LinkedList<URLContentChangedListener>();
private final Map<URL, Long> resourceMap = new ConcurrentHashMap();
private final int reloadIntervalMilliseconds;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public URLMonitor(int reloadIntervalMilliseconds) {
this.reloadIntervalMilliseconds = reloadIntervalMilliseconds;
}
public void shutdownScheduler() {
scheduler.shutdown();
}
public synchronized void addListener(URLContentChangedListener listener) {
listeners.add(listener);
if (listeners.size() == 1) {
scheduler.scheduleAtFixedRate(urlPoller,
reloadIntervalMilliseconds, reloadIntervalMilliseconds, TimeUnit.MILLISECONDS);
}
}
public void addURI(URL zipUrl) {
resourceMap.put(zipUrl, getCRC(zipUrl));
}
private Long getCRC(URL zipUrl) {
Long result = -1l;
try {
CRC32 crc = new CRC32();
CheckedInputStream cis = new CheckedInputStream(zipUrl.openStream(), crc);
byte[] buffer = new byte[1024];
int length;
//read the entry from zip file and extract it to disk
while( (length = cis.read(buffer)) > 0);
cis.close();
result = crc.getValue();
} catch (IOException e) {
LOG.warn("Unable to calculate CRC, resource doesn't exist?", e);
}
return result;
}
private final Runnable urlPoller = new Runnable() {
@Override
public void run() {
for (Map.Entry<URL, Long> entry : resourceMap.entrySet()) {
Long crc = getCRC(entry.getKey());
if (!entry.getValue().equals(crc)) {
entry.setValue(crc);
for (URLContentChangedListener listener : listeners) {
listener.urlContentChanged(entry.getKey());
}
}
}
}
};
public static interface URLContentChangedListener {
public void urlContentChanged(URL url);
}
} | bhutchinson/rice | rice-framework/krad-development-tools/src/main/java/org/kuali/rice/krad/devtools/datadictionary/URLMonitor.java | Java | apache-2.0 | 3,664 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.accumulo;
import com.facebook.presto.accumulo.conf.AccumuloConfig;
import com.facebook.presto.accumulo.conf.AccumuloTableProperties;
import com.facebook.presto.accumulo.index.ColumnCardinalityCache;
import com.facebook.presto.accumulo.index.IndexLookup;
import com.facebook.presto.accumulo.metadata.AccumuloTable;
import com.facebook.presto.accumulo.metadata.ZooKeeperMetadataManager;
import com.facebook.presto.spi.ColumnMetadata;
import com.facebook.presto.spi.ConnectorTableMetadata;
import com.facebook.presto.spi.SchemaTableName;
import com.facebook.presto.type.TypeRegistry;
import com.google.common.collect.ImmutableList;
import org.apache.accumulo.core.client.Connector;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static org.testng.Assert.assertNotNull;
public class TestAccumuloClient
{
private final AccumuloClient client;
private final ZooKeeperMetadataManager zooKeeperMetadataManager;
public TestAccumuloClient()
throws Exception
{
AccumuloConfig config = new AccumuloConfig()
.setUsername("root")
.setPassword("secret");
Connector connector = AccumuloQueryRunner.getAccumuloConnector();
config.setZooKeepers(connector.getInstance().getZooKeepers());
zooKeeperMetadataManager = new ZooKeeperMetadataManager(config, new TypeRegistry());
client = new AccumuloClient(connector, config, zooKeeperMetadataManager, new AccumuloTableManager(connector), new IndexLookup(connector, new ColumnCardinalityCache(connector, config)));
}
@Test
public void testCreateTableEmptyAccumuloColumn()
throws Exception
{
SchemaTableName tableName = new SchemaTableName("default", "test_create_table_empty_accumulo_column");
try {
List<ColumnMetadata> columns = ImmutableList.of(
new ColumnMetadata("id", BIGINT),
new ColumnMetadata("a", BIGINT),
new ColumnMetadata("b", BIGINT),
new ColumnMetadata("c", BIGINT),
new ColumnMetadata("d", BIGINT));
Map<String, Object> properties = new HashMap<>();
new AccumuloTableProperties().getTableProperties().forEach(meta -> properties.put(meta.getName(), meta.getDefaultValue()));
properties.put("external", true);
properties.put("column_mapping", "a:a:a,b::b,c:c:,d::");
client.createTable(new ConnectorTableMetadata(tableName, columns, properties));
assertNotNull(client.getTable(tableName));
}
finally {
AccumuloTable table = zooKeeperMetadataManager.getTable(tableName);
if (table != null) {
client.dropTable(table);
}
}
}
}
| svstanev/presto | presto-accumulo/src/test/java/com/facebook/presto/accumulo/TestAccumuloClient.java | Java | apache-2.0 | 3,498 |
package j_credential
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/swag"
strfmt "github.com/go-openapi/strfmt"
"koding/remoteapi/models"
)
// PostRemoteAPIJCredentialFetchUsersIDReader is a Reader for the PostRemoteAPIJCredentialFetchUsersID structure.
type PostRemoteAPIJCredentialFetchUsersIDReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *PostRemoteAPIJCredentialFetchUsersIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewPostRemoteAPIJCredentialFetchUsersIDOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
default:
return nil, runtime.NewAPIError("unknown error", response, response.Code())
}
}
// NewPostRemoteAPIJCredentialFetchUsersIDOK creates a PostRemoteAPIJCredentialFetchUsersIDOK with default headers values
func NewPostRemoteAPIJCredentialFetchUsersIDOK() *PostRemoteAPIJCredentialFetchUsersIDOK {
return &PostRemoteAPIJCredentialFetchUsersIDOK{}
}
/*PostRemoteAPIJCredentialFetchUsersIDOK handles this case with default header values.
OK
*/
type PostRemoteAPIJCredentialFetchUsersIDOK struct {
Payload PostRemoteAPIJCredentialFetchUsersIDOKBody
}
func (o *PostRemoteAPIJCredentialFetchUsersIDOK) Error() string {
return fmt.Sprintf("[POST /remote.api/JCredential.fetchUsers/{id}][%d] postRemoteApiJCredentialFetchUsersIdOK %+v", 200, o.Payload)
}
func (o *PostRemoteAPIJCredentialFetchUsersIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response payload
if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
/*PostRemoteAPIJCredentialFetchUsersIDOKBody post remote API j credential fetch users ID o k body
swagger:model PostRemoteAPIJCredentialFetchUsersIDOKBody
*/
type PostRemoteAPIJCredentialFetchUsersIDOKBody struct {
models.JCredential
models.DefaultResponse
}
// UnmarshalJSON unmarshals this object from a JSON structure
func (o *PostRemoteAPIJCredentialFetchUsersIDOKBody) UnmarshalJSON(raw []byte) error {
var postRemoteAPIJCredentialFetchUsersIDOKBodyAO0 models.JCredential
if err := swag.ReadJSON(raw, &postRemoteAPIJCredentialFetchUsersIDOKBodyAO0); err != nil {
return err
}
o.JCredential = postRemoteAPIJCredentialFetchUsersIDOKBodyAO0
var postRemoteAPIJCredentialFetchUsersIDOKBodyAO1 models.DefaultResponse
if err := swag.ReadJSON(raw, &postRemoteAPIJCredentialFetchUsersIDOKBodyAO1); err != nil {
return err
}
o.DefaultResponse = postRemoteAPIJCredentialFetchUsersIDOKBodyAO1
return nil
}
// MarshalJSON marshals this object to a JSON structure
func (o PostRemoteAPIJCredentialFetchUsersIDOKBody) MarshalJSON() ([]byte, error) {
var _parts [][]byte
postRemoteAPIJCredentialFetchUsersIDOKBodyAO0, err := swag.WriteJSON(o.JCredential)
if err != nil {
return nil, err
}
_parts = append(_parts, postRemoteAPIJCredentialFetchUsersIDOKBodyAO0)
postRemoteAPIJCredentialFetchUsersIDOKBodyAO1, err := swag.WriteJSON(o.DefaultResponse)
if err != nil {
return nil, err
}
_parts = append(_parts, postRemoteAPIJCredentialFetchUsersIDOKBodyAO1)
return swag.ConcatJSON(_parts...), nil
}
// Validate validates this post remote API j credential fetch users ID o k body
func (o *PostRemoteAPIJCredentialFetchUsersIDOKBody) Validate(formats strfmt.Registry) error {
var res []error
if err := o.JCredential.Validate(formats); err != nil {
res = append(res, err)
}
if err := o.DefaultResponse.Validate(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
| drewsetski/koding | go/src/koding/remoteapi/client/j_credential/post_remote_api_j_credential_fetch_users_id_responses.go | GO | apache-2.0 | 4,007 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.api.operators.collect;
import org.apache.flink.core.memory.DataInputViewStreamWrapper;
import org.apache.flink.core.memory.DataOutputViewStreamWrapper;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.operators.coordination.CoordinationRequest;
import org.apache.flink.runtime.operators.coordination.CoordinationRequestHandler;
import org.apache.flink.runtime.operators.coordination.CoordinationResponse;
import org.apache.flink.runtime.operators.coordination.OperatorCoordinator;
import org.apache.flink.runtime.operators.coordination.OperatorEvent;
import org.apache.flink.util.Preconditions;
import org.apache.flink.util.concurrent.ExecutorThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* {@link OperatorCoordinator} for {@link CollectSinkFunction}.
*
* <p>This coordinator only forwards requests and responses from clients and sinks and it does not
* store any results in itself.
*/
public class CollectSinkOperatorCoordinator
implements OperatorCoordinator, CoordinationRequestHandler {
private static final Logger LOG = LoggerFactory.getLogger(CollectSinkOperatorCoordinator.class);
private final int socketTimeout;
private InetSocketAddress address;
private Socket socket;
private DataInputViewStreamWrapper inStream;
private DataOutputViewStreamWrapper outStream;
private ExecutorService executorService;
public CollectSinkOperatorCoordinator(int socketTimeout) {
this.socketTimeout = socketTimeout;
}
@Override
public void start() throws Exception {
this.executorService =
Executors.newSingleThreadExecutor(
new ExecutorThreadFactory(
"collect-sink-operator-coordinator-executor-thread-pool"));
}
@Override
public void close() throws Exception {
closeConnection();
this.executorService.shutdown();
}
@Override
public void handleEventFromOperator(int subtask, OperatorEvent event) throws Exception {
Preconditions.checkArgument(
event instanceof CollectSinkAddressEvent,
"Operator event must be a CollectSinkAddressEvent");
address = ((CollectSinkAddressEvent) event).getAddress();
LOG.info("Received sink socket server address: " + address);
}
@Override
public CompletableFuture<CoordinationResponse> handleCoordinationRequest(
CoordinationRequest request) {
Preconditions.checkArgument(
request instanceof CollectCoordinationRequest,
"Coordination request must be a CollectCoordinationRequest");
CollectCoordinationRequest collectRequest = (CollectCoordinationRequest) request;
CompletableFuture<CoordinationResponse> responseFuture = new CompletableFuture<>();
if (address == null) {
completeWithEmptyResponse(collectRequest, responseFuture);
return responseFuture;
}
executorService.submit(() -> handleRequestImpl(collectRequest, responseFuture, address));
return responseFuture;
}
private void handleRequestImpl(
CollectCoordinationRequest request,
CompletableFuture<CoordinationResponse> responseFuture,
InetSocketAddress sinkAddress) {
if (sinkAddress == null) {
closeConnection();
completeWithEmptyResponse(request, responseFuture);
return;
}
try {
if (socket == null) {
socket = new Socket();
socket.setSoTimeout(socketTimeout);
socket.setKeepAlive(true);
socket.setTcpNoDelay(true);
socket.connect(sinkAddress);
inStream = new DataInputViewStreamWrapper(socket.getInputStream());
outStream = new DataOutputViewStreamWrapper(socket.getOutputStream());
LOG.info("Sink connection established");
}
// send version and offset to sink server
if (LOG.isDebugEnabled()) {
LOG.debug("Forwarding request to sink socket server");
}
request.serialize(outStream);
// fetch back serialized results
if (LOG.isDebugEnabled()) {
LOG.debug("Fetching serialized result from sink socket server");
}
responseFuture.complete(new CollectCoordinationResponse(inStream));
} catch (Exception e) {
// request failed, close current connection and send back empty results
// we catch every exception here because socket might suddenly becomes null if the sink
// fails
// and we do not want the coordinator to fail
if (LOG.isDebugEnabled()) {
// this is normal when sink restarts or job ends, so we print a debug log
LOG.debug("Collect sink coordinator encounters an exception", e);
}
closeConnection();
completeWithEmptyResponse(request, responseFuture);
}
}
private void completeWithEmptyResponse(
CollectCoordinationRequest request, CompletableFuture<CoordinationResponse> future) {
future.complete(
new CollectCoordinationResponse(
request.getVersion(),
// this lastCheckpointedOffset is OK
// because client will only expose results to the users when the
// checkpointed offset increases
-1,
Collections.emptyList()));
}
private void closeConnection() {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
LOG.warn("Failed to close sink socket server connection", e);
}
}
socket = null;
}
@Override
public void subtaskFailed(int subtask, @Nullable Throwable reason) {
// subtask failed, the socket server does not exist anymore
address = null;
}
@Override
public void subtaskReset(int subtask, long checkpointId) {
// nothing to do here, connections are re-created lazily
}
@Override
public void subtaskReady(int subtask, SubtaskGateway gateway) {
// nothing to do here, connections are re-created lazily
}
@Override
public void checkpointCoordinator(long checkpointId, CompletableFuture<byte[]> result)
throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(address);
result.complete(baos.toByteArray());
}
@Override
public void notifyCheckpointComplete(long checkpointId) {}
@Override
public void resetToCheckpoint(long checkpointId, @Nullable byte[] checkpointData)
throws Exception {
if (checkpointData == null) {
// restore before any checkpoint completed
closeConnection();
} else {
ByteArrayInputStream bais = new ByteArrayInputStream(checkpointData);
ObjectInputStream ois = new ObjectInputStream(bais);
address = (InetSocketAddress) ois.readObject();
}
}
/** Provider for {@link CollectSinkOperatorCoordinator}. */
public static class Provider implements OperatorCoordinator.Provider {
private final OperatorID operatorId;
private final int socketTimeout;
public Provider(OperatorID operatorId, int socketTimeout) {
this.operatorId = operatorId;
this.socketTimeout = socketTimeout;
}
@Override
public OperatorID getOperatorId() {
return operatorId;
}
@Override
public OperatorCoordinator create(Context context) {
// we do not send operator event so we don't need a context
return new CollectSinkOperatorCoordinator(socketTimeout);
}
}
}
| apache/flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/collect/CollectSinkOperatorCoordinator.java | Java | apache-2.0 | 9,405 |
cask :v1 => 'font-lohit-tamil-classical' do
version '2.5.3'
sha256 '325ea1496bb2ae4f77552c268190251a5155717dccda64d497da4388d17c2432'
url "https://fedorahosted.org/releases/l/o/lohit/lohit-tamil-classical-ttf-#{version}.tar.gz"
homepage 'https://fedorahosted.org/lohit/'
license :unknown
font "lohit-tamil-classical-ttf-#{version}/Lohit-Tamil-Classical.ttf"
end
| elmariofredo/homebrew-fonts | Casks/font-lohit-tamil-classical.rb | Ruby | bsd-2-clause | 376 |
class AddPlaneIdToNodes < ActiveRecord::Migration
def change
add_column :nodes, :plane_id, :integer
add_index :nodes, :plane_id
end
end
| irubi/rabel | db/migrate/20111209080432_add_plane_id_to_nodes.rb | Ruby | bsd-3-clause | 148 |
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* 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.
*/
package com.iluwatar.front.controller;
/**
*
* Command for archers.
*
*/
public class ArcherCommand implements Command {
@Override
public void process() {
new ArcherView().display();
}
}
| WeRockStar/java-design-patterns | front-controller/src/main/java/com/iluwatar/front/controller/ArcherCommand.java | Java | mit | 1,344 |
exports.x = "d";
| g0ddish/webpack | test/cases/parsing/harmony-duplicate-export/d.js | JavaScript | mit | 17 |
var test = require("tap").test
var server = require("./lib/server.js")
var common = require("./lib/common.js")
var client = common.freshClient()
var cache = require("./fixtures/underscore/cache.json")
function nop () {}
var URI = "https://npm.registry:8043/rewrite"
var STARRED = true
var USERNAME = "username"
var PASSWORD = "%1234@asdf%"
var EMAIL = "i@izs.me"
var AUTH = {
username : USERNAME,
password : PASSWORD,
email : EMAIL
}
var PARAMS = {
starred : STARRED,
auth : AUTH
}
test("star call contract", function (t) {
t.throws(function () {
client.star(undefined, PARAMS, nop)
}, "requires a URI")
t.throws(function () {
client.star([], PARAMS, nop)
}, "requires URI to be a string")
t.throws(function () {
client.star(URI, undefined, nop)
}, "requires params object")
t.throws(function () {
client.star(URI, "", nop)
}, "params must be object")
t.throws(function () {
client.star(URI, PARAMS, undefined)
}, "requires callback")
t.throws(function () {
client.star(URI, PARAMS, "callback")
}, "callback must be function")
t.throws(
function () {
var params = {
starred : STARRED
}
client.star(URI, params, nop)
},
{ name : "AssertionError", message : "must pass auth to star" },
"params must include auth"
)
t.test("token auth disallowed in star", function (t) {
var params = {
auth : {
token : "lol"
}
}
client.star(URI, params, function (err) {
t.equal(
err && err.message,
"This operation is unsupported for token-based auth",
"star doesn't support token-based auth"
)
t.end()
})
})
t.end()
})
test("star a package", function (t) {
server.expect("GET", "/underscore?write=true", function (req, res) {
t.equal(req.method, "GET")
res.json(cache)
})
server.expect("PUT", "/underscore", function (req, res) {
t.equal(req.method, "PUT")
var b = ""
req.setEncoding("utf8")
req.on("data", function (d) {
b += d
})
req.on("end", function () {
var updated = JSON.parse(b)
var already = [
"vesln", "mvolkmann", "lancehunt", "mikl", "linus", "vasc", "bat",
"dmalam", "mbrevoort", "danielr", "rsimoes", "thlorenz"
]
for (var i = 0; i < already.length; i++) {
var current = already[i]
t.ok(
updated.users[current],
current + " still likes this package"
)
}
t.ok(updated.users[USERNAME], "user is in the starred list")
res.statusCode = 201
res.json({starred:true})
})
})
var params = {
starred : STARRED,
auth : AUTH
}
client.star("http://localhost:1337/underscore", params, function (error, data) {
t.ifError(error, "no errors")
t.ok(data.starred, "was starred")
t.end()
})
})
| lwthatcher/Compass | web/node_modules/npm/node_modules/npm-registry-client/test/star.js | JavaScript | mit | 2,885 |
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* 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.
*/
package com.iluwatar.facade;
/**
*
* The Facade design pattern is often used when a system is very complex or difficult to understand
* because the system has a large number of interdependent classes or its source code is
* unavailable. This pattern hides the complexities of the larger system and provides a simpler
* interface to the client. It typically involves a single wrapper class which contains a set of
* members required by client. These members access the system on behalf of the facade client and
* hide the implementation details.
* <p>
* In this example the Facade is ({@link DwarvenGoldmineFacade}) and it provides a simpler interface
* to the goldmine subsystem.
*
*/
public class App {
/**
* Program entry point
*
* @param args command line args
*/
public static void main(String[] args) {
DwarvenGoldmineFacade facade = new DwarvenGoldmineFacade();
facade.startNewDay();
facade.digOutGold();
facade.endDay();
}
}
| DevFactory/java-design-patterns | facade/src/main/java/com/iluwatar/facade/App.java | Java | mit | 2,123 |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Graph.RBAC.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Graph;
using Microsoft.Azure.Graph.RBAC;
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Request parameters for creating a new service principal.
/// </summary>
public partial class ServicePrincipalCreateParameters
{
/// <summary>
/// Initializes a new instance of the ServicePrincipalCreateParameters
/// class.
/// </summary>
public ServicePrincipalCreateParameters()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ServicePrincipalCreateParameters
/// class.
/// </summary>
/// <param name="appId">application Id</param>
/// <param name="accountEnabled">Whether the account is enabled</param>
/// <param name="keyCredentials">A collection of KeyCredential
/// objects.</param>
/// <param name="passwordCredentials">A collection of
/// PasswordCredential objects</param>
public ServicePrincipalCreateParameters(string appId, bool accountEnabled, IList<KeyCredential> keyCredentials = default(IList<KeyCredential>), IList<PasswordCredential> passwordCredentials = default(IList<PasswordCredential>))
{
AppId = appId;
AccountEnabled = accountEnabled;
KeyCredentials = keyCredentials;
PasswordCredentials = passwordCredentials;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets application Id
/// </summary>
[JsonProperty(PropertyName = "appId")]
public string AppId { get; set; }
/// <summary>
/// Gets or sets whether the account is enabled
/// </summary>
[JsonProperty(PropertyName = "accountEnabled")]
public bool AccountEnabled { get; set; }
/// <summary>
/// Gets or sets a collection of KeyCredential objects.
/// </summary>
[JsonProperty(PropertyName = "keyCredentials")]
public IList<KeyCredential> KeyCredentials { get; set; }
/// <summary>
/// Gets or sets a collection of PasswordCredential objects
/// </summary>
[JsonProperty(PropertyName = "passwordCredentials")]
public IList<PasswordCredential> PasswordCredentials { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (AppId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "AppId");
}
}
}
}
| ScottHolden/azure-sdk-for-net | src/SDKs/Graph.RBAC/Graph.RBAC/Generated/Models/ServicePrincipalCreateParameters.cs | C# | mit | 3,231 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsLro
{
using Fixtures.Azure;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// LRORetrysOperations operations.
/// </summary>
internal partial class LRORetrysOperations : IServiceOperations<AutoRestLongRunningOperationTestService>, ILRORetrysOperations
{
/// <summary>
/// Initializes a new instance of the LRORetrysOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal LRORetrysOperations(AutoRestLongRunningOperationTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestLongRunningOperationTestService
/// </summary>
public AutoRestLongRunningOperationTestService Client { get; private set; }
/// <summary>
/// Long running put request, service returns a 500, then a 201 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Polls
/// return this value until the last poll returns a ‘200’ with
/// ProvisioningState=’Succeeded’
/// </summary>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ProductInner>> Put201CreatingSucceeded200WithHttpMessagesAsync(ProductInner product = default(ProductInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<ProductInner> _response = await BeginPut201CreatingSucceeded200WithHttpMessagesAsync(product, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Long running put request, service returns a 500, then a 200 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Poll
/// the endpoint indicated in the Azure-AsyncOperation header for operation
/// status
/// </summary>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ProductInner,LRORetrysPutAsyncRelativeRetrySucceededHeadersInner>> PutAsyncRelativeRetrySucceededWithHttpMessagesAsync(ProductInner product = default(ProductInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<ProductInner,LRORetrysPutAsyncRelativeRetrySucceededHeadersInner> _response = await BeginPutAsyncRelativeRetrySucceededWithHttpMessagesAsync(product, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request, with an entity that contains ProvisioningState=’Accepted’.
/// Polls return this value until the last poll returns a ‘200’ with
/// ProvisioningState=’Succeeded’
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ProductInner,LRORetrysDeleteProvisioning202Accepted200SucceededHeadersInner>> DeleteProvisioning202Accepted200SucceededWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse<ProductInner,LRORetrysDeleteProvisioning202Accepted200SucceededHeadersInner> _response = await BeginDeleteProvisioning202Accepted200SucceededWithHttpMessagesAsync(customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request. Polls return this value until the last poll returns a
/// ‘200’ with ProvisioningState=’Succeeded’
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationHeaderResponse<LRORetrysDelete202Retry200HeadersInner>> Delete202Retry200WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationHeaderResponse<LRORetrysDelete202Retry200HeadersInner> _response = await BeginDelete202Retry200WithHttpMessagesAsync(customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request. Poll the endpoint indicated in the Azure-AsyncOperation
/// header for operation status
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationHeaderResponse<LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner>> DeleteAsyncRelativeRetrySucceededWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationHeaderResponse<LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner> _response = await BeginDeleteAsyncRelativeRetrySucceededWithHttpMessagesAsync(customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Long running post request, service returns a 500, then a 202 to the initial
/// request, with 'Location' and 'Retry-After' headers, Polls return a 200 with
/// a response body after success
/// </summary>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationHeaderResponse<LRORetrysPost202Retry200HeadersInner>> Post202Retry200WithHttpMessagesAsync(ProductInner product = default(ProductInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationHeaderResponse<LRORetrysPost202Retry200HeadersInner> _response = await BeginPost202Retry200WithHttpMessagesAsync(product, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Long running post request, service returns a 500, then a 202 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Poll
/// the endpoint indicated in the Azure-AsyncOperation header for operation
/// status
/// </summary>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationHeaderResponse<LRORetrysPostAsyncRelativeRetrySucceededHeadersInner>> PostAsyncRelativeRetrySucceededWithHttpMessagesAsync(ProductInner product = default(ProductInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationHeaderResponse<LRORetrysPostAsyncRelativeRetrySucceededHeadersInner> _response = await BeginPostAsyncRelativeRetrySucceededWithHttpMessagesAsync(product, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Long running put request, service returns a 500, then a 201 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Polls
/// return this value until the last poll returns a ‘200’ with
/// ProvisioningState=’Succeeded’
/// </summary>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ProductInner>> BeginPut201CreatingSucceeded200WithHttpMessagesAsync(ProductInner product = default(ProductInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginPut201CreatingSucceeded200", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/put/201/creating/succeeded/200").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(product != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(product, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ProductInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ProductInner>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ProductInner>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Long running put request, service returns a 500, then a 200 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Poll
/// the endpoint indicated in the Azure-AsyncOperation header for operation
/// status
/// </summary>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ProductInner,LRORetrysPutAsyncRelativeRetrySucceededHeadersInner>> BeginPutAsyncRelativeRetrySucceededWithHttpMessagesAsync(ProductInner product = default(ProductInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginPutAsyncRelativeRetrySucceeded", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/putasync/retry/succeeded").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(product != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(product, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ProductInner,LRORetrysPutAsyncRelativeRetrySucceededHeadersInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ProductInner>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysPutAsyncRelativeRetrySucceededHeadersInner>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request, with an entity that contains ProvisioningState=’Accepted’.
/// Polls return this value until the last poll returns a ‘200’ with
/// ProvisioningState=’Succeeded’
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ProductInner,LRORetrysDeleteProvisioning202Accepted200SucceededHeadersInner>> BeginDeleteProvisioning202Accepted200SucceededWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDeleteProvisioning202Accepted200Succeeded", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/delete/provisioning/202/accepted/200/succeeded").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ProductInner,LRORetrysDeleteProvisioning202Accepted200SucceededHeadersInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ProductInner>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 202)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ProductInner>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysDeleteProvisioning202Accepted200SucceededHeadersInner>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request. Polls return this value until the last poll returns a
/// ‘200’ with ProvisioningState=’Succeeded’
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationHeaderResponse<LRORetrysDelete202Retry200HeadersInner>> BeginDelete202Retry200WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete202Retry200", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/delete/202/retry/200").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationHeaderResponse<LRORetrysDelete202Retry200HeadersInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysDelete202Retry200HeadersInner>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request. Poll the endpoint indicated in the Azure-AsyncOperation
/// header for operation status
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationHeaderResponse<LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner>> BeginDeleteAsyncRelativeRetrySucceededWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDeleteAsyncRelativeRetrySucceeded", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/deleteasync/retry/succeeded").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationHeaderResponse<LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysDeleteAsyncRelativeRetrySucceededHeadersInner>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Long running post request, service returns a 500, then a 202 to the initial
/// request, with 'Location' and 'Retry-After' headers, Polls return a 200 with
/// a response body after success
/// </summary>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationHeaderResponse<LRORetrysPost202Retry200HeadersInner>> BeginPost202Retry200WithHttpMessagesAsync(ProductInner product = default(ProductInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginPost202Retry200", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/post/202/retry/200").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(product != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(product, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationHeaderResponse<LRORetrysPost202Retry200HeadersInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysPost202Retry200HeadersInner>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Long running post request, service returns a 500, then a 202 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Poll
/// the endpoint indicated in the Azure-AsyncOperation header for operation
/// status
/// </summary>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationHeaderResponse<LRORetrysPostAsyncRelativeRetrySucceededHeadersInner>> BeginPostAsyncRelativeRetrySucceededWithHttpMessagesAsync(ProductInner product = default(ProductInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginPostAsyncRelativeRetrySucceeded", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/postasync/retry/succeeded").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(product != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(product, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationHeaderResponse<LRORetrysPostAsyncRelativeRetrySucceededHeadersInner>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysPostAsyncRelativeRetrySucceededHeadersInner>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| sergey-shandar/autorest | src/generator/AutoRest.CSharp.Azure.Fluent.Tests/Expected/AcceptanceTests/Lro/LRORetrysOperations.cs | C# | mit | 67,705 |
// Type definitions for non-npm package amap-js-api 1.4
// Project: https://lbs.amap.com/api/javascript-api/summary
// Definitions by: breeze9527 <https://github.com/breeze9527>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
/// <reference path="array-bounds.d.ts" />
/// <reference path="bounds.d.ts" />
/// <reference path="browser.d.ts" />
/// <reference path="common.d.ts" />
/// <reference path="convert-from.d.ts" />
/// <reference path="dom-util.d.ts" />
/// <reference path="event.d.ts" />
/// <reference path="geometry-util.d.ts" />
/// <reference path="lngLat.d.ts" />
/// <reference path="map.d.ts" />
/// <reference path="pixel.d.ts" />
/// <reference path="size.d.ts" />
/// <reference path="type-util.d.ts" />
/// <reference path="util.d.ts" />
/// <reference path="view2D.d.ts" />
/// <reference path="layer/building.d.ts" />
/// <reference path="layer/flexible.d.ts" />
/// <reference path="layer/labelsLayer.d.ts" />
/// <reference path="layer/layer.d.ts" />
/// <reference path="layer/layerGroup.d.ts" />
/// <reference path="layer/massMarks.d.ts" />
/// <reference path="layer/mediaLayer.d.ts" />
/// <reference path="layer/tileLayer.d.ts" />
/// <reference path="layer/wms.d.ts" />
/// <reference path="layer/wmts.d.ts" />
/// <reference path="overlay/bezierCurve.d.ts" />
/// <reference path="overlay/circle.d.ts" />
/// <reference path="overlay/circleMarker.d.ts" />
/// <reference path="overlay/contextMenu.d.ts" />
/// <reference path="overlay/ellipse.d.ts" />
/// <reference path="overlay/geoJSON.d.ts" />
/// <reference path="overlay/icon.d.ts" />
/// <reference path="overlay/infoWindow.d.ts" />
/// <reference path="overlay/labelMarker.d.ts" />
/// <reference path="overlay/marker.d.ts" />
/// <reference path="overlay/markerShape.d.ts" />
/// <reference path="overlay/overlay.d.ts" />
/// <reference path="overlay/overlayGroup.d.ts" />
/// <reference path="overlay/pathOverlay.d.ts" />
/// <reference path="overlay/polygon.d.ts" />
/// <reference path="overlay/polyline.d.ts" />
/// <reference path="overlay/rectangle.d.ts" />
/// <reference path="overlay/shapeOverlay.d.ts" />
/// <reference path="overlay/text.d.ts" />
| borisyankov/DefinitelyTyped | types/amap-js-api/index.d.ts | TypeScript | mit | 2,198 |
module.exports = {
"env": {
"node": true,
"commonjs": true,
"es6": true
},
"ecmaFeatures": {
"arrowFunctions": true,
"binaryLiterals": false,
"blockBindings": true,
"classes": false,
"defaultParams": true,
"destructuring": true,
"forOf": false,
"generators": false,
"modules": true,
"objectLiteralComputedProperties": false,
"objectLiteralDuplicateProperties": false,
"objectLiteralShorthandMethods": true,
"objectLiteralShorthandProperties": true,
"octalLiterals": false,
"regexUFlag": false,
"regexYFlag": false,
"restParams": true,
"spread": true,
"superInFunctions": true,
"templateStrings": true,
"unicodeCodePointEscapes": false,
"globalReturns": false,
"jsx": true,
"experimentalObjectRestSpread": true
},
"parser": "babel-eslint",
"rules": {
"array-bracket-spacing": [ 2, "always" ],
"arrow-body-style": [ 2, "as-needed" ],
"arrow-parens": [ 2, "as-needed" ],
"block-scoped-var": 2,
"block-spacing": [ 2, "always" ],
"brace-style": [ 2, "1tbs", {
"allowSingleLine": false
} ],
"comma-dangle": [ 2, "never" ],
"comma-spacing": [ 2, {
"after": true,
"before": false
} ],
"consistent-return": 2,
"consistent-this": [ 2, "self" ],
"constructor-super": 2,
"curly": [ 2, "all" ],
"dot-location": [ 2, "property" ],
"dot-notation": 2,
"eol-last": 2,
"indent": [ 2, 2, {
"SwitchCase": 1
} ],
"jsx-quotes": [ 2, "prefer-double" ],
"max-len": [ 2, 125, 2, {
"ignorePattern": "((^import[^;]+;$)|(^\\s*it\\())",
"ignoreUrls": true
} ],
"new-cap": 2,
"no-alert": 2,
"no-confusing-arrow": 2,
"no-caller": 2,
"no-class-assign": 2,
"no-cond-assign": [ 2, "always" ],
"no-console": 1,
"no-const-assign": 2,
"no-constant-condition": 2,
"no-control-regex": 2,
"no-debugger": 1,
"no-dupe-args": 2,
"no-dupe-class-members": 2,
"no-dupe-keys": 2,
"no-duplicate-case": 2,
"no-else-return": 2,
"no-empty": 2,
"no-empty-character-class": 2,
"no-eq-null": 2,
"no-eval": 2,
"no-ex-assign": 2,
"no-extend-native": 2,
"no-extra-bind": 2,
"no-extra-boolean-cast": 2,
"no-extra-parens": [ 2, "functions" ],
"no-extra-semi": 2,
"no-func-assign": 2,
"no-implicit-coercion": [ 2, {
"boolean": true,
"number": true,
"string": true
} ],
"no-implied-eval": 2,
"no-inner-declarations": [ 2, "both" ],
"no-invalid-regexp": 2,
"no-invalid-this": 2,
"no-irregular-whitespace": 2,
"no-lonely-if": 2,
"no-negated-condition": 2,
"no-negated-in-lhs": 2,
"no-new": 2,
"no-new-func": 2,
"no-new-object": 2,
"no-obj-calls": 2,
"no-proto": 2,
"no-redeclare": 2,
"no-regex-spaces": 2,
"no-return-assign": 2,
"no-self-compare": 2,
"no-sequences": 2,
"no-sparse-arrays": 2,
"no-this-before-super": 2,
"no-trailing-spaces": 2,
"no-undef": 2,
"no-unexpected-multiline": 2,
"no-unneeded-ternary": 2,
"no-unreachable": 2,
"no-unused-vars": [ 1, {
"args": "after-used",
"vars": "all",
"varsIgnorePattern": "React"
} ],
"no-use-before-define": 2,
"no-useless-call": 2,
"no-useless-concat": 2,
"no-var": 2,
"no-warning-comments": [ 1, {
"location": "anywhere",
"terms": [
"todo"
]
} ],
"no-with": 2,
"object-curly-spacing": [ 2, "always" ],
"object-shorthand": 2,
"one-var": [ 2, "never" ],
"prefer-arrow-callback": 2,
"prefer-const": 2,
"prefer-spread": 2,
"prefer-template": 2,
"radix": 2,
"semi": 2,
"sort-vars": [ 2, {
"ignoreCase": true
} ],
"keyword-spacing": 2,
"space-before-blocks": [ 2, "always" ],
"space-before-function-paren": [ 2, "never" ],
"space-infix-ops": [ 2, {
"int32Hint": false
} ],
"use-isnan": 2,
"valid-typeof": 2,
"vars-on-top": 2,
"yoda": [ 2, "never" ]
}
};
| dgilroy77/Car.ly | node_modules/eslint-plugin-jsx-a11y/.eslintrc.js | JavaScript | mit | 4,092 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Constraints;
class Url extends \Symfony\Component\Validator\Constraint
{
public $message = 'This value is not a valid URL';
public $protocols = array('http', 'https');
/**
* {@inheritDoc}
*/
public function getTargets()
{
return self::PROPERTY_CONSTRAINT;
}
} | radzikowski/alf | vendor/symfony/src/Symfony/Component/Validator/Constraints/Url.php | PHP | mit | 579 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.LanguageParser;
using Microsoft.Build.Tasks.Hosting;
using Microsoft.Build.Tasks.InteropUtilities;
using Microsoft.Build.Utilities;
#if (!STANDALONEBUILD)
using Microsoft.Internal.Performance;
#endif
namespace Microsoft.Build.Tasks
{
/// <summary>
/// This class defines the "Csc" XMake task, which enables building assemblies from C#
/// source files by invoking the C# compiler. This is the new Roslyn XMake task,
/// meaning that the code is compiled by using the Roslyn compiler server, rather
/// than csc.exe. The two should be functionally identical, but the compiler server
/// should be significantly faster with larger projects and have a smaller memory
/// footprint.
/// </summary>
public class Csc : ManagedCompiler
{
private bool _useHostCompilerIfAvailable = false;
#region Properties
// Please keep these alphabetized. These are the parameters specific to Csc. The
// ones shared between Vbc and Csc are defined in ManagedCompiler.cs, which is
// the base class.
public bool AllowUnsafeBlocks
{
set { Bag["AllowUnsafeBlocks"] = value; }
get { return GetBoolParameterWithDefault("AllowUnsafeBlocks", false); }
}
public string ApplicationConfiguration
{
set { Bag["ApplicationConfiguration"] = value; }
get { return (string)Bag["ApplicationConfiguration"]; }
}
public string BaseAddress
{
set { Bag["BaseAddress"] = value; }
get { return (string)Bag["BaseAddress"]; }
}
public bool CheckForOverflowUnderflow
{
set { Bag["CheckForOverflowUnderflow"] = value; }
get { return GetBoolParameterWithDefault("CheckForOverflowUnderflow", false); }
}
public string DocumentationFile
{
set { Bag["DocumentationFile"] = value; }
get { return (string)Bag["DocumentationFile"]; }
}
public string DisabledWarnings
{
set { Bag["DisabledWarnings"] = value; }
get { return (string)Bag["DisabledWarnings"]; }
}
public bool ErrorEndLocation
{
set { Bag["ErrorEndLocation"] = value; }
get { return GetBoolParameterWithDefault("ErrorEndLocation", false); }
}
public string ErrorReport
{
set { Bag["ErrorReport"] = value; }
get { return (string)Bag["ErrorReport"]; }
}
public bool GenerateFullPaths
{
set { Bag["GenerateFullPaths"] = value; }
get { return GetBoolParameterWithDefault("GenerateFullPaths", false); }
}
public string LangVersion
{
set { Bag["LangVersion"] = value; }
get { return (string)Bag["LangVersion"]; }
}
public string ModuleAssemblyName
{
set { Bag["ModuleAssemblyName"] = value; }
get { return (string)Bag["ModuleAssemblyName"]; }
}
public bool NoStandardLib
{
set { Bag["NoStandardLib"] = value; }
get { return GetBoolParameterWithDefault("NoStandardLib", false); }
}
public string PdbFile
{
set { Bag["PdbFile"] = value; }
get { return (string)Bag["PdbFile"]; }
}
/// <summary>
/// Name of the language passed to "/preferreduilang" compiler option.
/// </summary>
/// <remarks>
/// If set to null, "/preferreduilang" option is omitted, and csc.exe uses its default setting.
/// Otherwise, the value is passed to "/preferreduilang" as is.
/// </remarks>
public string PreferredUILang
{
set { Bag["PreferredUILang"] = value; }
get { return (string)Bag["PreferredUILang"]; }
}
public string VsSessionGuid
{
set { Bag["VsSessionGuid"] = value; }
get { return (string)Bag["VsSessionGuid"]; }
}
public bool UseHostCompilerIfAvailable
{
set { _useHostCompilerIfAvailable = value; }
get { return _useHostCompilerIfAvailable; }
}
public int WarningLevel
{
set { Bag["WarningLevel"] = value; }
get { return GetIntParameterWithDefault("WarningLevel", 4); }
}
public string WarningsAsErrors
{
set { Bag["WarningsAsErrors"] = value; }
get { return (string)Bag["WarningsAsErrors"]; }
}
public string WarningsNotAsErrors
{
set { Bag["WarningsNotAsErrors"] = value; }
get { return (string)Bag["WarningsNotAsErrors"]; }
}
#endregion
#region Tool Members
/// <summary>
/// Return the name of the tool to execute.
/// </summary>
override protected string ToolName
{
get
{
return "csc2.exe";
}
}
/// <summary>
/// Return the path to the tool to execute.
/// </summary>
override protected string GenerateFullPathToTool()
{
string pathToTool = ToolLocationHelper.GetPathToBuildToolsFile(ToolName, ToolLocationHelper.CurrentToolsVersion);
if (null == pathToTool)
{
pathToTool = ToolLocationHelper.GetPathToDotNetFrameworkFile(ToolName, TargetDotNetFrameworkVersion.VersionLatest);
if (null == pathToTool)
{
Log.LogErrorWithCodeFromResources("General.FrameworksFileNotFound", ToolName, ToolLocationHelper.GetDotNetFrameworkVersionFolderPrefix(TargetDotNetFrameworkVersion.VersionLatest));
}
}
return pathToTool;
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file.
/// </summary>
override protected internal void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
{
commandLine.AppendSwitchIfNotNull("/lib:", this.AdditionalLibPaths, ",");
commandLine.AppendPlusOrMinusSwitch("/unsafe", this.Bag, "AllowUnsafeBlocks");
commandLine.AppendPlusOrMinusSwitch("/checked", this.Bag, "CheckForOverflowUnderflow");
commandLine.AppendSwitchWithSplitting("/nowarn:", this.DisabledWarnings, ",", ';', ',');
commandLine.AppendWhenTrue("/fullpaths", this.Bag, "GenerateFullPaths");
commandLine.AppendSwitchIfNotNull("/langversion:", this.LangVersion);
commandLine.AppendSwitchIfNotNull("/moduleassemblyname:", this.ModuleAssemblyName);
commandLine.AppendSwitchIfNotNull("/pdb:", this.PdbFile);
commandLine.AppendPlusOrMinusSwitch("/nostdlib", this.Bag, "NoStandardLib");
commandLine.AppendSwitchIfNotNull("/platform:", this.PlatformWith32BitPreference);
commandLine.AppendSwitchIfNotNull("/errorreport:", this.ErrorReport);
commandLine.AppendSwitchWithInteger("/warn:", this.Bag, "WarningLevel");
commandLine.AppendSwitchIfNotNull("/doc:", this.DocumentationFile);
commandLine.AppendSwitchIfNotNull("/baseaddress:", this.BaseAddress);
commandLine.AppendSwitchUnquotedIfNotNull("/define:", this.GetDefineConstantsSwitch(this.DefineConstants));
commandLine.AppendSwitchIfNotNull("/win32res:", this.Win32Resource);
commandLine.AppendSwitchIfNotNull("/main:", this.MainEntryPoint);
commandLine.AppendSwitchIfNotNull("/appconfig:", this.ApplicationConfiguration);
commandLine.AppendWhenTrue("/errorendlocation", this.Bag, "ErrorEndLocation");
commandLine.AppendSwitchIfNotNull("/preferreduilang:", this.PreferredUILang);
commandLine.AppendPlusOrMinusSwitch("/highentropyva", this.Bag, "HighEntropyVA");
// If not design time build and the globalSessionGuid property was set then add a -globalsessionguid:<guid>
bool designTime = false;
if (this.HostObject != null)
{
var csHost = this.HostObject as ICscHostObject;
designTime = csHost.IsDesignTime();
}
if (!designTime)
{
if (!string.IsNullOrWhiteSpace(this.VsSessionGuid))
{
commandLine.AppendSwitchIfNotNull("/sqmsessionguid:", this.VsSessionGuid);
}
}
this.AddReferencesToCommandLine(commandLine);
base.AddResponseFileCommands(commandLine);
// This should come after the "TreatWarningsAsErrors" flag is processed (in managedcompiler.cs).
// Because if TreatWarningsAsErrors=false, then we'll have a /warnaserror- on the command-line,
// and then any specific warnings that should be treated as errors should be specified with
// /warnaserror+:<list> after the /warnaserror- switch. The order of the switches on the command-line
// does matter.
//
// Note that
// /warnaserror+
// is just shorthand for:
// /warnaserror+:<all possible warnings>
//
// Similarly,
// /warnaserror-
// is just shorthand for:
// /warnaserror-:<all possible warnings>
commandLine.AppendSwitchWithSplitting("/warnaserror+:", this.WarningsAsErrors, ",", ';', ',');
commandLine.AppendSwitchWithSplitting("/warnaserror-:", this.WarningsNotAsErrors, ",", ';', ',');
// It's a good idea for the response file to be the very last switch passed, just
// from a predictability perspective.
if (this.ResponseFiles != null)
{
foreach (ITaskItem response in this.ResponseFiles)
{
commandLine.AppendSwitchIfNotNull("@", response.ItemSpec);
}
}
}
#endregion
/// <summary>
/// The C# compiler (starting with Whidbey) supports assembly aliasing for references.
/// See spec at http://devdiv/spectool/Documents/Whidbey/VCSharp/Design%20Time/M3%20DCRs/DCR%20Assembly%20aliases.doc.
/// This method handles the necessary work of looking at the "Aliases" attribute on
/// the incoming "References" items, and making sure to generate the correct
/// command-line on csc.exe. The syntax for aliasing a reference is:
/// csc.exe /reference:Foo=System.Xml.dll
///
/// The "Aliases" attribute on the "References" items is actually a comma-separated
/// list of aliases, and if any of the aliases specified is the string "global",
/// then we add that reference to the command-line without an alias.
/// </summary>
/// <param name="commandLine"></param>
private void AddReferencesToCommandLine
(
CommandLineBuilderExtension commandLine
)
{
// If there were no references passed in, don't add any /reference: switches
// on the command-line.
if ((this.References == null) || (this.References.Length == 0))
{
return;
}
// Loop through all the references passed in. We'll be adding separate
// /reference: switches for each reference, and in some cases even multiple
// /reference: switches per reference.
foreach (ITaskItem reference in this.References)
{
// See if there was an "Alias" attribute on the reference.
string aliasString = reference.GetMetadata(ItemMetadataNames.aliases);
string switchName = "/reference:";
bool embed = MetadataConversionUtilities.TryConvertItemMetadataToBool
(
reference,
ItemMetadataNames.embedInteropTypes
);
if (embed == true)
{
switchName = "/link:";
}
if ((aliasString == null) || (aliasString.Length == 0))
{
// If there was no "Alias" attribute, just add this as a global reference.
commandLine.AppendSwitchIfNotNull(switchName, reference.ItemSpec);
}
else
{
// If there was an "Alias" attribute, it contains a comma-separated list
// of aliases to use for this reference. For each one of those aliases,
// we're going to add a separate /reference: switch to the csc.exe
// command-line
string[] aliases = aliasString.Split(',');
foreach (string alias in aliases)
{
// Trim whitespace.
string trimmedAlias = alias.Trim();
if (alias.Length == 0)
{
continue;
}
// The alias should be a valid C# identifier. Therefore it cannot
// contain comma, space, semicolon, or double-quote. Let's check for
// the existence of those characters right here, and bail immediately
// if any are present. There are a whole bunch of other characters
// that are not allowed in a C# identifier, but we'll just let csc.exe
// error out on those. The ones we're checking for here are the ones
// that could seriously interfere with the command-line parsing or could
// allow parameter injection.
if (trimmedAlias.IndexOfAny(new char[] { ',', ' ', ';', '"' }) != -1)
{
ErrorUtilities.VerifyThrowArgument
(
false,
"Csc.AssemblyAliasContainsIllegalCharacters",
reference.ItemSpec,
trimmedAlias
);
}
// The alias called "global" is special. It means that we don't
// give it an alias on the command-line.
if (String.Compare("global", trimmedAlias, StringComparison.OrdinalIgnoreCase) == 0)
{
commandLine.AppendSwitchIfNotNull(switchName, reference.ItemSpec);
}
else
{
// We have a valid (and explicit) alias for this reference. Add
// it to the command-line using the syntax:
// /reference:Foo=System.Xml.dll
commandLine.AppendSwitchAliased(switchName, trimmedAlias, reference.ItemSpec);
}
}
}
}
}
/// <summary>
/// Determines whether a particular string is a valid C# identifier. Legal
/// identifiers must start with a letter, and all the characters must be
/// letters or numbers. Underscore is considered a letter.
/// </summary>
private static bool IsLegalIdentifier
(
string identifier
)
{
// Must be non-empty.
if (identifier.Length == 0)
{
return false;
}
// First character must be a letter.
// From 2.4.2 of the C# Language Specification
// identifier-start-letter-character:
if (
!TokenChar.IsLetter(identifier[0]) &&
(identifier[0] != '_')
)
{
return false;
}
// All the other characters must be letters or numbers.
// From 2.4.2 of the C# Language Specification
// identifier-part-letter-character:
for (int i = 1; i < identifier.Length; i++)
{
char currentChar = identifier[i];
if (
!TokenChar.IsLetter(currentChar) &&
!TokenChar.IsDecimalDigit(currentChar) &&
!TokenChar.IsConnecting(currentChar) &&
!TokenChar.IsCombining(currentChar) &&
!TokenChar.IsFormatting(currentChar)
)
{
return false;
}
}
return true;
}
/// <summary>
/// Old VS projects had some pretty messed-up looking values for the
/// "DefineConstants" property. It worked fine in the IDE, because it
/// effectively munged up the string so that it ended up being valid for
/// the compiler. We do the equivalent munging here now.
///
/// Basically, we take the incoming string, and split it on comma/semicolon/space.
/// Then we look at the resulting list of strings, and remove any that are
/// illegal identifiers, and pass the remaining ones through to the compiler.
///
/// Note that CSharp does support assigning a value to the constants ... in
/// other words, a constant is either defined or not defined ... it can't have
/// an actual value.
/// </summary>
internal string GetDefineConstantsSwitch
(
string originalDefineConstants
)
{
if (originalDefineConstants == null)
{
return null;
}
StringBuilder finalDefineConstants = new StringBuilder();
// Split the incoming string on comma/semicolon/space.
string[] allIdentifiers = originalDefineConstants.Split(new char[] { ',', ';', ' ' });
// Loop through all the parts, and for the ones that are legal C# identifiers,
// add them to the outgoing string.
foreach (string singleIdentifier in allIdentifiers)
{
if (Csc.IsLegalIdentifier(singleIdentifier))
{
// Separate them with a semicolon if there's something already in
// the outgoing string.
if (finalDefineConstants.Length > 0)
{
finalDefineConstants.Append(";");
}
finalDefineConstants.Append(singleIdentifier);
}
else if (singleIdentifier.Length > 0)
{
Log.LogWarningWithCodeFromResources("Csc.InvalidParameterWarning", "/define:", singleIdentifier);
}
}
if (finalDefineConstants.Length > 0)
{
return finalDefineConstants.ToString();
}
else
{
// We wouldn't want to pass in an empty /define: switch on the csc.exe command-line.
return null;
}
}
/// <summary>
/// This method will initialize the host compiler object with all the switches,
/// parameters, resources, references, sources, etc.
///
/// It returns true if everything went according to plan. It returns false if the
/// host compiler had a problem with one of the parameters that was passed in.
///
/// This method also sets the "this.HostCompilerSupportsAllParameters" property
/// accordingly.
///
/// Example:
/// If we attempted to pass in WarningLevel="9876", then this method would
/// set HostCompilerSupportsAllParameters=true, but it would give a
/// return value of "false". This is because the host compiler fully supports
/// the WarningLevel parameter, but 9876 happens to be an illegal value.
///
/// Example:
/// If we attempted to pass in NoConfig=false, then this method would set
/// HostCompilerSupportsAllParameters=false, because while this is a legal
/// thing for csc.exe, the IDE compiler cannot support it. In this situation
/// the return value will also be false.
/// </summary>
private bool InitializeHostCompiler
(
// NOTE: For compat reasons this must remain ICscHostObject
// we can dynamically test for smarter interfaces later..
ICscHostObject cscHostObject
)
{
bool success;
this.HostCompilerSupportsAllParameters = this.UseHostCompilerIfAvailable;
string param = "Unknown";
try
{
// Need to set these separately, because they don't require a CommitChanges to the C# compiler in the IDE.
param = "LinkResources"; this.CheckHostObjectSupport(param, cscHostObject.SetLinkResources(this.LinkResources));
param = "References"; this.CheckHostObjectSupport(param, cscHostObject.SetReferences(this.References));
param = "Resources"; this.CheckHostObjectSupport(param, cscHostObject.SetResources(this.Resources));
param = "Sources"; this.CheckHostObjectSupport(param, cscHostObject.SetSources(this.Sources));
// For host objects which support it, pass the list of analyzers.
IAnalyzerHostObject analyzerHostObject = cscHostObject as IAnalyzerHostObject;
if (analyzerHostObject != null)
{
param = "Analyzers"; this.CheckHostObjectSupport(param, analyzerHostObject.SetAnalyzers(this.Analyzers));
}
}
catch (Exception e)
{
if (ExceptionHandling.IsCriticalException(e))
{
throw;
}
if (this.HostCompilerSupportsAllParameters)
{
// If the host compiler doesn't support everything we need, we're going to end up
// shelling out to the command-line compiler anyway. That means the command-line
// compiler will log the error. So here, we only log the error if we would've
// tried to use the host compiler.
Log.LogErrorWithCodeFromResources("General.CouldNotSetHostObjectParameter", param, e.Message);
}
return false;
}
try
{
param = "BeginInitialization";
cscHostObject.BeginInitialization();
param = "AdditionalLibPaths"; this.CheckHostObjectSupport(param, cscHostObject.SetAdditionalLibPaths(this.AdditionalLibPaths));
param = "AddModules"; this.CheckHostObjectSupport(param, cscHostObject.SetAddModules(this.AddModules));
param = "AllowUnsafeBlocks"; this.CheckHostObjectSupport(param, cscHostObject.SetAllowUnsafeBlocks(this.AllowUnsafeBlocks));
param = "BaseAddress"; this.CheckHostObjectSupport(param, cscHostObject.SetBaseAddress(this.BaseAddress));
param = "CheckForOverflowUnderflow"; this.CheckHostObjectSupport(param, cscHostObject.SetCheckForOverflowUnderflow(this.CheckForOverflowUnderflow));
param = "CodePage"; this.CheckHostObjectSupport(param, cscHostObject.SetCodePage(this.CodePage));
// These two -- EmitDebugInformation and DebugType -- must go together, with DebugType
// getting set last, because it is more specific.
param = "EmitDebugInformation"; this.CheckHostObjectSupport(param, cscHostObject.SetEmitDebugInformation(this.EmitDebugInformation));
param = "DebugType"; this.CheckHostObjectSupport(param, cscHostObject.SetDebugType(this.DebugType));
param = "DefineConstants"; this.CheckHostObjectSupport(param, cscHostObject.SetDefineConstants(this.GetDefineConstantsSwitch(this.DefineConstants)));
param = "DelaySign"; this.CheckHostObjectSupport(param, cscHostObject.SetDelaySign((this.Bag["DelaySign"] != null), this.DelaySign));
param = "DisabledWarnings"; this.CheckHostObjectSupport(param, cscHostObject.SetDisabledWarnings(this.DisabledWarnings));
param = "DocumentationFile"; this.CheckHostObjectSupport(param, cscHostObject.SetDocumentationFile(this.DocumentationFile));
param = "ErrorReport"; this.CheckHostObjectSupport(param, cscHostObject.SetErrorReport(this.ErrorReport));
param = "FileAlignment"; this.CheckHostObjectSupport(param, cscHostObject.SetFileAlignment(this.FileAlignment));
param = "GenerateFullPaths"; this.CheckHostObjectSupport(param, cscHostObject.SetGenerateFullPaths(this.GenerateFullPaths));
param = "KeyContainer"; this.CheckHostObjectSupport(param, cscHostObject.SetKeyContainer(this.KeyContainer));
param = "KeyFile"; this.CheckHostObjectSupport(param, cscHostObject.SetKeyFile(this.KeyFile));
param = "LangVersion"; this.CheckHostObjectSupport(param, cscHostObject.SetLangVersion(this.LangVersion));
param = "MainEntryPoint"; this.CheckHostObjectSupport(param, cscHostObject.SetMainEntryPoint(this.TargetType, this.MainEntryPoint));
param = "ModuleAssemblyName"; this.CheckHostObjectSupport(param, cscHostObject.SetModuleAssemblyName(this.ModuleAssemblyName));
param = "NoConfig"; this.CheckHostObjectSupport(param, cscHostObject.SetNoConfig(this.NoConfig));
param = "NoStandardLib"; this.CheckHostObjectSupport(param, cscHostObject.SetNoStandardLib(this.NoStandardLib));
param = "Optimize"; this.CheckHostObjectSupport(param, cscHostObject.SetOptimize(this.Optimize));
param = "OutputAssembly"; this.CheckHostObjectSupport(param, cscHostObject.SetOutputAssembly(this.OutputAssembly.ItemSpec));
param = "PdbFile"; this.CheckHostObjectSupport(param, cscHostObject.SetPdbFile(this.PdbFile));
// For host objects which support it, set platform with 32BitPreference, HighEntropyVA, and SubsystemVersion
ICscHostObject4 cscHostObject4 = cscHostObject as ICscHostObject4;
if (cscHostObject4 != null)
{
param = "PlatformWith32BitPreference"; this.CheckHostObjectSupport(param, cscHostObject4.SetPlatformWith32BitPreference(this.PlatformWith32BitPreference));
param = "HighEntropyVA"; this.CheckHostObjectSupport(param, cscHostObject4.SetHighEntropyVA(this.HighEntropyVA));
param = "SubsystemVersion"; this.CheckHostObjectSupport(param, cscHostObject4.SetSubsystemVersion(this.SubsystemVersion));
}
else
{
param = "Platform"; this.CheckHostObjectSupport(param, cscHostObject.SetPlatform(this.Platform));
}
// For host objects which support it, set the analyzer ruleset and additional files.
IAnalyzerHostObject analyzerHostObject = cscHostObject as IAnalyzerHostObject;
if (analyzerHostObject != null)
{
param = "CodeAnalysisRuleSet"; this.CheckHostObjectSupport(param, analyzerHostObject.SetRuleSet(this.CodeAnalysisRuleSet));
param = "AdditionalFiles"; this.CheckHostObjectSupport(param, analyzerHostObject.SetAdditionalFiles(this.AdditionalFiles));
}
param = "ResponseFiles"; this.CheckHostObjectSupport(param, cscHostObject.SetResponseFiles(this.ResponseFiles));
param = "TargetType"; this.CheckHostObjectSupport(param, cscHostObject.SetTargetType(this.TargetType));
param = "TreatWarningsAsErrors"; this.CheckHostObjectSupport(param, cscHostObject.SetTreatWarningsAsErrors(this.TreatWarningsAsErrors));
param = "WarningLevel"; this.CheckHostObjectSupport(param, cscHostObject.SetWarningLevel(this.WarningLevel));
// This must come after TreatWarningsAsErrors.
param = "WarningsAsErrors"; this.CheckHostObjectSupport(param, cscHostObject.SetWarningsAsErrors(this.WarningsAsErrors));
// This must come after TreatWarningsAsErrors.
param = "WarningsNotAsErrors"; this.CheckHostObjectSupport(param, cscHostObject.SetWarningsNotAsErrors(this.WarningsNotAsErrors));
param = "Win32Icon"; this.CheckHostObjectSupport(param, cscHostObject.SetWin32Icon(this.Win32Icon));
// In order to maintain compatibility with previous host compilers, we must
// light-up for ICscHostObject2/ICscHostObject3
if (cscHostObject is ICscHostObject2)
{
ICscHostObject2 cscHostObject2 = (ICscHostObject2)cscHostObject;
param = "Win32Manifest"; this.CheckHostObjectSupport(param, cscHostObject2.SetWin32Manifest(this.GetWin32ManifestSwitch(this.NoWin32Manifest, this.Win32Manifest)));
}
else
{
// If we have been given a property that the host compiler doesn't support
// then we need to state that we are falling back to the command line compiler
if (!String.IsNullOrEmpty(Win32Manifest))
{
this.CheckHostObjectSupport("Win32Manifest", false);
}
}
// This must come after Win32Manifest
param = "Win32Resource"; this.CheckHostObjectSupport(param, cscHostObject.SetWin32Resource(this.Win32Resource));
if (cscHostObject is ICscHostObject3)
{
ICscHostObject3 cscHostObject3 = (ICscHostObject3)cscHostObject;
param = "ApplicationConfiguration"; this.CheckHostObjectSupport(param, cscHostObject3.SetApplicationConfiguration(this.ApplicationConfiguration));
}
else
{
// If we have been given a property that the host compiler doesn't support
// then we need to state that we are falling back to the command line compiler
if (!String.IsNullOrEmpty(ApplicationConfiguration))
{
this.CheckHostObjectSupport("ApplicationConfiguration", false);
}
}
// If we have been given a property value that the host compiler doesn't support
// then we need to state that we are falling back to the command line compiler.
// Null is supported because it means that option should be omitted, and compiler default used - obviously always valid.
// Explicitly specified name of current locale is also supported, since it is effectively a no-op.
// Other options are not supported since in-proc compiler always uses current locale.
if (!String.IsNullOrEmpty(PreferredUILang) && !String.Equals(PreferredUILang, System.Globalization.CultureInfo.CurrentUICulture.Name, StringComparison.OrdinalIgnoreCase))
{
this.CheckHostObjectSupport("PreferredUILang", false);
}
}
catch (Exception e)
{
if (ExceptionHandling.IsCriticalException(e))
{
throw;
}
if (this.HostCompilerSupportsAllParameters)
{
// If the host compiler doesn't support everything we need, we're going to end up
// shelling out to the command-line compiler anyway. That means the command-line
// compiler will log the error. So here, we only log the error if we would've
// tried to use the host compiler.
Log.LogErrorWithCodeFromResources("General.CouldNotSetHostObjectParameter", param, e.Message);
}
return false;
}
finally
{
int errorCode;
string errorMessage;
success = cscHostObject.EndInitialization(out errorMessage, out errorCode);
if (this.HostCompilerSupportsAllParameters)
{
// If the host compiler doesn't support everything we need, we're going to end up
// shelling out to the command-line compiler anyway. That means the command-line
// compiler will log the error. So here, we only log the error if we would've
// tried to use the host compiler.
// If EndInitialization returns false, then there was an error. If EndInitialization was
// successful, but there is a valid 'errorMessage,' interpret it as a warning.
if (!success)
{
Log.LogError(null, "CS" + errorCode.ToString("D4", CultureInfo.InvariantCulture), null, null, 0, 0, 0, 0, errorMessage);
}
else if (errorMessage != null && errorMessage.Length > 0)
{
Log.LogWarning(null, "CS" + errorCode.ToString("D4", CultureInfo.InvariantCulture), null, null, 0, 0, 0, 0, errorMessage);
}
}
}
return (success);
}
/// <summary>
/// This method will get called during Execute() if a host object has been passed into the Csc
/// task. Returns one of the following values to indicate what the next action should be:
/// UseHostObjectToExecute Host compiler exists and was initialized.
/// UseAlternateToolToExecute Host compiler doesn't exist or was not appropriate.
/// NoActionReturnSuccess Host compiler was already up-to-date, and we're done.
/// NoActionReturnFailure Bad parameters were passed into the task.
/// </summary>
override protected HostObjectInitializationStatus InitializeHostObject()
{
if (this.HostObject != null)
{
// When the host object was passed into the task, it was passed in as a generic
// "Object" (because ITask interface obviously can't have any Csc-specific stuff
// in it, and each task is going to want to communicate with its host in a unique
// way). Now we cast it to the specific type that the Csc task expects. If the
// host object does not match this type, the host passed in an invalid host object
// to Csc, and we error out.
// NOTE: For compat reasons this must remain ICscHostObject
// we can dynamically test for smarter interfaces later..
using (RCWForCurrentContext<ICscHostObject> hostObject = new RCWForCurrentContext<ICscHostObject>(this.HostObject as ICscHostObject))
{
ICscHostObject cscHostObject = hostObject.RCW;
if (cscHostObject != null)
{
bool hostObjectSuccessfullyInitialized = InitializeHostCompiler(cscHostObject);
// If we're currently only in design-time (as opposed to build-time),
// then we're done. We've initialized the host compiler as best we
// can, and we certainly don't want to actually do the final compile.
// So return true, saying we're done and successful.
if (cscHostObject.IsDesignTime())
{
// If we are design-time then we do not want to continue the build at
// this time.
return hostObjectSuccessfullyInitialized ?
HostObjectInitializationStatus.NoActionReturnSuccess :
HostObjectInitializationStatus.NoActionReturnFailure;
}
if (!this.HostCompilerSupportsAllParameters || UseAlternateCommandLineToolToExecute())
{
// Since the host compiler has refused to take on the responsibility for this compilation,
// we're about to shell out to the command-line compiler to handle it. If some of the
// references don't exist on disk, we know the command-line compiler will fail, so save
// the trouble, and just throw a consistent error ourselves. This allows us to give
// more information than the compiler would, and also make things consistent across
// Vbc / Csc / etc.
// This suite behaves differently in localized builds than on English builds because
// VBC.EXE doesn't localize the word "error" when they emit errors and so we can't scan for it.
if (!CheckAllReferencesExistOnDisk())
{
return HostObjectInitializationStatus.NoActionReturnFailure;
}
// The host compiler doesn't support some of the switches/parameters
// being passed to it. Therefore, we resort to using the command-line compiler
// in this case.
UsedCommandLineTool = true;
return HostObjectInitializationStatus.UseAlternateToolToExecute;
}
// Ok, by now we validated that the host object supports the necessary switches
// and parameters. Last thing to check is whether the host object is up to date,
// and in that case, we will inform the caller that no further action is necessary.
if (hostObjectSuccessfullyInitialized)
{
return cscHostObject.IsUpToDate() ?
HostObjectInitializationStatus.NoActionReturnSuccess :
HostObjectInitializationStatus.UseHostObjectToExecute;
}
else
{
return HostObjectInitializationStatus.NoActionReturnFailure;
}
}
else
{
Log.LogErrorWithCodeFromResources("General.IncorrectHostObject", "Csc", "ICscHostObject");
}
}
}
// No appropriate host object was found.
UsedCommandLineTool = true;
return HostObjectInitializationStatus.UseAlternateToolToExecute;
}
/// <summary>
/// This method will get called during Execute() if a host object has been passed into the Csc
/// task. Returns true if the compilation succeeded, otherwise false.
/// </summary>
override protected bool CallHostObjectToExecute()
{
Debug.Assert(this.HostObject != null, "We should not be here if the host object has not been set.");
ICscHostObject cscHostObject = this.HostObject as ICscHostObject;
Debug.Assert(cscHostObject != null, "Wrong kind of host object passed in!");
try
{
#if (!STANDALONEBUILD)
CodeMarkers.Instance.CodeMarker(CodeMarkerEvent.perfMSBuildHostCompileBegin);
#endif
return cscHostObject.Compile();
}
finally
{
#if (!STANDALONEBUILD)
CodeMarkers.Instance.CodeMarker(CodeMarkerEvent.perfMSBuildHostCompileEnd);
#endif
}
}
}
}
| MetSystem/msbuild | src/XMakeTasks/Csc.cs | C# | mit | 41,306 |
<?php
/**
* Plugins administration panel.
*
* @package WordPress
* @subpackage Administration
*/
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! current_user_can( 'activate_plugins' ) ) {
wp_die( __( 'Sorry, you are not allowed to manage plugins for this site.' ) );
}
$wp_list_table = _get_list_table( 'WP_Plugins_List_Table' );
$pagenum = $wp_list_table->get_pagenum();
$action = $wp_list_table->current_action();
$plugin = isset( $_REQUEST['plugin'] ) ? wp_unslash( $_REQUEST['plugin'] ) : '';
$s = isset( $_REQUEST['s'] ) ? urlencode( wp_unslash( $_REQUEST['s'] ) ) : '';
// Clean up request URI from temporary args for screen options/paging uri's to work as expected.
$_SERVER['REQUEST_URI'] = remove_query_arg( array( 'error', 'deleted', 'activate', 'activate-multi', 'deactivate', 'deactivate-multi', '_error_nonce' ), $_SERVER['REQUEST_URI'] );
wp_enqueue_script( 'updates' );
if ( $action ) {
switch ( $action ) {
case 'activate':
if ( ! current_user_can( 'activate_plugin', $plugin ) ) {
wp_die( __( 'Sorry, you are not allowed to activate this plugin.' ) );
}
if ( is_multisite() && ! is_network_admin() && is_network_only_plugin( $plugin ) ) {
wp_redirect( self_admin_url( "plugins.php?plugin_status=$status&paged=$page&s=$s" ) );
exit;
}
check_admin_referer( 'activate-plugin_' . $plugin );
$result = activate_plugin( $plugin, self_admin_url( 'plugins.php?error=true&plugin=' . urlencode( $plugin ) ), is_network_admin() );
if ( is_wp_error( $result ) ) {
if ( 'unexpected_output' == $result->get_error_code() ) {
$redirect = self_admin_url( 'plugins.php?error=true&charsout=' . strlen( $result->get_error_data() ) . '&plugin=' . urlencode( $plugin ) . "&plugin_status=$status&paged=$page&s=$s" );
wp_redirect( add_query_arg( '_error_nonce', wp_create_nonce( 'plugin-activation-error_' . $plugin ), $redirect ) );
exit;
} else {
wp_die( $result );
}
}
if ( ! is_network_admin() ) {
$recent = (array) get_option( 'recently_activated' );
unset( $recent[ $plugin ] );
update_option( 'recently_activated', $recent );
} else {
$recent = (array) get_site_option( 'recently_activated' );
unset( $recent[ $plugin ] );
update_site_option( 'recently_activated', $recent );
}
if ( isset( $_GET['from'] ) && 'import' == $_GET['from'] ) {
wp_redirect( self_admin_url( 'import.php?import=' . str_replace( '-importer', '', dirname( $plugin ) ) ) ); // overrides the ?error=true one above and redirects to the Imports page, stripping the -importer suffix
} elseif ( isset( $_GET['from'] ) && 'press-this' == $_GET['from'] ) {
wp_redirect( self_admin_url( 'press-this.php' ) );
} else {
wp_redirect( self_admin_url( "plugins.php?activate=true&plugin_status=$status&paged=$page&s=$s" ) ); // overrides the ?error=true one above
}
exit;
case 'activate-selected':
if ( ! current_user_can( 'activate_plugins' ) ) {
wp_die( __( 'Sorry, you are not allowed to activate plugins for this site.' ) );
}
check_admin_referer( 'bulk-plugins' );
$plugins = isset( $_POST['checked'] ) ? (array) wp_unslash( $_POST['checked'] ) : array();
if ( is_network_admin() ) {
foreach ( $plugins as $i => $plugin ) {
// Only activate plugins which are not already network activated.
if ( is_plugin_active_for_network( $plugin ) ) {
unset( $plugins[ $i ] );
}
}
} else {
foreach ( $plugins as $i => $plugin ) {
// Only activate plugins which are not already active and are not network-only when on Multisite.
if ( is_plugin_active( $plugin ) || ( is_multisite() && is_network_only_plugin( $plugin ) ) ) {
unset( $plugins[ $i ] );
}
// Only activate plugins which the user can activate.
if ( ! current_user_can( 'activate_plugin', $plugin ) ) {
unset( $plugins[ $i ] );
}
}
}
if ( empty( $plugins ) ) {
wp_redirect( self_admin_url( "plugins.php?plugin_status=$status&paged=$page&s=$s" ) );
exit;
}
activate_plugins( $plugins, self_admin_url( 'plugins.php?error=true' ), is_network_admin() );
if ( ! is_network_admin() ) {
$recent = (array) get_option( 'recently_activated' );
} else {
$recent = (array) get_site_option( 'recently_activated' );
}
foreach ( $plugins as $plugin ) {
unset( $recent[ $plugin ] );
}
if ( ! is_network_admin() ) {
update_option( 'recently_activated', $recent );
} else {
update_site_option( 'recently_activated', $recent );
}
wp_redirect( self_admin_url( "plugins.php?activate-multi=true&plugin_status=$status&paged=$page&s=$s" ) );
exit;
case 'update-selected':
check_admin_referer( 'bulk-plugins' );
if ( isset( $_GET['plugins'] ) ) {
$plugins = explode( ',', wp_unslash( $_GET['plugins'] ) );
} elseif ( isset( $_POST['checked'] ) ) {
$plugins = (array) wp_unslash( $_POST['checked'] );
} else {
$plugins = array();
}
$title = __( 'Update Plugins' );
$parent_file = 'plugins.php';
wp_enqueue_script( 'updates' );
require_once( ABSPATH . 'wp-admin/admin-header.php' );
echo '<div class="wrap">';
echo '<h1>' . esc_html( $title ) . '</h1>';
$url = self_admin_url( 'update.php?action=update-selected&plugins=' . urlencode( join( ',', $plugins ) ) );
$url = wp_nonce_url( $url, 'bulk-update-plugins' );
echo "<iframe src='$url' style='width: 100%; height:100%; min-height:850px;'></iframe>";
echo '</div>';
require_once( ABSPATH . 'wp-admin/admin-footer.php' );
exit;
case 'error_scrape':
if ( ! current_user_can( 'activate_plugin', $plugin ) ) {
wp_die( __( 'Sorry, you are not allowed to activate this plugin.' ) );
}
check_admin_referer( 'plugin-activation-error_' . $plugin );
$valid = validate_plugin( $plugin );
if ( is_wp_error( $valid ) ) {
wp_die( $valid );
}
if ( ! WP_DEBUG ) {
error_reporting( E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR );
}
ini_set( 'display_errors', true ); //Ensure that Fatal errors are displayed.
// Go back to "sandbox" scope so we get the same errors as before
plugin_sandbox_scrape( $plugin );
/** This action is documented in wp-admin/includes/plugin.php */
do_action( "activate_{$plugin}" );
exit;
case 'deactivate':
if ( ! current_user_can( 'deactivate_plugin', $plugin ) ) {
wp_die( __( 'Sorry, you are not allowed to deactivate this plugin.' ) );
}
check_admin_referer( 'deactivate-plugin_' . $plugin );
if ( ! is_network_admin() && is_plugin_active_for_network( $plugin ) ) {
wp_redirect( self_admin_url( "plugins.php?plugin_status=$status&paged=$page&s=$s" ) );
exit;
}
deactivate_plugins( $plugin, false, is_network_admin() );
if ( ! is_network_admin() ) {
update_option( 'recently_activated', array( $plugin => time() ) + (array) get_option( 'recently_activated' ) );
} else {
update_site_option( 'recently_activated', array( $plugin => time() ) + (array) get_site_option( 'recently_activated' ) );
}
if ( headers_sent() ) {
echo "<meta http-equiv='refresh' content='" . esc_attr( "0;url=plugins.php?deactivate=true&plugin_status=$status&paged=$page&s=$s" ) . "' />";
} else {
wp_redirect( self_admin_url( "plugins.php?deactivate=true&plugin_status=$status&paged=$page&s=$s" ) );
}
exit;
case 'deactivate-selected':
if ( ! current_user_can( 'deactivate_plugins' ) ) {
wp_die( __( 'Sorry, you are not allowed to deactivate plugins for this site.' ) );
}
check_admin_referer( 'bulk-plugins' );
$plugins = isset( $_POST['checked'] ) ? (array) wp_unslash( $_POST['checked'] ) : array();
// Do not deactivate plugins which are already deactivated.
if ( is_network_admin() ) {
$plugins = array_filter( $plugins, 'is_plugin_active_for_network' );
} else {
$plugins = array_filter( $plugins, 'is_plugin_active' );
$plugins = array_diff( $plugins, array_filter( $plugins, 'is_plugin_active_for_network' ) );
foreach ( $plugins as $i => $plugin ) {
// Only deactivate plugins which the user can deactivate.
if ( ! current_user_can( 'deactivate_plugin', $plugin ) ) {
unset( $plugins[ $i ] );
}
}
}
if ( empty( $plugins ) ) {
wp_redirect( self_admin_url( "plugins.php?plugin_status=$status&paged=$page&s=$s" ) );
exit;
}
deactivate_plugins( $plugins, false, is_network_admin() );
$deactivated = array();
foreach ( $plugins as $plugin ) {
$deactivated[ $plugin ] = time();
}
if ( ! is_network_admin() ) {
update_option( 'recently_activated', $deactivated + (array) get_option( 'recently_activated' ) );
} else {
update_site_option( 'recently_activated', $deactivated + (array) get_site_option( 'recently_activated' ) );
}
wp_redirect( self_admin_url( "plugins.php?deactivate-multi=true&plugin_status=$status&paged=$page&s=$s" ) );
exit;
case 'delete-selected':
if ( ! current_user_can( 'delete_plugins' ) ) {
wp_die( __( 'Sorry, you are not allowed to delete plugins for this site.' ) );
}
check_admin_referer( 'bulk-plugins' );
//$_POST = from the plugin form; $_GET = from the FTP details screen.
$plugins = isset( $_REQUEST['checked'] ) ? (array) wp_unslash( $_REQUEST['checked'] ) : array();
if ( empty( $plugins ) ) {
wp_redirect( self_admin_url( "plugins.php?plugin_status=$status&paged=$page&s=$s" ) );
exit;
}
$plugins = array_filter( $plugins, 'is_plugin_inactive' ); // Do not allow to delete Activated plugins.
if ( empty( $plugins ) ) {
wp_redirect( self_admin_url( "plugins.php?error=true&main=true&plugin_status=$status&paged=$page&s=$s" ) );
exit;
}
// Bail on all if any paths are invalid.
// validate_file() returns truthy for invalid files
$invalid_plugin_files = array_filter( $plugins, 'validate_file' );
if ( $invalid_plugin_files ) {
wp_redirect( self_admin_url( "plugins.php?plugin_status=$status&paged=$page&s=$s" ) );
exit;
}
include( ABSPATH . 'wp-admin/update.php' );
$parent_file = 'plugins.php';
if ( ! isset( $_REQUEST['verify-delete'] ) ) {
wp_enqueue_script( 'jquery' );
require_once( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap">
<?php
$plugin_info = array();
$have_non_network_plugins = false;
foreach ( (array) $plugins as $plugin ) {
$plugin_slug = dirname( $plugin );
if ( '.' == $plugin_slug ) {
$data = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin );
if ( $data ) {
$plugin_info[ $plugin ] = $data;
$plugin_info[ $plugin ]['is_uninstallable'] = is_uninstallable_plugin( $plugin );
if ( ! $plugin_info[ $plugin ]['Network'] ) {
$have_non_network_plugins = true;
}
}
} else {
// Get plugins list from that folder.
$folder_plugins = get_plugins( '/' . $plugin_slug );
if ( $folder_plugins ) {
foreach ( $folder_plugins as $plugin_file => $data ) {
$plugin_info[ $plugin_file ] = _get_plugin_data_markup_translate( $plugin_file, $data );
$plugin_info[ $plugin_file ]['is_uninstallable'] = is_uninstallable_plugin( $plugin );
if ( ! $plugin_info[ $plugin_file ]['Network'] ) {
$have_non_network_plugins = true;
}
}
}
}
}
$plugins_to_delete = count( $plugin_info );
?>
<?php if ( 1 == $plugins_to_delete ) : ?>
<h1><?php _e( 'Delete Plugin' ); ?></h1>
<?php if ( $have_non_network_plugins && is_network_admin() ) : ?>
<div class="error"><p><strong><?php _e( 'Caution:' ); ?></strong> <?php _e( 'This plugin may be active on other sites in the network.' ); ?></p></div>
<?php endif; ?>
<p><?php _e( 'You are about to remove the following plugin:' ); ?></p>
<?php else : ?>
<h1><?php _e( 'Delete Plugins' ); ?></h1>
<?php if ( $have_non_network_plugins && is_network_admin() ) : ?>
<div class="error"><p><strong><?php _e( 'Caution:' ); ?></strong> <?php _e( 'These plugins may be active on other sites in the network.' ); ?></p></div>
<?php endif; ?>
<p><?php _e( 'You are about to remove the following plugins:' ); ?></p>
<?php endif; ?>
<ul class="ul-disc">
<?php
$data_to_delete = false;
foreach ( $plugin_info as $plugin ) {
if ( $plugin['is_uninstallable'] ) {
/* translators: 1: Plugin name, 2: Plugin author. */
echo '<li>', sprintf( __( '%1$s by %2$s (will also <strong>delete its data</strong>)' ), '<strong>' . $plugin['Name'] . '</strong>', '<em>' . $plugin['AuthorName'] . '</em>' ), '</li>';
$data_to_delete = true;
} else {
/* translators: 1: Plugin name, 2: Plugin author. */
echo '<li>', sprintf( _x( '%1$s by %2$s', 'plugin' ), '<strong>' . $plugin['Name'] . '</strong>', '<em>' . $plugin['AuthorName'] ) . '</em>', '</li>';
}
}
?>
</ul>
<p>
<?php
if ( $data_to_delete ) {
_e( 'Are you sure you want to delete these files and data?' );
} else {
_e( 'Are you sure you want to delete these files?' );
}
?>
</p>
<form method="post" action="<?php echo esc_url( $_SERVER['REQUEST_URI'] ); ?>" style="display:inline;">
<input type="hidden" name="verify-delete" value="1" />
<input type="hidden" name="action" value="delete-selected" />
<?php
foreach ( (array) $plugins as $plugin ) {
echo '<input type="hidden" name="checked[]" value="' . esc_attr( $plugin ) . '" />';
}
?>
<?php wp_nonce_field( 'bulk-plugins' ); ?>
<?php submit_button( $data_to_delete ? __( 'Yes, delete these files and data' ) : __( 'Yes, delete these files' ), '', 'submit', false ); ?>
</form>
<?php
$referer = wp_get_referer();
?>
<form method="post" action="<?php echo $referer ? esc_url( $referer ) : ''; ?>" style="display:inline;">
<?php submit_button( __( 'No, return me to the plugin list' ), '', 'submit', false ); ?>
</form>
</div>
<?php
require_once( ABSPATH . 'wp-admin/admin-footer.php' );
exit;
} else {
$plugins_to_delete = count( $plugins );
} // endif verify-delete
$delete_result = delete_plugins( $plugins );
set_transient( 'plugins_delete_result_' . $user_ID, $delete_result ); //Store the result in a cache rather than a URL param due to object type & length
wp_redirect( self_admin_url( "plugins.php?deleted=$plugins_to_delete&plugin_status=$status&paged=$page&s=$s" ) );
exit;
case 'clear-recent-list':
if ( ! is_network_admin() ) {
update_option( 'recently_activated', array() );
} else {
update_site_option( 'recently_activated', array() );
}
break;
case 'resume':
if ( is_multisite() ) {
return;
}
if ( ! current_user_can( 'resume_plugin', $plugin ) ) {
wp_die( __( 'Sorry, you are not allowed to resume this plugin.' ) );
}
check_admin_referer( 'resume-plugin_' . $plugin );
$result = resume_plugin( $plugin, self_admin_url( "plugins.php?error=resuming&plugin_status=$status&paged=$page&s=$s" ) );
if ( is_wp_error( $result ) ) {
wp_die( $result );
}
wp_redirect( self_admin_url( "plugins.php?resume=true&plugin_status=$status&paged=$page&s=$s" ) );
exit;
default:
if ( isset( $_POST['checked'] ) ) {
check_admin_referer( 'bulk-plugins' );
$plugins = isset( $_POST['checked'] ) ? (array) wp_unslash( $_POST['checked'] ) : array();
$sendback = wp_get_referer();
/** This action is documented in wp-admin/edit-comments.php */
$sendback = apply_filters( 'handle_bulk_actions-' . get_current_screen()->id, $sendback, $action, $plugins ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
wp_safe_redirect( $sendback );
exit;
}
break;
}
}
$wp_list_table->prepare_items();
wp_enqueue_script( 'plugin-install' );
add_thickbox();
add_screen_option( 'per_page', array( 'default' => 999 ) );
get_current_screen()->add_help_tab(
array(
'id' => 'overview',
'title' => __( 'Overview' ),
'content' =>
'<p>' . __( 'Plugins extend and expand the functionality of WordPress. Once a plugin is installed, you may activate it or deactivate it here.' ) . '</p>' .
'<p>' . __( 'The search for installed plugins will search for terms in their name, description, or author.' ) . ' <span id="live-search-desc" class="hide-if-no-js">' . __( 'The search results will be updated as you type.' ) . '</span></p>' .
'<p>' . sprintf(
/* translators: %s: WordPress Plugin Directory URL. */
__( 'If you would like to see more plugins to choose from, click on the “Add New” button and you will be able to browse or search for additional plugins from the <a href="%s">WordPress Plugin Directory</a>. Plugins in the WordPress Plugin Directory are designed and developed by third parties, and are compatible with the license WordPress uses. Oh, and they’re free!' ),
__( 'https://wordpress.org/plugins/' )
) . '</p>',
)
);
get_current_screen()->add_help_tab(
array(
'id' => 'compatibility-problems',
'title' => __( 'Troubleshooting' ),
'content' =>
'<p>' . __( 'Most of the time, plugins play nicely with the core of WordPress and with other plugins. Sometimes, though, a plugin’s code will get in the way of another plugin, causing compatibility issues. If your site starts doing strange things, this may be the problem. Try deactivating all your plugins and re-activating them in various combinations until you isolate which one(s) caused the issue.' ) . '</p>' .
'<p>' . sprintf(
/* translators: WP_PLUGIN_DIR constant value. */
__( 'If something goes wrong with a plugin and you can’t use WordPress, delete or rename that file in the %s directory and it will be automatically deactivated.' ),
'<code>' . WP_PLUGIN_DIR . '</code>'
) . '</p>',
)
);
get_current_screen()->set_help_sidebar(
'<p><strong>' . __( 'For more information:' ) . '</strong></p>' .
'<p>' . __( '<a href="https://wordpress.org/support/article/managing-plugins/">Documentation on Managing Plugins</a>' ) . '</p>' .
'<p>' . __( '<a href="https://wordpress.org/support/">Support</a>' ) . '</p>'
);
get_current_screen()->set_screen_reader_content(
array(
'heading_views' => __( 'Filter plugins list' ),
'heading_pagination' => __( 'Plugins list navigation' ),
'heading_list' => __( 'Plugins list' ),
)
);
$title = __( 'Plugins' );
$parent_file = 'plugins.php';
require_once( ABSPATH . 'wp-admin/admin-header.php' );
$invalid = validate_active_plugins();
if ( ! empty( $invalid ) ) {
foreach ( $invalid as $plugin_file => $error ) {
echo '<div id="message" class="error"><p>';
printf(
/* translators: 1: Plugin file, 2: Error message. */
__( 'The plugin %1$s has been deactivated due to an error: %2$s' ),
'<code>' . esc_html( $plugin_file ) . '</code>',
$error->get_error_message()
);
echo '</p></div>';
}
}
?>
<?php
if ( isset( $_GET['error'] ) ) :
if ( isset( $_GET['main'] ) ) {
$errmsg = __( 'You cannot delete a plugin while it is active on the main site.' );
} elseif ( isset( $_GET['charsout'] ) ) {
$errmsg = sprintf(
/* translators: %d: Number of characters. */
_n(
'The plugin generated %d character of <strong>unexpected output</strong> during activation.',
'The plugin generated %d characters of <strong>unexpected output</strong> during activation.',
$_GET['charsout']
),
$_GET['charsout']
);
$errmsg .= ' ' . __( 'If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.' );
} elseif ( 'resuming' === $_GET['error'] ) {
$errmsg = __( 'Plugin could not be resumed because it triggered a <strong>fatal error</strong>.' );
} else {
$errmsg = __( 'Plugin could not be activated because it triggered a <strong>fatal error</strong>.' );
}
?>
<div id="message" class="error"><p><?php echo $errmsg; ?></p>
<?php
if ( ! isset( $_GET['main'] ) && ! isset( $_GET['charsout'] ) && wp_verify_nonce( $_GET['_error_nonce'], 'plugin-activation-error_' . $plugin ) ) {
$iframe_url = add_query_arg(
array(
'action' => 'error_scrape',
'plugin' => urlencode( $plugin ),
'_wpnonce' => urlencode( $_GET['_error_nonce'] ),
),
admin_url( 'plugins.php' )
);
?>
<iframe style="border:0" width="100%" height="70px" src="<?php echo esc_url( $iframe_url ); ?>"></iframe>
<?php
}
?>
</div>
<?php
elseif ( isset( $_GET['deleted'] ) ) :
$delete_result = get_transient( 'plugins_delete_result_' . $user_ID );
// Delete it once we're done.
delete_transient( 'plugins_delete_result_' . $user_ID );
if ( is_wp_error( $delete_result ) ) :
?>
<div id="message" class="error notice is-dismissible">
<p>
<?php
printf(
/* translators: %s: Error message. */
__( 'Plugin could not be deleted due to an error: %s' ),
$delete_result->get_error_message()
);
?>
</p>
</div>
<?php else : ?>
<div id="message" class="updated notice is-dismissible">
<p>
<?php
if ( 1 == (int) $_GET['deleted'] ) {
_e( 'The selected plugin has been deleted.' );
} else {
_e( 'The selected plugins have been deleted.' );
}
?>
</p>
</div>
<?php endif; ?>
<?php elseif ( isset( $_GET['activate'] ) ) : ?>
<div id="message" class="updated notice is-dismissible"><p><?php _e( 'Plugin activated.' ); ?></p></div>
<?php elseif ( isset( $_GET['activate-multi'] ) ) : ?>
<div id="message" class="updated notice is-dismissible"><p><?php _e( 'Selected plugins activated.' ); ?></p></div>
<?php elseif ( isset( $_GET['deactivate'] ) ) : ?>
<div id="message" class="updated notice is-dismissible"><p><?php _e( 'Plugin deactivated.' ); ?></p></div>
<?php elseif ( isset( $_GET['deactivate-multi'] ) ) : ?>
<div id="message" class="updated notice is-dismissible"><p><?php _e( 'Selected plugins deactivated.' ); ?></p></div>
<?php elseif ( 'update-selected' == $action ) : ?>
<div id="message" class="updated notice is-dismissible"><p><?php _e( 'All selected plugins are up to date.' ); ?></p></div>
<?php elseif ( isset( $_GET['resume'] ) ) : ?>
<div id="message" class="updated notice is-dismissible"><p><?php _e( 'Plugin resumed.' ); ?></p></div>
<?php endif; ?>
<div class="wrap">
<h1 class="wp-heading-inline">
<?php
echo esc_html( $title );
?>
</h1>
<?php
if ( ( ! is_multisite() || is_network_admin() ) && current_user_can( 'install_plugins' ) ) {
?>
<a href="<?php echo self_admin_url( 'plugin-install.php' ); ?>" class="page-title-action"><?php echo esc_html_x( 'Add New', 'plugin' ); ?></a>
<?php
}
if ( strlen( $s ) ) {
/* translators: %s: Search query. */
printf( '<span class="subtitle">' . __( 'Search results for “%s”' ) . '</span>', esc_html( urldecode( $s ) ) );
}
?>
<hr class="wp-header-end">
<?php
/**
* Fires before the plugins list table is rendered.
*
* This hook also fires before the plugins list table is rendered in the Network Admin.
*
* Please note: The 'active' portion of the hook name does not refer to whether the current
* view is for active plugins, but rather all plugins actively-installed.
*
* @since 3.0.0
*
* @param array[] $plugins_all An array of arrays containing information on all installed plugins.
*/
do_action( 'pre_current_active_plugins', $plugins['all'] );
?>
<?php $wp_list_table->views(); ?>
<form class="search-form search-plugins" method="get">
<?php $wp_list_table->search_box( __( 'Search Installed Plugins' ), 'plugin' ); ?>
</form>
<form method="post" id="bulk-action-form">
<input type="hidden" name="plugin_status" value="<?php echo esc_attr( $status ); ?>" />
<input type="hidden" name="paged" value="<?php echo esc_attr( $page ); ?>" />
<?php $wp_list_table->display(); ?>
</form>
<span class="spinner"></span>
</div>
<?php
wp_print_request_filesystem_credentials_modal();
wp_print_admin_notice_templates();
wp_print_update_row_templates();
include( ABSPATH . 'wp-admin/admin-footer.php' );
| kirsley/repobase | wp-admin/plugins.php | PHP | gpl-2.0 | 24,347 |
<?php
/*
* Post relationship class.
*
* $HeadURL: http://plugins.svn.wordpress.org/types/tags/1.6.5.1/embedded/classes/relationship.php $
* $LastChangedDate: 2015-01-16 14:28:15 +0000 (Fri, 16 Jan 2015) $
* $LastChangedRevision: 1069430 $
* $LastChangedBy: iworks $
*
*/
/**
* Post relationship class
*
* @since Types 1.2
* @package Types
* @subpackage Classes
* @version 0.1
* @category Relationship
* @author srdjan <srdjan@icanlocalize.com>
*
*/
class WPCF_Relationship
{
/**
* Custom field
*
* @var type
*/
var $cf = array();
var $data = array();
/**
* Settings
*
* @var type
*/
var $settings = array();
var $items_per_page = 5;
var $items_per_page_option_name = '_wpcf_relationship_items_per_page';
var $child_form = null;
/**
* Construct function.
*/
function __construct()
{
$this->cf = new WPCF_Field;
$this->settings = get_option( 'wpcf_post_relationship', array() );
add_action( 'wp_ajax_add-types_reltax_add',
array($this, 'ajaxAddTax') );
}
/**
* Sets current data.
*
* @param type $parent
* @param type $child
* @param type $field
* @param type $data
*/
function set( $parent, $child, $data = array() )
{
return $this->_set( $parent, $child, $data );
}
/**
* Sets current data.
*
* @param type $parent
* @param type $child
* @param type $field
* @param type $data
*/
function _set( $parent, $child, $data = array() )
{
$this->parent = $parent;
$this->child = $child;
$this->cf = new WPCF_Field;
// TODO Revise usage
$this->data = $data;
}
/**
* Meta box form on post edit page.
*
* @param type $parent Parent post
* @param type $post_type Child post type
* @return type string HTML formatted form table
*/
function child_meta_form($parent, $post_type)
{
if ( is_integer( $parent ) ) {
$parent = get_post( $parent );
}
$output = '';
require_once dirname( __FILE__ ) . '/relationship/form-child.php';
$this->child_form = new WPCF_Relationship_Child_Form(
$parent,
$post_type,
$this->settings( $parent->post_type, $post_type )
);
$output .= $this->child_form->render();
return $output;
}
/**
* Child row rendered on AJAX 'Add New Child' call.
*
* @param type $parent_id
* @param type $child_id
* @return type
*/
function child_row($parent_id, $child_id)
{
$parent = get_post( intval( $parent_id ) );
$child = get_post( intval( $child_id ) );
if ( empty( $parent ) || empty( $child ) ) {
return new WP_Error( 'wpcf-relationship-save-child', 'no parent/child post' );
}
$output = '';
$this->child_form = $this->_get_child_form( $parent, $child );
$output .= $this->child_form->child_row( $child );
return $output;
}
/**
* Returns HTML formatted form.
*
* @param type $parent
* @param type $child
* @return \WPCF_Relationship_Child_Form
*/
function _get_child_form($parent, $child)
{
require_once dirname( __FILE__ ) . '/relationship/form-child.php';
return new WPCF_Relationship_Child_Form(
$parent,
$child->post_type,
$this->settings( $parent->post_type, $child->post_type )
);
}
function get_child()
{
$r = $this->child;
$r->parent = $this->parent;
$r->form = $this->_get_child_form( $r->parent, $this->child );
return $r;
}
/**
* Save items_per_page settings.
*
* @param type $parent
* @param type $child
* @param int $num
*/
function save_items_per_page($parent, $child, $num)
{
if ( post_type_exists( $parent ) && post_type_exists( $child ) ) {
$option_name = $this->items_per_page_option_name . '_' . $parent . '_' . $child;
if ( $num == 'all' ) {
$num = 9999999999999999;
}
update_option( $option_name, intval( $num ) );
}
}
/**
* Return items_per_page settings
*
* @param type $parent
* @param type $child
* @return type
*/
function get_items_per_page($parent, $child)
{
$per_page = get_option( $this->items_per_page_option_name . '_' . $parent . '_' . $child,
$this->items_per_page );
return empty( $per_page ) ? $this->items_per_page : $per_page;
}
/**
* Adjusts post name when saving.
*
* @todo Revise (not used?)
* @param type $post
* @return type
*/
function get_insert_post_name($post)
{
if ( empty( $post->post_title ) ) {
return $post->post_type . '-' . $post->ID;
}
return $post->post_title;
}
/**
* Bulk saving children.
*
* @param type $parent_id
* @param type $children
*/
function save_children($parent_id, $children)
{
foreach ( $children as $child_id => $fields ) {
$this->save_child( $parent_id, $child_id, $fields );
}
}
/**
* Unified save child function.
*
* @param type $child_id
* @param type $parent_id
*/
function save_child( $parent_id, $child_id, $save_fields = array() )
{
global $wpdb;
$parent = get_post( intval( $parent_id ) );
$child = get_post( intval( $child_id ) );
$post_data = array();
if ( empty( $parent ) || empty( $child ) ) {
return new WP_Error( 'wpcf-relationship-save-child', 'no parent/child post' );
}
// Save relationship
update_post_meta( $child->ID,
'_wpcf_belongs_' . $parent->post_type . '_id', $parent->ID );
// Check if added via AJAX
$check = get_post_meta( $child->ID, '_wpcf_relationship_new', true );
$new = !empty( $check );
delete_post_meta( $child->ID, '_wpcf_relationship_new' );
// Set post data
$post_data['ID'] = $child->ID;
// Title needs to be checked if submitted at all
if ( !isset( $save_fields['_wp_title'] ) ) {
// If not submitted that means it is not offered to be edited
if ( !empty( $child->post_title ) ) {
$post_title = $child->post_title;
} else {
// DO NOT LET IT BE EMPTY
$post_title = $child->post_type . ' ' . $child->ID;
}
} else {
$post_title = $save_fields['_wp_title'];
}
$post_data['post_title'] = $post_title;
$post_data['post_content'] = isset( $save_fields['_wp_body'] ) ? $save_fields['_wp_body'] : $child->post_content;
$post_data['post_type'] = $child->post_type;
// Check post status - if new, convert to 'publish' else keep remaining
if ( $new ) {
$post_data['post_status'] = 'publish';
} else {
$post_data['post_status'] = get_post_status( $child->ID );
}
/*
*
*
*
*
*
*
* UPDATE POST
*/
$cf = new WPCF_Field;
if (
isset( $_POST['wpcf_post_relationship'][$parent_id])
&& isset( $_POST['wpcf_post_relationship'][$parent_id][$child_id] )
) {
$_POST['wpcf'] = array();
foreach( $_POST['wpcf_post_relationship'][$parent_id][$child_id] as $slug => $value ) {
$_POST['wpcf'][$cf->__get_slug_no_prefix( $slug )] = $value;
$_POST['wpcf'][$slug] = $value;
}
}
unset($cf);
$updated_id = wp_update_post( $post_data );
if ( empty( $updated_id ) ) {
return new WP_Error( 'relationship-update-post-failed', 'Updating post failed' );
}
// Save parents
if ( !empty( $save_fields['parents'] ) ) {
foreach ( $save_fields['parents'] as $parent_post_type => $parent_post_id ) {
update_post_meta( $child->ID,
'_wpcf_belongs_' . $parent_post_type . '_id',
$parent_post_id );
}
}
// Update taxonomies
if ( !empty( $save_fields['taxonomies'] ) && is_array( $save_fields['taxonomies'] ) ) {
$_save_data = array();
foreach ( $save_fields['taxonomies'] as $taxonomy => $t ) {
if ( !is_taxonomy_hierarchical( $taxonomy ) ) {
$_save_data[$taxonomy] = strval( $t );
continue;
}
foreach ( $t as $term_id ) {
if ( $term_id != '-1' ) {
$term = get_term( $term_id, $taxonomy );
if ( empty( $term ) ) {
continue;
}
$_save_data[$taxonomy][] = $term_id;
}
}
}
wp_delete_object_term_relationships( $child->ID,
array_keys( $save_fields['taxonomies'] ) );
foreach ( $_save_data as $_taxonomy => $_terms ) {
wp_set_post_terms( $child->ID, $_terms, $_taxonomy,
$append = false );
}
}
// Unset non-types
unset( $save_fields['_wp_title'], $save_fields['_wp_body'],
$save_fields['parents'], $save_fields['taxonomies'] );
/*
*
*
*
*
*
*
* UPDATE Loop over fields
*/
foreach ( $save_fields as $slug => $value ) {
if ( defined( 'WPTOOLSET_FORMS_VERSION' ) ) {
// Get field by slug
$field = wpcf_fields_get_field_by_slug( str_replace( WPCF_META_PREFIX,
'', $slug ) );
if ( empty( $field ) ) {
continue;
}
// Set config
$config = wptoolset_form_filter_types_field( $field, $child->ID );
// Check if valid
$valid = wptoolset_form_validate_field( 'post', $config, $value );
if ( is_wp_error( $valid ) ) {
$errors = $valid->get_error_data();
$msg = sprintf( __( 'Child post "%s" field "%s" not updated:',
'wpcf' ), $child->post_title, $field['name'] );
wpcf_admin_message_store( $msg . ' ' . implode( ', ',
$errors ), 'error' );
continue;
}
}
$this->cf->set( $child, $field );
$this->cf->context = 'post_relationship';
$this->cf->save( $value );
}
do_action( 'wpcf_relationship_save_child', $child, $parent );
clean_post_cache( $parent->ID );
clean_post_cache( $child->ID );
// Added because of caching meta 1.5.4
wp_cache_flush();
return true;
}
/**
* Saves new child.
*
* @param type $parent_id
* @param type $post_type
* @return type
*/
function add_new_child($parent_id, $post_type)
{
global $wpdb;
$parent = get_post( $parent_id );
if ( empty( $parent ) ) {
return new WP_Error( 'wpcf-relationship-no-parent', 'No parent' );
}
$new_post = array(
'post_title' => __('New'). ': '.$post_type,
'post_type' => $post_type,
'post_status' => 'draft',
);
$id = wp_insert_post( $new_post, true );
/**
* return wp_error
*/
if ( is_wp_error( $id ) ) {
return $id;
}
/**
* Mark that it is new post
*/
update_post_meta( $id, '_wpcf_relationship_new', 1 );
/**
* Save relationship
*/
update_post_meta( $id, '_wpcf_belongs_' . $parent->post_type . '_id', $parent->ID );
/**
* Fix title
*/
$wpdb->update(
$wpdb->posts,
array('post_title' => $post_type . ' ' . $id),
array('ID' => $id), array('%s'), array('%d')
);
do_action( 'wpcf_relationship_add_child', get_post( $id ), $parent );
wp_cache_flush();
return $id;
}
/**
* Saved relationship settings.
*
* @param type $parent
* @param type $child
* @return type
*/
function settings($parent, $child)
{
return isset( $this->settings[$parent][$child] ) ? $this->settings[$parent][$child] : array();
}
/**
* Fetches submitted data.
*
* @param type $parent_id
* @param type $child_id
* @return type
*/
function get_submitted_data($parent_id, $child_id, $field)
{
if ( !is_string( $field ) ) {
$_field_slug = $field->slug;
} else {
$_field_slug = $field;
}
return isset( $_POST['wpcf_post_relationship'][$parent_id][$child_id][$_field_slug] ) ? $_POST['wpcf_post_relationship'][$parent_id][$child_id][$_field_slug] : null;
}
/**
* Gets all parents per post type.
*
* @param type $child
* @return type
*/
public static function get_parents($child)
{
$parents = array();
$item_parents = wpcf_pr_admin_get_belongs( $child->post_type );
if ( $item_parents ) {
foreach ( $item_parents as $post_type => $data ) {
// Get parent ID
$meta = wpcf_get_post_meta( $child->ID,
'_wpcf_belongs_' . $post_type . '_id', true );
if ( !empty( $meta ) ) {
$parent_post = get_post( $meta );
if ( !empty( $parent_post ) ) {
$parents[$parent_post->post_type] = $parent_post;
}
}
}
}
return $parents;
}
/**
* Gets post parent by post type.
*
* @param type $post_id
* @param type $parent_post_type
* @return type
*/
public static function get_parent($post_id, $parent_post_type)
{
return wpcf_get_post_meta( $post_id,
'_wpcf_belongs_' . $parent_post_type . '_id', true );
}
/**
* AJAX adding taxonomies
*/
public function ajaxAddTax()
{
if ( isset( $_POST['types_reltax'] ) ) {
$data = array_shift( $_POST['types_reltax'] );
$tax = key( $data );
$val = array_shift( $data );
$__nonce = array_shift( $_POST['types_reltax_nonce'] );
$nonce = array_shift( $__nonce );
$_POST['action'] = 'add-' . $tax;
$_POST['post_category'][$tax] = $val;
$_POST['tax_input'][$tax] = $val;
$_POST['new'.$tax] = $val;
$_REQUEST["_ajax_nonce-add-{$tax}"] = $nonce;
_wp_ajax_add_hierarchical_term();
}
die();
}
/**
* Meta box form on post edit page.
*
* @param type $parent Parent post
* @param type $post_type Child post type
* @return type string HTML formatted list
*/
function child_list($parent, $post_type)
{
if ( is_integer( $parent ) ) {
$parent = get_post( $parent );
}
$output = '';
require_once dirname( __FILE__ ) . '/relationship/form-child.php';
$this->child_form = new WPCF_Relationship_Child_Form(
$parent,
$post_type,
$this->settings( $parent->post_type, $post_type )
);
foreach($this->child_form->children as $child) {
$output .= sprintf(
'<li>%s</li>',
apply_filters('post_title', $child->post_title)
);
}
if ( $output ) {
$output = sprintf(
'<ul>%s</ul>',
$output
);
} else {
$output = sprintf(
'<p class="info">%s</p>',
$this->child_form->child_post_type_object->labels->not_found
);
}
return $output;
}
}
| cgb37/umlib-wp.local | wp-content/plugins/types/embedded/classes/relationship.php | PHP | gpl-2.0 | 16,640 |
/*
* Copyright (c) 1999, 2017, 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.util.locale.provider;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.spi.DateFormatProvider;
import java.util.Calendar;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.Set;
import java.util.TimeZone;
/**
* Concrete implementation of the {@link java.text.spi.DateFormatProvider
* DateFormatProvider} class for the JRE LocaleProviderAdapter.
*
* @author Naoto Sato
* @author Masayoshi Okutsu
*/
public class DateFormatProviderImpl extends DateFormatProvider implements AvailableLanguageTags {
private final LocaleProviderAdapter.Type type;
private final Set<String> langtags;
public DateFormatProviderImpl(LocaleProviderAdapter.Type type, Set<String> langtags) {
this.type = type;
this.langtags = langtags;
}
/**
* Returns an array of all locales for which this locale service provider
* can provide localized objects or names.
*
* @return An array of all locales for which this locale service provider
* can provide localized objects or names.
*/
@Override
public Locale[] getAvailableLocales() {
return LocaleProviderAdapter.toLocaleArray(langtags);
}
@Override
public boolean isSupportedLocale(Locale locale) {
return LocaleProviderAdapter.forType(type).isSupportedProviderLocale(locale, langtags);
}
/**
* Returns a new <code>DateFormat</code> instance which formats time
* with the given formatting style for the specified locale.
* @param style the given formatting style. Either one of
* {@link java.text.DateFormat#SHORT DateFormat.SHORT},
* {@link java.text.DateFormat#MEDIUM DateFormat.MEDIUM},
* {@link java.text.DateFormat#LONG DateFormat.LONG}, or
* {@link java.text.DateFormat#FULL DateFormat.FULL}.
* @param locale the desired locale.
* @exception IllegalArgumentException if <code>style</code> is invalid,
* or if <code>locale</code> isn't
* one of the locales returned from
* {@link java.util.spi.LocaleServiceProvider#getAvailableLocales()
* getAvailableLocales()}.
* @exception NullPointerException if <code>locale</code> is null
* @return a time formatter.
* @see java.text.DateFormat#getTimeInstance(int, java.util.Locale)
*/
@Override
public DateFormat getTimeInstance(int style, Locale locale) {
return getInstance(-1, style, locale);
}
/**
* Returns a new <code>DateFormat</code> instance which formats date
* with the given formatting style for the specified locale.
* @param style the given formatting style. Either one of
* {@link java.text.DateFormat#SHORT DateFormat.SHORT},
* {@link java.text.DateFormat#MEDIUM DateFormat.MEDIUM},
* {@link java.text.DateFormat#LONG DateFormat.LONG}, or
* {@link java.text.DateFormat#FULL DateFormat.FULL}.
* @param locale the desired locale.
* @exception IllegalArgumentException if <code>style</code> is invalid,
* or if <code>locale</code> isn't
* one of the locales returned from
* {@link java.util.spi.LocaleServiceProvider#getAvailableLocales()
* getAvailableLocales()}.
* @exception NullPointerException if <code>locale</code> is null
* @return a date formatter.
* @see java.text.DateFormat#getDateInstance(int, java.util.Locale)
*/
@Override
public DateFormat getDateInstance(int style, Locale locale) {
return getInstance(style, -1, locale);
}
/**
* Returns a new <code>DateFormat</code> instance which formats date and time
* with the given formatting style for the specified locale.
* @param dateStyle the given date formatting style. Either one of
* {@link java.text.DateFormat#SHORT DateFormat.SHORT},
* {@link java.text.DateFormat#MEDIUM DateFormat.MEDIUM},
* {@link java.text.DateFormat#LONG DateFormat.LONG}, or
* {@link java.text.DateFormat#FULL DateFormat.FULL}.
* @param timeStyle the given time formatting style. Either one of
* {@link java.text.DateFormat#SHORT DateFormat.SHORT},
* {@link java.text.DateFormat#MEDIUM DateFormat.MEDIUM},
* {@link java.text.DateFormat#LONG DateFormat.LONG}, or
* {@link java.text.DateFormat#FULL DateFormat.FULL}.
* @param locale the desired locale.
* @exception IllegalArgumentException if <code>dateStyle</code> or
* <code>timeStyle</code> is invalid,
* or if <code>locale</code> isn't
* one of the locales returned from
* {@link java.util.spi.LocaleServiceProvider#getAvailableLocales()
* getAvailableLocales()}.
* @exception NullPointerException if <code>locale</code> is null
* @return a date/time formatter.
* @see java.text.DateFormat#getDateTimeInstance(int, int, java.util.Locale)
*/
@Override
public DateFormat getDateTimeInstance(int dateStyle, int timeStyle,
Locale locale) {
return getInstance(dateStyle, timeStyle, locale);
}
private DateFormat getInstance(int dateStyle, int timeStyle, Locale locale) {
if (locale == null) {
throw new NullPointerException();
}
// Check for region override
Locale rg = CalendarDataUtility.findRegionOverride(locale);
SimpleDateFormat sdf = new SimpleDateFormat("", rg);
Calendar cal = sdf.getCalendar();
try {
String pattern = LocaleProviderAdapter.forType(type)
.getLocaleResources(rg).getDateTimePattern(timeStyle, dateStyle,
cal);
sdf.applyPattern(pattern);
} catch (MissingResourceException mre) {
// Specify the fallback pattern
sdf.applyPattern("M/d/yy h:mm a");
}
// Check for timezone override
String tz = locale.getUnicodeLocaleType("tz");
if (tz != null) {
sdf.setTimeZone(
TimeZoneNameUtility.convertLDMLShortID(tz)
.map(TimeZone::getTimeZone)
.orElseGet(sdf::getTimeZone));
}
return sdf;
}
@Override
public Set<String> getAvailableLanguageTags() {
return langtags;
}
}
| md-5/jdk10 | src/java.base/share/classes/sun/util/locale/provider/DateFormatProviderImpl.java | Java | gpl-2.0 | 7,634 |
/*
* Copyright (c) 1997, 2013, 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.config.metro.dev;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;
/**
* Parses a XML fragment and is expected to return a corresponding WebServiceFeature.
*
* @author Fabian Ritzmann
*/
public interface FeatureReader<T extends WebServiceFeature> {
public static final QName ENABLED_ATTRIBUTE_NAME = new QName("enabled");
/**
* Parse an XML stream and return the corresponding WebServiceFeature instance.
*/
public T parse(XMLEventReader reader) throws WebServiceException;
}
| FauxFaux/jdk9-jaxws | src/java.xml.ws/share/classes/com/sun/xml/internal/ws/config/metro/dev/FeatureReader.java | Java | gpl-2.0 | 1,858 |
/*
* Copyright 2003-2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 16 Network Circle, Menlo
* Park, CA 94025 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.cldc.util.j2me;
import java.util.*;
/**
* This class is an implementation of the subsetted
* CLDC 1.1 Calendar class.
*
* @see java.util.Calendar
* @see java.util.TimeZone
*/
public class CalendarImpl extends Calendar {
/* ERA */
private static final int BC = 0;
private static final int AD = 1;
/* January 1, year 1 (Gregorian) */
private static final int JAN_1_1_JULIAN_DAY = 1721426;
/* January 1, 1970 (Gregorian) */
private static final int EPOCH_JULIAN_DAY = 2440588;
/* 0-based, for day-in-year */
private static final int NUM_DAYS[]
= {0,31,59,90,120,151,181,212,243,273,304,334};
/* 0-based, for day-in-year */
private static final int LEAP_NUM_DAYS[]
= {0,31,60,91,121,152,182,213,244,274,305,335};
/**
* Useful millisecond constants. Although ONE_DAY and ONE_WEEK can fit
* into ints, they must be longs in order to prevent arithmetic overflow
* when performing (bug 4173516).
*/
private static final int ONE_SECOND = 1000;
private static final int ONE_MINUTE = 60*ONE_SECOND;
private static final int ONE_HOUR = 60*ONE_MINUTE;
private static final long ONE_DAY = 24*ONE_HOUR;
private static final long ONE_WEEK = 7*ONE_DAY;
/**
* The point at which the Gregorian calendar rules are used, measured in
* milliseconds from the standard epoch. Default is October 15, 1582
* (Gregorian) 00:00:00 UTC or -12219292800000L. For this value, October 4,
* 1582 (Julian) is followed by October 15, 1582 (Gregorian). This
* corresponds to Julian day number 2299161.
*/
private static final long gregorianCutover = -12219292800000L;
/**
* The year of the gregorianCutover, with 0 representing
* 1 BC, -1 representing 2 BC, etc.
*/
private static final int gregorianCutoverYear = 1582;
public CalendarImpl() {
super();
}
/**
* Converts UTC as milliseconds to time field values.
*/
protected void computeFields() {
int rawOffset = getTimeZone().getRawOffset();
long localMillis = time + rawOffset;
// Check for very extreme values -- millis near Long.MIN_VALUE or
// Long.MAX_VALUE. For these values, adding the zone offset can push
// the millis past MAX_VALUE to MIN_VALUE, or vice versa. This produces
// the undesirable effect that the time can wrap around at the ends,
// yielding, for example, a Date(Long.MAX_VALUE) with a big BC year
// (should be AD). Handle this by pinning such values to Long.MIN_VALUE
// or Long.MAX_VALUE. - liu 8/11/98 bug 4149677
if (time > 0 && localMillis < 0 && rawOffset > 0) {
localMillis = Long.MAX_VALUE;
} else if (time < 0 && localMillis > 0 && rawOffset < 0) {
localMillis = Long.MIN_VALUE;
}
// Time to fields takes the wall millis (Standard or DST).
timeToFields(localMillis);
long ndays = (localMillis / ONE_DAY);
int millisInDay = (int)(localMillis - (ndays * ONE_DAY));
if (millisInDay < 0) millisInDay += ONE_DAY;
// Call getOffset() to get the TimeZone offset.
// The millisInDay value must be standard local millis.
int dstOffset = getTimeZone().getOffset(AD,
this.fields[YEAR],
this.fields[MONTH],
this.fields[DATE],
this.fields[DAY_OF_WEEK],
millisInDay) - rawOffset;
// Adjust our millisInDay for DST, if necessary.
millisInDay += dstOffset;
// If DST has pushed us into the next day,
// we must call timeToFields() again.
// This happens in DST between 12:00 am and 1:00 am every day.
// The call to timeToFields() will give the wrong day,
// since the Standard time is in the previous day
if (millisInDay >= ONE_DAY) {
long dstMillis = localMillis + dstOffset;
millisInDay -= ONE_DAY;
// As above, check for and pin extreme values
if (localMillis > 0 && dstMillis < 0 && dstOffset > 0) {
dstMillis = Long.MAX_VALUE;
} else if (localMillis < 0 && dstMillis > 0 && dstOffset < 0) {
dstMillis = Long.MIN_VALUE;
}
timeToFields(dstMillis);
}
// Fill in all time-related fields based on millisInDay.
// so as not to perturb flags.
this.fields[MILLISECOND] = millisInDay % 1000;
millisInDay /= 1000;
this.fields[SECOND] = millisInDay % 60;
millisInDay /= 60;
this.fields[MINUTE] = millisInDay % 60;
millisInDay /= 60;
this.fields[HOUR_OF_DAY] = millisInDay;
this.fields[AM_PM] = millisInDay / 12;
this.fields[HOUR] = millisInDay % 12;
}
/**
* Convert the time as milliseconds to the date fields. Millis must be
* given as local wall millis to get the correct local day. For example,
* if it is 11:30 pm Standard, and DST is in effect, the correct DST millis
* must be passed in to get the right date.
* <p>
* Fields that are completed by this method: YEAR, MONTH, DATE, DAY_OF_WEEK.
* @param theTime the time in wall millis (either Standard or DST),
* whichever is in effect
*/
private void timeToFields(long theTime) {
int dayOfYear, rawYear;
boolean isLeap;
// Compute the year, month, and day of month from the given millis
if (theTime >= gregorianCutover) {
// The Gregorian epoch day is zero for Monday January 1, year 1.
long gregorianEpochDay =
millisToJulianDay(theTime) - JAN_1_1_JULIAN_DAY;
// Here we convert from the day number to the multiple radix
// representation. We use 400-year, 100-year, and 4-year cycles.
// For example, the 4-year cycle has 4 years + 1 leap day; giving
// 1461 == 365*4 + 1 days.
int[] rem = new int[1];
// 400-year cycle length
int n400 = floorDivide(gregorianEpochDay, 146097, rem);
// 100-year cycle length
int n100 = floorDivide(rem[0], 36524, rem);
// 4-year cycle length
int n4 = floorDivide(rem[0], 1461, rem);
int n1 = floorDivide(rem[0], 365, rem);
rawYear = 400*n400 + 100*n100 + 4*n4 + n1;
// zero-based day of year
dayOfYear = rem[0];
// Dec 31 at end of 4- or 400-yr cycle
if (n100 == 4 || n1 == 4) {
dayOfYear = 365;
} else {
++rawYear;
}
// equiv. to (rawYear%4 == 0)
isLeap =
((rawYear&0x3) == 0) && (rawYear%100 != 0 || rawYear%400 == 0);
// Gregorian day zero is a Monday
this.fields[DAY_OF_WEEK] = (int)((gregorianEpochDay+1) % 7);
} else {
// The Julian epoch day (not the same as Julian Day)
// is zero on Saturday December 30, 0 (Gregorian).
long julianEpochDay =
millisToJulianDay(theTime) - (JAN_1_1_JULIAN_DAY - 2);
rawYear = (int) floorDivide(4*julianEpochDay + 1464, 1461);
// Compute the Julian calendar day number for January 1, year
long january1 = 365*(rawYear-1) + floorDivide(rawYear-1, 4);
dayOfYear = (int)(julianEpochDay - january1); // 0-based
// Julian leap years occurred historically every 4 years starting
// with 8 AD. Before 8 AD the spacing is irregular; every 3 years
// from 45 BC to 9 BC, and then none until 8 AD. However, we don't
// implement this historical detail; instead, we implement the
// computationally cleaner proleptic calendar, which assumes
// consistent 4-year cycles throughout time.
// equiv. to (rawYear%4 == 0)
isLeap = ((rawYear&0x3) == 0);
// Julian calendar day zero is a Saturday
this.fields[DAY_OF_WEEK] = (int)((julianEpochDay-1) % 7);
}
// Common Julian/Gregorian calculation
int correction = 0;
// zero-based DOY for March 1
int march1 = isLeap ? 60 : 59;
if (dayOfYear >= march1) correction = isLeap ? 1 : 2;
// zero-based month
int month_field = (12 * (dayOfYear + correction) + 6) / 367;
// one-based DOM
int date_field = dayOfYear -
(isLeap ? LEAP_NUM_DAYS[month_field] : NUM_DAYS[month_field]) + 1;
// Normalize day of week
this.fields[DAY_OF_WEEK] += (this.fields[DAY_OF_WEEK] < 0) ? (SUNDAY+7) : SUNDAY;
this.fields[YEAR] = rawYear;
// If year is < 1 we are in BC
if (this.fields[YEAR] < 1) {
this.fields[YEAR] = 1 - this.fields[YEAR];
}
// 0-based
this.fields[MONTH] = month_field + JANUARY;
this.fields[DATE] = date_field;
}
/*
* The following two static arrays are used privately by the
* <code>toString(Calendar calendar)</code> function below.
*/
static String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
static String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
/**
* Converts this <code>Date</code> object to a <code>String</code>
* of the form:
* <blockquote><pre>
* dow mon dd hh:mm:ss zzz yyyy</pre></blockquote>
* where:<ul>
* <li><tt>dow</tt> is the day of the week (<tt>Sun, Mon, Tue, Wed,
* Thu, Fri, Sat</tt>).
* <li><tt>mon</tt> is the month (<tt>Jan, Feb, Mar, Apr, May, Jun,
* Jul, Aug, Sep, Oct, Nov, Dec</tt>).
* <li><tt>dd</tt> is the day of the month (<tt>01</tt> through
* <tt>31</tt>), as two decimal digits.
* <li><tt>hh</tt> is the hour of the day (<tt>00</tt> through
* <tt>23</tt>), as two decimal digits.
* <li><tt>mm</tt> is the minute within the hour (<tt>00</tt> through
* <tt>59</tt>), as two decimal digits.
* <li><tt>ss</tt> is the second within the minute (<tt>00</tt> through
* <tt>61</tt>, as two decimal digits.
* <li><tt>zzz</tt> is the time zone (and may reflect daylight savings
* time). If time zone information is not available,
* then <tt>zzz</tt> is empty - that is, it consists
* of no characters at all.
* <li><tt>yyyy</tt> is the year, as four decimal digits.
* </ul>
*
* @return a string representation of this date.
*/
public static String toString(Calendar calendar) {
// Printing in the absence of a Calendar
// implementation class is not supported
if (calendar == null) {
return "Thu Jan 01 00:00:00 UTC 1970";
}
int dow = calendar.get(Calendar.DAY_OF_WEEK);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour_of_day = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
int year = calendar.get(Calendar.YEAR);
String yr = Integer.toString(year);
TimeZone zone = calendar.getTimeZone();
String zoneID = zone.getID();
if (zoneID == null) zoneID = "";
// The total size of the string buffer
// 3+1+3+1+2+1+2+1+2+1+2+1+zoneID.length+1+yr.length
// = 21 + zoneID.length + yr.length
StringBuffer sb = new StringBuffer(25 + zoneID.length() + yr.length());
sb.append(days[dow-1]).append(' ');
sb.append(months[month]).append(' ');
appendTwoDigits(sb, day).append(' ');
appendTwoDigits(sb, hour_of_day).append(':');
appendTwoDigits(sb, minute).append(':');
appendTwoDigits(sb, seconds).append(' ');
if (zoneID.length() > 0) sb.append(zoneID).append(' ');
appendFourDigits(sb, year);
return sb.toString();
}
/**
* Converts this <code>Date</code> object to a <code>String</code>.
* The output format is as follows:
* <blockquote><pre>yyyy MM dd hh mm ss +zzzz</pre></blockquote>
* where:<ul>
* <li><dd>yyyy</dd> is the year, as four decimal digits.
* Year values larger than <dd>9999</dd> will be truncated
* to <dd>9999</dd>.
* <li><dd>MM</dd> is the month (<dd>01</dd> through <dd>12</dd>),
* as two decimal digits.
* <li><dd>dd</dd> is the day of the month (<dd>01</dd> through
* <dd>31</dd>), as two decimal digits.
* <li><dd>hh</dd> is the hour of the day (<dd>00</dd> through
* <dd>23</dd>), as two decimal digits.
* <li><dd>mm</dd> is the minute within the hour (<dd>00</dd>
* through <dd>59</dd>), as two decimal digits.
* <li><dd>ss</dd> is the second within the minute (<dd>00</dd>
* through <dd>59</dd>), as two decimal digits.
* <li><dd>zzzz</dd> is the time zone offset in hours and minutes
* (four decimal digits <dd>"hhmm"</dd>) relative to GMT,
* preceded by a "+" or "-" character (<dd>-1200</dd>
* through <dd>+1200</dd>).
* For instance, Pacific Standard Time zone is printed
* as <dd>-0800</dd>. GMT is printed as <dd>+0000</dd>.
* </ul>
*
* @return a string representation of this date.
*/
public static String toISO8601String(Calendar calendar) {
// Printing in the absence of a Calendar
// implementation class is not supported
if (calendar == null) {
return "0000 00 00 00 00 00 +0000";
}
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour_of_day = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
String yr = Integer.toString(year);
// The total size of the string buffer
// yr.length+1+2+1+2+1+2+1+2+1+2+1+5 = 25 + yr.length
StringBuffer sb = new StringBuffer(25 + yr.length());
appendFourDigits(sb, year).append(' ');
appendTwoDigits(sb, month).append(' ');
appendTwoDigits(sb, day).append(' ');
appendTwoDigits(sb, hour_of_day).append(' ');
appendTwoDigits(sb, minute).append(' ');
appendTwoDigits(sb, seconds).append(' ');
// TimeZone offset is represented in milliseconds.
// Convert the offset to minutes:
TimeZone t = calendar.getTimeZone();
int zoneOffsetInMinutes = t.getRawOffset() / 1000 / 60;
if (zoneOffsetInMinutes < 0) {
zoneOffsetInMinutes = Math.abs(zoneOffsetInMinutes);
sb.append('-');
} else {
sb.append('+');
}
int zoneHours = zoneOffsetInMinutes / 60;
int zoneMinutes = zoneOffsetInMinutes % 60;
appendTwoDigits(sb, zoneHours);
appendTwoDigits(sb, zoneMinutes);
return sb.toString();
}
private static StringBuffer appendFourDigits(StringBuffer sb, int number) {
if (number >= 0 && number < 1000) {
sb.append('0');
if (number < 100) {
sb.append('0');
}
if (number < 10) {
sb.append('0');
}
}
return sb.append(number);
}
private static StringBuffer appendTwoDigits(StringBuffer sb, int number) {
if (number < 10) {
sb.append('0');
}
return sb.append(number);
}
/////////////////////////////
// Fields => Time computation
/////////////////////////////
/**
* Converts time field values to UTC as milliseconds.
* @exception IllegalArgumentException if any fields are invalid.
*/
protected void computeTime() {
correctTime();
// This function takes advantage of the fact that unset fields in
// the time field list have a value of zero.
// First, use the year to determine whether to use the Gregorian or the
// Julian calendar. If the year is not the year of the cutover, this
// computation will be correct. But if the year is the cutover year,
// this may be incorrect. In that case, assume the Gregorian calendar,
// make the computation, and then recompute if the resultant millis
// indicate the wrong calendar has been assumed.
// A date such as Oct. 10, 1582 does not exist in a Gregorian calendar
// with the default changeover of Oct. 15, 1582, since in such a
// calendar Oct. 4 (Julian) is followed by Oct. 15 (Gregorian). This
// algorithm will interpret such a date using the Julian calendar,
// yielding Oct. 20, 1582 (Gregorian).
int year = this.fields[YEAR];
boolean isGregorian = year >= gregorianCutoverYear;
long julianDay = calculateJulianDay(isGregorian, year);
long millis = julianDayToMillis(julianDay);
// The following check handles portions of the cutover year BEFORE the
// cutover itself happens. The check for the julianDate number is for a
// rare case; it's a hardcoded number, but it's efficient. The given
// Julian day number corresponds to Dec 3, 292269055 BC, which
// corresponds to millis near Long.MIN_VALUE. The need for the check
// arises because for extremely negative Julian day numbers, the millis
// actually overflow to be positive values. Without the check, the
// initial date is interpreted with the Gregorian calendar, even when
// the cutover doesn't warrant it.
if (isGregorian != (millis >= gregorianCutover) &&
julianDay != -106749550580L) { // See above
julianDay = calculateJulianDay(!isGregorian, year);
millis = julianDayToMillis(julianDay);
}
// Do the time portion of the conversion.
int millisInDay = 0;
// Hours
// Don't normalize here; let overflow bump into the next period.
// This is consistent with how we handle other fields.
millisInDay += this.fields[HOUR_OF_DAY];
millisInDay *= 60;
// now get minutes
millisInDay += this.fields[MINUTE];
millisInDay *= 60;
// now get seconds
millisInDay += this.fields[SECOND];
millisInDay *= 1000;
// now get millis
millisInDay += this.fields[MILLISECOND];
// Compute the time zone offset and DST offset. There are two potential
// ambiguities here. We'll assume a 2:00 am (wall time) switchover time
// for discussion purposes here.
// 1. The transition into DST. Here, a designated time of 2:00 am - 2:59 am
// can be in standard or in DST depending. However, 2:00 am is an invalid
// representation (the representation jumps from 1:59:59 am Std to 3:00:00 am DST).
// We assume standard time.
// 2. The transition out of DST. Here, a designated time of 1:00 am - 1:59 am
// can be in standard or DST. Both are valid representations (the rep
// jumps from 1:59:59 DST to 1:00:00 Std).
// Again, we assume standard time.
// We use the TimeZone object to get the zone offset
int zoneOffset = getTimeZone().getRawOffset();
// Now add date and millisInDay together, to make millis contain local wall
// millis, with no zone or DST adjustments
millis += millisInDay;
// Normalize the millisInDay to 0..ONE_DAY-1. If the millis is out
// of range, then we must call timeToFields() to recompute our
// fields.
int[] normalizedMillisInDay = new int[1];
floorDivide(millis, (int)ONE_DAY, normalizedMillisInDay);
// We need to have the month, the day, and the day of the week.
// Calling timeToFields will compute the MONTH and DATE fields.
//
// It's tempting to try to use DAY_OF_WEEK here, if it
// is set, but we CAN'T. Even if it's set, it might have
// been set wrong by the user. We should rely only on
// the Julian day number, which has been computed correctly
// using the disambiguation algorithm above. [LIU]
int dow = julianDayToDayOfWeek(julianDay);
// It's tempting to try to use DAY_OF_WEEK here, if it
// is set, but we CAN'T. Even if it's set, it might have
// been set wrong by the user. We should rely only on
// the Julian day number, which has been computed correctly
// using the disambiguation algorithm above. [LIU]
int dstOffset = getTimeZone().getOffset(AD,
this.fields[YEAR],
this.fields[MONTH],
this.fields[DATE],
dow,
normalizedMillisInDay[0]) -
zoneOffset;
// Note: Because we pass in wall millisInDay, rather than
// standard millisInDay, we interpret "1:00 am" on the day
// of cessation of DST as "1:00 am Std" (assuming the time
// of cessation is 2:00 am).
// Store our final computed GMT time, with timezone adjustments.
time = millis - zoneOffset - dstOffset;
}
/**
* Compute the Julian day number under either the Gregorian or the
* Julian calendar, using the given year and the remaining fields.
* @param isGregorian if true, use the Gregorian calendar
* @param year the adjusted year number, with 0 indicating the
* year 1 BC, -1 indicating 2 BC, etc.
* @return the Julian day number
*/
private long calculateJulianDay(boolean isGregorian, int year) {
int month = 0;
month = this.fields[MONTH] - JANUARY;
// If the month is out of range, adjust it into range
if (month < 0 || month > 11) {
int[] rem = new int[1];
year += floorDivide(month, 12, rem);
month = rem[0];
}
boolean isLeap = year%4 == 0;
long julianDay =
365L*(year - 1) + floorDivide((year - 1), 4) + (JAN_1_1_JULIAN_DAY - 3);
if (isGregorian) {
isLeap = isLeap && ((year%100 != 0) || (year%400 == 0));
// Add 2 because Gregorian calendar starts 2 days after Julian calendar
julianDay +=
floorDivide((year - 1), 400) - floorDivide((year - 1), 100) + 2;
}
// At this point julianDay is the 0-based day BEFORE the first day of
// January 1, year 1 of the given calendar. If julianDay == 0, it
// specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian
// or Gregorian).
julianDay += isLeap ? LEAP_NUM_DAYS[month] : NUM_DAYS[month];
julianDay += this.fields[DATE];
return julianDay;
}
/**
* Validates the field values for HOUR_OF_DAY, AM_PM and HOUR
* The calendar will give preference in the following order
* HOUR_OF_DAY, AM_PM, HOUR
*/
private void correctTime() {
int value;
if (isSet[HOUR_OF_DAY]) {
value = this.fields[HOUR_OF_DAY] % 24;
this.fields[HOUR_OF_DAY] = value;
this.fields[AM_PM] = (value < 12) ? AM : PM;
this.isSet[HOUR_OF_DAY] = false;
return;
}
if(isSet[AM_PM]) {
// Determines AM PM with the 24 hour clock
// This prevents the user from inputing an invalid one.
if (this.fields[AM_PM] != AM && this.fields[AM_PM] != PM) {
value = this.fields[HOUR_OF_DAY];
this.fields[AM_PM] = (value < 12) ? AM : PM;
}
this.isSet[AM_PM] = false;
}
if (isSet[HOUR]) {
value = this.fields[HOUR];
if (value > 12) {
this.fields[HOUR_OF_DAY] = (value % 12) + 12;
this.fields[HOUR] = value % 12;
this.fields[AM_PM] = PM;
} else {
if (this.fields[AM_PM] == PM) {
this.fields[HOUR_OF_DAY] = value + 12;
} else {
this.fields[HOUR_OF_DAY] = value;
}
}
this.isSet[HOUR] = false;
}
}
/////////////////
// Implementation
/////////////////
/**
* Converts time as milliseconds to Julian day.
* @param millis the given milliseconds.
* @return the Julian day number.
*/
private static long millisToJulianDay(long millis) {
return EPOCH_JULIAN_DAY + floorDivide(millis, ONE_DAY);
}
/**
* Converts Julian day to time as milliseconds.
* @param julian the given Julian day number.
* @return time as milliseconds.
*/
private static long julianDayToMillis(long julian) {
return (julian - EPOCH_JULIAN_DAY) * ONE_DAY;
}
private static int julianDayToDayOfWeek(long julian) {
// If julian is negative, then julian%7 will be negative, so we adjust
// accordingly. We add 1 because Julian day 0 is Monday.
int dayOfWeek = (int)((julian + 1) % 7);
return dayOfWeek + ((dayOfWeek < 0) ? (7 + SUNDAY) : SUNDAY);
}
/**
* Divide two long integers, returning the floor of the quotient.
* <p>
* Unlike the built-in division, this is mathematically well-behaved.
* E.g., <code>-1/4</code> => 0
* but <code>floorDivide(-1,4)</code> => -1.
* @param numerator the numerator
* @param denominator a divisor which must be > 0
* @return the floor of the quotient.
*/
public static long floorDivide(long numerator, long denominator) {
// We do this computation in order to handle
// a numerator of Long.MIN_VALUE correctly
return (numerator >= 0) ?
numerator / denominator :
((numerator + 1) / denominator) - 1;
}
/**
* Divide two integers, returning the floor of the quotient.
* <p>
* Unlike the built-in division, this is mathematically well-behaved.
* E.g., <code>-1/4</code> => 0
* but <code>floorDivide(-1,4)</code> => -1.
* @param numerator the numerator
* @param denominator a divisor which must be > 0
* @return the floor of the quotient.
*/
private static int floorDivide(int numerator, int denominator) {
// We do this computation in order to handle
// a numerator of Integer.MIN_VALUE correctly
return (numerator >= 0) ?
numerator / denominator :
((numerator + 1) / denominator) - 1;
}
/**
* Divide two integers, returning the floor of the quotient, and
* the modulus remainder.
* <p>
* Unlike the built-in division, this is mathematically well-behaved.
* E.g., <code>-1/4</code> => 0 and <code>-1%4</code> => -1,
* but <code>floorDivide(-1,4)</code> => -1 with <code>remainder[0]</code> => 3.
* @param numerator the numerator
* @param denominator a divisor which must be > 0
* @param remainder an array of at least one element in which the value
* <code>numerator mod denominator</code> is returned. Unlike <code>numerator
* % denominator</code>, this will always be non-negative.
* @return the floor of the quotient.
*/
private static int
floorDivide(int numerator, int denominator, int[] remainder) {
if (numerator >= 0) {
remainder[0] = numerator % denominator;
return numerator / denominator;
}
int quotient = ((numerator + 1) / denominator) - 1;
remainder[0] = numerator - (quotient * denominator);
return quotient;
}
/**
* Divide two integers, returning the floor of the quotient, and
* the modulus remainder.
* <p>
* Unlike the built-in division, this is mathematically well-behaved.
* E.g., <code>-1/4</code> => 0 and <code>-1%4</code> => -1,
* but <code>floorDivide(-1,4)</code> => -1 with <code>remainder[0]</code> => 3.
* @param numerator the numerator
* @param denominator a divisor which must be > 0
* @param remainder an array of at least one element in which the value
* <code>numerator mod denominator</code> is returned. Unlike <code>numerator
* % denominator</code>, this will always be non-negative.
* @return the floor of the quotient.
*/
private static int
floorDivide(long numerator, int denominator, int[] remainder) {
if (numerator >= 0) {
remainder[0] = (int)(numerator % denominator);
return (int)(numerator / denominator);
}
int quotient = (int)(((numerator + 1) / denominator) - 1);
remainder[0] = (int)(numerator - (quotient * denominator));
return quotient;
}
}
| wufucious/moped | squawk/cldc/src/com/sun/cldc/util/j2me/CalendarImpl.java | Java | gpl-2.0 | 30,363 |