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 |
|---|---|---|---|---|---|
/*
* eXist Open Source Native XML Database
* Copyright (C) 2015 The eXist Project
* http://exist-db.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.exist.security.internal;
import org.exist.security.AbstractRealm;
import org.exist.security.AbstractAccount;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.config.Configuration;
import org.exist.config.ConfigurationException;
import org.exist.config.Configurator;
import org.exist.config.annotation.ConfigurationClass;
import org.exist.config.annotation.ConfigurationFieldAsElement;
import org.exist.security.Group;
import org.exist.security.PermissionDeniedException;
import org.exist.security.SchemaType;
import org.exist.security.SecurityManager;
import org.exist.security.Account;
import org.exist.security.internal.aider.UserAider;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Optional;
import java.util.Properties;
import org.exist.security.Credential;
import org.exist.storage.DBBroker;
/**
* Represents a user within the database.
*
* @author Wolfgang Meier <wolfgang@exist-db.org>
* @author {Marco.Tampucci, Massimo.Martinelli} @isti.cnr.it
* @author Adam retter <adam@exist-db.org>
*/
@ConfigurationClass("account")
public class AccountImpl extends AbstractAccount {
private final static Logger LOG = LogManager.getLogger(AccountImpl.class);
public static boolean CHECK_PASSWORDS = true;
private final static SecurityProperties securityProperties = new SecurityProperties();
public static SecurityProperties getSecurityProperties() {
return securityProperties;
}
/*
static {
Properties props = new Properties();
try {
props.load(AccountImpl.class.getClassLoader().getResourceAsStream(
"org/exist/security/security.properties"));
} catch(IOException e) {
}
String option = props.getProperty("passwords.encoding", "md5");
setPasswordEncoding(option);
option = props.getProperty("passwords.check", "yes");
CHECK_PASSWORDS = option.equalsIgnoreCase("yes")
|| option.equalsIgnoreCase("true");
}
static public void enablePasswordChecks(boolean check) {
CHECK_PASSWORDS = check;
}
static public void setPasswordEncoding(String encoding) {
if(encoding != null) {
LOG.equals("Setting password encoding to " + encoding);
if(encoding.equalsIgnoreCase("plain")) {
PASSWORD_ENCODING = PLAIN_ENCODING;
} else if(encoding.equalsIgnoreCase("md5")) {
PASSWORD_ENCODING = MD5_ENCODING;
} else {
PASSWORD_ENCODING = SIMPLE_MD5_ENCODING;
}
}
}*/
@ConfigurationFieldAsElement("password")
private String password = null;
@ConfigurationFieldAsElement("digestPassword")
private String digestPassword = null;
/**
* Create a new user with name and password
*
* @param realm
* @param id
* @param name
* @param password
* @throws ConfigurationException
*/
public AccountImpl(final DBBroker broker, final AbstractRealm realm, final int id, final String name,final String password) throws ConfigurationException {
super(broker, realm, id, name);
setPassword(password);
}
public AccountImpl(final DBBroker broker, final AbstractRealm realm, final int id, final String name, final String password, final Group group, final boolean hasDbaRole) throws ConfigurationException {
super(broker, realm, id, name);
setPassword(password);
this.groups.add(group);
this.hasDbaRole = hasDbaRole;
}
public AccountImpl(final DBBroker broker, final AbstractRealm realm, final int id, final String name, final String password, final Group group) throws ConfigurationException {
super(broker, realm, id, name);
setPassword(password);
this.groups.add(group);
}
/**
* Create a new user with name
*
* @param realm
* @param name
* The account name
* @throws ConfigurationException
*/
public AccountImpl(final DBBroker broker, final AbstractRealm realm, final String name) throws ConfigurationException {
super(broker, realm, Account.UNDEFINED_ID, name);
}
// /**
// * Create a new user with name, password and primary group
// *
// * @param name
// * @param password
// * @param primaryGroup
// * @throws ConfigurationException
// * @throws PermissionDeniedException
// */
// public AccountImpl(AbstractRealm realm, int id, String name, String password, String primaryGroup) throws ConfigurationException {
// this(realm, id, name, password);
// addGroup(primaryGroup);
// }
public AccountImpl(final DBBroker broker, final AbstractRealm realm, final int id, final Account from_user) throws ConfigurationException, PermissionDeniedException {
super(broker, realm, id, from_user.getName());
instantiate(from_user);
}
private void instantiate(final Account from_user) throws PermissionDeniedException {
//copy metadata
for(final SchemaType metadataKey : from_user.getMetadataKeys()) {
final String metadataValue = from_user.getMetadataValue(metadataKey);
setMetadataValue(metadataKey, metadataValue);
}
//copy umask
setUserMask(from_user.getUserMask());
if(from_user instanceof AccountImpl) {
final AccountImpl user = (AccountImpl) from_user;
groups = new ArrayList<>(user.groups);
password = user.password;
digestPassword = user.digestPassword;
hasDbaRole = user.hasDbaRole;
_cred = user._cred;
} else if(from_user instanceof UserAider) {
final UserAider user = (UserAider) from_user;
final String[] groups = user.getGroups();
for (final String group : groups) {
addGroup(group);
}
setPassword(user.getPassword());
digestPassword = user.getDigestPassword();
} else {
addGroup(from_user.getDefaultGroup());
//TODO: groups
}
}
public AccountImpl(final DBBroker broker, final AbstractRealm realm, final AccountImpl from_user) throws ConfigurationException {
super(broker, realm, from_user.id, from_user.name);
//copy metadata
for(final SchemaType metadataKey : from_user.getMetadataKeys()) {
final String metadataValue = from_user.getMetadataValue(metadataKey);
setMetadataValue(metadataKey, metadataValue);
}
groups = from_user.groups;
password = from_user.password;
digestPassword = from_user.digestPassword;
hasDbaRole = from_user.hasDbaRole;
_cred = from_user._cred;
//this.realm = realm; //set via super()
}
public AccountImpl(final AbstractRealm realm, final Configuration configuration) throws ConfigurationException {
super(realm, configuration);
//this is required because the classes fields are initialized after the super constructor
if(this.configuration != null) {
this.configuration = Configurator.configure(this, this.configuration);
}
this.hasDbaRole = this.hasGroup(SecurityManager.DBA_GROUP);
}
public AccountImpl(final AbstractRealm realm, final Configuration configuration, final boolean removed) throws ConfigurationException {
this(realm, configuration);
this.removed = removed;
}
/**
* Get the user's password
*
* @return Description of the Return Value
* @deprecated
*/
@Override
public final String getPassword() {
return password;
}
@Override
public final String getDigestPassword() {
return digestPassword;
}
@Override
public final void setPassword(final String passwd) {
_cred = new Password(this, passwd);
if(passwd == null) {
this.password = null;
this.digestPassword = null;
} else {
this.password = _cred.toString();
this.digestPassword = _cred.getDigest();
}
}
@Override
public void setCredential(final Credential credential) {
this._cred = credential;
this.password = _cred.toString();
this.digestPassword = _cred.getDigest();
}
public final static class SecurityProperties {
private final static boolean DEFAULT_CHECK_PASSWORDS = true;
private final static String PROP_CHECK_PASSWORDS = "passwords.check";
private Properties loadedSecurityProperties = null;
private Boolean checkPasswords = null;
public synchronized boolean isCheckPasswords() {
if(checkPasswords == null) {
final String property = getProperty(PROP_CHECK_PASSWORDS);
if(property == null || property.length() == 0) {
checkPasswords = DEFAULT_CHECK_PASSWORDS;
} else {
checkPasswords = property.equalsIgnoreCase("yes") || property.equalsIgnoreCase("true");
}
}
return checkPasswords;
}
public synchronized void enableCheckPasswords(final boolean enable) {
this.checkPasswords = enable;
}
private synchronized String getProperty(final String propertyName) {
if(loadedSecurityProperties == null) {
loadedSecurityProperties = new Properties();
try(final InputStream is = AccountImpl.class.getResourceAsStream("security.properties")) {
if(is != null) {
loadedSecurityProperties.load(is);
}
} catch(final IOException ioe) {
LOG.error("Unable to load security.properties, using defaults. " + ioe.getMessage(), ioe);
}
}
return loadedSecurityProperties.getProperty(propertyName);
}
}
//this method is used by Configurator
public final Group insertGroup(final int index, final String name) throws PermissionDeniedException {
//if we cant find the group in our own realm, try other realms
final Group group = Optional.ofNullable(getRealm().getGroup(name))
.orElse(getRealm().getSecurityManager().getGroup(name));
return insertGroup(index, group);
}
private Group insertGroup(final int index, final Group group) throws PermissionDeniedException {
if(group == null){
return null;
}
final Account user = getDatabase().getActiveBroker().getCurrentSubject();
group.assertCanModifyGroup(user);
if(!groups.contains(group)) {
groups.add(index, group);
if(SecurityManager.DBA_GROUP.equals(group.getName())) {
hasDbaRole = true;
}
}
return group;
}
}
| ljo/exist | src/org/exist/security/internal/AccountImpl.java | Java | lgpl-2.1 | 11,934 |
/*
[The "BSD licence"]
Copyright (c) 2004 Jean Bovet
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package edu.usfca.vas.window.fa;
import com.jgoodies.forms.factories.Borders;
import com.jgoodies.forms.factories.DefaultComponentFactory;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.*;
import edu.usfca.xj.appkit.frame.XJDialog;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WindowMachineFASettings extends XJDialog {
private WindowMachineFA wm = null;
public WindowMachineFASettings(WindowMachineFA wm) {
super(wm.getWindow().getJavaContainer(), true);
this.wm = wm;
initComponents();
setResizable(false);
resize();
setDefaultButton(okButton);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
close();
}
});
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
popValues();
close();
}
});
}
public void resize() {
Dimension d = dialogPane.getPreferredSize();
d.height += 30;
setSize(d);
}
public void pushValues() {
nameField.setText(wm.getTitle());
nameField.selectAll();
widthField.setText(String.valueOf(wm.getGraphicSize().width));
heightField.setText(String.valueOf(wm.getGraphicSize().height));
verticalSpinner.setValue(new Integer(wm.getVerticalMagnetics()));
horizontalSpinner.setValue(new Integer(wm.getHorizontalMagnetics()));
}
public void popValues() {
wm.setGraphicsSize(Integer.parseInt(widthField.getText()), Integer.parseInt(heightField.getText()));
wm.setTitle(nameField.getText());
Integer horizontal = (Integer)horizontalSpinner.getValue();
Integer vertical = (Integer)horizontalSpinner.getValue();
wm.setMagnetics(horizontal.intValue(), vertical.intValue());
}
public void display() {
pushValues();
center();
runModal();
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
DefaultComponentFactory compFactory = DefaultComponentFactory.getInstance();
dialogPane = new JPanel();
contentPane = new JPanel();
label1 = new JLabel();
nameField = new JTextField();
goodiesFormsSeparator2 = compFactory.createSeparator("Machine Size");
label2 = new JLabel();
widthField = new JTextField();
label3 = new JLabel();
heightField = new JTextField();
goodiesFormsSeparator1 = compFactory.createSeparator("Magnetic Layout Grid");
label6 = new JLabel();
verticalSpinner = new JSpinner();
label4 = new JLabel();
horizontalSpinner = new JSpinner();
buttonBar = new JPanel();
okButton = new JButton();
cancelButton = new JButton();
CellConstraints cc = new CellConstraints();
//======== this ========
setTitle("Machine Settings");
Container contentPane2 = getContentPane();
contentPane2.setLayout(new BorderLayout());
//======== dialogPane ========
{
dialogPane.setBorder(Borders.DIALOG_BORDER);
dialogPane.setPreferredSize(new Dimension(350, 300));
dialogPane.setLayout(new BorderLayout());
//======== contentPane ========
{
contentPane.setLayout(new FormLayout(
new ColumnSpec[] {
new ColumnSpec(Sizes.dluX(10)),
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
new ColumnSpec(Sizes.dluX(30)),
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
new ColumnSpec(ColumnSpec.FILL, Sizes.DEFAULT, FormSpec.DEFAULT_GROW),
FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
new ColumnSpec("10px")
},
new RowSpec[] {
FormFactory.DEFAULT_ROWSPEC,
FormFactory.LINE_GAP_ROWSPEC,
new RowSpec(Sizes.dluY(10)),
FormFactory.LINE_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.LINE_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.LINE_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.LINE_GAP_ROWSPEC,
new RowSpec(Sizes.dluY(10)),
FormFactory.LINE_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.LINE_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.LINE_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC
}));
//---- label1 ----
label1.setHorizontalAlignment(SwingConstants.RIGHT);
label1.setText("Name:");
contentPane.add(label1, cc.xy(3, 1));
contentPane.add(nameField, cc.xywh(5, 1, 3, 1));
contentPane.add(goodiesFormsSeparator2, cc.xywh(3, 5, 5, 1));
//---- label2 ----
label2.setHorizontalAlignment(SwingConstants.RIGHT);
label2.setText("Width:");
contentPane.add(label2, cc.xy(3, 7));
contentPane.add(widthField, cc.xywh(5, 7, 3, 1));
//---- label3 ----
label3.setHorizontalAlignment(SwingConstants.RIGHT);
label3.setText("Height:");
contentPane.add(label3, cc.xy(3, 9));
contentPane.add(heightField, cc.xywh(5, 9, 3, 1));
contentPane.add(goodiesFormsSeparator1, cc.xywh(3, 13, 5, 1));
//---- label6 ----
label6.setHorizontalAlignment(SwingConstants.RIGHT);
label6.setText("Vertical:");
contentPane.add(label6, cc.xy(3, 15));
//---- verticalSpinner ----
verticalSpinner.setModel(new SpinnerNumberModel(new Integer(0), new Integer(0), null, new Integer(1)));
contentPane.add(verticalSpinner, cc.xy(5, 15));
//---- label4 ----
label4.setHorizontalAlignment(SwingConstants.RIGHT);
label4.setText("Horizontal:");
contentPane.add(label4, cc.xy(3, 17));
//---- horizontalSpinner ----
horizontalSpinner.setModel(new SpinnerNumberModel(new Integer(1), new Integer(0), null, new Integer(1)));
contentPane.add(horizontalSpinner, cc.xy(5, 17));
}
dialogPane.add(contentPane, BorderLayout.CENTER);
//======== buttonBar ========
{
buttonBar.setBorder(Borders.BUTTON_BAR_GAP_BORDER);
buttonBar.setLayout(new FormLayout(
new ColumnSpec[] {
FormFactory.GLUE_COLSPEC,
FormFactory.BUTTON_COLSPEC,
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.BUTTON_COLSPEC
},
RowSpec.decodeSpecs("pref")));
//---- okButton ----
okButton.setText("OK");
buttonBar.add(okButton, cc.xy(2, 1));
//---- cancelButton ----
cancelButton.setText("Cancel");
buttonBar.add(cancelButton, cc.xy(4, 1));
}
dialogPane.add(buttonBar, BorderLayout.SOUTH);
}
contentPane2.add(dialogPane, BorderLayout.CENTER);
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
private JPanel dialogPane;
private JPanel contentPane;
private JLabel label1;
private JTextField nameField;
private JComponent goodiesFormsSeparator2;
private JLabel label2;
private JTextField widthField;
private JLabel label3;
private JTextField heightField;
private JComponent goodiesFormsSeparator1;
private JLabel label6;
private JSpinner verticalSpinner;
private JLabel label4;
private JSpinner horizontalSpinner;
private JPanel buttonBar;
private JButton okButton;
private JButton cancelButton;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
| jamesmowens/hit-automaton | src/edu/usfca/vas/window/fa/WindowMachineFASettings.java | Java | lgpl-2.1 | 10,270 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.undertow.sso.elytron;
import java.util.function.Supplier;
import io.undertow.server.session.SecureRandomSessionIdGenerator;
import io.undertow.server.session.SessionIdGenerator;
/**
* Adapts a {@link SessionIdGenerator} to {@link Supplier}.
* @author Paul Ferraro
*/
public class SingleSignOnIdentifierFactory implements Supplier<String> {
private final SessionIdGenerator generator;
public SingleSignOnIdentifierFactory() {
this(new SecureRandomSessionIdGenerator());
}
public SingleSignOnIdentifierFactory(SessionIdGenerator generator) {
this.generator = generator;
}
@Override
public String get() {
return this.generator.createSessionId();
}
}
| xasx/wildfly | undertow/src/main/java/org/wildfly/extension/undertow/sso/elytron/SingleSignOnIdentifierFactory.java | Java | lgpl-2.1 | 1,767 |
package util.events;
public class UsedReposChangedEvent extends Event {
}
| jinified/HubTurbo | src/main/java/util/events/UsedReposChangedEvent.java | Java | lgpl-3.0 | 75 |
/*
* Copyright (C) 2011 The MusicMod 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 org.yammp.dialog;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.util.MediaUtils;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnShowListener;
import android.database.Cursor;
import android.media.AudioManager;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class PlaylistDialog extends FragmentActivity implements Constants, TextWatcher,
OnCancelListener, OnShowListener {
private AlertDialog mPlaylistDialog;
private String action;
private EditText mPlaylist;
private String mDefaultName, mOriginalName;
private long mRenameId;
private long[] mList = new long[] {};
private OnClickListener mRenamePlaylistListener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String name = mPlaylist.getText().toString();
mUtils.renamePlaylist(mRenameId, name);
finish();
}
};
private OnClickListener mCreatePlaylistListener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String name = mPlaylist.getText().toString();
if (name != null && name.length() > 0) {
int id = idForplaylist(name);
if (id >= 0) {
mUtils.clearPlaylist(id);
mUtils.addToPlaylist(mList, id);
} else {
long new_id = mUtils.createPlaylist(name);
if (new_id >= 0) {
mUtils.addToPlaylist(mList, new_id);
}
}
finish();
}
}
};
private MediaUtils mUtils;
@Override
public void afterTextChanged(Editable s) {
// don't care about this one
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// don't care about this one
}
@Override
public void onCancel(DialogInterface dialog) {
if (dialog == mPlaylistDialog) {
finish();
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mUtils = ((YAMMPApplication) getApplication()).getMediaUtils();
setContentView(new LinearLayout(this));
action = getIntent().getAction();
mRenameId = icicle != null ? icicle.getLong(INTENT_KEY_RENAME) : getIntent().getLongExtra(
INTENT_KEY_RENAME, -1);
mList = icicle != null ? icicle.getLongArray(INTENT_KEY_LIST) : getIntent()
.getLongArrayExtra(INTENT_KEY_LIST);
if (INTENT_RENAME_PLAYLIST.equals(action)) {
mOriginalName = nameForId(mRenameId);
mDefaultName = icicle != null ? icicle.getString(INTENT_KEY_DEFAULT_NAME)
: mOriginalName;
} else if (INTENT_CREATE_PLAYLIST.equals(action)) {
mDefaultName = icicle != null ? icicle.getString(INTENT_KEY_DEFAULT_NAME)
: makePlaylistName();
mOriginalName = mDefaultName;
}
DisplayMetrics dm = new DisplayMetrics();
dm = getResources().getDisplayMetrics();
mPlaylistDialog = new AlertDialog.Builder(this).create();
mPlaylistDialog.setVolumeControlStream(AudioManager.STREAM_MUSIC);
if (action != null && mRenameId >= 0 && mOriginalName != null || mDefaultName != null) {
mPlaylist = new EditText(this);
mPlaylist.setSingleLine(true);
mPlaylist.setText(mDefaultName);
mPlaylist.setSelection(mDefaultName.length());
mPlaylist.addTextChangedListener(this);
mPlaylistDialog.setIcon(android.R.drawable.ic_dialog_info);
String promptformat;
String prompt = "";
if (INTENT_RENAME_PLAYLIST.equals(action)) {
promptformat = getString(R.string.rename_playlist_prompt);
prompt = String.format(promptformat, mOriginalName, mDefaultName);
} else if (INTENT_CREATE_PLAYLIST.equals(action)) {
promptformat = getString(R.string.create_playlist_prompt);
prompt = String.format(promptformat, mDefaultName);
}
mPlaylistDialog.setTitle(prompt);
mPlaylistDialog.setView(mPlaylist, (int) (8 * dm.density), (int) (8 * dm.density),
(int) (8 * dm.density), (int) (4 * dm.density));
if (INTENT_RENAME_PLAYLIST.equals(action)) {
mPlaylistDialog.setButton(Dialog.BUTTON_POSITIVE, getString(R.string.save),
mRenamePlaylistListener);
mPlaylistDialog.setOnShowListener(this);
} else if (INTENT_CREATE_PLAYLIST.equals(action)) {
mPlaylistDialog.setButton(Dialog.BUTTON_POSITIVE, getString(R.string.save),
mCreatePlaylistListener);
}
mPlaylistDialog.setButton(Dialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
mPlaylistDialog.setOnCancelListener(this);
mPlaylistDialog.show();
} else {
Toast.makeText(this, R.string.error_bad_parameters, Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
public void onPause() {
if (mPlaylistDialog != null && mPlaylistDialog.isShowing()) {
mPlaylistDialog.dismiss();
}
super.onPause();
}
@Override
public void onSaveInstanceState(Bundle outcicle) {
if (INTENT_RENAME_PLAYLIST.equals(action)) {
outcicle.putString(INTENT_KEY_DEFAULT_NAME, mPlaylist.getText().toString());
outcicle.putLong(INTENT_KEY_RENAME, mRenameId);
} else if (INTENT_CREATE_PLAYLIST.equals(action)) {
outcicle.putString(INTENT_KEY_DEFAULT_NAME, mPlaylist.getText().toString());
}
}
@Override
public void onShow(DialogInterface dialog) {
if (dialog == mPlaylistDialog) {
setSaveButton();
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
setSaveButton();
}
private int idForplaylist(String name) {
Cursor cursor = mUtils.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Playlists._ID }, MediaStore.Audio.Playlists.NAME
+ "=?", new String[] { name }, MediaStore.Audio.Playlists.NAME);
int id = -1;
if (cursor != null) {
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
id = cursor.getInt(0);
}
cursor.close();
}
return id;
}
private String makePlaylistName() {
String template = getString(R.string.new_playlist_name_template);
int num = 1;
String[] cols = new String[] { MediaStore.Audio.Playlists.NAME };
ContentResolver resolver = getContentResolver();
String whereclause = MediaStore.Audio.Playlists.NAME + " != ''";
Cursor cursor = resolver.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, cols,
whereclause, null, MediaStore.Audio.Playlists.NAME);
if (cursor == null) return null;
String suggestedname;
suggestedname = String.format(template, num++);
// Need to loop until we've made 1 full pass through without finding a
// match. Looping more than once shouldn't happen very often, but will
// happen if you have playlists named
// "New Playlist 1"/10/2/3/4/5/6/7/8/9, where making only one pass would
// result in "New Playlist 10" being erroneously picked for the new
// name.
boolean done = false;
while (!done) {
done = true;
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
String playlistname = cursor.getString(0);
if (playlistname.compareToIgnoreCase(suggestedname) == 0) {
suggestedname = String.format(template, num++);
done = false;
}
cursor.moveToNext();
}
}
cursor.close();
return suggestedname;
};
private String nameForId(long id) {
Cursor cursor = mUtils.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Playlists.NAME }, MediaStore.Audio.Playlists._ID
+ "=?", new String[] { Long.valueOf(id).toString() },
MediaStore.Audio.Playlists.NAME);
String name = null;
if (cursor != null) {
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
name = cursor.getString(0);
}
cursor.close();
}
return name;
}
private void setSaveButton() {
String typedname = mPlaylist.getText().toString();
Button button = mPlaylistDialog.getButton(Dialog.BUTTON_POSITIVE);
if (button == null) return;
if (typedname.trim().length() == 0 || PLAYLIST_NAME_FAVORITES.equals(typedname)) {
button.setEnabled(false);
} else {
button.setEnabled(true);
if (idForplaylist(typedname) >= 0 && !mOriginalName.equals(typedname)) {
button.setText(R.string.overwrite);
} else {
button.setText(R.string.save);
}
}
button.invalidate();
}
@Override
protected void onResume() {
super.onResume();
if (mPlaylistDialog != null) {
mPlaylistDialog.show();
}
}
}
| archeng504/yammp | src/org/yammp/dialog/PlaylistDialog.java | Java | lgpl-3.0 | 9,445 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.federation.store;
import static org.apache.hadoop.hdfs.server.federation.FederationTestUtils.NAMENODES;
import static org.apache.hadoop.hdfs.server.federation.FederationTestUtils.NAMESERVICES;
import static org.apache.hadoop.hdfs.server.federation.FederationTestUtils.ROUTERS;
import static org.apache.hadoop.hdfs.server.federation.FederationTestUtils.verifyException;
import static org.apache.hadoop.hdfs.server.federation.store.FederationStateStoreTestUtils.clearRecords;
import static org.apache.hadoop.hdfs.server.federation.store.FederationStateStoreTestUtils.createMockRegistrationForNamenode;
import static org.apache.hadoop.hdfs.server.federation.store.FederationStateStoreTestUtils.synchronizeRecords;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.hadoop.hdfs.server.federation.resolver.FederationNamenodeServiceState;
import org.apache.hadoop.hdfs.server.federation.resolver.FederationNamespaceInfo;
import org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys;
import org.apache.hadoop.hdfs.server.federation.store.protocol.GetNamenodeRegistrationsRequest;
import org.apache.hadoop.hdfs.server.federation.store.protocol.GetNamenodeRegistrationsResponse;
import org.apache.hadoop.hdfs.server.federation.store.protocol.GetNamespaceInfoRequest;
import org.apache.hadoop.hdfs.server.federation.store.protocol.GetNamespaceInfoResponse;
import org.apache.hadoop.hdfs.server.federation.store.protocol.NamenodeHeartbeatRequest;
import org.apache.hadoop.hdfs.server.federation.store.protocol.NamenodeHeartbeatResponse;
import org.apache.hadoop.hdfs.server.federation.store.protocol.UpdateNamenodeRegistrationRequest;
import org.apache.hadoop.hdfs.server.federation.store.records.MembershipState;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.util.Time;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Test the basic {@link MembershipStore} membership functionality.
*/
public class TestStateStoreMembershipState extends TestStateStoreBase {
private static MembershipStore membershipStore;
@BeforeClass
public static void create() {
// Reduce expirations to 2 seconds
getConf().setLong(
RBFConfigKeys.FEDERATION_STORE_MEMBERSHIP_EXPIRATION_MS,
TimeUnit.SECONDS.toMillis(2));
// Set deletion time to 2 seconds
getConf().setLong(
RBFConfigKeys.FEDERATION_STORE_MEMBERSHIP_EXPIRATION_DELETION_MS,
TimeUnit.SECONDS.toMillis(2));
}
@Before
public void setup() throws IOException, InterruptedException {
membershipStore =
getStateStore().getRegisteredRecordStore(MembershipStore.class);
// Clear NN registrations
assertTrue(clearRecords(getStateStore(), MembershipState.class));
}
@Test
public void testNamenodeStateOverride() throws Exception {
// Populate the state store
// 1) ns0:nn0 - Standby
String ns = "ns0";
String nn = "nn0";
MembershipState report = createRegistration(
ns, nn, ROUTERS[1], FederationNamenodeServiceState.STANDBY);
assertTrue(namenodeHeartbeat(report));
// Load data into cache and calculate quorum
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
MembershipState existingState = getNamenodeRegistration(ns, nn);
assertEquals(
FederationNamenodeServiceState.STANDBY, existingState.getState());
// Override cache
UpdateNamenodeRegistrationRequest request =
UpdateNamenodeRegistrationRequest.newInstance(
ns, nn, FederationNamenodeServiceState.ACTIVE);
assertTrue(membershipStore.updateNamenodeRegistration(request).getResult());
MembershipState newState = getNamenodeRegistration(ns, nn);
assertEquals(FederationNamenodeServiceState.ACTIVE, newState.getState());
// Override cache
UpdateNamenodeRegistrationRequest request1 =
UpdateNamenodeRegistrationRequest.newInstance(ns, nn,
FederationNamenodeServiceState.OBSERVER);
assertTrue(
membershipStore.updateNamenodeRegistration(request1).getResult());
MembershipState newState1 = getNamenodeRegistration(ns, nn);
assertEquals(FederationNamenodeServiceState.OBSERVER, newState1.getState());
}
@Test
public void testStateStoreDisconnected() throws Exception {
// Close the data store driver
getStateStore().closeDriver();
assertFalse(getStateStore().isDriverReady());
NamenodeHeartbeatRequest hbRequest = NamenodeHeartbeatRequest.newInstance();
hbRequest.setNamenodeMembership(
createMockRegistrationForNamenode(
"test", "test", FederationNamenodeServiceState.UNAVAILABLE));
verifyException(membershipStore, "namenodeHeartbeat",
StateStoreUnavailableException.class,
new Class[] {NamenodeHeartbeatRequest.class},
new Object[] {hbRequest });
// Information from cache, no exception should be triggered for these
// TODO - should cached info expire at some point?
GetNamenodeRegistrationsRequest getRequest =
GetNamenodeRegistrationsRequest.newInstance();
verifyException(membershipStore,
"getNamenodeRegistrations", null,
new Class[] {GetNamenodeRegistrationsRequest.class},
new Object[] {getRequest});
verifyException(membershipStore,
"getExpiredNamenodeRegistrations", null,
new Class[] {GetNamenodeRegistrationsRequest.class},
new Object[] {getRequest});
UpdateNamenodeRegistrationRequest overrideRequest =
UpdateNamenodeRegistrationRequest.newInstance();
verifyException(membershipStore,
"updateNamenodeRegistration", null,
new Class[] {UpdateNamenodeRegistrationRequest.class},
new Object[] {overrideRequest});
}
private void registerAndLoadRegistrations(
List<MembershipState> registrationList) throws IOException {
// Populate
assertTrue(synchronizeRecords(
getStateStore(), registrationList, MembershipState.class));
// Load into cache
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
}
private MembershipState createRegistration(String ns, String nn,
String router, FederationNamenodeServiceState state) throws IOException {
MembershipState record = MembershipState.newInstance(
router, ns,
nn, "testcluster", "testblock-" + ns, "testrpc-"+ ns + nn,
"testservice-"+ ns + nn, "testlifeline-"+ ns + nn,
"http", "testweb-" + ns + nn, state, false);
return record;
}
@Test
public void testRegistrationMajorityQuorum()
throws InterruptedException, IOException {
// Populate the state store with a set of non-matching elements
// 1) ns0:nn0 - Standby (newest)
// 2) ns0:nn0 - Active (oldest)
// 3) ns0:nn0 - Active (2nd oldest)
// 4) ns0:nn0 - Active (3nd oldest element, newest active element)
// Verify the selected entry is the newest majority opinion (4)
String ns = "ns0";
String nn = "nn0";
// Active - oldest
MembershipState report = createRegistration(
ns, nn, ROUTERS[1], FederationNamenodeServiceState.ACTIVE);
assertTrue(namenodeHeartbeat(report));
Thread.sleep(1000);
// Active - 2nd oldest
report = createRegistration(
ns, nn, ROUTERS[2], FederationNamenodeServiceState.ACTIVE);
assertTrue(namenodeHeartbeat(report));
Thread.sleep(1000);
// Active - 3rd oldest, newest active element
report = createRegistration(
ns, nn, ROUTERS[3], FederationNamenodeServiceState.ACTIVE);
assertTrue(namenodeHeartbeat(report));
// standby - newest overall
report = createRegistration(
ns, nn, ROUTERS[0], FederationNamenodeServiceState.STANDBY);
assertTrue(namenodeHeartbeat(report));
// Load and calculate quorum
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
// Verify quorum entry
MembershipState quorumEntry = getNamenodeRegistration(
report.getNameserviceId(), report.getNamenodeId());
assertNotNull(quorumEntry);
assertEquals(quorumEntry.getRouterId(), ROUTERS[3]);
}
@Test
public void testRegistrationQuorumExcludesExpired()
throws InterruptedException, IOException {
// Populate the state store with some expired entries and verify the expired
// entries are ignored.
// 1) ns0:nn0 - Active
// 2) ns0:nn0 - Expired
// 3) ns0:nn0 - Expired
// 4) ns0:nn0 - Expired
// Verify the selected entry is the active entry
List<MembershipState> registrationList = new ArrayList<>();
String ns = "ns0";
String nn = "nn0";
String rpcAddress = "testrpcaddress";
String serviceAddress = "testserviceaddress";
String lifelineAddress = "testlifelineaddress";
String blockPoolId = "testblockpool";
String clusterId = "testcluster";
String webScheme = "http";
String webAddress = "testwebaddress";
boolean safemode = false;
// Active
MembershipState record = MembershipState.newInstance(
ROUTERS[0], ns, nn, clusterId, blockPoolId,
rpcAddress, serviceAddress, lifelineAddress, webScheme,
webAddress, FederationNamenodeServiceState.ACTIVE, safemode);
registrationList.add(record);
// Expired
record = MembershipState.newInstance(
ROUTERS[1], ns, nn, clusterId, blockPoolId,
rpcAddress, serviceAddress, lifelineAddress, webScheme,
webAddress, FederationNamenodeServiceState.EXPIRED, safemode);
registrationList.add(record);
// Expired
record = MembershipState.newInstance(
ROUTERS[2], ns, nn, clusterId, blockPoolId,
rpcAddress, serviceAddress, lifelineAddress, webScheme, webAddress,
FederationNamenodeServiceState.EXPIRED, safemode);
registrationList.add(record);
// Expired
record = MembershipState.newInstance(
ROUTERS[3], ns, nn, clusterId, blockPoolId,
rpcAddress, serviceAddress, lifelineAddress, webScheme, webAddress,
FederationNamenodeServiceState.EXPIRED, safemode);
registrationList.add(record);
registerAndLoadRegistrations(registrationList);
// Verify quorum entry chooses active membership
MembershipState quorumEntry = getNamenodeRegistration(
record.getNameserviceId(), record.getNamenodeId());
assertNotNull(quorumEntry);
assertEquals(ROUTERS[0], quorumEntry.getRouterId());
}
@Test
public void testRegistrationQuorumAllExpired() throws IOException {
// 1) ns0:nn0 - Expired (oldest)
// 2) ns0:nn0 - Expired
// 3) ns0:nn0 - Expired
// 4) ns0:nn0 - Expired
// Verify no entry is either selected or cached
List<MembershipState> registrationList = new ArrayList<>();
String ns = NAMESERVICES[0];
String nn = NAMENODES[0];
String rpcAddress = "testrpcaddress";
String serviceAddress = "testserviceaddress";
String lifelineAddress = "testlifelineaddress";
String blockPoolId = "testblockpool";
String clusterId = "testcluster";
String webScheme = "http";
String webAddress = "testwebaddress";
boolean safemode = false;
long startingTime = Time.now();
// Expired
MembershipState record = MembershipState.newInstance(
ROUTERS[0], ns, nn, clusterId, blockPoolId,
rpcAddress, webAddress, lifelineAddress, webScheme, webAddress,
FederationNamenodeServiceState.EXPIRED, safemode);
record.setDateModified(startingTime - 10000);
registrationList.add(record);
// Expired
record = MembershipState.newInstance(
ROUTERS[1], ns, nn, clusterId, blockPoolId,
rpcAddress, serviceAddress, lifelineAddress, webScheme, webAddress,
FederationNamenodeServiceState.EXPIRED, safemode);
record.setDateModified(startingTime);
registrationList.add(record);
// Expired
record = MembershipState.newInstance(
ROUTERS[2], ns, nn, clusterId, blockPoolId,
rpcAddress, serviceAddress, lifelineAddress, webScheme, webAddress,
FederationNamenodeServiceState.EXPIRED, safemode);
record.setDateModified(startingTime);
registrationList.add(record);
// Expired
record = MembershipState.newInstance(
ROUTERS[3], ns, nn, clusterId, blockPoolId,
rpcAddress, serviceAddress, lifelineAddress, webScheme, webAddress,
FederationNamenodeServiceState.EXPIRED, safemode);
record.setDateModified(startingTime);
registrationList.add(record);
registerAndLoadRegistrations(registrationList);
// Verify no entry is found for this nameservice
assertNull(getNamenodeRegistration(
record.getNameserviceId(), record.getNamenodeId()));
}
@Test
public void testRegistrationNoQuorum()
throws InterruptedException, IOException {
// Populate the state store with a set of non-matching elements
// 1) ns0:nn0 - Standby (newest)
// 2) ns0:nn0 - Standby (oldest)
// 3) ns0:nn0 - Active (2nd oldest)
// 4) ns0:nn0 - Active (3nd oldest element, newest active element)
// Verify the selected entry is the newest entry (1)
MembershipState report1 = createRegistration(
NAMESERVICES[0], NAMENODES[0], ROUTERS[1],
FederationNamenodeServiceState.STANDBY);
assertTrue(namenodeHeartbeat(report1));
Thread.sleep(100);
MembershipState report2 = createRegistration(
NAMESERVICES[0], NAMENODES[0], ROUTERS[2],
FederationNamenodeServiceState.ACTIVE);
assertTrue(namenodeHeartbeat(report2));
Thread.sleep(100);
MembershipState report3 = createRegistration(
NAMESERVICES[0], NAMENODES[0], ROUTERS[3],
FederationNamenodeServiceState.ACTIVE);
assertTrue(namenodeHeartbeat(report3));
Thread.sleep(100);
MembershipState report4 = createRegistration(
NAMESERVICES[0], NAMENODES[0], ROUTERS[0],
FederationNamenodeServiceState.STANDBY);
assertTrue(namenodeHeartbeat(report4));
// Load and calculate quorum
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
// Verify quorum entry uses the newest data, even though it is standby
MembershipState quorumEntry = getNamenodeRegistration(
report1.getNameserviceId(), report1.getNamenodeId());
assertNotNull(quorumEntry);
assertEquals(ROUTERS[0], quorumEntry.getRouterId());
assertEquals(
FederationNamenodeServiceState.STANDBY, quorumEntry.getState());
}
@Test
public void testRegistrationExpiredAndDeletion()
throws InterruptedException, IOException, TimeoutException {
// Populate the state store with a single NN element
// 1) ns0:nn0 - Active
// Wait for the entry to expire without heartbeating
// Verify the NN entry is populated as EXPIRED internally in the state store
MembershipState report = createRegistration(
NAMESERVICES[0], NAMENODES[0], ROUTERS[0],
FederationNamenodeServiceState.ACTIVE);
assertTrue(namenodeHeartbeat(report));
// Load cache
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
// Verify quorum and entry
MembershipState quorumEntry = getNamenodeRegistration(
report.getNameserviceId(), report.getNamenodeId());
assertNotNull(quorumEntry);
assertEquals(ROUTERS[0], quorumEntry.getRouterId());
assertEquals(FederationNamenodeServiceState.ACTIVE, quorumEntry.getState());
quorumEntry = getExpiredNamenodeRegistration(report.getNameserviceId(),
report.getNamenodeId());
assertNull(quorumEntry);
// Wait past expiration (set in conf to 2 seconds)
GenericTestUtils.waitFor(() -> {
try {
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
// Verify entry is expired and is no longer in the cache
return getNamenodeRegistration(NAMESERVICES[0], NAMENODES[0]) == null;
} catch (IOException e) {
return false;
}
}, 100, 3000);
// Verify entry is in expired membership records
quorumEntry = getExpiredNamenodeRegistration(NAMESERVICES[0], NAMENODES[0]);
assertNotNull(quorumEntry);
// Verify entry is now expired and can't be used by RPC service
quorumEntry = getNamenodeRegistration(
report.getNameserviceId(), report.getNamenodeId());
assertNull(quorumEntry);
quorumEntry = getExpiredNamenodeRegistration(
report.getNameserviceId(), report.getNamenodeId());
assertNotNull(quorumEntry);
// Heartbeat again, updates dateModified
assertTrue(namenodeHeartbeat(report));
// Reload cache
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
// Verify updated entry marked as active and is accessible to RPC server
quorumEntry = getNamenodeRegistration(
report.getNameserviceId(), report.getNamenodeId());
assertNotNull(quorumEntry);
assertEquals(ROUTERS[0], quorumEntry.getRouterId());
assertEquals(FederationNamenodeServiceState.ACTIVE, quorumEntry.getState());
quorumEntry = getExpiredNamenodeRegistration(
report.getNameserviceId(), report.getNamenodeId());
assertNull(quorumEntry);
// Wait past expiration (set in conf to 2 seconds)
GenericTestUtils.waitFor(() -> {
try {
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
// Verify entry is expired and is no longer in the cache
return getNamenodeRegistration(NAMESERVICES[0], NAMENODES[0]) == null;
} catch (IOException e) {
return false;
}
}, 100, 3000);
// Verify entry is in expired membership records
quorumEntry = getExpiredNamenodeRegistration(NAMESERVICES[0], NAMENODES[0]);
assertNotNull(quorumEntry);
// Wait past deletion (set in conf to 2 seconds)
GenericTestUtils.waitFor(() -> {
try {
assertTrue(getStateStore().loadCache(MembershipStore.class, true));
// Verify entry is deleted from even the expired membership records
return getExpiredNamenodeRegistration(NAMESERVICES[0], NAMENODES[0])
== null;
} catch (IOException e) {
return false;
}
}, 100, 3000);
}
@Test
public void testNamespaceInfoWithUnavailableNameNodeRegistration()
throws IOException {
// Populate the state store with one ACTIVE NameNode entry
// and one UNAVAILABLE NameNode entry
// 1) ns0:nn0 - ACTIVE
// 2) ns0:nn1 - UNAVAILABLE
List<MembershipState> registrationList = new ArrayList<>();
String router = ROUTERS[0];
String ns = NAMESERVICES[0];
String rpcAddress = "testrpcaddress";
String serviceAddress = "testserviceaddress";
String lifelineAddress = "testlifelineaddress";
String blockPoolId = "testblockpool";
String clusterId = "testcluster";
String webScheme = "http";
String webAddress = "testwebaddress";
boolean safemode = false;
MembershipState record = MembershipState.newInstance(
router, ns, NAMENODES[0], clusterId, blockPoolId,
rpcAddress, serviceAddress, lifelineAddress, webScheme,
webAddress, FederationNamenodeServiceState.ACTIVE, safemode);
registrationList.add(record);
// Set empty clusterId and blockPoolId for UNAVAILABLE NameNode
record = MembershipState.newInstance(
router, ns, NAMENODES[1], "", "",
rpcAddress, serviceAddress, lifelineAddress, webScheme,
webAddress, FederationNamenodeServiceState.UNAVAILABLE, safemode);
registrationList.add(record);
registerAndLoadRegistrations(registrationList);
GetNamespaceInfoRequest request = GetNamespaceInfoRequest.newInstance();
GetNamespaceInfoResponse response
= membershipStore.getNamespaceInfo(request);
Set<FederationNamespaceInfo> namespaces = response.getNamespaceInfo();
// Verify only one namespace is registered
assertEquals(1, namespaces.size());
// Verify the registered namespace has a valid pair of clusterId
// and blockPoolId derived from ACTIVE NameNode
FederationNamespaceInfo namespace = namespaces.iterator().next();
assertEquals(ns, namespace.getNameserviceId());
assertEquals(clusterId, namespace.getClusterId());
assertEquals(blockPoolId, namespace.getBlockPoolId());
}
/**
* Get a single namenode membership record from the store.
*
* @param nsId The HDFS nameservice ID to search for
* @param nnId The HDFS namenode ID to search for
* @return The single NamenodeMembershipRecord that matches the query or null
* if not found.
* @throws IOException if the query could not be executed.
*/
private MembershipState getNamenodeRegistration(
final String nsId, final String nnId) throws IOException {
MembershipState partial = MembershipState.newInstance();
partial.setNameserviceId(nsId);
partial.setNamenodeId(nnId);
GetNamenodeRegistrationsRequest request =
GetNamenodeRegistrationsRequest.newInstance(partial);
GetNamenodeRegistrationsResponse response =
membershipStore.getNamenodeRegistrations(request);
List<MembershipState> results = response.getNamenodeMemberships();
if (results != null && results.size() == 1) {
MembershipState record = results.get(0);
return record;
}
return null;
}
/**
* Get a single expired namenode membership record from the store.
*
* @param nsId The HDFS nameservice ID to search for
* @param nnId The HDFS namenode ID to search for
* @return The single expired NamenodeMembershipRecord that matches the query
* or null if not found.
* @throws IOException if the query could not be executed.
*/
private MembershipState getExpiredNamenodeRegistration(
final String nsId, final String nnId) throws IOException {
MembershipState partial = MembershipState.newInstance();
partial.setNameserviceId(nsId);
partial.setNamenodeId(nnId);
GetNamenodeRegistrationsRequest request =
GetNamenodeRegistrationsRequest.newInstance(partial);
GetNamenodeRegistrationsResponse response =
membershipStore.getExpiredNamenodeRegistrations(request);
List<MembershipState> results = response.getNamenodeMemberships();
if (results != null && results.size() == 1) {
MembershipState record = results.get(0);
return record;
}
return null;
}
/**
* Register a namenode heartbeat with the state store.
*
* @param store FederationMembershipStateStore instance to retrieve the
* membership data records.
* @param namenode A fully populated namenode membership record to be
* committed to the data store.
* @return True if successful, false otherwise.
* @throws IOException if the state store query could not be performed.
*/
private boolean namenodeHeartbeat(MembershipState namenode)
throws IOException {
NamenodeHeartbeatRequest request =
NamenodeHeartbeatRequest.newInstance(namenode);
NamenodeHeartbeatResponse response =
membershipStore.namenodeHeartbeat(request);
return response.getResult();
}
} | apurtell/hadoop | hadoop-hdfs-project/hadoop-hdfs-rbf/src/test/java/org/apache/hadoop/hdfs/server/federation/store/TestStateStoreMembershipState.java | Java | apache-2.0 | 24,181 |
//// [objectBindingPatternKeywordIdentifiers01.ts]
var { while } = { while: 1 }
//// [objectBindingPatternKeywordIdentifiers01.js]
var = { "while": 1 }["while"];
| jwbay/TypeScript | tests/baselines/reference/objectBindingPatternKeywordIdentifiers01.js | JavaScript | apache-2.0 | 170 |
package face
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// PersonClient is the an API for face detection, verification, and identification.
type PersonClient struct {
ManagementClient
}
// NewPersonClient creates an instance of the PersonClient client.
func NewPersonClient(subscriptionKey string, azureRegion AzureRegions) PersonClient {
return PersonClient{New(subscriptionKey, azureRegion)}
}
// AddFace add a representative face to a person for identification. The input face is specified as an image with a
// targetFace rectangle.
//
// personGroupID is specifying the person group containing the target person. personID is target person that the face
// is added to. userData is user-specified data about the target face to add for any purpose. The maximum length is
// 1KB. targetFace is a face rectangle to specify the target face to be added to a person in the format of
// "targetFace=left,top,width,height". E.g. "targetFace=10,10,100,100". If there is more than one face in the image,
// targetFace is required to specify which face to add. No targetFace means there is only one face detected in the
// entire image.
func (client PersonClient) AddFace(personGroupID string, personID string, userData string, targetFace string) (result autorest.Response, err error) {
req, err := client.AddFacePreparer(personGroupID, personID, userData, targetFace)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "AddFace", nil, "Failure preparing request")
return
}
resp, err := client.AddFaceSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.PersonClient", "AddFace", resp, "Failure sending request")
return
}
result, err = client.AddFaceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "AddFace", resp, "Failure responding to request")
}
return
}
// AddFacePreparer prepares the AddFace request.
func (client PersonClient) AddFacePreparer(personGroupID string, personID string, userData string, targetFace string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
"personId": autorest.Encode("path", personID),
}
queryParameters := map[string]interface{}{}
if len(userData) > 0 {
queryParameters["userData"] = autorest.Encode("query", userData)
}
if len(targetFace) > 0 {
queryParameters["targetFace"] = autorest.Encode("query", targetFace)
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}/persistedFaces", pathParameters),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("Ocp-Apim-Subscription-Key", client.SubscriptionKey))
return preparer.Prepare(&http.Request{})
}
// AddFaceSender sends the AddFace request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) AddFaceSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req)
}
// AddFaceResponder handles the response to the AddFace request. The method always
// closes the http.Response Body.
func (client PersonClient) AddFaceResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
// AddFaceFromStream add a representative face to a person for identification. The input face is specified as an image
// with a targetFace rectangle.
//
// personGroupID is specifying the person group containing the target person. personID is target person that the face
// is added to. userData is user-specified data about the target face to add for any purpose. The maximum length is
// 1KB. targetFace is a face rectangle to specify the target face to be added to a person, in the format of
// "targetFace=left,top,width,height". E.g. "targetFace=10,10,100,100". If there is more than one face in the image,
// targetFace is required to specify which face to add. No targetFace means there is only one face detected in the
// entire image.
func (client PersonClient) AddFaceFromStream(personGroupID string, personID string, userData string, targetFace string) (result autorest.Response, err error) {
req, err := client.AddFaceFromStreamPreparer(personGroupID, personID, userData, targetFace)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "AddFaceFromStream", nil, "Failure preparing request")
return
}
resp, err := client.AddFaceFromStreamSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.PersonClient", "AddFaceFromStream", resp, "Failure sending request")
return
}
result, err = client.AddFaceFromStreamResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "AddFaceFromStream", resp, "Failure responding to request")
}
return
}
// AddFaceFromStreamPreparer prepares the AddFaceFromStream request.
func (client PersonClient) AddFaceFromStreamPreparer(personGroupID string, personID string, userData string, targetFace string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
"personId": autorest.Encode("path", personID),
}
queryParameters := map[string]interface{}{}
if len(userData) > 0 {
queryParameters["userData"] = autorest.Encode("query", userData)
}
if len(targetFace) > 0 {
queryParameters["targetFace"] = autorest.Encode("query", targetFace)
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}/persistedFaces", pathParameters),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("Ocp-Apim-Subscription-Key", client.SubscriptionKey))
return preparer.Prepare(&http.Request{})
}
// AddFaceFromStreamSender sends the AddFaceFromStream request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) AddFaceFromStreamSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req)
}
// AddFaceFromStreamResponder handles the response to the AddFaceFromStream request. The method always
// closes the http.Response Body.
func (client PersonClient) AddFaceFromStreamResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
// Create create a new person in a specified person group.
//
// personGroupID is specifying the target person group to create the person.
func (client PersonClient) Create(personGroupID string, body CreatePersonRequest) (result CreatePersonResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: body,
Constraints: []validation.Constraint{{Target: "body.Name", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "body.Name", Name: validation.MaxLength, Rule: 128, Chain: nil}}},
{Target: "body.UserData", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "body.UserData", Name: validation.MaxLength, Rule: 16384, Chain: nil}}}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "face.PersonClient", "Create")
}
req, err := client.CreatePreparer(personGroupID, body)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "Create", nil, "Failure preparing request")
return
}
resp, err := client.CreateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.PersonClient", "Create", resp, "Failure sending request")
return
}
result, err = client.CreateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "Create", resp, "Failure responding to request")
}
return
}
// CreatePreparer prepares the Create request.
func (client PersonClient) CreatePreparer(personGroupID string, body CreatePersonRequest) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPost(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons", pathParameters),
autorest.WithJSON(body),
autorest.WithHeader("Ocp-Apim-Subscription-Key", client.SubscriptionKey))
return preparer.Prepare(&http.Request{})
}
// CreateSender sends the Create request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) CreateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req)
}
// CreateResponder handles the response to the Create request. The method always
// closes the http.Response Body.
func (client PersonClient) CreateResponder(resp *http.Response) (result CreatePersonResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete delete an existing person from a person group. Persisted face images of the person will also be deleted.
//
// personGroupID is specifying the person group containing the person. personID is the target personId to delete.
func (client PersonClient) Delete(personGroupID string, personID string) (result autorest.Response, err error) {
req, err := client.DeletePreparer(personGroupID, personID)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.PersonClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "Delete", resp, "Failure responding to request")
}
return
}
// DeletePreparer prepares the Delete request.
func (client PersonClient) DeletePreparer(personGroupID string, personID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
"personId": autorest.Encode("path", personID),
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}", pathParameters),
autorest.WithHeader("Ocp-Apim-Subscription-Key", client.SubscriptionKey))
return preparer.Prepare(&http.Request{})
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) DeleteSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req)
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client PersonClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
// DeleteFace delete a face from a person. Relative image for the persisted face will also be deleted.
//
// personGroupID is specifying the person group containing the target person. personID is specifying the person that
// the target persisted face belong to. persistedFaceID is the persisted face to remove.
func (client PersonClient) DeleteFace(personGroupID string, personID string, persistedFaceID string) (result autorest.Response, err error) {
req, err := client.DeleteFacePreparer(personGroupID, personID, persistedFaceID)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "DeleteFace", nil, "Failure preparing request")
return
}
resp, err := client.DeleteFaceSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.PersonClient", "DeleteFace", resp, "Failure sending request")
return
}
result, err = client.DeleteFaceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "DeleteFace", resp, "Failure responding to request")
}
return
}
// DeleteFacePreparer prepares the DeleteFace request.
func (client PersonClient) DeleteFacePreparer(personGroupID string, personID string, persistedFaceID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"persistedFaceId": autorest.Encode("path", persistedFaceID),
"personGroupId": autorest.Encode("path", personGroupID),
"personId": autorest.Encode("path", personID),
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}/persistedFaces/{persistedFaceId}", pathParameters),
autorest.WithHeader("Ocp-Apim-Subscription-Key", client.SubscriptionKey))
return preparer.Prepare(&http.Request{})
}
// DeleteFaceSender sends the DeleteFace request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) DeleteFaceSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req)
}
// DeleteFaceResponder handles the response to the DeleteFace request. The method always
// closes the http.Response Body.
func (client PersonClient) DeleteFaceResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
// Get retrieve a person's information, including registered persisted faces, name and userData.
//
// personGroupID is specifying the person group containing the target person. personID is specifying the target person.
func (client PersonClient) Get(personGroupID string, personID string) (result PersonResult, err error) {
req, err := client.GetPreparer(personGroupID, personID)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.PersonClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client PersonClient) GetPreparer(personGroupID string, personID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
"personId": autorest.Encode("path", personID),
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}", pathParameters),
autorest.WithHeader("Ocp-Apim-Subscription-Key", client.SubscriptionKey))
return preparer.Prepare(&http.Request{})
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req)
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client PersonClient) GetResponder(resp *http.Response) (result PersonResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetFace retrieve information about a persisted face (specified by persistedFaceId, personId and its belonging
// personGroupId).
//
// personGroupID is specifying the person group containing the target person. personID is specifying the target person
// that the face belongs to. persistedFaceID is the persistedFaceId of the target persisted face of the person.
func (client PersonClient) GetFace(personGroupID string, personID string, persistedFaceID string) (result PersonFaceResult, err error) {
req, err := client.GetFacePreparer(personGroupID, personID, persistedFaceID)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "GetFace", nil, "Failure preparing request")
return
}
resp, err := client.GetFaceSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.PersonClient", "GetFace", resp, "Failure sending request")
return
}
result, err = client.GetFaceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "GetFace", resp, "Failure responding to request")
}
return
}
// GetFacePreparer prepares the GetFace request.
func (client PersonClient) GetFacePreparer(personGroupID string, personID string, persistedFaceID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"persistedFaceId": autorest.Encode("path", persistedFaceID),
"personGroupId": autorest.Encode("path", personGroupID),
"personId": autorest.Encode("path", personID),
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}/persistedFaces/{persistedFaceId}", pathParameters),
autorest.WithHeader("Ocp-Apim-Subscription-Key", client.SubscriptionKey))
return preparer.Prepare(&http.Request{})
}
// GetFaceSender sends the GetFace request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) GetFaceSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req)
}
// GetFaceResponder handles the response to the GetFace request. The method always
// closes the http.Response Body.
func (client PersonClient) GetFaceResponder(resp *http.Response) (result PersonFaceResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List list all persons in a person group, and retrieve person information (including personId, name, userData and
// persistedFaceIds of registered faces of the person).
//
// personGroupID is personGroupId of the target person group.
func (client PersonClient) List(personGroupID string) (result ListPersonResult, err error) {
req, err := client.ListPreparer(personGroupID)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "face.PersonClient", "List", resp, "Failure sending request")
return
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client PersonClient) ListPreparer(personGroupID string) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons", pathParameters),
autorest.WithHeader("Ocp-Apim-Subscription-Key", client.SubscriptionKey))
return preparer.Prepare(&http.Request{})
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req)
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client PersonClient) ListResponder(resp *http.Response) (result ListPersonResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Update update name or userData of a person.
//
// personGroupID is specifying the person group containing the target person. personID is personId of the target
// person.
func (client PersonClient) Update(personGroupID string, personID string, body CreatePersonRequest) (result autorest.Response, err error) {
req, err := client.UpdatePreparer(personGroupID, personID, body)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "Update", nil, "Failure preparing request")
return
}
resp, err := client.UpdateSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.PersonClient", "Update", resp, "Failure sending request")
return
}
result, err = client.UpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "Update", resp, "Failure responding to request")
}
return
}
// UpdatePreparer prepares the Update request.
func (client PersonClient) UpdatePreparer(personGroupID string, personID string, body CreatePersonRequest) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"personGroupId": autorest.Encode("path", personGroupID),
"personId": autorest.Encode("path", personID),
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPatch(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}", pathParameters),
autorest.WithJSON(body),
autorest.WithHeader("Ocp-Apim-Subscription-Key", client.SubscriptionKey))
return preparer.Prepare(&http.Request{})
}
// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) UpdateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req)
}
// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client PersonClient) UpdateResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
// UpdateFace update a person persisted face's userData field.
//
// personGroupID is specifying the person group containing the target person. personID is personId of the target
// person. persistedFaceID is persistedFaceId of target face, which is persisted and will not expire.
func (client PersonClient) UpdateFace(personGroupID string, personID string, persistedFaceID string, body UpdatePersonFaceDataRequest) (result autorest.Response, err error) {
req, err := client.UpdateFacePreparer(personGroupID, personID, persistedFaceID, body)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "UpdateFace", nil, "Failure preparing request")
return
}
resp, err := client.UpdateFaceSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "face.PersonClient", "UpdateFace", resp, "Failure sending request")
return
}
result, err = client.UpdateFaceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "face.PersonClient", "UpdateFace", resp, "Failure responding to request")
}
return
}
// UpdateFacePreparer prepares the UpdateFace request.
func (client PersonClient) UpdateFacePreparer(personGroupID string, personID string, persistedFaceID string, body UpdatePersonFaceDataRequest) (*http.Request, error) {
urlParameters := map[string]interface{}{
"AzureRegion": client.AzureRegion,
}
pathParameters := map[string]interface{}{
"persistedFaceId": autorest.Encode("path", persistedFaceID),
"personGroupId": autorest.Encode("path", personGroupID),
"personId": autorest.Encode("path", personID),
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPatch(),
autorest.WithCustomBaseURL("https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0", urlParameters),
autorest.WithPathParameters("/persongroups/{personGroupId}/persons/{personId}/persistedFaces/{persistedFaceId}", pathParameters),
autorest.WithJSON(body),
autorest.WithHeader("Ocp-Apim-Subscription-Key", client.SubscriptionKey))
return preparer.Prepare(&http.Request{})
}
// UpdateFaceSender sends the UpdateFace request. The method will close the
// http.Response Body if it receives an error.
func (client PersonClient) UpdateFaceSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req)
}
// UpdateFaceResponder handles the response to the UpdateFace request. The method always
// closes the http.Response Body.
func (client PersonClient) UpdateFaceResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
| nhr/origin | vendor/github.com/Azure/azure-sdk-for-go/dataplane/cognitiveservices/face/person.go | GO | apache-2.0 | 28,461 |
<?php
/**
* This file is part of the OpenPNE package.
* (c) OpenPNE Project (http://www.openpne.jp/)
*
* For the full copyright and license information, please view the LICENSE
* file and the NOTICE file that were distributed with this source code.
*/
/**
* The upgrating strategy by importing member's email address.
*
* @package OpenPNE
* @subpackage task
* @author Kousuke Ebihara <ebihara@tejimaya.com>
*/
class opUpgradeFrom2ImportEmailAddressStrategy extends opUpgradeAbstractStrategy
{
public function run()
{
$this->getDatabaseManager();
$this->conn = Doctrine_Manager::connection();
$this->conn->beginTransaction();
try
{
$this->doRun();
$this->conn->commit();
}
catch (Exception $e)
{
$this->conn->rollback();
throw $e;
}
}
public function doRun()
{
set_include_path(dirname(__FILE__).'/lib'.PATH_SEPARATOR.get_include_path());
require_once 'OpenPNE2Util.class.php';
$results = $this->conn->fetchAssoc('SELECT c_member_id, pc_address, ktai_address FROM c_member_secure');
foreach ($results as $result)
{
if ($result['pc_address'])
{
$address = OpenPNE2Util::t_decrypt($result['pc_address']);
$this->conn->execute('INSERT INTO member_config (name, value, name_value_hash, member_id) VALUES ("pc_address", ?, ?, ?)', array($address, md5('pc_address,'.$address), $result['c_member_id']));
}
if ($result['ktai_address'])
{
$address = OpenPNE2Util::t_decrypt($result['ktai_address']);
$this->conn->execute('INSERT INTO member_config (name, value, name_value_hash, member_id) VALUES ("mobile_address", ?, ?, ?)', array($address, md5('mobile_address,'.$address), $result['c_member_id']));
}
}
}
}
| cripure/openpne3 | data/upgrade/2/opUpgradeFrom2ImportEmailAddressStrategy.class.php | PHP | apache-2.0 | 1,791 |
// Copyright 2017 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package ranger
import (
"github.com/pingcap/tidb/ast"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/model"
"github.com/pingcap/tidb/types"
)
// conditionChecker checks if this condition can be pushed to index plan.
type conditionChecker struct {
colName model.CIStr
shouldReserve bool // check if a access condition should be reserved in filter conditions.
length int
}
func (c *conditionChecker) check(condition expression.Expression) bool {
switch x := condition.(type) {
case *expression.ScalarFunction:
return c.checkScalarFunction(x)
case *expression.Column:
return c.checkColumn(x)
case *expression.Constant:
return true
}
return false
}
func (c *conditionChecker) checkScalarFunction(scalar *expression.ScalarFunction) bool {
switch scalar.FuncName.L {
case ast.LogicOr, ast.LogicAnd:
return c.check(scalar.GetArgs()[0]) && c.check(scalar.GetArgs()[1])
case ast.EQ, ast.NE, ast.GE, ast.GT, ast.LE, ast.LT:
if _, ok := scalar.GetArgs()[0].(*expression.Constant); ok {
if c.checkColumn(scalar.GetArgs()[1]) {
return scalar.FuncName.L != ast.NE || c.length == types.UnspecifiedLength
}
}
if _, ok := scalar.GetArgs()[1].(*expression.Constant); ok {
if c.checkColumn(scalar.GetArgs()[0]) {
return scalar.FuncName.L != ast.NE || c.length == types.UnspecifiedLength
}
}
case ast.IsNull, ast.IsTruth, ast.IsFalsity:
return c.checkColumn(scalar.GetArgs()[0])
case ast.UnaryNot:
// TODO: support "not like" convert to access conditions.
if s, ok := scalar.GetArgs()[0].(*expression.ScalarFunction); ok {
if s.FuncName.L == ast.Like {
return false
}
} else {
// "not column" or "not constant" can't lead to a range.
return false
}
return c.check(scalar.GetArgs()[0])
case ast.In:
if !c.checkColumn(scalar.GetArgs()[0]) {
return false
}
for _, v := range scalar.GetArgs()[1:] {
if _, ok := v.(*expression.Constant); !ok {
return false
}
}
return true
case ast.Like:
return c.checkLikeFunc(scalar)
case ast.GetParam:
return true
}
return false
}
func (c *conditionChecker) checkLikeFunc(scalar *expression.ScalarFunction) bool {
if !c.checkColumn(scalar.GetArgs()[0]) {
return false
}
pattern, ok := scalar.GetArgs()[1].(*expression.Constant)
if !ok {
return false
}
if pattern.Value.IsNull() {
return false
}
patternStr, err := pattern.Value.ToString()
if err != nil {
return false
}
if len(patternStr) == 0 {
return true
}
escape := byte(scalar.GetArgs()[2].(*expression.Constant).Value.GetInt64())
for i := 0; i < len(patternStr); i++ {
if patternStr[i] == escape {
i++
if i < len(patternStr)-1 {
continue
}
break
}
if i == 0 && (patternStr[i] == '%' || patternStr[i] == '_') {
return false
}
if patternStr[i] == '%' {
if i != len(patternStr)-1 {
c.shouldReserve = true
}
break
}
if patternStr[i] == '_' {
c.shouldReserve = true
break
}
}
return true
}
func (c *conditionChecker) checkColumn(expr expression.Expression) bool {
col, ok := expr.(*expression.Column)
if !ok {
return false
}
if c.colName.L != "" {
return c.colName.L == col.ColName.L
}
return true
}
| Nify/tidb | util/ranger/checker.go | GO | apache-2.0 | 3,716 |
/**
* $RCSfile$
* $Revision: 1653 $
* $Date: 2005-07-20 00:21:40 -0300 (Wed, 20 Jul 2005) $
*
* Copyright (C) 2004-2008 Jive Software. 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 org.jivesoftware.openfire.handler;
import java.util.Iterator;
import org.dom4j.Element;
import org.dom4j.QName;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.PacketException;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.user.User;
import org.jivesoftware.openfire.user.UserManager;
import org.jivesoftware.openfire.user.UserNotFoundException;
import org.jivesoftware.openfire.vcard.VCardManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.PacketError;
/**
* Implements the TYPE_IQ vcard-temp protocol. Clients
* use this protocol to set and retrieve the vCard information
* associated with someone's account.
* <p>
* A 'get' query retrieves the vcard for the addressee.
* A 'set' query sets the vcard information for the sender's account.
* </p>
* <p>
* Currently an empty implementation to allow usage with normal
* clients. Future implementation needed.
* </p>
* <h2>Assumptions</h2>
* This handler assumes that the request is addressed to the server.
* An appropriate TYPE_IQ tag matcher should be placed in front of this
* one to route TYPE_IQ requests not addressed to the server to
* another channel (probably for direct delivery to the recipient).
* <h2>Warning</h2>
* There should be a way of determining whether a session has
* authorization to access this feature. I'm not sure it is a good
* idea to do authorization in each handler. It would be nice if
* the framework could assert authorization policies across channels.
* <h2>Warning</h2>
* I have noticed incompatibility between vCard XML used by Exodus and Psi.
* There is a new vCard standard going through the JSF JEP process. We might
* want to start either standardizing on clients (probably the most practical),
* sending notices for non-conformance (useful),
* or attempting to translate between client versions (not likely).
*
* @author Iain Shigeoka
*/
public class IQvCardHandler extends IQHandler {
private static final Logger Log = LoggerFactory.getLogger(IQvCardHandler.class);
private IQHandlerInfo info;
private XMPPServer server;
private UserManager userManager;
public IQvCardHandler() {
super("XMPP vCard Handler");
info = new IQHandlerInfo("vCard", "vcard-temp");
}
@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {
IQ result = IQ.createResultIQ(packet);
IQ.Type type = packet.getType();
if (type.equals(IQ.Type.set)) {
try {
User user = userManager.getUser(packet.getFrom().getNode());
Element vcard = packet.getChildElement();
if (vcard != null) {
VCardManager.getInstance().setVCard(user.getUsername(), vcard);
}
}
catch (UserNotFoundException e) {
result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.item_not_found);
}
catch (Exception e) {
Log.error(e.getMessage(), e);
result.setError(PacketError.Condition.internal_server_error);
}
}
else if (type.equals(IQ.Type.get)) {
JID recipient = packet.getTo();
// If no TO was specified then get the vCard of the sender of the packet
if (recipient == null) {
recipient = packet.getFrom();
}
// By default return an empty vCard
result.setChildElement("vCard", "vcard-temp");
// Only try to get the vCard values of non-anonymous users
if (recipient != null) {
if (recipient.getNode() != null && server.isLocal(recipient)) {
VCardManager vManager = VCardManager.getInstance();
Element userVCard = vManager.getVCard(recipient.getNode());
if (userVCard != null) {
// Check if the requester wants to ignore some vCard's fields
Element filter = packet.getChildElement()
.element(QName.get("filter", "vcard-temp-filter"));
if (filter != null) {
// Create a copy so we don't modify the original vCard
userVCard = userVCard.createCopy();
// Ignore fields requested by the user
for (Iterator toFilter = filter.elementIterator(); toFilter.hasNext();)
{
Element field = (Element) toFilter.next();
Element fieldToRemove = userVCard.element(field.getName());
if (fieldToRemove != null) {
fieldToRemove.detach();
}
}
}
result.setChildElement(userVCard);
}
}
else {
result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.item_not_found);
}
} else {
result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.item_not_found);
}
}
else {
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.not_acceptable);
}
return result;
}
@Override
public void initialize(XMPPServer server) {
super.initialize(server);
this.server = server;
userManager = server.getUserManager();
}
@Override
public IQHandlerInfo getInfo() {
return info;
}
}
| haipeng-ssy/openfire_src | src/java/org/jivesoftware/openfire/handler/IQvCardHandler.java | Java | apache-2.0 | 6,967 |
/*
* Copyright 2014, 2015 Dominick Baier, Brock Allen
*
* 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 IdentityServer3.Core.Configuration;
using IdentityServer3.Core.Configuration.Hosting;
using IdentityServer3.Core.Extensions;
using IdentityServer3.Core.Logging;
using IdentityServer3.Core.Models;
using IdentityServer3.Core.Resources;
using IdentityServer3.Core.Results;
using IdentityServer3.Core.Services;
using IdentityServer3.Core.ViewModels;
using System;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web.Http;
namespace IdentityServer3.Core.Endpoints
{
[ErrorPageFilter]
[HostAuthentication(Constants.PrimaryAuthenticationType)]
[SecurityHeaders]
[NoCache]
[PreventUnsupportedRequestMediaTypes(allowFormUrlEncoded: true)]
internal class ClientPermissionsController : ApiController
{
private readonly static ILog Logger = LogProvider.GetCurrentClassLogger();
private readonly IClientPermissionsService clientPermissionsService;
private readonly IdentityServerOptions options;
private readonly IViewService viewSvc;
private readonly ILocalizationService localizationService;
private readonly IEventService eventService;
private readonly AntiForgeryToken antiForgeryToken;
public ClientPermissionsController(
IClientPermissionsService clientPermissionsService,
IdentityServerOptions options,
IViewService viewSvc,
ILocalizationService localizationService,
IEventService eventService,
AntiForgeryToken antiForgeryToken)
{
this.clientPermissionsService = clientPermissionsService;
this.options = options;
this.viewSvc = viewSvc;
this.localizationService = localizationService;
this.eventService = eventService;
this.antiForgeryToken = antiForgeryToken;
}
[HttpGet]
public async Task<IHttpActionResult> ShowPermissions()
{
Logger.Info("Permissions page requested");
if (User == null || User.Identity == null || User.Identity.IsAuthenticated == false)
{
Logger.Info("User not authenticated, redirecting to login");
return RedirectToLogin();
}
Logger.Info("Rendering permissions page");
return await RenderPermissionsPage();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IHttpActionResult> RevokePermission(RevokeClientPermission model)
{
Logger.Info("Revoke permissions requested");
if (User == null || User.Identity == null || User.Identity.IsAuthenticated == false)
{
Logger.Info("User not authenticated, redirecting to login");
return RedirectToLogin();
}
if (model != null && String.IsNullOrWhiteSpace(model.ClientId))
{
Logger.Warn("No model or client id submitted");
ModelState.AddModelError("ClientId", localizationService.GetMessage(MessageIds.ClientIdRequired));
}
if (model == null || ModelState.IsValid == false)
{
var error = ModelState.Where(x => x.Value.Errors.Any()).Select(x => x.Value.Errors.First().ErrorMessage).First();
Logger.WarnFormat("Rendering error: {0}", error);
return await RenderPermissionsPage(error);
}
Logger.InfoFormat("Revoking permissions for sub: {0}, name: {1}, clientID: {2}", User.GetSubjectId(), User.Identity.Name, model.ClientId);
await this.clientPermissionsService.RevokeClientPermissionsAsync(User.GetSubjectId(), model.ClientId);
await eventService.RaiseClientPermissionsRevokedEventAsync(User as ClaimsPrincipal, model.ClientId);
Logger.Info("Redirecting back to permissions page");
var url = Request.GetOwinContext().GetIdentityServerBaseUrl().EnsureTrailingSlash() +
Constants.RoutePaths.ClientPermissions;
return Redirect(url);
}
private IHttpActionResult RedirectToLogin()
{
var message = new SignInMessage();
var path = Url.Route(Constants.RouteNames.ClientPermissions, null);
var host = new Uri(Request.GetOwinEnvironment().GetIdentityServerHost());
var url = new Uri(host, path);
message.ReturnUrl = url.AbsoluteUri;
return new LoginResult(Request.GetOwinContext().Environment, message);
}
private async Task<IHttpActionResult> RenderPermissionsPage(string error = null)
{
var env = Request.GetOwinEnvironment();
var clients = await this.clientPermissionsService.GetClientPermissionsAsync(User.GetSubjectId());
var vm = new ClientPermissionsViewModel
{
RequestId = env.GetRequestId(),
SiteName = options.SiteName,
SiteUrl = env.GetIdentityServerBaseUrl(),
CurrentUser = env.GetCurrentUserDisplayName(),
LogoutUrl = env.GetIdentityServerLogoutUrl(),
RevokePermissionUrl = Request.GetOwinContext().GetPermissionsPageUrl(),
AntiForgery = antiForgeryToken.GetAntiForgeryToken(),
Clients = clients,
ErrorMessage = error
};
return new ClientPermissionsActionResult(this.viewSvc, Request.GetOwinEnvironment(), vm);
}
}
}
| uoko-J-Go/IdentityServer | source/Core/Endpoints/ClientPermissionsController.cs | C# | apache-2.0 | 6,208 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.project;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author Dmitry Avdeev
*/
@State(name = "ProjectType")
public class ProjectTypeService implements PersistentStateComponent<ProjectType> {
private ProjectType myProjectType;
@Nullable
public static ProjectType getProjectType(@Nullable Project project) {
ProjectType projectType;
if (project != null) {
projectType = getInstance(project).myProjectType;
if (projectType != null) return projectType;
}
return DefaultProjectTypeEP.getDefaultProjectType();
}
public static void setProjectType(@NotNull Project project, @Nullable ProjectType projectType) {
getInstance(project).loadState(projectType);
}
private static ProjectTypeService getInstance(@NotNull Project project) {
return ServiceManager.getService(project, ProjectTypeService.class);
}
@Nullable
@Override
public ProjectType getState() {
return myProjectType;
}
@Override
public void loadState(@Nullable ProjectType state) {
myProjectType = state;
}
}
| goodwinnk/intellij-community | platform/projectModel-api/src/com/intellij/openapi/project/ProjectTypeService.java | Java | apache-2.0 | 1,426 |
package main
import (
"fmt"
"os"
"github.com/Sirupsen/logrus"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/urfave/cli"
)
// fatal prints the error's details if it is a libcontainer specific error type
// then exits the program with an exit status of 1.
func fatal(err error) {
// make sure the error is written to the logger
logrus.Error(err)
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// setupSpec performs initial setup based on the cli.Context for the container
func setupSpec(context *cli.Context) (*specs.Spec, error) {
bundle := context.String("bundle")
if bundle != "" {
if err := os.Chdir(bundle); err != nil {
return nil, err
}
}
spec, err := loadSpec(specConfig)
if err != nil {
return nil, err
}
notifySocket := os.Getenv("NOTIFY_SOCKET")
if notifySocket != "" {
setupSdNotify(spec, notifySocket)
}
if os.Geteuid() != 0 {
return nil, fmt.Errorf("runc should be run as root")
}
return spec, nil
}
| MadDogTechnology/kops | vendor/github.com/opencontainers/runc/utils.go | GO | apache-2.0 | 961 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.uiDesigner.wizard;
import com.intellij.ide.wizard.StepAdapter;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiType;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.psi.util.PropertyUtilBase;
import com.intellij.uiDesigner.UIDesignerBundle;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
/**
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
final class BindToExistingBeanStep extends StepAdapter{
private static final Logger LOG = Logger.getInstance("#com.intellij.uiDesigner.wizard.BindToExistingBeanStep");
private JScrollPane myScrollPane;
private JTable myTable;
private final WizardData myData;
private final MyTableModel myTableModel;
private JCheckBox myChkIsModified;
private JCheckBox myChkGetData;
private JCheckBox myChkSetData;
private JPanel myPanel;
BindToExistingBeanStep(@NotNull final WizardData data) {
myData = data;
myTableModel = new MyTableModel();
myTable.setModel(myTableModel);
myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
myTable.getColumnModel().setColumnSelectionAllowed(true);
myScrollPane.getViewport().setBackground(myTable.getBackground());
myTable.setSurrendersFocusOnKeystroke(true);
// Customize "Form Property" column
{
final TableColumn column = myTable.getColumnModel().getColumn(0/*Form Property*/);
column.setCellRenderer(new FormPropertyTableCellRenderer(myData.myProject));
}
// Customize "Bean Property" column
{
final TableColumn column = myTable.getColumnModel().getColumn(1/*Bean Property*/);
column.setCellRenderer(new BeanPropertyTableCellRenderer());
final MyTableCellEditor cellEditor = new MyTableCellEditor();
column.setCellEditor(cellEditor);
final DefaultCellEditor editor = (DefaultCellEditor)myTable.getDefaultEditor(Object.class);
editor.setClickCountToStart(1);
myTable.setRowHeight(cellEditor.myCbx.getPreferredSize().height);
}
myChkGetData.setSelected(true);
myChkGetData.setEnabled(false);
myChkSetData.setSelected(true);
myChkSetData.setEnabled(false);
myChkIsModified.setSelected(myData.myGenerateIsModified);
}
public JComponent getComponent() {
return myPanel;
}
public void _init() {
// Check that data is correct
LOG.assertTrue(!myData.myBindToNewBean);
LOG.assertTrue(myData.myBeanClass != null);
myTableModel.fireTableDataChanged();
}
public void _commit(boolean finishChosen) {
// Stop editing if any
final TableCellEditor cellEditor = myTable.getCellEditor();
if(cellEditor != null){
cellEditor.stopCellEditing();
}
myData.myGenerateIsModified = myChkIsModified.isSelected();
// TODO[vova] check that at least one binding field exists
}
private final class MyTableModel extends AbstractTableModel{
private final String[] myColumnNames;
public MyTableModel() {
myColumnNames = new String[]{
UIDesignerBundle.message("column.form.field"),
UIDesignerBundle.message("column.bean.property")};
}
public int getColumnCount() {
return myColumnNames.length;
}
public String getColumnName(final int column) {
return myColumnNames[column];
}
public int getRowCount() {
return myData.myBindings.length;
}
public boolean isCellEditable(final int row, final int column) {
return column == 1/*Bean Property*/;
}
public Object getValueAt(final int row, final int column) {
if(column == 0/*Form Property*/){
return myData.myBindings[row].myFormProperty;
}
else if(column == 1/*Bean Property*/){
return myData.myBindings[row].myBeanProperty;
}
else{
throw new IllegalArgumentException("unknown column: " + column);
}
}
public void setValueAt(final Object value, final int row, final int column) {
LOG.assertTrue(column == 1/*Bean Property*/);
final FormProperty2BeanProperty binding = myData.myBindings[row];
binding.myBeanProperty = (BeanProperty)value;
}
}
private final class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor{
private final ComboBox myCbx;
/* -1 if not defined*/
private int myEditingRow;
public MyTableCellEditor() {
myCbx = new ComboBox();
myCbx.setEditable(true);
myCbx.setRenderer(new BeanPropertyListCellRenderer());
myCbx.registerTableCellEditor(this);
final JComponent editorComponent = (JComponent)myCbx.getEditor().getEditorComponent();
editorComponent.setBorder(null);
myEditingRow = -1;
}
/**
* @return whether it's possible to convert {@code type1} into {@code type2}
* and vice versa.
*/
private boolean canConvert(@NonNls final String type1, @NonNls final String type2){
if("boolean".equals(type1) || "boolean".equals(type2)){
return type1.equals(type2);
}
else{
return true;
}
}
public Component getTableCellEditorComponent(
final JTable table,
final Object value,
final boolean isSelected,
final int row,
final int column
) {
myEditingRow = row;
final DefaultComboBoxModel model = (DefaultComboBoxModel)myCbx.getModel();
model.removeAllElements();
model.addElement(null/*<not defined>*/);
// Fill combobox with available bean's properties
final String[] rProps = PropertyUtilBase.getReadableProperties(myData.myBeanClass, true);
final String[] wProps = PropertyUtilBase.getWritableProperties(myData.myBeanClass, true);
final ArrayList<BeanProperty> rwProps = new ArrayList<>();
outer: for(int i = rProps.length - 1; i >= 0; i--){
final String propName = rProps[i];
if(ArrayUtil.find(wProps, propName) != -1){
LOG.assertTrue(!rwProps.contains(propName));
final PsiMethod getter = PropertyUtilBase.findPropertyGetter(myData.myBeanClass, propName, false, true);
if (getter == null) {
// possible if the getter is static: getReadableProperties() does not filter out static methods, and
// findPropertyGetter() checks for static/non-static
continue;
}
final PsiType returnType = getter.getReturnType();
LOG.assertTrue(returnType != null);
// There are two possible types: boolean and java.lang.String
@NonNls final String typeName = returnType.getCanonicalText();
LOG.assertTrue(typeName != null);
if(!"boolean".equals(typeName) && !"java.lang.String".equals(typeName)){
continue;
}
// Check that the property is not in use yet
for(int j = myData.myBindings.length - 1; j >= 0; j--){
final BeanProperty _property = myData.myBindings[j].myBeanProperty;
if(j != row && _property != null && propName.equals(_property.myName)){
continue outer;
}
}
// Check that we conver types
if(
!canConvert(
myData.myBindings[row].myFormProperty.getComponentPropertyClassName(),
typeName
)
){
continue;
}
rwProps.add(new BeanProperty(propName, typeName));
}
}
Collections.sort(rwProps);
for (BeanProperty rwProp : rwProps) {
model.addElement(rwProp);
}
// Set initially selected item
if(myData.myBindings[row].myBeanProperty != null){
myCbx.setSelectedItem(myData.myBindings[row].myBeanProperty);
}
else{
myCbx.setSelectedIndex(0/*<not defined>*/);
}
return myCbx;
}
public Object getCellEditorValue() {
LOG.assertTrue(myEditingRow != -1);
try {
// our ComboBox is editable so its editor can contain:
// 1) BeanProperty object (it user just selected something from ComboBox)
// 2) java.lang.String if user type something into ComboBox
final Object selectedItem = myCbx.getEditor().getItem();
if(selectedItem instanceof BeanProperty){
return selectedItem;
}
else if(selectedItem instanceof String){
final String fieldName = ((String)selectedItem).trim();
if(fieldName.length() == 0){
return null; // binding is not defined
}
final String fieldType = myData.myBindings[myEditingRow].myFormProperty.getComponentPropertyClassName();
return new BeanProperty(fieldName, fieldType);
}
else{
throw new IllegalArgumentException("unknown selectedItem: " + selectedItem);
}
}
finally {
myEditingRow = -1; // unset editing row. So it's possible to invoke this method only once per editing
}
}
}
}
| jk1/intellij-community | plugins/ui-designer/src/com/intellij/uiDesigner/wizard/BindToExistingBeanStep.java | Java | apache-2.0 | 9,877 |
// @target: ES5
// @declaration: true
// @comments: true
/** This is class c2 without constuctor*/
class c2 {
}
var i2 = new c2();
var i2_c = c2;
class c3 {
/** Constructor comment*/
constructor() {
}
}
var i3 = new c3();
var i3_c = c3;
/** Class comment*/
class c4 {
/** Constructor comment*/
constructor() {
}
}
var i4 = new c4();
var i4_c = c4;
/** Class with statics*/
class c5 {
static s1: number;
}
var i5 = new c5();
var i5_c = c5;
/// class with statics and constructor
class c6 { /// class with statics and constructor2
/// s1 comment
static s1: number; /// s1 comment2
/// constructor comment
constructor() { /// constructor comment2
}
}
var i6 = new c6();
var i6_c = c6;
// class with statics and constructor
class c7 {
// s1 comment
static s1: number;
// constructor comment
constructor() {
}
}
var i7 = new c7();
var i7_c = c7;
/** class with statics and constructor
*/
class c8 {
/** s1 comment */
static s1: number; /** s1 comment2 */
/** constructor comment
*/
constructor() {
/** constructor comment2
*/
}
}
var i8 = new c8();
var i8_c = c8;
| DickvdBrink/TypeScript | tests/cases/compiler/commentsClass.ts | TypeScript | apache-2.0 | 1,241 |
# Copyright 2015 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.
# ==============================================================================
"""Libraries to build Recurrent Neural Networks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| ivano666/tensorflow | tensorflow/models/rnn/__init__.py | Python | apache-2.0 | 839 |
# Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from cinder.compute import nova
from cinder import context
from cinder import test
class FakeNovaClient(object):
class Volumes(object):
def __getattr__(self, item):
return None
def __init__(self):
self.volumes = self.Volumes()
def create_volume_snapshot(self, *args, **kwargs):
pass
def delete_volume_snapshot(self, *args, **kwargs):
pass
class NovaApiTestCase(test.TestCase):
def setUp(self):
super(NovaApiTestCase, self).setUp()
self.api = nova.API()
self.novaclient = FakeNovaClient()
self.ctx = context.get_admin_context()
self.mox.StubOutWithMock(nova, 'novaclient')
def test_update_server_volume(self):
nova.novaclient(self.ctx).AndReturn(self.novaclient)
self.mox.StubOutWithMock(self.novaclient.volumes,
'update_server_volume')
self.novaclient.volumes.update_server_volume('server_id', 'attach_id',
'new_volume_id')
self.mox.ReplayAll()
self.api.update_server_volume(self.ctx, 'server_id', 'attach_id',
'new_volume_id')
| Thingee/cinder | cinder/tests/compute/test_nova.py | Python | apache-2.0 | 1,814 |
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. 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.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/xml_highlight_rules', 'ace/mode/behaviour/xml', 'ace/mode/folding/xml'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules;
var XmlBehaviour = require("./behaviour/xml").XmlBehaviour;
var XmlFoldMode = require("./folding/xml").FoldMode;
var Mode = function() {
this.$tokenizer = new Tokenizer(new XmlHighlightRules().getRules());
this.$behaviour = new XmlBehaviour();
this.foldingRules = new XmlFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.getNextLineIndent = function(state, line, tab) {
return this.$getIndent(line);
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/xml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var xmlUtil = require("./xml_util");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var XmlHighlightRules = function() {
this.$rules = {
start : [{
token : "text",
regex : "<\\!\\[CDATA\\[",
next : "cdata"
}, {
token : "xml-pe",
regex : "<\\?.*?\\?>"
}, {
token : "comment",
merge : true,
regex : "<\\!--",
next : "comment"
}, {
token : "xml-pe",
regex : "<\\!.*?>"
}, {
token : "meta.tag", // opening tag
regex : "<\\/?",
next : "tag"
}, {
token : "text",
regex : "\\s+"
}, {
token : "constant.character.entity",
regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"
}, {
token : "text",
regex : "[^<]+"
}],
cdata : [{
token : "text",
regex : "\\]\\]>",
next : "start"
}, {
token : "text",
regex : "\\s+"
}, {
token : "text",
regex : "(?:[^\\]]|\\](?!\\]>))+"
}],
comment : [{
token : "comment",
regex : ".*?-->",
next : "start"
}, {
token : "comment",
merge : true,
regex : ".+"
}]
};
xmlUtil.tag(this.$rules, "tag", "start");
};
oop.inherits(XmlHighlightRules, TextHighlightRules);
exports.XmlHighlightRules = XmlHighlightRules;
});
define('ace/mode/xml_util', ['require', 'exports', 'module' ], function(require, exports, module) {
function string(state) {
return [{
token : "string",
regex : '".*?"'
}, {
token : "string", // multi line string start
merge : true,
regex : '["].*',
next : state + "_qqstring"
}, {
token : "string",
regex : "'.*?'"
}, {
token : "string", // multi line string start
merge : true,
regex : "['].*",
next : state + "_qstring"
}];
}
function multiLineString(quote, state) {
return [{
token : "string",
merge : true,
regex : ".*?" + quote,
next : state
}, {
token : "string",
merge : true,
regex : '.+'
}];
}
exports.tag = function(states, name, nextState, tagMap) {
states[name] = [{
token : "text",
regex : "\\s+"
}, {
token : !tagMap ? "meta.tag.tag-name" : function(value) {
if (tagMap[value])
return "meta.tag.tag-name." + tagMap[value];
else
return "meta.tag.tag-name";
},
merge : true,
regex : "[-_a-zA-Z0-9:]+",
next : name + "_embed_attribute_list"
}, {
token: "empty",
regex: "",
next : name + "_embed_attribute_list"
}];
states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list");
states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list");
states[name + "_embed_attribute_list"] = [{
token : "meta.tag",
merge : true,
regex : "\/?>",
next : nextState
}, {
token : "keyword.operator",
regex : "="
}, {
token : "entity.other.attribute-name",
regex : "[-_a-zA-Z0-9:]+"
}, {
token : "constant.numeric", // float
regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token : "text",
regex : "\\s+"
}].concat(string(name));
};
});
define('ace/mode/behaviour/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle', 'ace/token_iterator'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var CstyleBehaviour = require("./cstyle").CstyleBehaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
function hasType(token, type) {
var hasType = true;
var typeList = token.type.split('.');
var needleList = type.split('.');
needleList.forEach(function(needle){
if (typeList.indexOf(needle) == -1) {
hasType = false;
return false;
}
});
return hasType;
}
var XmlBehaviour = function () {
this.inherit(CstyleBehaviour, ["string_dquotes"]); // Get string behaviour
this.add("autoclosing", "insertion", function (state, action, editor, session, text) {
if (text == '>') {
var position = editor.getCursorPosition();
var iterator = new TokenIterator(session, position.row, position.column);
var token = iterator.getCurrentToken();
var atCursor = false;
if (!token || !hasType(token, 'meta.tag') && !(hasType(token, 'text') && token.value.match('/'))){
do {
token = iterator.stepBackward();
} while (token && (hasType(token, 'string') || hasType(token, 'keyword.operator') || hasType(token, 'entity.attribute-name') || hasType(token, 'text')));
} else {
atCursor = true;
}
if (!token || !hasType(token, 'meta.tag-name') || iterator.stepBackward().value.match('/')) {
return
}
var tag = token.value;
if (atCursor){
var tag = tag.substring(0, position.column - token.start);
}
return {
text: '>' + '</' + tag + '>',
selection: [1, 1]
}
}
});
this.add('autoindent', 'insertion', function (state, action, editor, session, text) {
if (text == "\n") {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChars = line.substring(cursor.column, cursor.column + 2);
if (rightChars == '</') {
var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString();
var next_indent = this.$getIndent(session.doc.getLine(cursor.row));
return {
text: '\n' + indent + '\n' + next_indent,
selection: [1, indent.length, 1, indent.length]
}
}
}
});
}
oop.inherits(XmlBehaviour, Behaviour);
exports.XmlBehaviour = XmlBehaviour;
});
define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/token_iterator', 'ace/lib/lang'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var lang = require("../../lib/lang");
var SAFE_INSERT_IN_TOKENS =
["text", "paren.rparen", "punctuation.operator"];
var SAFE_INSERT_BEFORE_TOKENS =
["text", "paren.rparen", "punctuation.operator", "comment"];
var autoInsertedBrackets = 0;
var autoInsertedRow = -1;
var autoInsertedLineEnd = "";
var maybeInsertedBrackets = 0;
var maybeInsertedRow = -1;
var maybeInsertedLineStart = "";
var maybeInsertedLineEnd = "";
var CstyleBehaviour = function () {
CstyleBehaviour.isSaneInsertion = function(editor, session) {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS))
return false;
}
iterator.stepForward();
return iterator.getCurrentTokenRow() !== cursor.row ||
this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
};
CstyleBehaviour.$matchTokenType = function(token, types) {
return types.indexOf(token.type || token) > -1;
};
CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isAutoInsertedClosing(cursor, line, autoInsertedLineEnd[0]))
autoInsertedBrackets = 0;
autoInsertedRow = cursor.row;
autoInsertedLineEnd = bracket + line.substr(cursor.column);
autoInsertedBrackets++;
};
CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isMaybeInsertedClosing(cursor, line))
maybeInsertedBrackets = 0;
maybeInsertedRow = cursor.row;
maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
maybeInsertedLineEnd = line.substr(cursor.column);
maybeInsertedBrackets++;
};
CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) {
return autoInsertedBrackets > 0 &&
cursor.row === autoInsertedRow &&
bracket === autoInsertedLineEnd[0] &&
line.substr(cursor.column) === autoInsertedLineEnd;
};
CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) {
return maybeInsertedBrackets > 0 &&
cursor.row === maybeInsertedRow &&
line.substr(cursor.column) === maybeInsertedLineEnd &&
line.substr(0, cursor.column) == maybeInsertedLineStart;
};
CstyleBehaviour.popAutoInsertedClosing = function() {
autoInsertedLineEnd = autoInsertedLineEnd.substr(1);
autoInsertedBrackets--;
};
CstyleBehaviour.clearMaybeInsertedClosing = function() {
maybeInsertedBrackets = 0;
maybeInsertedRow = -1;
};
this.add("braces", "insertion", function (state, action, editor, session, text) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (text == '{') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
return {
text: '{' + selected + '}',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
if (/[\]\}\)]/.test(line[cursor.column])) {
CstyleBehaviour.recordAutoInsert(editor, session, "}");
return {
text: '{}',
selection: [1, 1]
};
} else {
CstyleBehaviour.recordMaybeInsert(editor, session, "{");
return {
text: '{',
selection: [1, 1]
};
}
}
} else if (text == '}') {
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
} else if (text == "\n" || text == "\r\n") {
var closing = "";
if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
closing = lang.stringRepeat("}", maybeInsertedBrackets);
CstyleBehaviour.clearMaybeInsertedClosing();
}
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}' || closing !== "") {
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column}, '}');
if (!openBracePos)
return null;
var indent = this.getNextLineIndent(state, line.substring(0, cursor.column), session.getTabString());
var next_indent = this.$getIndent(line);
return {
text: '\n' + indent + '\n' + next_indent + closing,
selection: [1, indent.length, 1, indent.length]
};
}
}
});
this.add("braces", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
} else {
maybeInsertedBrackets--;
}
}
});
this.add("parens", "insertion", function (state, action, editor, session, text) {
if (text == '(') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return {
text: '(' + selected + ')',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, ")");
return {
text: '()',
selection: [1, 1]
};
}
} else if (text == ')') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("parens", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
});
this.add("brackets", "insertion", function (state, action, editor, session, text) {
if (text == '[') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return {
text: '[' + selected + ']',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, "]");
return {
text: '[]',
selection: [1, 1]
};
}
} else if (text == ']') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ']') {
var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("brackets", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '[') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ']') {
range.end.column++;
return range;
}
}
});
this.add("string_dquotes", "insertion", function (state, action, editor, session, text) {
if (text == '"' || text == "'") {
var quote = text;
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
return {
text: quote + selected + quote,
selection: false
};
} else {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column-1, cursor.column);
if (leftChar == '\\') {
return null;
}
var tokens = session.getTokens(selection.start.row);
var col = 0, token;
var quotepos = -1; // Track whether we're inside an open quote.
for (var x = 0; x < tokens.length; x++) {
token = tokens[x];
if (token.type == "string") {
quotepos = -1;
} else if (quotepos < 0) {
quotepos = token.value.indexOf(quote);
}
if ((token.value.length + col) > selection.start.column) {
break;
}
col += tokens[x].value.length;
}
if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) {
if (!CstyleBehaviour.isSaneInsertion(editor, session))
return;
return {
text: quote + quote,
selection: [1,1]
};
} else if (token && token.type === "string") {
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == quote) {
return {
text: '',
selection: [1, 1]
};
}
}
}
}
});
this.add("string_dquotes", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == '"') {
range.end.column++;
return range;
}
}
});
};
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
});
define('ace/mode/folding/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/range', 'ace/mode/folding/fold_mode', 'ace/token_iterator'], function(require, exports, module) {
var oop = require("../../lib/oop");
var lang = require("../../lib/lang");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var TokenIterator = require("../../token_iterator").TokenIterator;
var FoldMode = exports.FoldMode = function(voidElements) {
BaseFoldMode.call(this);
this.voidElements = voidElements || {};
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.getFoldWidget = function(session, foldStyle, row) {
var tag = this._getFirstTagInLine(session, row);
if (tag.closing)
return foldStyle == "markbeginend" ? "end" : "";
if (!tag.tagName || this.voidElements[tag.tagName.toLowerCase()])
return "";
if (tag.selfClosing)
return "";
if (tag.value.indexOf("/" + tag.tagName) !== -1)
return "";
return "start";
};
this._getFirstTagInLine = function(session, row) {
var tokens = session.getTokens(row);
var value = "";
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (token.type.indexOf("meta.tag") === 0)
value += token.value;
else
value += lang.stringRepeat(" ", token.value.length);
}
return this._parseTag(value);
};
this.tagRe = /^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/;
this._parseTag = function(tag) {
var match = this.tagRe.exec(tag);
var column = this.tagRe.lastIndex || 0;
this.tagRe.lastIndex = 0;
return {
value: tag,
match: match ? match[2] : "",
closing: match ? !!match[3] : false,
selfClosing: match ? !!match[5] || match[2] == "/>" : false,
tagName: match ? match[4] : "",
column: match[1] ? column + match[1].length : column
};
};
this._readTagForward = function(iterator) {
var token = iterator.getCurrentToken();
if (!token)
return null;
var value = "";
var start;
do {
if (token.type.indexOf("meta.tag") === 0) {
if (!start) {
var start = {
row: iterator.getCurrentTokenRow(),
column: iterator.getCurrentTokenColumn()
};
}
value += token.value;
if (value.indexOf(">") !== -1) {
var tag = this._parseTag(value);
tag.start = start;
tag.end = {
row: iterator.getCurrentTokenRow(),
column: iterator.getCurrentTokenColumn() + token.value.length
};
iterator.stepForward();
return tag;
}
}
} while(token = iterator.stepForward());
return null;
};
this._readTagBackward = function(iterator) {
var token = iterator.getCurrentToken();
if (!token)
return null;
var value = "";
var end;
do {
if (token.type.indexOf("meta.tag") === 0) {
if (!end) {
end = {
row: iterator.getCurrentTokenRow(),
column: iterator.getCurrentTokenColumn() + token.value.length
};
}
value = token.value + value;
if (value.indexOf("<") !== -1) {
var tag = this._parseTag(value);
tag.end = end;
tag.start = {
row: iterator.getCurrentTokenRow(),
column: iterator.getCurrentTokenColumn()
};
iterator.stepBackward();
return tag;
}
}
} while(token = iterator.stepBackward());
return null;
};
this._pop = function(stack, tag) {
while (stack.length) {
var top = stack[stack.length-1];
if (!tag || top.tagName == tag.tagName) {
return stack.pop();
}
else if (this.voidElements[tag.tagName]) {
return;
}
else if (this.voidElements[top.tagName]) {
stack.pop();
continue;
} else {
return null;
}
}
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
var firstTag = this._getFirstTagInLine(session, row);
if (!firstTag.match)
return null;
var isBackward = firstTag.closing || firstTag.selfClosing;
var stack = [];
var tag;
if (!isBackward) {
var iterator = new TokenIterator(session, row, firstTag.column);
var start = {
row: row,
column: firstTag.column + firstTag.tagName.length + 2
};
while (tag = this._readTagForward(iterator)) {
if (tag.selfClosing) {
if (!stack.length) {
tag.start.column += tag.tagName.length + 2;
tag.end.column -= 2;
return Range.fromPoints(tag.start, tag.end);
} else
continue;
}
if (tag.closing) {
this._pop(stack, tag);
if (stack.length == 0)
return Range.fromPoints(start, tag.start);
}
else {
stack.push(tag)
}
}
}
else {
var iterator = new TokenIterator(session, row, firstTag.column + firstTag.match.length);
var end = {
row: row,
column: firstTag.column
};
while (tag = this._readTagBackward(iterator)) {
if (tag.selfClosing) {
if (!stack.length) {
tag.start.column += tag.tagName.length + 2;
tag.end.column -= 2;
return Range.fromPoints(tag.start, tag.end);
} else
continue;
}
if (!tag.closing) {
this._pop(stack, tag);
if (stack.length == 0) {
tag.start.column += tag.tagName.length + 2;
return Range.fromPoints(tag.start, end);
}
}
else {
stack.push(tag)
}
}
}
};
}).call(FoldMode.prototype);
}); | McLeodMoores/starling | projects/web/web-engine/prototype/scripts/lib/ace/mode-xml.js | JavaScript | apache-2.0 | 29,974 |
package billing
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// CustomersClient is the billing client provides access to billing resources for Azure subscriptions.
type CustomersClient struct {
BaseClient
}
// NewCustomersClient creates an instance of the CustomersClient client.
func NewCustomersClient(subscriptionID string) CustomersClient {
return NewCustomersClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewCustomersClientWithBaseURI creates an instance of the CustomersClient client.
func NewCustomersClientWithBaseURI(baseURI string, subscriptionID string) CustomersClient {
return CustomersClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Get get the customer by id.
// Parameters:
// billingAccountName - billing Account Id.
// customerName - customer Id.
// expand - may be used to expand enabledAzureSkus, resellers.
func (client CustomersClient) Get(ctx context.Context, billingAccountName string, customerName string, expand string) (result Customer, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/CustomersClient.Get")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.GetPreparer(ctx, billingAccountName, customerName, expand)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.CustomersClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "billing.CustomersClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.CustomersClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client CustomersClient) GetPreparer(ctx context.Context, billingAccountName string, customerName string, expand string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"billingAccountName": autorest.Encode("path", billingAccountName),
"customerName": autorest.Encode("path", customerName),
}
const APIVersion = "2018-11-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
if len(expand) > 0 {
queryParameters["$expand"] = autorest.Encode("query", expand)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client CustomersClient) GetSender(req *http.Request) (*http.Response, error) {
sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
return autorest.SendWithSender(client, req, sd...)
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client CustomersClient) GetResponder(resp *http.Response) (result Customer, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListByBillingAccountName lists all customers which the current user can work with on-behalf of a partner.
// Parameters:
// billingAccountName - billing Account Id.
// filter - may be used to filter using hasPermission('{permissionId}') to only return customers for which the
// caller has the specified permission.
// skiptoken - skiptoken is only used if a previous operation returned a partial result. If a previous response
// contains a nextLink element, the value of the nextLink element will include a skiptoken parameter that
// specifies a starting point to use for subsequent calls.
func (client CustomersClient) ListByBillingAccountName(ctx context.Context, billingAccountName string, filter string, skiptoken string) (result CustomerListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/CustomersClient.ListByBillingAccountName")
defer func() {
sc := -1
if result.clr.Response.Response != nil {
sc = result.clr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.fn = client.listByBillingAccountNameNextResults
req, err := client.ListByBillingAccountNamePreparer(ctx, billingAccountName, filter, skiptoken)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.CustomersClient", "ListByBillingAccountName", nil, "Failure preparing request")
return
}
resp, err := client.ListByBillingAccountNameSender(req)
if err != nil {
result.clr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "billing.CustomersClient", "ListByBillingAccountName", resp, "Failure sending request")
return
}
result.clr, err = client.ListByBillingAccountNameResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.CustomersClient", "ListByBillingAccountName", resp, "Failure responding to request")
}
return
}
// ListByBillingAccountNamePreparer prepares the ListByBillingAccountName request.
func (client CustomersClient) ListByBillingAccountNamePreparer(ctx context.Context, billingAccountName string, filter string, skiptoken string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"billingAccountName": autorest.Encode("path", billingAccountName),
}
const APIVersion = "2018-11-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
if len(filter) > 0 {
queryParameters["$filter"] = autorest.Encode("query", filter)
}
if len(skiptoken) > 0 {
queryParameters["$skiptoken"] = autorest.Encode("query", skiptoken)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByBillingAccountNameSender sends the ListByBillingAccountName request. The method will close the
// http.Response Body if it receives an error.
func (client CustomersClient) ListByBillingAccountNameSender(req *http.Request) (*http.Response, error) {
sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
return autorest.SendWithSender(client, req, sd...)
}
// ListByBillingAccountNameResponder handles the response to the ListByBillingAccountName request. The method always
// closes the http.Response Body.
func (client CustomersClient) ListByBillingAccountNameResponder(resp *http.Response) (result CustomerListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByBillingAccountNameNextResults retrieves the next set of results, if any.
func (client CustomersClient) listByBillingAccountNameNextResults(ctx context.Context, lastResults CustomerListResult) (result CustomerListResult, err error) {
req, err := lastResults.customerListResultPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "billing.CustomersClient", "listByBillingAccountNameNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByBillingAccountNameSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "billing.CustomersClient", "listByBillingAccountNameNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByBillingAccountNameResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.CustomersClient", "listByBillingAccountNameNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByBillingAccountNameComplete enumerates all values, automatically crossing page boundaries as required.
func (client CustomersClient) ListByBillingAccountNameComplete(ctx context.Context, billingAccountName string, filter string, skiptoken string) (result CustomerListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/CustomersClient.ListByBillingAccountName")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.ListByBillingAccountName(ctx, billingAccountName, filter, skiptoken)
return
}
| pweil-/origin | vendor/github.com/Azure/azure-sdk-for-go/services/preview/billing/mgmt/2018-11-01-preview/billing/customers.go | GO | apache-2.0 | 10,163 |
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.model.option.definition;
import com.opengamma.analytics.financial.model.tree.RecombiningBinomialTree;
/**
*
* @param <T>
* @param <U>
*/
public abstract class BinomialOptionModelDefinition<T extends OptionDefinition, U extends StandardOptionDataBundle> {
public abstract double getUpFactor(T option, U data, int n, int j);
public abstract double getDownFactor(T option, U data, int n, int j);
public abstract RecombiningBinomialTree<Double> getUpProbabilityTree(T option, U data, int n, int j);
}
| charles-cooper/idylfin | src/com/opengamma/analytics/financial/model/option/definition/BinomialOptionModelDefinition.java | Java | apache-2.0 | 695 |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'preview', 'sv', {
preview: 'Förhandsgranska'
} );
| ldilov/uidb | plugins/ckeditor/plugins/preview/lang/sv.js | JavaScript | apache-2.0 | 225 |
/*
*
* JSMin.java 2006-02-13
*
* Updated 2007-08-20 with updates from jsmin.c (2007-05-22)
*
* Copyright (c) 2006 John Reilly (www.inconspicuous.org)
*
* This work is a translation from C to Java of jsmin.c published by
* Douglas Crockford. Permission is hereby granted to use the Java
* version under the same conditions as the jsmin.c on which it is
* based.
*
*
*
*
* jsmin.c 2003-04-21
*
* Copyright (c) 2002 Douglas Crockford (www.crockford.com)
*
* 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 shall be used for Good, not Evil.
*
* 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 org.saiku.plugin.util.packager;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;
class JSMin {
private static final int EOF = -1;
private final PushbackInputStream in;
private final OutputStream out;
private int theA;
private int theB;
public JSMin(InputStream in, OutputStream out) {
this.in = new PushbackInputStream(in);
this.out = out;
}
/**
* isAlphanum -- return true if the character is a letter, digit,
* underscore, dollar sign, or non-ASCII character.
*/
private static boolean isAlphanum(int c) {
return ( (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'Z') || c == '_' || c == '$' || c == '\\' ||
c > 126);
}
/**
* get -- return the next character from stdin. Watch out for lookahead. If
* the character is a control character, translate it to a space or
* linefeed.
*/
private int get() throws IOException {
int c = in.read();
if (c >= ' ' || c == '\n' || c == EOF) {
return c;
}
if (c == '\r') {
return '\n';
}
return ' ';
}
/**
* Get the next character without getting it.
*/
private int peek() throws IOException {
int lookaheadChar = in.read();
in.unread(lookaheadChar);
return lookaheadChar;
}
/**
* next -- get the next character, excluding comments. peek() is used to see
* if a '/' is followed by a '/' or '*'.
*/
private int next() throws IOException, UnterminatedCommentException {
int c = get();
if (c == '/') {
switch (peek()) {
case '/':
for (;;) {
c = get();
if (c <= '\n') {
return c;
}
}
case '*':
get();
for (;;) {
switch (get()) {
case '*':
if (peek() == '/') {
get();
return ' ';
}
break;
case EOF:
throw new UnterminatedCommentException();
}
}
default:
return c;
}
}
return c;
}
/**
* action -- do something! What you do is determined by the argument: 1
* Output A. Copy B to A. Get the next B. 2 Copy B to A. Get the next B.
* (Delete A). 3 Get the next B. (Delete B). action treats a string as a
* single character. Wow! action recognizes a regular expression if it is
* preceded by ( or , or =.
*/
private void action(int d) throws IOException, UnterminatedRegExpLiteralException,
UnterminatedCommentException, UnterminatedStringLiteralException {
switch (d) {
case 1:
out.write(theA);
case 2:
theA = theB;
if (theA == '\'' || theA == '"') {
for (;;) {
out.write(theA);
theA = get();
if (theA == theB) {
break;
}
if (theA <= '\n') {
throw new UnterminatedStringLiteralException();
}
if (theA == '\\') {
out.write(theA);
theA = get();
}
}
}
case 3:
theB = next();
if (theB == '/' && (theA == '(' || theA == ',' || theA == '=' ||
theA == ':' || theA == '[' || theA == '!' ||
theA == '&' || theA == '|' || theA == '?' ||
theA == '{' || theA == '}' || theA == ';' ||
theA == '\n')) {
out.write(theA);
out.write(theB);
for (;;) {
theA = get();
if (theA == '/') {
break;
} else if (theA == '\\') {
out.write(theA);
theA = get();
} else if (theA <= '\n') {
throw new UnterminatedRegExpLiteralException();
}
out.write(theA);
}
theB = next();
}
}
}
/**
* jsmin -- Copy the input to the output, deleting the characters which are
* insignificant to JavaScript. Comments will be removed. Tabs will be
* replaced with spaces. Carriage returns will be replaced with linefeeds.
* Most spaces and linefeeds will be removed.
*/
public void jsmin() throws IOException, UnterminatedRegExpLiteralException, UnterminatedCommentException, UnterminatedStringLiteralException{
theA = '\n';
action(3);
while (theA != EOF) {
switch (theA) {
case ' ':
if (isAlphanum(theB)) {
action(1);
} else {
action(2);
}
break;
case '\n':
switch (theB) {
case '{':
case '[':
case '(':
case '+':
case '-':
action(1);
break;
case ' ':
action(3);
break;
default:
if (isAlphanum(theB)) {
action(1);
} else {
action(2);
}
}
break;
default:
switch (theB) {
case ' ':
if (isAlphanum(theA)) {
action(1);
break;
}
action(3);
break;
case '\n':
switch (theA) {
case '}':
case ']':
case ')':
case '+':
case '-':
case '"':
case '\'':
action(1);
break;
default:
if (isAlphanum(theA)) {
action(1);
} else {
action(3);
}
}
break;
default:
action(1);
break;
}
}
}
out.flush();
}
private class UnterminatedCommentException extends Exception {
}
private class UnterminatedStringLiteralException extends Exception {
}
private class UnterminatedRegExpLiteralException extends Exception {
}
public static void main(String arg[]) {
try {
JSMin jsmin = new JSMin(new FileInputStream(arg[0]), System.out);
jsmin.jsmin();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnterminatedRegExpLiteralException e) {
e.printStackTrace();
} catch (UnterminatedCommentException e) {
e.printStackTrace();
} catch (UnterminatedStringLiteralException e) {
e.printStackTrace();
}
}
} | OSBI/saiku | saiku-bi-platform-plugin-p7.1/src/main/java/org/saiku/plugin/util/packager/JSMin.java | Java | apache-2.0 | 7,334 |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
#if DEV14_OR_LATER
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
#endif
namespace Microsoft.VisualStudioTools.Project {
internal class FolderNode : HierarchyNode, IDiskBasedNode {
#region ctors
/// <summary>
/// Constructor for the FolderNode
/// </summary>
/// <param name="root">Root node of the hierarchy</param>
/// <param name="relativePath">relative path from root i.e.: "NewFolder1\\NewFolder2\\NewFolder3</param>
/// <param name="element">Associated project element</param>
public FolderNode(ProjectNode root, ProjectElement element)
: base(root, element) {
}
#endregion
#region overridden properties
public override bool CanOpenCommandPrompt {
get {
return true;
}
}
internal override string FullPathToChildren {
get {
return Url;
}
}
public override int SortPriority {
get { return DefaultSortOrderNode.FolderNode; }
}
/// <summary>
/// This relates to the SCC glyph
/// </summary>
public override VsStateIcon StateIconIndex {
get {
// The SCC manager does not support being asked for the state icon of a folder (result of the operation is undefined)
return VsStateIcon.STATEICON_NOSTATEICON;
}
}
public override bool CanAddFiles {
get {
return true;
}
}
#endregion
#region overridden methods
protected override NodeProperties CreatePropertiesObject() {
return new FolderNodeProperties(this);
}
protected internal override void DeleteFromStorage(string path) {
this.DeleteFolder(path);
}
/// <summary>
/// Get the automation object for the FolderNode
/// </summary>
/// <returns>An instance of the Automation.OAFolderNode type if succeeded</returns>
public override object GetAutomationObject() {
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) {
return null;
}
return new Automation.OAFolderItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this);
}
#if DEV14_OR_LATER
protected override bool SupportsIconMonikers {
get { return true; }
}
protected override ImageMoniker GetIconMoniker(bool open) {
return open ? KnownMonikers.FolderOpened : KnownMonikers.FolderClosed;
}
#else
public override object GetIconHandle(bool open) {
return ProjectMgr.GetIconHandleByName(open ?
ProjectNode.ImageName.OpenFolder :
ProjectNode.ImageName.Folder
);
}
#endif
/// <summary>
/// Rename Folder
/// </summary>
/// <param name="label">new Name of Folder</param>
/// <returns>VSConstants.S_OK, if succeeded</returns>
public override int SetEditLabel(string label) {
if (IsBeingCreated) {
return FinishFolderAdd(label, false);
} else {
if (String.Equals(CommonUtils.GetFileOrDirectoryName(Url), label, StringComparison.Ordinal)) {
// Label matches current Name
return VSConstants.S_OK;
}
string newPath = CommonUtils.GetAbsoluteDirectoryPath(CommonUtils.GetParent(Url), label);
// Verify that No Directory/file already exists with the new name among current children
var existingChild = Parent.FindImmediateChildByName(label);
if (existingChild != null && existingChild != this) {
return ShowFileOrFolderAlreadyExistsErrorMessage(newPath);
}
// Verify that No Directory/file already exists with the new name on disk.
// Unless the path exists because it is the path to the source file also.
if ((Directory.Exists(newPath) || File.Exists(newPath)) && !CommonUtils.IsSamePath(Url, newPath)) {
return ShowFileOrFolderAlreadyExistsErrorMessage(newPath);
}
if (!ProjectMgr.Tracker.CanRenameItem(Url, newPath, VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_Directory)) {
return VSConstants.S_OK;
}
}
try {
var oldTriggerFlag = this.ProjectMgr.EventTriggeringFlag;
ProjectMgr.EventTriggeringFlag |= ProjectNode.EventTriggering.DoNotTriggerTrackerQueryEvents;
try {
RenameFolder(label);
} finally {
ProjectMgr.EventTriggeringFlag = oldTriggerFlag;
}
//Refresh the properties in the properties window
IVsUIShell shell = this.ProjectMgr.GetService(typeof(SVsUIShell)) as IVsUIShell;
Utilities.CheckNotNull(shell, "Could not get the UI shell from the project");
ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0));
// Notify the listeners that the name of this folder is changed. This will
// also force a refresh of the SolutionExplorer's node.
ProjectMgr.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Caption, 0);
} catch (Exception e) {
if (e.IsCriticalException()) {
throw;
}
throw new InvalidOperationException(SR.GetString(SR.RenameFolder, e.Message));
}
return VSConstants.S_OK;
}
internal static string PathTooLongMessage {
get {
return SR.GetString(SR.PathTooLongShortMessage);
}
}
private int FinishFolderAdd(string label, bool wasCancelled) {
// finish creation
string filename = label.Trim();
if (filename == "." || filename == "..") {
Debug.Assert(!wasCancelled); // cancelling leaves us with a valid label
NativeMethods.SetErrorDescription("{0} is an invalid filename.", filename);
return VSConstants.E_FAIL;
}
var path = Path.Combine(Parent.FullPathToChildren, label);
if (path.Length >= NativeMethods.MAX_FOLDER_PATH) {
if (wasCancelled) {
// cancelling an edit label doesn't result in the error
// being displayed, so we'll display one for the user.
Utilities.ShowMessageBox(
ProjectMgr.Site,
null,
PathTooLongMessage,
OLEMSGICON.OLEMSGICON_CRITICAL,
OLEMSGBUTTON.OLEMSGBUTTON_OK,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST
);
} else {
NativeMethods.SetErrorDescription(PathTooLongMessage);
}
return VSConstants.E_FAIL;
}
if (filename == GetEditLabel() || Parent.FindImmediateChildByName(filename) == null) {
if (ProjectMgr.QueryFolderAdd(Parent, path)) {
Directory.CreateDirectory(path);
IsBeingCreated = false;
var relativePath = CommonUtils.GetRelativeDirectoryPath(
ProjectMgr.ProjectHome,
CommonUtils.GetAbsoluteDirectoryPath(CommonUtils.GetParent(Url), label)
);
this.ItemNode.Rename(relativePath);
ProjectMgr.OnItemDeleted(this);
this.Parent.RemoveChild(this);
ProjectMgr.Site.GetUIThread().MustBeCalledFromUIThread();
this.ID = ProjectMgr.ItemIdMap.Add(this);
this.Parent.AddChild(this);
ExpandItem(EXPANDFLAGS.EXPF_SelectItem);
ProjectMgr.Tracker.OnFolderAdded(
path,
VSADDDIRECTORYFLAGS.VSADDDIRECTORYFLAGS_NoFlags
);
}
} else {
Debug.Assert(!wasCancelled); // we choose a label which didn't exist when we started the edit
// Set error: folder already exists
NativeMethods.SetErrorDescription("The folder {0} already exists.", filename);
return VSConstants.E_FAIL;
}
return VSConstants.S_OK;
}
public override int MenuCommandId {
get { return VsMenus.IDM_VS_CTXT_FOLDERNODE; }
}
public override Guid ItemTypeGuid {
get {
return VSConstants.GUID_ItemType_PhysicalFolder;
}
}
public override string Url {
get {
return CommonUtils.EnsureEndSeparator(ItemNode.Url);
}
}
public override string Caption {
get {
// it might have a backslash at the end...
// and it might consist of Grandparent\parent\this\
return CommonUtils.GetFileOrDirectoryName(Url);
}
}
public override string GetMkDocument() {
Debug.Assert(!string.IsNullOrEmpty(this.Url), "No url specified for this node");
Debug.Assert(Path.IsPathRooted(this.Url), "Url should not be a relative path");
return this.Url;
}
/// <summary>
/// Recursively walks the folder nodes and redraws the state icons
/// </summary>
protected internal override void UpdateSccStateIcons() {
for (HierarchyNode child = this.FirstChild; child != null; child = child.NextSibling) {
child.UpdateSccStateIcons();
}
}
internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) {
if (cmdGroup == VsMenus.guidStandardCommandSet97) {
switch ((VsCommands)cmd) {
case VsCommands.Copy:
case VsCommands.Paste:
case VsCommands.Cut:
case VsCommands.Rename:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
case VsCommands.NewFolder:
if (!IsNonMemberItem) {
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
break;
}
} else if (cmdGroup == VsMenus.guidStandardCommandSet2K) {
if ((VsCommands2K)cmd == VsCommands2K.EXCLUDEFROMPROJECT) {
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
} else if (cmdGroup != ProjectMgr.SharedCommandGuid) {
return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP;
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) {
if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage) {
return this.ProjectMgr.CanProjectDeleteItems;
}
return false;
}
protected internal override void GetSccFiles(IList<string> files, IList<tagVsSccFilesFlags> flags) {
for (HierarchyNode n = this.FirstChild; n != null; n = n.NextSibling) {
n.GetSccFiles(files, flags);
}
}
protected internal override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags) {
for (HierarchyNode n = this.FirstChild; n != null; n = n.NextSibling) {
n.GetSccSpecialFiles(sccFile, files, flags);
}
}
#endregion
#region virtual methods
/// <summary>
/// Override if your node is not a file system folder so that
/// it does nothing or it deletes it from your storage location.
/// </summary>
/// <param name="path">Path to the folder to delete</param>
public virtual void DeleteFolder(string path) {
if (Directory.Exists(path)) {
try {
try {
Directory.Delete(path, true);
} catch (UnauthorizedAccessException) {
// probably one or more files are read only
foreach (var file in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)) {
// We will ignore all exceptions here and rethrow when
// we retry the Directory.Delete.
try {
File.SetAttributes(file, FileAttributes.Normal);
} catch (UnauthorizedAccessException) {
} catch (IOException) {
}
}
Directory.Delete(path, true);
}
} catch (IOException ioEx) {
// re-throw with a friendly path
throw new IOException(ioEx.Message.Replace(path, GetEditLabel()));
}
}
}
/// <summary>
/// creates the physical directory for a folder node
/// Override if your node does not use file system folder
/// </summary>
public virtual void CreateDirectory() {
if (Directory.Exists(this.Url) == false) {
Directory.CreateDirectory(this.Url);
}
}
/// <summary>
/// Creates a folder nodes physical directory
/// Override if your node does not use file system folder
/// </summary>
/// <param name="newName"></param>
/// <returns></returns>
public virtual void CreateDirectory(string newName) {
if (String.IsNullOrEmpty(newName)) {
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty), "newName");
}
// on a new dir && enter, we get called with the same name (so do nothing if name is the same
string strNewDir = CommonUtils.GetAbsoluteDirectoryPath(CommonUtils.GetParent(Url), newName);
if (!CommonUtils.IsSameDirectory(Url, strNewDir)) {
if (Directory.Exists(strNewDir)) {
throw new InvalidOperationException(SR.GetString(SR.DirectoryExistsShortMessage));
}
Directory.CreateDirectory(strNewDir);
}
}
/// <summary>
/// Rename the physical directory for a folder node
/// Override if your node does not use file system folder
/// </summary>
/// <returns></returns>
public virtual void RenameDirectory(string newPath) {
if (Directory.Exists(this.Url)) {
if (CommonUtils.IsSamePath(this.Url, newPath)) {
// This is a rename to the same location with (possible) capitilization changes.
// Directory.Move does not allow renaming to the same name so P/Invoke MoveFile to bypass this.
if (!NativeMethods.MoveFile(this.Url, newPath)) {
// Rather than perform error handling, Call Directory.Move and let it handle the error handling.
// If this succeeds, then we didn't really have errors that needed handling.
Directory.Move(this.Url, newPath);
}
} else if (Directory.Exists(newPath)) {
// Directory exists and it wasn't the source. Item cannot be moved as name exists.
ShowFileOrFolderAlreadyExistsErrorMessage(newPath);
} else {
Directory.Move(this.Url, newPath);
}
}
}
void IDiskBasedNode.RenameForDeferredSave(string basePath, string baseNewPath) {
string oldPath = Path.Combine(basePath, ItemNode.GetMetadata(ProjectFileConstants.Include));
string newPath = Path.Combine(baseNewPath, ItemNode.GetMetadata(ProjectFileConstants.Include));
Directory.CreateDirectory(newPath);
ProjectMgr.UpdatePathForDeferredSave(oldPath, newPath);
}
#endregion
#region helper methods
/// <summary>
/// Renames the folder to the new name.
/// </summary>
public virtual void RenameFolder(string newName) {
// Do the rename (note that we only do the physical rename if the leaf name changed)
string newPath = Path.Combine(Parent.FullPathToChildren, newName);
string oldPath = Url;
if (!String.Equals(Path.GetFileName(Url), newName, StringComparison.Ordinal)) {
RenameDirectory(CommonUtils.GetAbsoluteDirectoryPath(ProjectMgr.ProjectHome, newPath));
}
bool wasExpanded = GetIsExpanded();
ReparentFolder(newPath);
var oldTriggerFlag = ProjectMgr.EventTriggeringFlag;
ProjectMgr.EventTriggeringFlag |= ProjectNode.EventTriggering.DoNotTriggerTrackerEvents;
try {
// Let all children know of the new path
for (HierarchyNode child = this.FirstChild; child != null; child = child.NextSibling) {
FolderNode node = child as FolderNode;
if (node == null) {
child.SetEditLabel(child.GetEditLabel());
} else {
node.RenameFolder(node.GetEditLabel());
}
}
} finally {
ProjectMgr.EventTriggeringFlag = oldTriggerFlag;
}
ProjectMgr.Tracker.OnItemRenamed(oldPath, newPath, VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_Directory);
// Some of the previous operation may have changed the selection so set it back to us
ExpandItem(wasExpanded ? EXPANDFLAGS.EXPF_ExpandFolder : EXPANDFLAGS.EXPF_CollapseFolder);
ExpandItem(EXPANDFLAGS.EXPF_SelectItem);
}
/// <summary>
/// Moves the HierarchyNode from the old path to be a child of the
/// newly specified node.
///
/// This is a low-level operation that only updates the hierarchy and our MSBuild
/// state. The parents of the node must already be created.
///
/// To do a general rename, call RenameFolder instead.
/// </summary>
internal void ReparentFolder(string newPath) {
// Reparent the folder
ProjectMgr.OnItemDeleted(this);
Parent.RemoveChild(this);
ProjectMgr.Site.GetUIThread().MustBeCalledFromUIThread();
ID = ProjectMgr.ItemIdMap.Add(this);
ItemNode.Rename(CommonUtils.GetRelativeDirectoryPath(ProjectMgr.ProjectHome, newPath));
var parent = ProjectMgr.GetParentFolderForPath(newPath);
Debug.Assert(parent != null, "ReparentFolder called without full path to parent being created");
parent.AddChild(this);
}
/// <summary>
/// Show error message if not in automation mode, otherwise throw exception
/// </summary>
/// <param name="newPath">path of file or folder already existing on disk</param>
/// <returns>S_OK</returns>
private int ShowFileOrFolderAlreadyExistsErrorMessage(string newPath) {
//A file or folder with the name '{0}' already exists on disk at this location. Please choose another name.
//If this file or folder does not appear in the Solution Explorer, then it is not currently part of your project. To view files which exist on disk, but are not in the project, select Show All Files from the Project menu.
string errorMessage = SR.GetString(SR.FileOrFolderAlreadyExists, newPath);
if (!Utilities.IsInAutomationFunction(this.ProjectMgr.Site)) {
string title = null;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
Utilities.ShowMessageBox(this.ProjectMgr.Site, title, errorMessage, icon, buttons, defaultButton);
return VSConstants.S_OK;
} else {
throw new InvalidOperationException(errorMessage);
}
}
protected override void OnCancelLabelEdit() {
if (IsBeingCreated) {
// finish the creation
FinishFolderAdd(GetEditLabel(), true);
}
}
internal bool IsBeingCreated {
get {
return ProjectMgr.FolderBeingCreated == this;
}
set {
if (value) {
ProjectMgr.FolderBeingCreated = this;
} else {
ProjectMgr.FolderBeingCreated = null;
}
}
}
#endregion
protected override void RaiseOnItemRemoved(string documentToRemove, string[] filesToBeDeleted) {
VSREMOVEDIRECTORYFLAGS[] removeFlags = new VSREMOVEDIRECTORYFLAGS[1];
this.ProjectMgr.Tracker.OnFolderRemoved(documentToRemove, removeFlags[0]);
}
}
}
| zhoffice/nodejstools | Common/Product/SharedProject/FolderNode.cs | C# | apache-2.0 | 23,776 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.core.ml.dataframe.stats.outlierdetection;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.Objects;
import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg;
public class Parameters implements Writeable, ToXContentObject {
public static final ParseField N_NEIGHBORS = new ParseField("n_neighbors");
public static final ParseField METHOD = new ParseField("method");
public static final ParseField FEATURE_INFLUENCE_THRESHOLD = new ParseField("feature_influence_threshold");
public static final ParseField COMPUTE_FEATURE_INFLUENCE = new ParseField("compute_feature_influence");
public static final ParseField OUTLIER_FRACTION = new ParseField("outlier_fraction");
public static final ParseField STANDARDIZATION_ENABLED = new ParseField("standardization_enabled");
public static Parameters fromXContent(XContentParser parser, boolean ignoreUnknownFields) {
return createParser(ignoreUnknownFields).apply(parser, null);
}
private static ConstructingObjectParser<Parameters, Void> createParser(boolean ignoreUnknownFields) {
ConstructingObjectParser<Parameters, Void> parser = new ConstructingObjectParser<>("outlier_detection_parameters",
ignoreUnknownFields,
a -> new Parameters(
(int) a[0],
(String) a[1],
(boolean) a[2],
(double) a[3],
(double) a[4],
(boolean) a[5]
));
parser.declareInt(constructorArg(), N_NEIGHBORS);
parser.declareString(constructorArg(), METHOD);
parser.declareBoolean(constructorArg(), COMPUTE_FEATURE_INFLUENCE);
parser.declareDouble(constructorArg(), FEATURE_INFLUENCE_THRESHOLD);
parser.declareDouble(constructorArg(), OUTLIER_FRACTION);
parser.declareBoolean(constructorArg(), STANDARDIZATION_ENABLED);
return parser;
}
private final int nNeighbors;
private final String method;
private final boolean computeFeatureInfluence;
private final double featureInfluenceThreshold;
private final double outlierFraction;
private final boolean standardizationEnabled;
public Parameters(int nNeighbors, String method, boolean computeFeatureInfluence, double featureInfluenceThreshold,
double outlierFraction, boolean standardizationEnabled) {
this.nNeighbors = nNeighbors;
this.method = method;
this.computeFeatureInfluence = computeFeatureInfluence;
this.featureInfluenceThreshold = featureInfluenceThreshold;
this.outlierFraction = outlierFraction;
this.standardizationEnabled = standardizationEnabled;
}
public Parameters(StreamInput in) throws IOException {
this.nNeighbors = in.readVInt();
this.method = in.readString();
this.computeFeatureInfluence = in.readBoolean();
this.featureInfluenceThreshold = in.readDouble();
this.outlierFraction = in.readDouble();
this.standardizationEnabled = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(nNeighbors);
out.writeString(method);
out.writeBoolean(computeFeatureInfluence);
out.writeDouble(featureInfluenceThreshold);
out.writeDouble(outlierFraction);
out.writeBoolean(standardizationEnabled);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(N_NEIGHBORS.getPreferredName(), nNeighbors);
builder.field(METHOD.getPreferredName(), method);
builder.field(COMPUTE_FEATURE_INFLUENCE.getPreferredName(), computeFeatureInfluence);
builder.field(FEATURE_INFLUENCE_THRESHOLD.getPreferredName(), featureInfluenceThreshold);
builder.field(OUTLIER_FRACTION.getPreferredName(), outlierFraction);
builder.field(STANDARDIZATION_ENABLED.getPreferredName(), standardizationEnabled);
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Parameters that = (Parameters) o;
return nNeighbors == that.nNeighbors
&& Objects.equals(method, that.method)
&& computeFeatureInfluence == that.computeFeatureInfluence
&& featureInfluenceThreshold == that.featureInfluenceThreshold
&& outlierFraction == that.outlierFraction
&& standardizationEnabled == that.standardizationEnabled;
}
@Override
public int hashCode() {
return Objects.hash(nNeighbors, method, computeFeatureInfluence, featureInfluenceThreshold, outlierFraction,
standardizationEnabled);
}
}
| robin13/elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/dataframe/stats/outlierdetection/Parameters.java | Java | apache-2.0 | 5,618 |
/*
* IzPack - Copyright 2001-2010 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2005,2009 Ivan SZKIBA
* Copyright 2010,2011 Rene Krell
*
* 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.izforge.izpack.api.config;
import java.lang.reflect.Array;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.izforge.izpack.api.config.spi.AbstractBeanInvocationHandler;
import com.izforge.izpack.api.config.spi.BeanTool;
import com.izforge.izpack.api.config.spi.IniHandler;
public class BasicProfile extends CommonMultiMap<String, Profile.Section> implements Profile
{
private static final String SECTION_SYSTEM_PROPERTIES = "@prop";
private static final String SECTION_ENVIRONMENT = "@env";
private static final Pattern EXPRESSION = Pattern.compile(
"(?<!\\\\)\\$\\{(([^\\[\\}]+)(\\[([0-9]+)\\])?/)?([^\\[^/\\}]+)(\\[(([0-9]+))\\])?\\}");
private static final int G_SECTION = 2;
private static final int G_SECTION_IDX = 4;
private static final int G_OPTION = 5;
private static final int G_OPTION_IDX = 7;
private static final long serialVersionUID = -1817521505004015256L;
private List<String> _comment;
private List<String> _footerComment;
private final boolean _propertyFirstUpper;
private final boolean _treeMode;
public BasicProfile()
{
this(false, false);
}
public BasicProfile(boolean treeMode, boolean propertyFirstUpper)
{
_treeMode = treeMode;
_propertyFirstUpper = propertyFirstUpper;
}
@Override public List<String> getHeaderComment()
{
return _comment;
}
@Override public void setHeaderComment(List<String> value)
{
_comment = value;
}
@Override public List<String> getFooterComment()
{
return _footerComment;
}
@Override public void setFooterComment(List<String> value)
{
_footerComment = value;
}
@Override public Section add(String name)
{
if (isTreeMode())
{
int idx = name.lastIndexOf(getPathSeparator());
if (idx > 0)
{
String parent = name.substring(0, idx);
if (!containsKey(parent))
{
add(parent);
}
}
}
Section section = newSection(name);
add(name, section);
return section;
}
@Override public void add(String section, String option, Object value)
{
getOrAdd(section).add(option, value);
}
@Override public <T> T as(Class<T> clazz)
{
return as(clazz, null);
}
@Override public <T> T as(Class<T> clazz, String prefix)
{
return clazz.cast(Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { clazz },
new BeanInvocationHandler(prefix)));
}
@Override public String fetch(Object sectionName, Object optionName)
{
Section sec = get(sectionName);
return (sec == null) ? null : sec.fetch(optionName);
}
@Override public <T> T fetch(Object sectionName, Object optionName, Class<T> clazz)
{
Section sec = get(sectionName);
return (sec == null) ? BeanTool.getInstance().zero(clazz) : sec.fetch(optionName, clazz);
}
@Override public String get(Object sectionName, Object optionName)
{
Section sec = get(sectionName);
return (sec == null) ? null : sec.get(optionName);
}
@Override public <T> T get(Object sectionName, Object optionName, Class<T> clazz)
{
Section sec = get(sectionName);
return (sec == null) ? BeanTool.getInstance().zero(clazz) : sec.get(optionName, clazz);
}
@Override public String put(String sectionName, String optionName, Object value)
{
return getOrAdd(sectionName).put(optionName, value);
}
@Override public Section remove(Section section)
{
return remove((Object) section.getName());
}
@Override public String removeOptionFromSection(Object sectionName, Object optionName)
{
Section sec = get(sectionName);
return (sec == null) ? null : sec.remove(optionName);
}
boolean isTreeMode()
{
return _treeMode;
}
char getPathSeparator()
{
return PATH_SEPARATOR;
}
boolean isPropertyFirstUpper()
{
return _propertyFirstUpper;
}
Section newSection(String name)
{
return new BasicProfileSection(this, name);
}
void resolve(StringBuilder buffer, Section owner)
{
Matcher m = EXPRESSION.matcher(buffer);
while (m.find())
{
String sectionName = m.group(G_SECTION);
String optionName = m.group(G_OPTION);
int optionIndex = parseOptionIndex(m);
Section section = parseSection(m, owner);
String value = null;
if (SECTION_ENVIRONMENT.equals(sectionName))
{
value = Config.getEnvironment(optionName);
}
else if (SECTION_SYSTEM_PROPERTIES.equals(sectionName))
{
value = Config.getSystemProperty(optionName);
}
else if (section != null)
{
value = (optionIndex == -1) ? section.fetch(optionName) : section.fetch(optionName, optionIndex);
}
if (value != null)
{
buffer.replace(m.start(), m.end(), value);
m.reset(buffer);
}
}
}
void store(IniHandler formatter)
{
formatter.startIni();
store(formatter, getHeaderComment());
for (Ini.Section s : values())
{
store(formatter, s);
}
if (_footerComment != null)
{
store(formatter, _footerComment);
}
formatter.endIni();
}
void store(IniHandler formatter, Section s)
{
store(formatter, getComment(s.getName()));
formatter.startSection(s.getName());
for (String name : s.keySet())
{
store(formatter, s, name);
}
formatter.endSection();
}
void store(IniHandler formatter, List<String> comment)
{
formatter.handleComment(comment);
}
void store(IniHandler formatter, Section section, String option)
{
store(formatter, section.getComment(option));
int n = section.length(option);
for (int i = 0; i < n; i++)
{
store(formatter, section, option, i);
}
}
void store(IniHandler formatter, Section section, String option, int index)
{
formatter.handleOption(option, section.get(option, index));
}
private Section getOrAdd(String sectionName)
{
Section section = get(sectionName);
return ((section == null)) ? add(sectionName) : section;
}
private int parseOptionIndex(Matcher m)
{
return (m.group(G_OPTION_IDX) == null) ? -1 : Integer.parseInt(m.group(G_OPTION_IDX));
}
private Section parseSection(Matcher m, Section owner)
{
String sectionName = m.group(G_SECTION);
int sectionIndex = parseSectionIndex(m);
return (sectionName == null) ? owner : ((sectionIndex == -1) ? get(sectionName) : get(sectionName, sectionIndex));
}
private int parseSectionIndex(Matcher m)
{
return (m.group(G_SECTION_IDX) == null) ? -1 : Integer.parseInt(m.group(G_SECTION_IDX));
}
private final class BeanInvocationHandler extends AbstractBeanInvocationHandler
{
private final String _prefix;
private BeanInvocationHandler(String prefix)
{
_prefix = prefix;
}
@Override protected Object getPropertySpi(String property, Class<?> clazz)
{
String key = transform(property);
Object o = null;
if (containsKey(key))
{
if (clazz.isArray())
{
o = Array.newInstance(clazz.getComponentType(), length(key));
for (int i = 0; i < length(key); i++)
{
Array.set(o, i, get(key, i).as(clazz.getComponentType()));
}
}
else
{
o = get(key).as(clazz);
}
}
return o;
}
@Override protected void setPropertySpi(String property, Object value, Class<?> clazz)
{
String key = transform(property);
remove(key);
if (value != null)
{
if (clazz.isArray())
{
for (int i = 0; i < Array.getLength(value); i++)
{
Section sec = add(key);
sec.from(Array.get(value, i));
}
}
else
{
Section sec = add(key);
sec.from(value);
}
}
}
@Override protected boolean hasPropertySpi(String property)
{
return containsKey(transform(property));
}
String transform(String property)
{
String ret = (_prefix == null) ? property : (_prefix + property);
if (isPropertyFirstUpper())
{
StringBuilder buff = new StringBuilder();
buff.append(Character.toUpperCase(property.charAt(0)));
buff.append(property.substring(1));
ret = buff.toString();
}
return ret;
}
}
}
| akuhtz/izpack | izpack-api/src/main/java/com/izforge/izpack/api/config/BasicProfile.java | Java | apache-2.0 | 10,403 |
/* Copyright 2015 Samsung Electronics 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 "iotjs_def.h"
#include "iotjs_module_timer.h"
#include "iotjs_handlewrap.h"
namespace iotjs {
class TimerWrap : public HandleWrap {
public:
explicit TimerWrap(Environment* env, JObject& jtimer)
: HandleWrap(jtimer, reinterpret_cast<uv_handle_t*>(&_handle))
, _jcallback(NULL) {
// Initialze timer handler.
uv_timer_init(env->loop(), &_handle);
}
// Timer timeout callback handler.
void OnTimeout();
// Timer close callback handler.
void OnClose();
// Start timer.
int Start(int64_t timeout, int64_t repeat, JObject& jcallback);
// Stop & close timer.
int Stop();
// Retreive javascript callback function.
JObject* jcallback() { return _jcallback; }
protected:
// timer handle.
uv_timer_t _handle;
// Javascript callback function.
JObject* _jcallback;
};
// This function is called from uv when timeout expires.
static void TimeoutHandler(uv_timer_t* handle) {
// Find timer wrap from handle.
HandleWrap* handle_wrap = HandleWrap::FromHandle((uv_handle_t*)handle);
TimerWrap* timer_wrap = reinterpret_cast<TimerWrap*>(handle_wrap);
// Call the timeout handler.
timer_wrap->OnTimeout();
}
void TimerWrap::OnTimeout() {
// Verification.
IOTJS_ASSERT(jobject().IsObject());
IOTJS_ASSERT(_jcallback != NULL);
IOTJS_ASSERT(_jcallback->IsFunction());
// Call javascirpt timeout callback function.
MakeCallback(*_jcallback, jobject(), JArgList::Empty());
}
// Start timer.
int TimerWrap::Start(int64_t timeout, int64_t repeat, JObject& jcallback) {
// We should not have javascript callback handler yet.
IOTJS_ASSERT(_jcallback == NULL);
IOTJS_ASSERT(jcallback.IsFunction());
// Create new Javascirpt function reference for the callback function.
_jcallback = new JObject(jcallback);
// Start uv timer.
return uv_timer_start(&_handle,
TimeoutHandler,
timeout,
repeat);
}
// This function is called from uv after timer close.
static void OnTimerClose(uv_handle_t* handle) {
// Find timer wrap from handle.
HandleWrap* handle_wrap = HandleWrap::FromHandle(handle);
TimerWrap* timer_wrap = reinterpret_cast<TimerWrap*>(handle_wrap);
// Call the close handler.
timer_wrap->OnClose();
}
void TimerWrap::OnClose() {
// If we have javascript timeout callback reference, release it.
if (_jcallback != NULL) {
delete _jcallback;
_jcallback = NULL;
}
}
int TimerWrap::Stop() {
// Close timer.
if (!uv_is_closing(__handle)) {
Close(OnTimerClose);
}
return 0;
}
JHANDLER_FUNCTION(Start) {
// Check parameters.
JHANDLER_CHECK(handler.GetThis()->IsObject());
JHANDLER_CHECK(handler.GetArgLength() >= 3);
JHANDLER_CHECK(handler.GetArg(0)->IsNumber());
JHANDLER_CHECK(handler.GetArg(1)->IsNumber());
JHANDLER_CHECK(handler.GetArg(2)->IsFunction());
JObject* jtimer = handler.GetThis();
// Take timer wrap.
TimerWrap* timer_wrap = reinterpret_cast<TimerWrap*>(jtimer->GetNative());
IOTJS_ASSERT(timer_wrap != NULL);
IOTJS_ASSERT(timer_wrap->jobject().IsObject());
// parameters.
int64_t timeout = handler.GetArg(0)->GetInt64();
int64_t repeat = handler.GetArg(1)->GetInt64();
JObject* jcallback = handler.GetArg(2);
// We do not permit double start.
JHANDLER_CHECK(timer_wrap->jcallback() == NULL);
// Start timer.
int res = timer_wrap->Start(timeout, repeat, *jcallback);
JObject ret(res);
handler.Return(ret);
return true;
}
JHANDLER_FUNCTION(Stop) {
JHANDLER_CHECK(handler.GetThis()->IsObject());
JObject* jtimer = handler.GetThis();
TimerWrap* timer_wrap = reinterpret_cast<TimerWrap*>(jtimer->GetNative());
IOTJS_ASSERT(timer_wrap != NULL);
IOTJS_ASSERT(timer_wrap->jobject().IsObject());
// Stop timer.
int res = timer_wrap->Stop();
JObject ret(res);
handler.Return(ret);
return true;
}
JHANDLER_FUNCTION(Timer) {
JHANDLER_CHECK(handler.GetThis()->IsObject());
Environment* env = Environment::GetEnv();
JObject* jtimer = handler.GetThis();
TimerWrap* timer_wrap = new TimerWrap(env, *jtimer);
IOTJS_ASSERT(timer_wrap->jobject().IsObject());
IOTJS_ASSERT(jtimer->GetNative() != 0);;
return true;
}
JObject* InitTimer() {
Module* module = GetBuiltinModule(MODULE_TIMER);
JObject* timer = module->module;
if (timer == NULL) {
timer = new JObject(Timer);
JObject prototype;
timer->SetProperty("prototype", prototype);
prototype.SetMethod("start", Start);
prototype.SetMethod("stop", Stop);
module->module = timer;
}
return timer;
}
} // namespace iotjs
| wateret/iotjs | src/iotjs_module_timer.cpp | C++ | apache-2.0 | 5,218 |
package io.cattle.platform.docker.machine.launch;
import io.cattle.platform.lock.definition.AbstractLockDefinition;
import io.cattle.platform.lock.definition.LockDefinition;
public class MachineDriverLoaderLock extends AbstractLockDefinition implements LockDefinition {
private static final String LOCK_NAME = "MACHINE.DRIVER.LOADER";
public MachineDriverLoaderLock() {
super(LOCK_NAME);
}
}
| wlan0/cattle | code/implementation/docker/machine/src/main/java/io/cattle/platform/docker/machine/launch/MachineDriverLoaderLock.java | Java | apache-2.0 | 416 |
/*
* Copyright 2007 Sascha Weinreuter
*
* 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.intellij.plugins.relaxNG.validation;
import com.intellij.javaee.UriUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.AtomicNotNullLazyValue;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.util.CachedValue;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.psi.xml.XmlFile;
import com.intellij.util.containers.ContainerUtil;
import com.thaiopensource.datatype.xsd.DatatypeLibraryFactoryImpl;
import com.thaiopensource.relaxng.impl.SchemaReaderImpl;
import com.thaiopensource.util.PropertyMap;
import com.thaiopensource.util.PropertyMapBuilder;
import com.thaiopensource.validate.Schema;
import com.thaiopensource.xml.sax.Sax2XMLReaderCreator;
import com.thaiopensource.xml.sax.XMLReaderCreator;
import org.intellij.plugins.relaxNG.compact.RncFileType;
import org.intellij.plugins.relaxNG.model.resolve.RelaxIncludeIndex;
import org.jetbrains.annotations.NotNull;
import org.kohsuke.rngom.ast.builder.BuildException;
import org.kohsuke.rngom.ast.builder.IncludedGrammar;
import org.kohsuke.rngom.ast.builder.SchemaBuilder;
import org.kohsuke.rngom.ast.om.ParsedPattern;
import org.kohsuke.rngom.binary.SchemaBuilderImpl;
import org.kohsuke.rngom.binary.SchemaPatternBuilder;
import org.kohsuke.rngom.digested.DPattern;
import org.kohsuke.rngom.digested.DSchemaBuilderImpl;
import org.kohsuke.rngom.dt.CachedDatatypeLibraryFactory;
import org.kohsuke.rngom.dt.CascadingDatatypeLibraryFactory;
import org.kohsuke.rngom.dt.DoNothingDatatypeLibraryFactoryImpl;
import org.kohsuke.rngom.dt.builtin.BuiltinDatatypeLibraryFactory;
import org.kohsuke.rngom.parse.IllegalSchemaException;
import org.kohsuke.rngom.parse.Parseable;
import org.kohsuke.rngom.parse.compact.CompactParseable;
import org.kohsuke.rngom.parse.xml.SAXParseable;
import org.relaxng.datatype.DatatypeLibrary;
import org.relaxng.datatype.DatatypeLibraryFactory;
import org.relaxng.datatype.helpers.DatatypeLibraryLoader;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.StringReader;
import java.util.concurrent.ConcurrentMap;
public class RngParser {
private static final Logger LOG = Logger.getInstance("#org.intellij.plugins.relaxNG.validation.RngParser");
private static final NotNullLazyValue<DatatypeLibraryFactory> DT_LIBRARY_FACTORY = new AtomicNotNullLazyValue<DatatypeLibraryFactory>() {
@NotNull
@Override
protected DatatypeLibraryFactory compute() {
return new BuiltinDatatypeLibraryFactory(new CachedDatatypeLibraryFactory(
new CascadingDatatypeLibraryFactory(createXsdDatatypeFactory(), new DatatypeLibraryLoader())) {
@Override
public synchronized DatatypeLibrary createDatatypeLibrary(String namespaceURI) {
return super.createDatatypeLibrary(namespaceURI);
}
});
}
};
private static final ConcurrentMap<String, DPattern> ourCache = ContainerUtil.createConcurrentSoftMap();
private static DatatypeLibraryFactory createXsdDatatypeFactory() {
try {
return new DatatypeLibraryFactoryImpl();
} catch (Throwable e) {
LOG.error("Could not create DT library implementation 'com.thaiopensource.datatype.xsd.DatatypeLibraryFactoryImpl'. Plugin's classpath seems to be broken.", e);
return new DoNothingDatatypeLibraryFactoryImpl();
}
}
static final Key<CachedValue<Schema>> SCHEMA_KEY = Key.create("SCHEMA");
public static final DefaultHandler DEFAULT_HANDLER = new DefaultHandler() {
@Override
public void error(SAXParseException e) throws SAXException {
LOG.info("e.getMessage() = " + e.getMessage() + " [" + e.getSystemId() + "]");
LOG.info(e);
}
};
static final PropertyMap EMPTY_PROPS = new PropertyMapBuilder().toPropertyMap();
public static DPattern getCachedPattern(final PsiFile descriptorFile, final ErrorHandler eh) {
final VirtualFile file = descriptorFile.getVirtualFile();
if (file == null) {
return parsePattern(descriptorFile, eh, false);
}
String url = file.getUrl();
DPattern pattern = ourCache.get(url);
if (pattern == null) {
pattern = parsePattern(descriptorFile, eh, false);
}
if (pattern != null) {
DPattern oldPattern = ourCache.putIfAbsent(url, pattern);
if (oldPattern != null) {
return oldPattern;
}
}
return pattern;
}
public static DPattern parsePattern(final PsiFile file, final ErrorHandler eh, boolean checking) {
try {
final Parseable p = createParsable(file, eh);
if (checking) {
p.parse(new SchemaBuilderImpl(eh, DT_LIBRARY_FACTORY.getValue(), new SchemaPatternBuilder()));
} else {
return p.parse(new DSchemaBuilderImpl());
}
} catch (BuildException e) {
LOG.info(e);
} catch (IllegalSchemaException e) {
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("invalid schema: " + virtualFile.getPresentableUrl(), e);
} else {
LOG.info("invalid schema: " + virtualFile.getPresentableUrl() + ". [" + e.getMessage() + "]");
}
}
}
return null;
}
private static Parseable createParsable(final PsiFile file, final ErrorHandler eh) {
final InputSource source = makeInputSource(file);
final VirtualFile virtualFile = file.getVirtualFile();
if (file.getFileType() == RncFileType.getInstance()) {
return new CompactParseable(source, eh) {
@Override
public ParsedPattern parseInclude(String uri, SchemaBuilder schemaBuilder, IncludedGrammar g, String inheritedNs)
throws BuildException, IllegalSchemaException
{
ProgressManager.checkCanceled();
return super.parseInclude(resolveURI(virtualFile, uri), schemaBuilder, g, inheritedNs);
}
};
} else {
return new SAXParseable(source, eh) {
@Override
public ParsedPattern parseInclude(String uri, SchemaBuilder schemaBuilder, IncludedGrammar g, String inheritedNs)
throws BuildException, IllegalSchemaException
{
ProgressManager.checkCanceled();
return super.parseInclude(resolveURI(virtualFile, uri), schemaBuilder, g, inheritedNs);
}
};
}
}
private static String resolveURI(VirtualFile descriptorFile, String s) {
final VirtualFile file = UriUtil.findRelativeFile(s, descriptorFile);
if (file != null) {
s = VfsUtilCore.fixIDEAUrl(file.getUrl());
}
return s;
}
public static Schema getCachedSchema(final XmlFile descriptorFile) {
CachedValue<Schema> value = descriptorFile.getUserData(SCHEMA_KEY);
if (value == null) {
final CachedValueProvider<Schema> provider = () -> {
final InputSource inputSource = makeInputSource(descriptorFile);
try {
final Schema schema = new MySchemaReader(descriptorFile).createSchema(inputSource, EMPTY_PROPS);
final PsiElementProcessor.CollectElements<XmlFile> processor = new PsiElementProcessor.CollectElements<>();
RelaxIncludeIndex.processForwardDependencies(descriptorFile, processor);
if (processor.getCollection().size() > 0) {
return CachedValueProvider.Result.create(schema, processor.toArray(), descriptorFile);
} else {
return CachedValueProvider.Result.createSingleDependency(schema, descriptorFile);
}
} catch (Exception e) {
LOG.info(e);
return CachedValueProvider.Result.createSingleDependency(null, descriptorFile);
}
};
final CachedValuesManager mgr = CachedValuesManager.getManager(descriptorFile.getProject());
value = mgr.createCachedValue(provider, false);
descriptorFile.putUserData(SCHEMA_KEY, value);
}
return value.getValue();
}
private static InputSource makeInputSource(PsiFile descriptorFile) {
final InputSource inputSource = new InputSource(new StringReader(descriptorFile.getText()));
final VirtualFile file = descriptorFile.getVirtualFile();
if (file != null) {
inputSource.setSystemId(VfsUtilCore.fixIDEAUrl(file.getUrl()));
}
return inputSource;
}
static class MySchemaReader extends SchemaReaderImpl {
private final PsiFile myDescriptorFile;
public MySchemaReader(PsiFile descriptorFile) {
myDescriptorFile = descriptorFile;
}
@Override
protected com.thaiopensource.relaxng.parse.Parseable createParseable(XMLReaderCreator xmlReaderCreator, InputSource inputSource, ErrorHandler errorHandler) {
if (myDescriptorFile.getFileType() == RncFileType.getInstance()) {
return new com.thaiopensource.relaxng.parse.compact.CompactParseable(inputSource, errorHandler);
} else {
return new com.thaiopensource.relaxng.parse.sax.SAXParseable(new Sax2XMLReaderCreator(), inputSource, errorHandler);
}
}
}
} | apixandru/intellij-community | xml/relaxng/src/org/intellij/plugins/relaxNG/validation/RngParser.java | Java | apache-2.0 | 10,006 |
/*
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 validation
import (
"encoding/json"
"fmt"
"math"
"net"
"path"
"path/filepath"
"reflect"
"regexp"
"strings"
"unicode"
"unicode/utf8"
"github.com/google/go-cmp/cmp"
v1 "k8s.io/api/core/v1"
apiequality "k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/resource"
apimachineryvalidation "k8s.io/apimachinery/pkg/api/validation"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
unversionedvalidation "k8s.io/apimachinery/pkg/apis/meta/v1/validation"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation"
"k8s.io/apimachinery/pkg/util/validation/field"
utilfeature "k8s.io/apiserver/pkg/util/feature"
schedulinghelper "k8s.io/component-helpers/scheduling/corev1"
apiservice "k8s.io/kubernetes/pkg/api/service"
"k8s.io/kubernetes/pkg/apis/core"
api "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/apis/core/helper"
podshelper "k8s.io/kubernetes/pkg/apis/core/pods"
corev1 "k8s.io/kubernetes/pkg/apis/core/v1"
"k8s.io/kubernetes/pkg/capabilities"
"k8s.io/kubernetes/pkg/cluster/ports"
"k8s.io/kubernetes/pkg/features"
"k8s.io/kubernetes/pkg/fieldpath"
netutils "k8s.io/utils/net"
)
const isNegativeErrorMsg string = apimachineryvalidation.IsNegativeErrorMsg
const isInvalidQuotaResource string = `must be a standard resource for quota`
const fieldImmutableErrorMsg string = apimachineryvalidation.FieldImmutableErrorMsg
const isNotIntegerErrorMsg string = `must be an integer`
const isNotPositiveErrorMsg string = `must be greater than zero`
var pdPartitionErrorMsg string = validation.InclusiveRangeError(1, 255)
var fileModeErrorMsg = "must be a number between 0 and 0777 (octal), both inclusive"
// BannedOwners is a black list of object that are not allowed to be owners.
var BannedOwners = apimachineryvalidation.BannedOwners
var iscsiInitiatorIqnRegex = regexp.MustCompile(`iqn\.\d{4}-\d{2}\.([[:alnum:]-.]+)(:[^,;*&$|\s]+)$`)
var iscsiInitiatorEuiRegex = regexp.MustCompile(`^eui.[[:alnum:]]{16}$`)
var iscsiInitiatorNaaRegex = regexp.MustCompile(`^naa.[[:alnum:]]{32}$`)
var allowedEphemeralContainerFields = map[string]bool{
"Name": true,
"Image": true,
"Command": true,
"Args": true,
"WorkingDir": true,
"Ports": false,
"EnvFrom": true,
"Env": true,
"Resources": false,
"VolumeMounts": true,
"VolumeDevices": true,
"LivenessProbe": false,
"ReadinessProbe": false,
"StartupProbe": false,
"Lifecycle": false,
"TerminationMessagePath": true,
"TerminationMessagePolicy": true,
"ImagePullPolicy": true,
"SecurityContext": true,
"Stdin": true,
"StdinOnce": true,
"TTY": true,
}
// validOS stores the set of valid OSes within pod spec.
// The valid values currently are linux, windows.
// In future, they can be expanded to values from
// https://github.com/opencontainers/runtime-spec/blob/master/config.md#platform-specific-configuration
var validOS = sets.NewString(string(core.Linux), string(core.Windows))
// ValidateHasLabel requires that metav1.ObjectMeta has a Label with key and expectedValue
func ValidateHasLabel(meta metav1.ObjectMeta, fldPath *field.Path, key, expectedValue string) field.ErrorList {
allErrs := field.ErrorList{}
actualValue, found := meta.Labels[key]
if !found {
allErrs = append(allErrs, field.Required(fldPath.Child("labels").Key(key),
fmt.Sprintf("must be '%s'", expectedValue)))
return allErrs
}
if actualValue != expectedValue {
allErrs = append(allErrs, field.Invalid(fldPath.Child("labels").Key(key), meta.Labels,
fmt.Sprintf("must be '%s'", expectedValue)))
}
return allErrs
}
// ValidateAnnotations validates that a set of annotations are correctly defined.
func ValidateAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {
return apimachineryvalidation.ValidateAnnotations(annotations, fldPath)
}
func ValidateDNS1123Label(value string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for _, msg := range validation.IsDNS1123Label(value) {
allErrs = append(allErrs, field.Invalid(fldPath, value, msg))
}
return allErrs
}
// ValidateQualifiedName validates if name is what Kubernetes calls a "qualified name".
func ValidateQualifiedName(value string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for _, msg := range validation.IsQualifiedName(value) {
allErrs = append(allErrs, field.Invalid(fldPath, value, msg))
}
return allErrs
}
// ValidateDNS1123Subdomain validates that a name is a proper DNS subdomain.
func ValidateDNS1123Subdomain(value string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for _, msg := range validation.IsDNS1123Subdomain(value) {
allErrs = append(allErrs, field.Invalid(fldPath, value, msg))
}
return allErrs
}
func ValidatePodSpecificAnnotations(annotations map[string]string, spec *core.PodSpec, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
if value, isMirror := annotations[core.MirrorPodAnnotationKey]; isMirror {
if len(spec.NodeName) == 0 {
allErrs = append(allErrs, field.Invalid(fldPath.Key(core.MirrorPodAnnotationKey), value, "must set spec.nodeName if mirror pod annotation is set"))
}
}
if annotations[core.TolerationsAnnotationKey] != "" {
allErrs = append(allErrs, ValidateTolerationsInPodAnnotations(annotations, fldPath)...)
}
if !opts.AllowInvalidPodDeletionCost {
if _, err := helper.GetDeletionCostFromPodAnnotations(annotations); err != nil {
allErrs = append(allErrs, field.Invalid(fldPath.Key(core.PodDeletionCost), annotations[core.PodDeletionCost], "must be a 32bit integer"))
}
}
allErrs = append(allErrs, ValidateSeccompPodAnnotations(annotations, fldPath)...)
allErrs = append(allErrs, ValidateAppArmorPodAnnotations(annotations, spec, fldPath)...)
return allErrs
}
// ValidateTolerationsInPodAnnotations tests that the serialized tolerations in Pod.Annotations has valid data
func ValidateTolerationsInPodAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
tolerations, err := helper.GetTolerationsFromPodAnnotations(annotations)
if err != nil {
allErrs = append(allErrs, field.Invalid(fldPath, core.TolerationsAnnotationKey, err.Error()))
return allErrs
}
if len(tolerations) > 0 {
allErrs = append(allErrs, ValidateTolerations(tolerations, fldPath.Child(core.TolerationsAnnotationKey))...)
}
return allErrs
}
func ValidatePodSpecificAnnotationUpdates(newPod, oldPod *core.Pod, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
newAnnotations := newPod.Annotations
oldAnnotations := oldPod.Annotations
for k, oldVal := range oldAnnotations {
if newVal, exists := newAnnotations[k]; exists && newVal == oldVal {
continue // No change.
}
if strings.HasPrefix(k, v1.AppArmorBetaContainerAnnotationKeyPrefix) {
allErrs = append(allErrs, field.Forbidden(fldPath.Key(k), "may not remove or update AppArmor annotations"))
}
if k == core.MirrorPodAnnotationKey {
allErrs = append(allErrs, field.Forbidden(fldPath.Key(k), "may not remove or update mirror pod annotation"))
}
}
// Check for additions
for k := range newAnnotations {
if _, ok := oldAnnotations[k]; ok {
continue // No change.
}
if strings.HasPrefix(k, v1.AppArmorBetaContainerAnnotationKeyPrefix) {
allErrs = append(allErrs, field.Forbidden(fldPath.Key(k), "may not add AppArmor annotations"))
}
if k == core.MirrorPodAnnotationKey {
allErrs = append(allErrs, field.Forbidden(fldPath.Key(k), "may not add mirror pod annotation"))
}
}
allErrs = append(allErrs, ValidatePodSpecificAnnotations(newAnnotations, &newPod.Spec, fldPath, opts)...)
return allErrs
}
func ValidateEndpointsSpecificAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
return allErrs
}
// ValidateNameFunc validates that the provided name is valid for a given resource type.
// Not all resources have the same validation rules for names. Prefix is true
// if the name will have a value appended to it. If the name is not valid,
// this returns a list of descriptions of individual characteristics of the
// value that were not valid. Otherwise this returns an empty list or nil.
type ValidateNameFunc apimachineryvalidation.ValidateNameFunc
// ValidatePodName can be used to check whether the given pod name is valid.
// Prefix indicates this name will be used as part of generation, in which case
// trailing dashes are allowed.
var ValidatePodName = apimachineryvalidation.NameIsDNSSubdomain
// ValidateReplicationControllerName can be used to check whether the given replication
// controller name is valid.
// Prefix indicates this name will be used as part of generation, in which case
// trailing dashes are allowed.
var ValidateReplicationControllerName = apimachineryvalidation.NameIsDNSSubdomain
// ValidateServiceName can be used to check whether the given service name is valid.
// Prefix indicates this name will be used as part of generation, in which case
// trailing dashes are allowed.
var ValidateServiceName = apimachineryvalidation.NameIsDNS1035Label
// ValidateNodeName can be used to check whether the given node name is valid.
// Prefix indicates this name will be used as part of generation, in which case
// trailing dashes are allowed.
var ValidateNodeName = apimachineryvalidation.NameIsDNSSubdomain
// ValidateNamespaceName can be used to check whether the given namespace name is valid.
// Prefix indicates this name will be used as part of generation, in which case
// trailing dashes are allowed.
var ValidateNamespaceName = apimachineryvalidation.ValidateNamespaceName
// ValidateLimitRangeName can be used to check whether the given limit range name is valid.
// Prefix indicates this name will be used as part of generation, in which case
// trailing dashes are allowed.
var ValidateLimitRangeName = apimachineryvalidation.NameIsDNSSubdomain
// ValidateResourceQuotaName can be used to check whether the given
// resource quota name is valid.
// Prefix indicates this name will be used as part of generation, in which case
// trailing dashes are allowed.
var ValidateResourceQuotaName = apimachineryvalidation.NameIsDNSSubdomain
// ValidateSecretName can be used to check whether the given secret name is valid.
// Prefix indicates this name will be used as part of generation, in which case
// trailing dashes are allowed.
var ValidateSecretName = apimachineryvalidation.NameIsDNSSubdomain
// ValidateServiceAccountName can be used to check whether the given service account name is valid.
// Prefix indicates this name will be used as part of generation, in which case
// trailing dashes are allowed.
var ValidateServiceAccountName = apimachineryvalidation.ValidateServiceAccountName
// ValidateEndpointsName can be used to check whether the given endpoints name is valid.
// Prefix indicates this name will be used as part of generation, in which case
// trailing dashes are allowed.
var ValidateEndpointsName = apimachineryvalidation.NameIsDNSSubdomain
// ValidateClusterName can be used to check whether the given cluster name is valid.
var ValidateClusterName = apimachineryvalidation.ValidateClusterName
// ValidateClassName can be used to check whether the given class name is valid.
// It is defined here to avoid import cycle between pkg/apis/storage/validation
// (where it should be) and this file.
var ValidateClassName = apimachineryvalidation.NameIsDNSSubdomain
// ValidatePriorityClassName can be used to check whether the given priority
// class name is valid.
var ValidatePriorityClassName = apimachineryvalidation.NameIsDNSSubdomain
// ValidateRuntimeClassName can be used to check whether the given RuntimeClass name is valid.
// Prefix indicates this name will be used as part of generation, in which case
// trailing dashes are allowed.
func ValidateRuntimeClassName(name string, fldPath *field.Path) field.ErrorList {
var allErrs field.ErrorList
for _, msg := range apimachineryvalidation.NameIsDNSSubdomain(name, false) {
allErrs = append(allErrs, field.Invalid(fldPath, name, msg))
}
return allErrs
}
// validateOverhead can be used to check whether the given Overhead is valid.
func validateOverhead(overhead core.ResourceList, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
// reuse the ResourceRequirements validation logic
return ValidateResourceRequirements(&core.ResourceRequirements{Limits: overhead}, fldPath, opts)
}
// Validates that given value is not negative.
func ValidateNonnegativeField(value int64, fldPath *field.Path) field.ErrorList {
return apimachineryvalidation.ValidateNonnegativeField(value, fldPath)
}
// Validates that a Quantity is not negative
func ValidateNonnegativeQuantity(value resource.Quantity, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if value.Cmp(resource.Quantity{}) < 0 {
allErrs = append(allErrs, field.Invalid(fldPath, value.String(), isNegativeErrorMsg))
}
return allErrs
}
// Validates that a Quantity is positive
func ValidatePositiveQuantityValue(value resource.Quantity, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if value.Cmp(resource.Quantity{}) <= 0 {
allErrs = append(allErrs, field.Invalid(fldPath, value.String(), isNotPositiveErrorMsg))
}
return allErrs
}
func ValidateImmutableField(newVal, oldVal interface{}, fldPath *field.Path) field.ErrorList {
return apimachineryvalidation.ValidateImmutableField(newVal, oldVal, fldPath)
}
func ValidateImmutableAnnotation(newVal string, oldVal string, annotation string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if oldVal != newVal {
allErrs = append(allErrs, field.Invalid(fldPath.Child("annotations", annotation), newVal, fieldImmutableErrorMsg))
}
return allErrs
}
// ValidateObjectMeta validates an object's metadata on creation. It expects that name generation has already
// been performed.
// It doesn't return an error for rootscoped resources with namespace, because namespace should already be cleared before.
// TODO: Remove calls to this method scattered in validations of specific resources, e.g., ValidatePodUpdate.
func ValidateObjectMeta(meta *metav1.ObjectMeta, requiresNamespace bool, nameFn ValidateNameFunc, fldPath *field.Path) field.ErrorList {
allErrs := apimachineryvalidation.ValidateObjectMeta(meta, requiresNamespace, apimachineryvalidation.ValidateNameFunc(nameFn), fldPath)
// run additional checks for the finalizer name
for i := range meta.Finalizers {
allErrs = append(allErrs, validateKubeFinalizerName(string(meta.Finalizers[i]), fldPath.Child("finalizers").Index(i))...)
}
return allErrs
}
// ValidateObjectMetaUpdate validates an object's metadata when updated
func ValidateObjectMetaUpdate(newMeta, oldMeta *metav1.ObjectMeta, fldPath *field.Path) field.ErrorList {
allErrs := apimachineryvalidation.ValidateObjectMetaUpdate(newMeta, oldMeta, fldPath)
// run additional checks for the finalizer name
for i := range newMeta.Finalizers {
allErrs = append(allErrs, validateKubeFinalizerName(string(newMeta.Finalizers[i]), fldPath.Child("finalizers").Index(i))...)
}
return allErrs
}
func ValidateVolumes(volumes []core.Volume, podMeta *metav1.ObjectMeta, fldPath *field.Path, opts PodValidationOptions) (map[string]core.VolumeSource, field.ErrorList) {
allErrs := field.ErrorList{}
allNames := sets.String{}
allCreatedPVCs := sets.String{}
// Determine which PVCs will be created for this pod. We need
// the exact name of the pod for this. Without it, this sanity
// check has to be skipped.
if podMeta != nil && podMeta.Name != "" {
for _, vol := range volumes {
if vol.VolumeSource.Ephemeral != nil {
allCreatedPVCs.Insert(podMeta.Name + "-" + vol.Name)
}
}
}
vols := make(map[string]core.VolumeSource)
for i, vol := range volumes {
idxPath := fldPath.Index(i)
namePath := idxPath.Child("name")
el := validateVolumeSource(&vol.VolumeSource, idxPath, vol.Name, podMeta, opts)
if len(vol.Name) == 0 {
el = append(el, field.Required(namePath, ""))
} else {
el = append(el, ValidateDNS1123Label(vol.Name, namePath)...)
}
if allNames.Has(vol.Name) {
el = append(el, field.Duplicate(namePath, vol.Name))
}
if len(el) == 0 {
allNames.Insert(vol.Name)
vols[vol.Name] = vol.VolumeSource
} else {
allErrs = append(allErrs, el...)
}
// A PersistentVolumeClaimSource should not reference a created PVC. That doesn't
// make sense.
if vol.PersistentVolumeClaim != nil && allCreatedPVCs.Has(vol.PersistentVolumeClaim.ClaimName) {
allErrs = append(allErrs, field.Invalid(idxPath.Child("persistentVolumeClaim").Child("claimName"), vol.PersistentVolumeClaim.ClaimName,
"must not reference a PVC that gets created for an ephemeral volume"))
}
}
return vols, allErrs
}
func IsMatchedVolume(name string, volumes map[string]core.VolumeSource) bool {
if _, ok := volumes[name]; ok {
return true
}
return false
}
// isMatched checks whether the volume with the given name is used by a
// container and if so, if it involves a PVC.
func isMatchedDevice(name string, volumes map[string]core.VolumeSource) (isMatched bool, isPVC bool) {
if source, ok := volumes[name]; ok {
if source.PersistentVolumeClaim != nil ||
source.Ephemeral != nil {
return true, true
}
return true, false
}
return false, false
}
func mountNameAlreadyExists(name string, devices map[string]string) bool {
if _, ok := devices[name]; ok {
return true
}
return false
}
func mountPathAlreadyExists(mountPath string, devices map[string]string) bool {
for _, devPath := range devices {
if mountPath == devPath {
return true
}
}
return false
}
func deviceNameAlreadyExists(name string, mounts map[string]string) bool {
if _, ok := mounts[name]; ok {
return true
}
return false
}
func devicePathAlreadyExists(devicePath string, mounts map[string]string) bool {
for _, mountPath := range mounts {
if mountPath == devicePath {
return true
}
}
return false
}
func validateVolumeSource(source *core.VolumeSource, fldPath *field.Path, volName string, podMeta *metav1.ObjectMeta, opts PodValidationOptions) field.ErrorList {
numVolumes := 0
allErrs := field.ErrorList{}
if source.EmptyDir != nil {
numVolumes++
if source.EmptyDir.SizeLimit != nil && source.EmptyDir.SizeLimit.Cmp(resource.Quantity{}) < 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("emptyDir").Child("sizeLimit"), "SizeLimit field must be a valid resource quantity"))
}
}
if source.HostPath != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("hostPath"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateHostPathVolumeSource(source.HostPath, fldPath.Child("hostPath"))...)
}
}
if source.GitRepo != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("gitRepo"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateGitRepoVolumeSource(source.GitRepo, fldPath.Child("gitRepo"))...)
}
}
if source.GCEPersistentDisk != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("gcePersistentDisk"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateGCEPersistentDiskVolumeSource(source.GCEPersistentDisk, fldPath.Child("persistentDisk"))...)
}
}
if source.AWSElasticBlockStore != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("awsElasticBlockStore"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateAWSElasticBlockStoreVolumeSource(source.AWSElasticBlockStore, fldPath.Child("awsElasticBlockStore"))...)
}
}
if source.Secret != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("secret"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateSecretVolumeSource(source.Secret, fldPath.Child("secret"))...)
}
}
if source.NFS != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("nfs"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateNFSVolumeSource(source.NFS, fldPath.Child("nfs"))...)
}
}
if source.ISCSI != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("iscsi"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateISCSIVolumeSource(source.ISCSI, fldPath.Child("iscsi"))...)
}
if source.ISCSI.InitiatorName != nil && len(volName+":"+source.ISCSI.TargetPortal) > 64 {
tooLongErr := "Total length of <volume name>:<iscsi.targetPortal> must be under 64 characters if iscsi.initiatorName is specified."
allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), volName, tooLongErr))
}
}
if source.Glusterfs != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("glusterfs"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateGlusterfsVolumeSource(source.Glusterfs, fldPath.Child("glusterfs"))...)
}
}
if source.Flocker != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("flocker"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateFlockerVolumeSource(source.Flocker, fldPath.Child("flocker"))...)
}
}
if source.PersistentVolumeClaim != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("persistentVolumeClaim"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validatePersistentClaimVolumeSource(source.PersistentVolumeClaim, fldPath.Child("persistentVolumeClaim"))...)
}
}
if source.RBD != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("rbd"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateRBDVolumeSource(source.RBD, fldPath.Child("rbd"))...)
}
}
if source.Cinder != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("cinder"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateCinderVolumeSource(source.Cinder, fldPath.Child("cinder"))...)
}
}
if source.CephFS != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("cephFS"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateCephFSVolumeSource(source.CephFS, fldPath.Child("cephfs"))...)
}
}
if source.Quobyte != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("quobyte"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateQuobyteVolumeSource(source.Quobyte, fldPath.Child("quobyte"))...)
}
}
if source.DownwardAPI != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("downwarAPI"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateDownwardAPIVolumeSource(source.DownwardAPI, fldPath.Child("downwardAPI"), opts)...)
}
}
if source.FC != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("fc"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateFCVolumeSource(source.FC, fldPath.Child("fc"))...)
}
}
if source.FlexVolume != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("flexVolume"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateFlexVolumeSource(source.FlexVolume, fldPath.Child("flexVolume"))...)
}
}
if source.ConfigMap != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("configMap"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateConfigMapVolumeSource(source.ConfigMap, fldPath.Child("configMap"))...)
}
}
if source.AzureFile != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("azureFile"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateAzureFile(source.AzureFile, fldPath.Child("azureFile"))...)
}
}
if source.VsphereVolume != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("vsphereVolume"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateVsphereVolumeSource(source.VsphereVolume, fldPath.Child("vsphereVolume"))...)
}
}
if source.PhotonPersistentDisk != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("photonPersistentDisk"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validatePhotonPersistentDiskVolumeSource(source.PhotonPersistentDisk, fldPath.Child("photonPersistentDisk"))...)
}
}
if source.PortworxVolume != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("portworxVolume"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validatePortworxVolumeSource(source.PortworxVolume, fldPath.Child("portworxVolume"))...)
}
}
if source.AzureDisk != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("azureDisk"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateAzureDisk(source.AzureDisk, fldPath.Child("azureDisk"))...)
}
}
if source.StorageOS != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("storageos"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateStorageOSVolumeSource(source.StorageOS, fldPath.Child("storageos"))...)
}
}
if source.Projected != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("projected"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateProjectedVolumeSource(source.Projected, fldPath.Child("projected"), opts)...)
}
}
if source.ScaleIO != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("scaleIO"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateScaleIOVolumeSource(source.ScaleIO, fldPath.Child("scaleIO"))...)
}
}
if source.CSI != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("csi"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateCSIVolumeSource(source.CSI, fldPath.Child("csi"))...)
}
}
if source.Ephemeral != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("ephemeral"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateEphemeralVolumeSource(source.Ephemeral, fldPath.Child("ephemeral"))...)
// Check the expected name for the PVC. This gets skipped if information is missing,
// because that already gets flagged as a problem elsewhere. For example,
// ValidateObjectMeta as called by validatePodMetadataAndSpec checks that the name is set.
if podMeta != nil && podMeta.Name != "" && volName != "" {
pvcName := podMeta.Name + "-" + volName
for _, msg := range ValidatePersistentVolumeName(pvcName, false) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), volName, fmt.Sprintf("PVC name %q: %v", pvcName, msg)))
}
}
}
}
if numVolumes == 0 {
allErrs = append(allErrs, field.Required(fldPath, "must specify a volume type"))
}
return allErrs
}
func validateHostPathVolumeSource(hostPath *core.HostPathVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(hostPath.Path) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("path"), ""))
return allErrs
}
allErrs = append(allErrs, validatePathNoBacksteps(hostPath.Path, fldPath.Child("path"))...)
allErrs = append(allErrs, validateHostPathType(hostPath.Type, fldPath.Child("type"))...)
return allErrs
}
func validateGitRepoVolumeSource(gitRepo *core.GitRepoVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(gitRepo.Repository) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("repository"), ""))
}
pathErrs := validateLocalDescendingPath(gitRepo.Directory, fldPath.Child("directory"))
allErrs = append(allErrs, pathErrs...)
return allErrs
}
func validateISCSIVolumeSource(iscsi *core.ISCSIVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(iscsi.TargetPortal) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("targetPortal"), ""))
}
if len(iscsi.IQN) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("iqn"), ""))
} else {
if !strings.HasPrefix(iscsi.IQN, "iqn") && !strings.HasPrefix(iscsi.IQN, "eui") && !strings.HasPrefix(iscsi.IQN, "naa") {
allErrs = append(allErrs, field.Invalid(fldPath.Child("iqn"), iscsi.IQN, "must be valid format starting with iqn, eui, or naa"))
} else if strings.HasPrefix(iscsi.IQN, "iqn") && !iscsiInitiatorIqnRegex.MatchString(iscsi.IQN) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("iqn"), iscsi.IQN, "must be valid format"))
} else if strings.HasPrefix(iscsi.IQN, "eui") && !iscsiInitiatorEuiRegex.MatchString(iscsi.IQN) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("iqn"), iscsi.IQN, "must be valid format"))
} else if strings.HasPrefix(iscsi.IQN, "naa") && !iscsiInitiatorNaaRegex.MatchString(iscsi.IQN) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("iqn"), iscsi.IQN, "must be valid format"))
}
}
if iscsi.Lun < 0 || iscsi.Lun > 255 {
allErrs = append(allErrs, field.Invalid(fldPath.Child("lun"), iscsi.Lun, validation.InclusiveRangeError(0, 255)))
}
if (iscsi.DiscoveryCHAPAuth || iscsi.SessionCHAPAuth) && iscsi.SecretRef == nil {
allErrs = append(allErrs, field.Required(fldPath.Child("secretRef"), ""))
}
if iscsi.InitiatorName != nil {
initiator := *iscsi.InitiatorName
if !strings.HasPrefix(initiator, "iqn") && !strings.HasPrefix(initiator, "eui") && !strings.HasPrefix(initiator, "naa") {
allErrs = append(allErrs, field.Invalid(fldPath.Child("initiatorname"), initiator, "must be valid format starting with iqn, eui, or naa"))
}
if strings.HasPrefix(initiator, "iqn") && !iscsiInitiatorIqnRegex.MatchString(initiator) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("initiatorname"), initiator, "must be valid format"))
} else if strings.HasPrefix(initiator, "eui") && !iscsiInitiatorEuiRegex.MatchString(initiator) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("initiatorname"), initiator, "must be valid format"))
} else if strings.HasPrefix(initiator, "naa") && !iscsiInitiatorNaaRegex.MatchString(initiator) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("initiatorname"), initiator, "must be valid format"))
}
}
return allErrs
}
func validateISCSIPersistentVolumeSource(iscsi *core.ISCSIPersistentVolumeSource, pvName string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(iscsi.TargetPortal) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("targetPortal"), ""))
}
if iscsi.InitiatorName != nil && len(pvName+":"+iscsi.TargetPortal) > 64 {
tooLongErr := "Total length of <volume name>:<iscsi.targetPortal> must be under 64 characters if iscsi.initiatorName is specified."
allErrs = append(allErrs, field.Invalid(fldPath.Child("targetportal"), iscsi.TargetPortal, tooLongErr))
}
if len(iscsi.IQN) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("iqn"), ""))
} else {
if !strings.HasPrefix(iscsi.IQN, "iqn") && !strings.HasPrefix(iscsi.IQN, "eui") && !strings.HasPrefix(iscsi.IQN, "naa") {
allErrs = append(allErrs, field.Invalid(fldPath.Child("iqn"), iscsi.IQN, "must be valid format"))
} else if strings.HasPrefix(iscsi.IQN, "iqn") && !iscsiInitiatorIqnRegex.MatchString(iscsi.IQN) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("iqn"), iscsi.IQN, "must be valid format"))
} else if strings.HasPrefix(iscsi.IQN, "eui") && !iscsiInitiatorEuiRegex.MatchString(iscsi.IQN) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("iqn"), iscsi.IQN, "must be valid format"))
} else if strings.HasPrefix(iscsi.IQN, "naa") && !iscsiInitiatorNaaRegex.MatchString(iscsi.IQN) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("iqn"), iscsi.IQN, "must be valid format"))
}
}
if iscsi.Lun < 0 || iscsi.Lun > 255 {
allErrs = append(allErrs, field.Invalid(fldPath.Child("lun"), iscsi.Lun, validation.InclusiveRangeError(0, 255)))
}
if (iscsi.DiscoveryCHAPAuth || iscsi.SessionCHAPAuth) && iscsi.SecretRef == nil {
allErrs = append(allErrs, field.Required(fldPath.Child("secretRef"), ""))
}
if iscsi.SecretRef != nil {
if len(iscsi.SecretRef.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("secretRef", "name"), ""))
}
}
if iscsi.InitiatorName != nil {
initiator := *iscsi.InitiatorName
if !strings.HasPrefix(initiator, "iqn") && !strings.HasPrefix(initiator, "eui") && !strings.HasPrefix(initiator, "naa") {
allErrs = append(allErrs, field.Invalid(fldPath.Child("initiatorname"), initiator, "must be valid format"))
}
if strings.HasPrefix(initiator, "iqn") && !iscsiInitiatorIqnRegex.MatchString(initiator) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("initiatorname"), initiator, "must be valid format"))
} else if strings.HasPrefix(initiator, "eui") && !iscsiInitiatorEuiRegex.MatchString(initiator) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("initiatorname"), initiator, "must be valid format"))
} else if strings.HasPrefix(initiator, "naa") && !iscsiInitiatorNaaRegex.MatchString(initiator) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("initiatorname"), initiator, "must be valid format"))
}
}
return allErrs
}
func validateFCVolumeSource(fc *core.FCVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(fc.TargetWWNs) < 1 && len(fc.WWIDs) < 1 {
allErrs = append(allErrs, field.Required(fldPath.Child("targetWWNs"), "must specify either targetWWNs or wwids, but not both"))
}
if len(fc.TargetWWNs) != 0 && len(fc.WWIDs) != 0 {
allErrs = append(allErrs, field.Invalid(fldPath.Child("targetWWNs"), fc.TargetWWNs, "targetWWNs and wwids can not be specified simultaneously"))
}
if len(fc.TargetWWNs) != 0 {
if fc.Lun == nil {
allErrs = append(allErrs, field.Required(fldPath.Child("lun"), "lun is required if targetWWNs is specified"))
} else {
if *fc.Lun < 0 || *fc.Lun > 255 {
allErrs = append(allErrs, field.Invalid(fldPath.Child("lun"), fc.Lun, validation.InclusiveRangeError(0, 255)))
}
}
}
return allErrs
}
func validateGCEPersistentDiskVolumeSource(pd *core.GCEPersistentDiskVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(pd.PDName) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("pdName"), ""))
}
if pd.Partition < 0 || pd.Partition > 255 {
allErrs = append(allErrs, field.Invalid(fldPath.Child("partition"), pd.Partition, pdPartitionErrorMsg))
}
return allErrs
}
func validateAWSElasticBlockStoreVolumeSource(PD *core.AWSElasticBlockStoreVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(PD.VolumeID) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("volumeID"), ""))
}
if PD.Partition < 0 || PD.Partition > 255 {
allErrs = append(allErrs, field.Invalid(fldPath.Child("partition"), PD.Partition, pdPartitionErrorMsg))
}
return allErrs
}
func validateSecretVolumeSource(secretSource *core.SecretVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(secretSource.SecretName) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("secretName"), ""))
}
secretMode := secretSource.DefaultMode
if secretMode != nil && (*secretMode > 0777 || *secretMode < 0) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("defaultMode"), *secretMode, fileModeErrorMsg))
}
itemsPath := fldPath.Child("items")
for i, kp := range secretSource.Items {
itemPath := itemsPath.Index(i)
allErrs = append(allErrs, validateKeyToPath(&kp, itemPath)...)
}
return allErrs
}
func validateConfigMapVolumeSource(configMapSource *core.ConfigMapVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(configMapSource.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("name"), ""))
}
configMapMode := configMapSource.DefaultMode
if configMapMode != nil && (*configMapMode > 0777 || *configMapMode < 0) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("defaultMode"), *configMapMode, fileModeErrorMsg))
}
itemsPath := fldPath.Child("items")
for i, kp := range configMapSource.Items {
itemPath := itemsPath.Index(i)
allErrs = append(allErrs, validateKeyToPath(&kp, itemPath)...)
}
return allErrs
}
func validateKeyToPath(kp *core.KeyToPath, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(kp.Key) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("key"), ""))
}
if len(kp.Path) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("path"), ""))
}
allErrs = append(allErrs, validateLocalNonReservedPath(kp.Path, fldPath.Child("path"))...)
if kp.Mode != nil && (*kp.Mode > 0777 || *kp.Mode < 0) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("mode"), *kp.Mode, fileModeErrorMsg))
}
return allErrs
}
func validatePersistentClaimVolumeSource(claim *core.PersistentVolumeClaimVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(claim.ClaimName) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("claimName"), ""))
}
return allErrs
}
func validateNFSVolumeSource(nfs *core.NFSVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(nfs.Server) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("server"), ""))
}
if len(nfs.Path) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("path"), ""))
}
if !path.IsAbs(nfs.Path) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("path"), nfs.Path, "must be an absolute path"))
}
return allErrs
}
func validateQuobyteVolumeSource(quobyte *core.QuobyteVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(quobyte.Registry) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("registry"), "must be a host:port pair or multiple pairs separated by commas"))
} else if len(quobyte.Tenant) >= 65 {
allErrs = append(allErrs, field.Required(fldPath.Child("tenant"), "must be a UUID and may not exceed a length of 64 characters"))
} else {
for _, hostPortPair := range strings.Split(quobyte.Registry, ",") {
if _, _, err := net.SplitHostPort(hostPortPair); err != nil {
allErrs = append(allErrs, field.Invalid(fldPath.Child("registry"), quobyte.Registry, "must be a host:port pair or multiple pairs separated by commas"))
}
}
}
if len(quobyte.Volume) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("volume"), ""))
}
return allErrs
}
func validateGlusterfsVolumeSource(glusterfs *core.GlusterfsVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(glusterfs.EndpointsName) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("endpoints"), ""))
}
if len(glusterfs.Path) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("path"), ""))
}
return allErrs
}
func validateGlusterfsPersistentVolumeSource(glusterfs *core.GlusterfsPersistentVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(glusterfs.EndpointsName) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("endpoints"), ""))
}
if len(glusterfs.Path) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("path"), ""))
}
if glusterfs.EndpointsNamespace != nil {
endpointNs := glusterfs.EndpointsNamespace
if *endpointNs == "" {
allErrs = append(allErrs, field.Invalid(fldPath.Child("endpointsNamespace"), *endpointNs, "if the endpointnamespace is set, it must be a valid namespace name"))
} else {
for _, msg := range ValidateNamespaceName(*endpointNs, false) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("endpointsNamespace"), *endpointNs, msg))
}
}
}
return allErrs
}
func validateFlockerVolumeSource(flocker *core.FlockerVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(flocker.DatasetName) == 0 && len(flocker.DatasetUUID) == 0 {
//TODO: consider adding a RequiredOneOf() error for this and similar cases
allErrs = append(allErrs, field.Required(fldPath, "one of datasetName and datasetUUID is required"))
}
if len(flocker.DatasetName) != 0 && len(flocker.DatasetUUID) != 0 {
allErrs = append(allErrs, field.Invalid(fldPath, "resource", "datasetName and datasetUUID can not be specified simultaneously"))
}
if strings.Contains(flocker.DatasetName, "/") {
allErrs = append(allErrs, field.Invalid(fldPath.Child("datasetName"), flocker.DatasetName, "must not contain '/'"))
}
return allErrs
}
var validVolumeDownwardAPIFieldPathExpressions = sets.NewString(
"metadata.name",
"metadata.namespace",
"metadata.labels",
"metadata.annotations",
"metadata.uid")
func validateDownwardAPIVolumeFile(file *core.DownwardAPIVolumeFile, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
if len(file.Path) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("path"), ""))
}
allErrs = append(allErrs, validateLocalNonReservedPath(file.Path, fldPath.Child("path"))...)
if file.FieldRef != nil {
allErrs = append(allErrs, validateObjectFieldSelector(file.FieldRef, &validVolumeDownwardAPIFieldPathExpressions, fldPath.Child("fieldRef"))...)
if file.ResourceFieldRef != nil {
allErrs = append(allErrs, field.Invalid(fldPath, "resource", "fieldRef and resourceFieldRef can not be specified simultaneously"))
}
} else if file.ResourceFieldRef != nil {
localValidContainerResourceFieldPathPrefixes := validContainerResourceFieldPathPrefixes
if opts.AllowDownwardAPIHugePages {
localValidContainerResourceFieldPathPrefixes = validContainerResourceFieldPathPrefixesWithDownwardAPIHugePages
}
allErrs = append(allErrs, validateContainerResourceFieldSelector(file.ResourceFieldRef, &validContainerResourceFieldPathExpressions, &localValidContainerResourceFieldPathPrefixes, fldPath.Child("resourceFieldRef"), true)...)
} else {
allErrs = append(allErrs, field.Required(fldPath, "one of fieldRef and resourceFieldRef is required"))
}
if file.Mode != nil && (*file.Mode > 0777 || *file.Mode < 0) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("mode"), *file.Mode, fileModeErrorMsg))
}
return allErrs
}
func validateDownwardAPIVolumeSource(downwardAPIVolume *core.DownwardAPIVolumeSource, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
downwardAPIMode := downwardAPIVolume.DefaultMode
if downwardAPIMode != nil && (*downwardAPIMode > 0777 || *downwardAPIMode < 0) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("defaultMode"), *downwardAPIMode, fileModeErrorMsg))
}
for _, file := range downwardAPIVolume.Items {
allErrs = append(allErrs, validateDownwardAPIVolumeFile(&file, fldPath, opts)...)
}
return allErrs
}
func validateProjectionSources(projection *core.ProjectedVolumeSource, projectionMode *int32, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
allPaths := sets.String{}
for i, source := range projection.Sources {
numSources := 0
srcPath := fldPath.Child("sources").Index(i)
if projPath := srcPath.Child("secret"); source.Secret != nil {
numSources++
if len(source.Secret.Name) == 0 {
allErrs = append(allErrs, field.Required(projPath.Child("name"), ""))
}
itemsPath := projPath.Child("items")
for i, kp := range source.Secret.Items {
itemPath := itemsPath.Index(i)
allErrs = append(allErrs, validateKeyToPath(&kp, itemPath)...)
if len(kp.Path) > 0 {
curPath := kp.Path
if !allPaths.Has(curPath) {
allPaths.Insert(curPath)
} else {
allErrs = append(allErrs, field.Invalid(fldPath, source.Secret.Name, "conflicting duplicate paths"))
}
}
}
}
if projPath := srcPath.Child("configMap"); source.ConfigMap != nil {
numSources++
if len(source.ConfigMap.Name) == 0 {
allErrs = append(allErrs, field.Required(projPath.Child("name"), ""))
}
itemsPath := projPath.Child("items")
for i, kp := range source.ConfigMap.Items {
itemPath := itemsPath.Index(i)
allErrs = append(allErrs, validateKeyToPath(&kp, itemPath)...)
if len(kp.Path) > 0 {
curPath := kp.Path
if !allPaths.Has(curPath) {
allPaths.Insert(curPath)
} else {
allErrs = append(allErrs, field.Invalid(fldPath, source.ConfigMap.Name, "conflicting duplicate paths"))
}
}
}
}
if projPath := srcPath.Child("downwardAPI"); source.DownwardAPI != nil {
numSources++
for _, file := range source.DownwardAPI.Items {
allErrs = append(allErrs, validateDownwardAPIVolumeFile(&file, projPath, opts)...)
if len(file.Path) > 0 {
curPath := file.Path
if !allPaths.Has(curPath) {
allPaths.Insert(curPath)
} else {
allErrs = append(allErrs, field.Invalid(fldPath, curPath, "conflicting duplicate paths"))
}
}
}
}
if projPath := srcPath.Child("serviceAccountToken"); source.ServiceAccountToken != nil {
numSources++
if source.ServiceAccountToken.ExpirationSeconds < 10*60 {
allErrs = append(allErrs, field.Invalid(projPath.Child("expirationSeconds"), source.ServiceAccountToken.ExpirationSeconds, "may not specify a duration less than 10 minutes"))
}
if source.ServiceAccountToken.ExpirationSeconds > 1<<32 {
allErrs = append(allErrs, field.Invalid(projPath.Child("expirationSeconds"), source.ServiceAccountToken.ExpirationSeconds, "may not specify a duration larger than 2^32 seconds"))
}
if source.ServiceAccountToken.Path == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("path"), ""))
}
}
if numSources > 1 {
allErrs = append(allErrs, field.Forbidden(srcPath, "may not specify more than 1 volume type"))
}
}
return allErrs
}
func validateProjectedVolumeSource(projection *core.ProjectedVolumeSource, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
projectionMode := projection.DefaultMode
if projectionMode != nil && (*projectionMode > 0777 || *projectionMode < 0) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("defaultMode"), *projectionMode, fileModeErrorMsg))
}
allErrs = append(allErrs, validateProjectionSources(projection, projectionMode, fldPath, opts)...)
return allErrs
}
var supportedHostPathTypes = sets.NewString(
string(core.HostPathUnset),
string(core.HostPathDirectoryOrCreate),
string(core.HostPathDirectory),
string(core.HostPathFileOrCreate),
string(core.HostPathFile),
string(core.HostPathSocket),
string(core.HostPathCharDev),
string(core.HostPathBlockDev))
func validateHostPathType(hostPathType *core.HostPathType, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if hostPathType != nil && !supportedHostPathTypes.Has(string(*hostPathType)) {
allErrs = append(allErrs, field.NotSupported(fldPath, hostPathType, supportedHostPathTypes.List()))
}
return allErrs
}
// This validate will make sure targetPath:
// 1. is not abs path
// 2. does not have any element which is ".."
func validateLocalDescendingPath(targetPath string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if path.IsAbs(targetPath) {
allErrs = append(allErrs, field.Invalid(fldPath, targetPath, "must be a relative path"))
}
allErrs = append(allErrs, validatePathNoBacksteps(targetPath, fldPath)...)
return allErrs
}
// validatePathNoBacksteps makes sure the targetPath does not have any `..` path elements when split
//
// This assumes the OS of the apiserver and the nodes are the same. The same check should be done
// on the node to ensure there are no backsteps.
func validatePathNoBacksteps(targetPath string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
parts := strings.Split(filepath.ToSlash(targetPath), "/")
for _, item := range parts {
if item == ".." {
allErrs = append(allErrs, field.Invalid(fldPath, targetPath, "must not contain '..'"))
break // even for `../../..`, one error is sufficient to make the point
}
}
return allErrs
}
// validateMountPropagation verifies that MountPropagation field is valid and
// allowed for given container.
func validateMountPropagation(mountPropagation *core.MountPropagationMode, container *core.Container, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if mountPropagation == nil {
return allErrs
}
supportedMountPropagations := sets.NewString(string(core.MountPropagationBidirectional), string(core.MountPropagationHostToContainer), string(core.MountPropagationNone))
if !supportedMountPropagations.Has(string(*mountPropagation)) {
allErrs = append(allErrs, field.NotSupported(fldPath, *mountPropagation, supportedMountPropagations.List()))
}
if container == nil {
// The container is not available yet.
// Stop validation now, Pod validation will refuse final
// Pods with Bidirectional propagation in non-privileged containers.
return allErrs
}
privileged := container.SecurityContext != nil && container.SecurityContext.Privileged != nil && *container.SecurityContext.Privileged
if *mountPropagation == core.MountPropagationBidirectional && !privileged {
allErrs = append(allErrs, field.Forbidden(fldPath, "Bidirectional mount propagation is available only to privileged containers"))
}
return allErrs
}
// This validate will make sure targetPath:
// 1. is not abs path
// 2. does not contain any '..' elements
// 3. does not start with '..'
func validateLocalNonReservedPath(targetPath string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, validateLocalDescendingPath(targetPath, fldPath)...)
// Don't report this error if the check for .. elements already caught it.
if strings.HasPrefix(targetPath, "..") && !strings.HasPrefix(targetPath, "../") {
allErrs = append(allErrs, field.Invalid(fldPath, targetPath, "must not start with '..'"))
}
return allErrs
}
func validateRBDVolumeSource(rbd *core.RBDVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(rbd.CephMonitors) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("monitors"), ""))
}
if len(rbd.RBDImage) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("image"), ""))
}
return allErrs
}
func validateRBDPersistentVolumeSource(rbd *core.RBDPersistentVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(rbd.CephMonitors) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("monitors"), ""))
}
if len(rbd.RBDImage) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("image"), ""))
}
return allErrs
}
func validateCinderVolumeSource(cd *core.CinderVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(cd.VolumeID) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("volumeID"), ""))
}
if cd.SecretRef != nil {
if len(cd.SecretRef.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("secretRef", "name"), ""))
}
}
return allErrs
}
func validateCinderPersistentVolumeSource(cd *core.CinderPersistentVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(cd.VolumeID) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("volumeID"), ""))
}
if cd.SecretRef != nil {
if len(cd.SecretRef.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("secretRef", "name"), ""))
}
if len(cd.SecretRef.Namespace) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("secretRef", "namespace"), ""))
}
}
return allErrs
}
func validateCephFSVolumeSource(cephfs *core.CephFSVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(cephfs.Monitors) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("monitors"), ""))
}
return allErrs
}
func validateCephFSPersistentVolumeSource(cephfs *core.CephFSPersistentVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(cephfs.Monitors) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("monitors"), ""))
}
return allErrs
}
func validateFlexVolumeSource(fv *core.FlexVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(fv.Driver) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("driver"), ""))
}
// Make sure user-specified options don't use kubernetes namespaces
for k := range fv.Options {
namespace := k
if parts := strings.SplitN(k, "/", 2); len(parts) == 2 {
namespace = parts[0]
}
normalized := "." + strings.ToLower(namespace)
if strings.HasSuffix(normalized, ".kubernetes.io") || strings.HasSuffix(normalized, ".k8s.io") {
allErrs = append(allErrs, field.Invalid(fldPath.Child("options").Key(k), k, "kubernetes.io and k8s.io namespaces are reserved"))
}
}
return allErrs
}
func validateFlexPersistentVolumeSource(fv *core.FlexPersistentVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(fv.Driver) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("driver"), ""))
}
// Make sure user-specified options don't use kubernetes namespaces
for k := range fv.Options {
namespace := k
if parts := strings.SplitN(k, "/", 2); len(parts) == 2 {
namespace = parts[0]
}
normalized := "." + strings.ToLower(namespace)
if strings.HasSuffix(normalized, ".kubernetes.io") || strings.HasSuffix(normalized, ".k8s.io") {
allErrs = append(allErrs, field.Invalid(fldPath.Child("options").Key(k), k, "kubernetes.io and k8s.io namespaces are reserved"))
}
}
return allErrs
}
func validateAzureFile(azure *core.AzureFileVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if azure.SecretName == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("secretName"), ""))
}
if azure.ShareName == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("shareName"), ""))
}
return allErrs
}
func validateAzureFilePV(azure *core.AzureFilePersistentVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if azure.SecretName == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("secretName"), ""))
}
if azure.ShareName == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("shareName"), ""))
}
if azure.SecretNamespace != nil {
if len(*azure.SecretNamespace) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("secretNamespace"), ""))
}
}
return allErrs
}
func validateAzureDisk(azure *core.AzureDiskVolumeSource, fldPath *field.Path) field.ErrorList {
var supportedCachingModes = sets.NewString(string(core.AzureDataDiskCachingNone), string(core.AzureDataDiskCachingReadOnly), string(core.AzureDataDiskCachingReadWrite))
var supportedDiskKinds = sets.NewString(string(core.AzureSharedBlobDisk), string(core.AzureDedicatedBlobDisk), string(core.AzureManagedDisk))
diskURISupportedManaged := []string{"/subscriptions/{sub-id}/resourcegroups/{group-name}/providers/microsoft.compute/disks/{disk-id}"}
diskURISupportedblob := []string{"https://{account-name}.blob.core.windows.net/{container-name}/{disk-name}.vhd"}
allErrs := field.ErrorList{}
if azure.DiskName == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("diskName"), ""))
}
if azure.DataDiskURI == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("diskURI"), ""))
}
if azure.CachingMode != nil && !supportedCachingModes.Has(string(*azure.CachingMode)) {
allErrs = append(allErrs, field.NotSupported(fldPath.Child("cachingMode"), *azure.CachingMode, supportedCachingModes.List()))
}
if azure.Kind != nil && !supportedDiskKinds.Has(string(*azure.Kind)) {
allErrs = append(allErrs, field.NotSupported(fldPath.Child("kind"), *azure.Kind, supportedDiskKinds.List()))
}
// validate that DiskUri is the correct format
if azure.Kind != nil && *azure.Kind == core.AzureManagedDisk && strings.Index(azure.DataDiskURI, "/subscriptions/") != 0 {
allErrs = append(allErrs, field.NotSupported(fldPath.Child("diskURI"), azure.DataDiskURI, diskURISupportedManaged))
}
if azure.Kind != nil && *azure.Kind != core.AzureManagedDisk && strings.Index(azure.DataDiskURI, "https://") != 0 {
allErrs = append(allErrs, field.NotSupported(fldPath.Child("diskURI"), azure.DataDiskURI, diskURISupportedblob))
}
return allErrs
}
func validateVsphereVolumeSource(cd *core.VsphereVirtualDiskVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(cd.VolumePath) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("volumePath"), ""))
}
return allErrs
}
func validatePhotonPersistentDiskVolumeSource(cd *core.PhotonPersistentDiskVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(cd.PdID) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("pdID"), ""))
}
return allErrs
}
func validatePortworxVolumeSource(pwx *core.PortworxVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(pwx.VolumeID) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("volumeID"), ""))
}
return allErrs
}
func validateScaleIOVolumeSource(sio *core.ScaleIOVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if sio.Gateway == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("gateway"), ""))
}
if sio.System == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("system"), ""))
}
if sio.VolumeName == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("volumeName"), ""))
}
return allErrs
}
func validateScaleIOPersistentVolumeSource(sio *core.ScaleIOPersistentVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if sio.Gateway == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("gateway"), ""))
}
if sio.System == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("system"), ""))
}
if sio.VolumeName == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("volumeName"), ""))
}
return allErrs
}
func validateLocalVolumeSource(ls *core.LocalVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if ls.Path == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("path"), ""))
return allErrs
}
allErrs = append(allErrs, validatePathNoBacksteps(ls.Path, fldPath.Child("path"))...)
return allErrs
}
func validateStorageOSVolumeSource(storageos *core.StorageOSVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(storageos.VolumeName) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("volumeName"), ""))
} else {
allErrs = append(allErrs, ValidateDNS1123Label(storageos.VolumeName, fldPath.Child("volumeName"))...)
}
if len(storageos.VolumeNamespace) > 0 {
allErrs = append(allErrs, ValidateDNS1123Label(storageos.VolumeNamespace, fldPath.Child("volumeNamespace"))...)
}
if storageos.SecretRef != nil {
if len(storageos.SecretRef.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("secretRef", "name"), ""))
}
}
return allErrs
}
func validateStorageOSPersistentVolumeSource(storageos *core.StorageOSPersistentVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(storageos.VolumeName) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("volumeName"), ""))
} else {
allErrs = append(allErrs, ValidateDNS1123Label(storageos.VolumeName, fldPath.Child("volumeName"))...)
}
if len(storageos.VolumeNamespace) > 0 {
allErrs = append(allErrs, ValidateDNS1123Label(storageos.VolumeNamespace, fldPath.Child("volumeNamespace"))...)
}
if storageos.SecretRef != nil {
if len(storageos.SecretRef.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("secretRef", "name"), ""))
}
if len(storageos.SecretRef.Namespace) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("secretRef", "namespace"), ""))
}
}
return allErrs
}
func ValidateCSIDriverName(driverName string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(driverName) == 0 {
allErrs = append(allErrs, field.Required(fldPath, ""))
}
if len(driverName) > 63 {
allErrs = append(allErrs, field.TooLong(fldPath, driverName, 63))
}
for _, msg := range validation.IsDNS1123Subdomain(strings.ToLower(driverName)) {
allErrs = append(allErrs, field.Invalid(fldPath, driverName, msg))
}
return allErrs
}
func validateCSIPersistentVolumeSource(csi *core.CSIPersistentVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, ValidateCSIDriverName(csi.Driver, fldPath.Child("driver"))...)
if len(csi.VolumeHandle) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("volumeHandle"), ""))
}
if csi.ControllerPublishSecretRef != nil {
if len(csi.ControllerPublishSecretRef.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("controllerPublishSecretRef", "name"), ""))
} else {
allErrs = append(allErrs, ValidateDNS1123Label(csi.ControllerPublishSecretRef.Name, fldPath.Child("name"))...)
}
if len(csi.ControllerPublishSecretRef.Namespace) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("controllerPublishSecretRef", "namespace"), ""))
} else {
allErrs = append(allErrs, ValidateDNS1123Label(csi.ControllerPublishSecretRef.Namespace, fldPath.Child("namespace"))...)
}
}
if csi.ControllerExpandSecretRef != nil {
if len(csi.ControllerExpandSecretRef.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("controllerExpandSecretRef", "name"), ""))
} else {
allErrs = append(allErrs, ValidateDNS1123Label(csi.ControllerExpandSecretRef.Name, fldPath.Child("name"))...)
}
if len(csi.ControllerExpandSecretRef.Namespace) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("controllerExpandSecretRef", "namespace"), ""))
} else {
allErrs = append(allErrs, ValidateDNS1123Label(csi.ControllerExpandSecretRef.Namespace, fldPath.Child("namespace"))...)
}
}
if csi.NodePublishSecretRef != nil {
if len(csi.NodePublishSecretRef.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("nodePublishSecretRef ", "name"), ""))
} else {
allErrs = append(allErrs, ValidateDNS1123Label(csi.NodePublishSecretRef.Name, fldPath.Child("name"))...)
}
if len(csi.NodePublishSecretRef.Namespace) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("nodePublishSecretRef ", "namespace"), ""))
} else {
allErrs = append(allErrs, ValidateDNS1123Label(csi.NodePublishSecretRef.Namespace, fldPath.Child("namespace"))...)
}
}
return allErrs
}
func validateCSIVolumeSource(csi *core.CSIVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, ValidateCSIDriverName(csi.Driver, fldPath.Child("driver"))...)
if csi.NodePublishSecretRef != nil {
if len(csi.NodePublishSecretRef.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("nodePublishSecretRef ", "name"), ""))
} else {
for _, msg := range ValidateSecretName(csi.NodePublishSecretRef.Name, false) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), csi.NodePublishSecretRef.Name, msg))
}
}
}
return allErrs
}
func validateEphemeralVolumeSource(ephemeral *core.EphemeralVolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if ephemeral.VolumeClaimTemplate == nil {
allErrs = append(allErrs, field.Required(fldPath.Child("volumeClaimTemplate"), ""))
} else {
opts := ValidationOptionsForPersistentVolumeClaimTemplate(ephemeral.VolumeClaimTemplate, nil)
allErrs = append(allErrs, ValidatePersistentVolumeClaimTemplate(ephemeral.VolumeClaimTemplate, fldPath.Child("volumeClaimTemplate"), opts)...)
}
return allErrs
}
// ValidatePersistentVolumeClaimTemplate verifies that the embedded object meta and spec are valid.
// Checking of the object data is very minimal because only labels and annotations are used.
func ValidatePersistentVolumeClaimTemplate(claimTemplate *core.PersistentVolumeClaimTemplate, fldPath *field.Path, opts PersistentVolumeClaimSpecValidationOptions) field.ErrorList {
allErrs := validatePersistentVolumeClaimTemplateObjectMeta(&claimTemplate.ObjectMeta, fldPath.Child("metadata"))
allErrs = append(allErrs, ValidatePersistentVolumeClaimSpec(&claimTemplate.Spec, fldPath.Child("spec"), opts)...)
return allErrs
}
func validatePersistentVolumeClaimTemplateObjectMeta(objMeta *metav1.ObjectMeta, fldPath *field.Path) field.ErrorList {
allErrs := apimachineryvalidation.ValidateAnnotations(objMeta.Annotations, fldPath.Child("annotations"))
allErrs = append(allErrs, unversionedvalidation.ValidateLabels(objMeta.Labels, fldPath.Child("labels"))...)
// All other fields are not supported and thus must not be set
// to avoid confusion. We could reject individual fields,
// but then adding a new one to ObjectMeta wouldn't be checked
// unless this code gets updated. Instead, we ensure that
// only allowed fields are set via reflection.
allErrs = append(allErrs, validateFieldAllowList(*objMeta, allowedPVCTemplateObjectMetaFields, "cannot be set for an ephemeral volume", fldPath)...)
return allErrs
}
var allowedPVCTemplateObjectMetaFields = map[string]bool{
"Annotations": true,
"Labels": true,
}
// PersistentVolumeSpecValidationOptions contains the different settings for PeristentVolume validation
type PersistentVolumeSpecValidationOptions struct {
// Allow spec to contain the "ReadWiteOncePod" access mode
AllowReadWriteOncePod bool
}
// ValidatePersistentVolumeName checks that a name is appropriate for a
// PersistentVolumeName object.
var ValidatePersistentVolumeName = apimachineryvalidation.NameIsDNSSubdomain
var supportedAccessModes = sets.NewString(string(core.ReadWriteOnce), string(core.ReadOnlyMany), string(core.ReadWriteMany))
var supportedReclaimPolicy = sets.NewString(string(core.PersistentVolumeReclaimDelete), string(core.PersistentVolumeReclaimRecycle), string(core.PersistentVolumeReclaimRetain))
var supportedVolumeModes = sets.NewString(string(core.PersistentVolumeBlock), string(core.PersistentVolumeFilesystem))
func ValidationOptionsForPersistentVolume(pv, oldPv *core.PersistentVolume) PersistentVolumeSpecValidationOptions {
opts := PersistentVolumeSpecValidationOptions{
AllowReadWriteOncePod: utilfeature.DefaultFeatureGate.Enabled(features.ReadWriteOncePod),
}
if oldPv == nil {
// If there's no old PV, use the options based solely on feature enablement
return opts
}
if helper.ContainsAccessMode(oldPv.Spec.AccessModes, core.ReadWriteOncePod) {
// If the old object allowed "ReadWriteOncePod", continue to allow it in the new object
opts.AllowReadWriteOncePod = true
}
return opts
}
func ValidatePersistentVolumeSpec(pvSpec *core.PersistentVolumeSpec, pvName string, validateInlinePersistentVolumeSpec bool, fldPath *field.Path, opts PersistentVolumeSpecValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
if validateInlinePersistentVolumeSpec {
if pvSpec.ClaimRef != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("claimRef"), "may not be specified in the context of inline volumes"))
}
if len(pvSpec.Capacity) != 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("capacity"), "may not be specified in the context of inline volumes"))
}
if pvSpec.CSI == nil {
allErrs = append(allErrs, field.Required(fldPath.Child("csi"), "has to be specified in the context of inline volumes"))
}
}
if len(pvSpec.AccessModes) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("accessModes"), ""))
}
expandedSupportedAccessModes := sets.StringKeySet(supportedAccessModes)
if opts.AllowReadWriteOncePod {
expandedSupportedAccessModes.Insert(string(core.ReadWriteOncePod))
}
foundReadWriteOncePod, foundNonReadWriteOncePod := false, false
for _, mode := range pvSpec.AccessModes {
if !expandedSupportedAccessModes.Has(string(mode)) {
allErrs = append(allErrs, field.NotSupported(fldPath.Child("accessModes"), mode, expandedSupportedAccessModes.List()))
}
if mode == core.ReadWriteOncePod {
foundReadWriteOncePod = true
} else if supportedAccessModes.Has(string(mode)) {
foundNonReadWriteOncePod = true
}
}
if foundReadWriteOncePod && foundNonReadWriteOncePod {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("accessModes"), "may not use ReadWriteOncePod with other access modes"))
}
if !validateInlinePersistentVolumeSpec {
if len(pvSpec.Capacity) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("capacity"), ""))
}
if _, ok := pvSpec.Capacity[core.ResourceStorage]; !ok || len(pvSpec.Capacity) > 1 {
allErrs = append(allErrs, field.NotSupported(fldPath.Child("capacity"), pvSpec.Capacity, []string{string(core.ResourceStorage)}))
}
capPath := fldPath.Child("capacity")
for r, qty := range pvSpec.Capacity {
allErrs = append(allErrs, validateBasicResource(qty, capPath.Key(string(r)))...)
allErrs = append(allErrs, ValidatePositiveQuantityValue(qty, capPath.Key(string(r)))...)
}
}
if len(string(pvSpec.PersistentVolumeReclaimPolicy)) > 0 {
if validateInlinePersistentVolumeSpec {
if pvSpec.PersistentVolumeReclaimPolicy != core.PersistentVolumeReclaimRetain {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("persistentVolumeReclaimPolicy"), "may only be "+string(core.PersistentVolumeReclaimRetain)+" in the context of inline volumes"))
}
} else {
if !supportedReclaimPolicy.Has(string(pvSpec.PersistentVolumeReclaimPolicy)) {
allErrs = append(allErrs, field.NotSupported(fldPath.Child("persistentVolumeReclaimPolicy"), pvSpec.PersistentVolumeReclaimPolicy, supportedReclaimPolicy.List()))
}
}
}
var nodeAffinitySpecified bool
var errs field.ErrorList
if pvSpec.NodeAffinity != nil {
if validateInlinePersistentVolumeSpec {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("nodeAffinity"), "may not be specified in the context of inline volumes"))
} else {
nodeAffinitySpecified, errs = validateVolumeNodeAffinity(pvSpec.NodeAffinity, fldPath.Child("nodeAffinity"))
allErrs = append(allErrs, errs...)
}
}
numVolumes := 0
if pvSpec.HostPath != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("hostPath"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateHostPathVolumeSource(pvSpec.HostPath, fldPath.Child("hostPath"))...)
}
}
if pvSpec.GCEPersistentDisk != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("gcePersistentDisk"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateGCEPersistentDiskVolumeSource(pvSpec.GCEPersistentDisk, fldPath.Child("persistentDisk"))...)
}
}
if pvSpec.AWSElasticBlockStore != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("awsElasticBlockStore"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateAWSElasticBlockStoreVolumeSource(pvSpec.AWSElasticBlockStore, fldPath.Child("awsElasticBlockStore"))...)
}
}
if pvSpec.Glusterfs != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("glusterfs"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateGlusterfsPersistentVolumeSource(pvSpec.Glusterfs, fldPath.Child("glusterfs"))...)
}
}
if pvSpec.Flocker != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("flocker"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateFlockerVolumeSource(pvSpec.Flocker, fldPath.Child("flocker"))...)
}
}
if pvSpec.NFS != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("nfs"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateNFSVolumeSource(pvSpec.NFS, fldPath.Child("nfs"))...)
}
}
if pvSpec.RBD != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("rbd"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateRBDPersistentVolumeSource(pvSpec.RBD, fldPath.Child("rbd"))...)
}
}
if pvSpec.Quobyte != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("quobyte"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateQuobyteVolumeSource(pvSpec.Quobyte, fldPath.Child("quobyte"))...)
}
}
if pvSpec.CephFS != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("cephFS"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateCephFSPersistentVolumeSource(pvSpec.CephFS, fldPath.Child("cephfs"))...)
}
}
if pvSpec.ISCSI != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("iscsi"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateISCSIPersistentVolumeSource(pvSpec.ISCSI, pvName, fldPath.Child("iscsi"))...)
}
}
if pvSpec.Cinder != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("cinder"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateCinderPersistentVolumeSource(pvSpec.Cinder, fldPath.Child("cinder"))...)
}
}
if pvSpec.FC != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("fc"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateFCVolumeSource(pvSpec.FC, fldPath.Child("fc"))...)
}
}
if pvSpec.FlexVolume != nil {
numVolumes++
allErrs = append(allErrs, validateFlexPersistentVolumeSource(pvSpec.FlexVolume, fldPath.Child("flexVolume"))...)
}
if pvSpec.AzureFile != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("azureFile"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateAzureFilePV(pvSpec.AzureFile, fldPath.Child("azureFile"))...)
}
}
if pvSpec.VsphereVolume != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("vsphereVolume"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateVsphereVolumeSource(pvSpec.VsphereVolume, fldPath.Child("vsphereVolume"))...)
}
}
if pvSpec.PhotonPersistentDisk != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("photonPersistentDisk"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validatePhotonPersistentDiskVolumeSource(pvSpec.PhotonPersistentDisk, fldPath.Child("photonPersistentDisk"))...)
}
}
if pvSpec.PortworxVolume != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("portworxVolume"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validatePortworxVolumeSource(pvSpec.PortworxVolume, fldPath.Child("portworxVolume"))...)
}
}
if pvSpec.AzureDisk != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("azureDisk"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateAzureDisk(pvSpec.AzureDisk, fldPath.Child("azureDisk"))...)
}
}
if pvSpec.ScaleIO != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("scaleIO"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateScaleIOPersistentVolumeSource(pvSpec.ScaleIO, fldPath.Child("scaleIO"))...)
}
}
if pvSpec.Local != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("local"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateLocalVolumeSource(pvSpec.Local, fldPath.Child("local"))...)
// NodeAffinity is required
if !nodeAffinitySpecified {
allErrs = append(allErrs, field.Required(fldPath.Child("nodeAffinity"), "Local volume requires node affinity"))
}
}
}
if pvSpec.StorageOS != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("storageos"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateStorageOSPersistentVolumeSource(pvSpec.StorageOS, fldPath.Child("storageos"))...)
}
}
if pvSpec.CSI != nil {
if numVolumes > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("csi"), "may not specify more than 1 volume type"))
} else {
numVolumes++
allErrs = append(allErrs, validateCSIPersistentVolumeSource(pvSpec.CSI, fldPath.Child("csi"))...)
}
}
if numVolumes == 0 {
allErrs = append(allErrs, field.Required(fldPath, "must specify a volume type"))
}
// do not allow hostPath mounts of '/' to have a 'recycle' reclaim policy
if pvSpec.HostPath != nil && path.Clean(pvSpec.HostPath.Path) == "/" && pvSpec.PersistentVolumeReclaimPolicy == core.PersistentVolumeReclaimRecycle {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("persistentVolumeReclaimPolicy"), "may not be 'recycle' for a hostPath mount of '/'"))
}
if len(pvSpec.StorageClassName) > 0 {
if validateInlinePersistentVolumeSpec {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("storageClassName"), "may not be specified in the context of inline volumes"))
} else {
for _, msg := range ValidateClassName(pvSpec.StorageClassName, false) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("storageClassName"), pvSpec.StorageClassName, msg))
}
}
}
if pvSpec.VolumeMode != nil {
if validateInlinePersistentVolumeSpec {
if *pvSpec.VolumeMode != core.PersistentVolumeFilesystem {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("volumeMode"), "may not specify volumeMode other than "+string(core.PersistentVolumeFilesystem)+" in the context of inline volumes"))
}
} else {
if !supportedVolumeModes.Has(string(*pvSpec.VolumeMode)) {
allErrs = append(allErrs, field.NotSupported(fldPath.Child("volumeMode"), *pvSpec.VolumeMode, supportedVolumeModes.List()))
}
}
}
return allErrs
}
func ValidatePersistentVolume(pv *core.PersistentVolume, opts PersistentVolumeSpecValidationOptions) field.ErrorList {
metaPath := field.NewPath("metadata")
allErrs := ValidateObjectMeta(&pv.ObjectMeta, false, ValidatePersistentVolumeName, metaPath)
allErrs = append(allErrs, ValidatePersistentVolumeSpec(&pv.Spec, pv.ObjectMeta.Name, false, field.NewPath("spec"), opts)...)
return allErrs
}
// ValidatePersistentVolumeUpdate tests to see if the update is legal for an end user to make.
// newPv is updated with fields that cannot be changed.
func ValidatePersistentVolumeUpdate(newPv, oldPv *core.PersistentVolume, opts PersistentVolumeSpecValidationOptions) field.ErrorList {
allErrs := ValidatePersistentVolume(newPv, opts)
// if oldPV does not have ControllerExpandSecretRef then allow it to be set
if (oldPv.Spec.CSI != nil && oldPv.Spec.CSI.ControllerExpandSecretRef == nil) &&
(newPv.Spec.CSI != nil && newPv.Spec.CSI.ControllerExpandSecretRef != nil) {
newPv = newPv.DeepCopy()
newPv.Spec.CSI.ControllerExpandSecretRef = nil
}
// PersistentVolumeSource should be immutable after creation.
if !apiequality.Semantic.DeepEqual(newPv.Spec.PersistentVolumeSource, oldPv.Spec.PersistentVolumeSource) {
pvcSourceDiff := cmp.Diff(oldPv.Spec.PersistentVolumeSource, newPv.Spec.PersistentVolumeSource)
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "persistentvolumesource"), fmt.Sprintf("spec.persistentvolumesource is immutable after creation\n%v", pvcSourceDiff)))
}
allErrs = append(allErrs, ValidateImmutableField(newPv.Spec.VolumeMode, oldPv.Spec.VolumeMode, field.NewPath("volumeMode"))...)
// Allow setting NodeAffinity if oldPv NodeAffinity was not set
if oldPv.Spec.NodeAffinity != nil {
allErrs = append(allErrs, ValidateImmutableField(newPv.Spec.NodeAffinity, oldPv.Spec.NodeAffinity, field.NewPath("nodeAffinity"))...)
}
return allErrs
}
// ValidatePersistentVolumeStatusUpdate tests to see if the status update is legal for an end user to make.
func ValidatePersistentVolumeStatusUpdate(newPv, oldPv *core.PersistentVolume) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&newPv.ObjectMeta, &oldPv.ObjectMeta, field.NewPath("metadata"))
if len(newPv.ResourceVersion) == 0 {
allErrs = append(allErrs, field.Required(field.NewPath("resourceVersion"), ""))
}
return allErrs
}
type PersistentVolumeClaimSpecValidationOptions struct {
// Allow spec to contain the "ReadWiteOncePod" access mode
AllowReadWriteOncePod bool
// Allow pvc expansion after PVC is created and bound to a PV
EnableExpansion bool
// Allow users to recover from previously failing expansion operation
EnableRecoverFromExpansionFailure bool
}
func ValidationOptionsForPersistentVolumeClaim(pvc, oldPvc *core.PersistentVolumeClaim) PersistentVolumeClaimSpecValidationOptions {
opts := PersistentVolumeClaimSpecValidationOptions{
AllowReadWriteOncePod: utilfeature.DefaultFeatureGate.Enabled(features.ReadWriteOncePod),
EnableExpansion: utilfeature.DefaultFeatureGate.Enabled(features.ExpandPersistentVolumes),
EnableRecoverFromExpansionFailure: utilfeature.DefaultFeatureGate.Enabled(features.RecoverVolumeExpansionFailure),
}
if oldPvc == nil {
// If there's no old PVC, use the options based solely on feature enablement
return opts
}
if helper.ContainsAccessMode(oldPvc.Spec.AccessModes, core.ReadWriteOncePod) {
// If the old object allowed "ReadWriteOncePod", continue to allow it in the new object
opts.AllowReadWriteOncePod = true
}
return opts
}
func ValidationOptionsForPersistentVolumeClaimTemplate(claimTemplate, oldClaimTemplate *core.PersistentVolumeClaimTemplate) PersistentVolumeClaimSpecValidationOptions {
opts := PersistentVolumeClaimSpecValidationOptions{
AllowReadWriteOncePod: utilfeature.DefaultFeatureGate.Enabled(features.ReadWriteOncePod),
}
if oldClaimTemplate == nil {
// If there's no old PVC template, use the options based solely on feature enablement
return opts
}
if helper.ContainsAccessMode(oldClaimTemplate.Spec.AccessModes, core.ReadWriteOncePod) {
// If the old object allowed "ReadWriteOncePod", continue to allow it in the new object
opts.AllowReadWriteOncePod = true
}
return opts
}
// ValidatePersistentVolumeClaim validates a PersistentVolumeClaim
func ValidatePersistentVolumeClaim(pvc *core.PersistentVolumeClaim, opts PersistentVolumeClaimSpecValidationOptions) field.ErrorList {
allErrs := ValidateObjectMeta(&pvc.ObjectMeta, true, ValidatePersistentVolumeName, field.NewPath("metadata"))
allErrs = append(allErrs, ValidatePersistentVolumeClaimSpec(&pvc.Spec, field.NewPath("spec"), opts)...)
return allErrs
}
// validateDataSource validates a DataSource/DataSourceRef in a PersistentVolumeClaimSpec
func validateDataSource(dataSource *core.TypedLocalObjectReference, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(dataSource.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("name"), ""))
}
if len(dataSource.Kind) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("kind"), ""))
}
apiGroup := ""
if dataSource.APIGroup != nil {
apiGroup = *dataSource.APIGroup
}
if len(apiGroup) == 0 && dataSource.Kind != "PersistentVolumeClaim" {
allErrs = append(allErrs, field.Invalid(fldPath, dataSource.Kind, ""))
}
return allErrs
}
// ValidatePersistentVolumeClaimSpec validates a PersistentVolumeClaimSpec
func ValidatePersistentVolumeClaimSpec(spec *core.PersistentVolumeClaimSpec, fldPath *field.Path, opts PersistentVolumeClaimSpecValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
if len(spec.AccessModes) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("accessModes"), "at least 1 access mode is required"))
}
if spec.Selector != nil {
allErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(spec.Selector, fldPath.Child("selector"))...)
}
expandedSupportedAccessModes := sets.StringKeySet(supportedAccessModes)
if opts.AllowReadWriteOncePod {
expandedSupportedAccessModes.Insert(string(core.ReadWriteOncePod))
}
foundReadWriteOncePod, foundNonReadWriteOncePod := false, false
for _, mode := range spec.AccessModes {
if !expandedSupportedAccessModes.Has(string(mode)) {
allErrs = append(allErrs, field.NotSupported(fldPath.Child("accessModes"), mode, expandedSupportedAccessModes.List()))
}
if mode == core.ReadWriteOncePod {
foundReadWriteOncePod = true
} else if supportedAccessModes.Has(string(mode)) {
foundNonReadWriteOncePod = true
}
}
if foundReadWriteOncePod && foundNonReadWriteOncePod {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("accessModes"), "may not use ReadWriteOncePod with other access modes"))
}
storageValue, ok := spec.Resources.Requests[core.ResourceStorage]
if !ok {
allErrs = append(allErrs, field.Required(fldPath.Child("resources").Key(string(core.ResourceStorage)), ""))
} else if errs := ValidatePositiveQuantityValue(storageValue, fldPath.Child("resources").Key(string(core.ResourceStorage))); len(errs) > 0 {
allErrs = append(allErrs, errs...)
} else {
allErrs = append(allErrs, ValidateResourceQuantityValue(string(core.ResourceStorage), storageValue, fldPath.Child("resources").Key(string(core.ResourceStorage)))...)
}
if spec.StorageClassName != nil && len(*spec.StorageClassName) > 0 {
for _, msg := range ValidateClassName(*spec.StorageClassName, false) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("storageClassName"), *spec.StorageClassName, msg))
}
}
if spec.VolumeMode != nil && !supportedVolumeModes.Has(string(*spec.VolumeMode)) {
allErrs = append(allErrs, field.NotSupported(fldPath.Child("volumeMode"), *spec.VolumeMode, supportedVolumeModes.List()))
}
if spec.DataSource != nil {
allErrs = append(allErrs, validateDataSource(spec.DataSource, fldPath.Child("dataSource"))...)
}
if spec.DataSourceRef != nil {
allErrs = append(allErrs, validateDataSource(spec.DataSourceRef, fldPath.Child("dataSourceRef"))...)
}
if spec.DataSource != nil && spec.DataSourceRef != nil {
if !apiequality.Semantic.DeepEqual(spec.DataSource, spec.DataSourceRef) {
allErrs = append(allErrs, field.Invalid(fldPath, fldPath.Child("dataSource"),
"must match dataSourceRef"))
}
}
return allErrs
}
// ValidatePersistentVolumeClaimUpdate validates an update to a PersistentVolumeClaim
func ValidatePersistentVolumeClaimUpdate(newPvc, oldPvc *core.PersistentVolumeClaim, opts PersistentVolumeClaimSpecValidationOptions) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&newPvc.ObjectMeta, &oldPvc.ObjectMeta, field.NewPath("metadata"))
allErrs = append(allErrs, ValidatePersistentVolumeClaim(newPvc, opts)...)
newPvcClone := newPvc.DeepCopy()
oldPvcClone := oldPvc.DeepCopy()
// PVController needs to update PVC.Spec w/ VolumeName.
// Claims are immutable in order to enforce quota, range limits, etc. without gaming the system.
if len(oldPvc.Spec.VolumeName) == 0 {
// volumeName changes are allowed once.
oldPvcClone.Spec.VolumeName = newPvcClone.Spec.VolumeName // +k8s:verify-mutation:reason=clone
}
if validateStorageClassUpgrade(oldPvcClone.Annotations, newPvcClone.Annotations,
oldPvcClone.Spec.StorageClassName, newPvcClone.Spec.StorageClassName) {
newPvcClone.Spec.StorageClassName = nil
metav1.SetMetaDataAnnotation(&newPvcClone.ObjectMeta, core.BetaStorageClassAnnotation, oldPvcClone.Annotations[core.BetaStorageClassAnnotation])
} else {
// storageclass annotation should be immutable after creation
// TODO: remove Beta when no longer needed
allErrs = append(allErrs, ValidateImmutableAnnotation(newPvc.ObjectMeta.Annotations[v1.BetaStorageClassAnnotation], oldPvc.ObjectMeta.Annotations[v1.BetaStorageClassAnnotation], v1.BetaStorageClassAnnotation, field.NewPath("metadata"))...)
}
if opts.EnableExpansion {
// lets make sure storage values are same.
if newPvc.Status.Phase == core.ClaimBound && newPvcClone.Spec.Resources.Requests != nil {
newPvcClone.Spec.Resources.Requests["storage"] = oldPvc.Spec.Resources.Requests["storage"] // +k8s:verify-mutation:reason=clone
}
oldSize := oldPvc.Spec.Resources.Requests["storage"]
newSize := newPvc.Spec.Resources.Requests["storage"]
statusSize := oldPvc.Status.Capacity["storage"]
if !apiequality.Semantic.DeepEqual(newPvcClone.Spec, oldPvcClone.Spec) {
specDiff := cmp.Diff(oldPvcClone.Spec, newPvcClone.Spec)
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec"), fmt.Sprintf("spec is immutable after creation except resources.requests for bound claims\n%v", specDiff)))
}
if newSize.Cmp(oldSize) < 0 {
if !opts.EnableRecoverFromExpansionFailure {
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "resources", "requests", "storage"), "field can not be less than previous value"))
} else {
// This validation permits reducing pvc requested size up to capacity recorded in pvc.status
// so that users can recover from volume expansion failure, but Kubernetes does not actually
// support volume shrinking
if newSize.Cmp(statusSize) <= 0 {
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "resources", "requests", "storage"), "field can not be less than status.capacity"))
}
}
}
} else {
// changes to Spec are not allowed, but updates to label/and some annotations are OK.
// no-op updates pass validation.
if !apiequality.Semantic.DeepEqual(newPvcClone.Spec, oldPvcClone.Spec) {
specDiff := cmp.Diff(oldPvcClone.Spec, newPvcClone.Spec)
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec"), fmt.Sprintf("field is immutable after creation\n%v", specDiff)))
}
}
allErrs = append(allErrs, ValidateImmutableField(newPvc.Spec.VolumeMode, oldPvc.Spec.VolumeMode, field.NewPath("volumeMode"))...)
return allErrs
}
// Provide an upgrade path from PVC with storage class specified in beta
// annotation to storage class specified in attribute. We allow update of
// StorageClassName only if following four conditions are met at the same time:
// 1. The old pvc's StorageClassAnnotation is set
// 2. The old pvc's StorageClassName is not set
// 3. The new pvc's StorageClassName is set and equal to the old value in annotation
// 4. If the new pvc's StorageClassAnnotation is set,it must be equal to the old pv/pvc's StorageClassAnnotation
func validateStorageClassUpgrade(oldAnnotations, newAnnotations map[string]string, oldScName, newScName *string) bool {
oldSc, oldAnnotationExist := oldAnnotations[core.BetaStorageClassAnnotation]
newScInAnnotation, newAnnotationExist := newAnnotations[core.BetaStorageClassAnnotation]
return oldAnnotationExist /* condition 1 */ &&
oldScName == nil /* condition 2*/ &&
(newScName != nil && *newScName == oldSc) /* condition 3 */ &&
(!newAnnotationExist || newScInAnnotation == oldSc) /* condition 4 */
}
var resizeStatusSet = sets.NewString(string(core.PersistentVolumeClaimNoExpansionInProgress),
string(core.PersistentVolumeClaimControllerExpansionInProgress),
string(core.PersistentVolumeClaimControllerExpansionFailed),
string(core.PersistentVolumeClaimNodeExpansionPending),
string(core.PersistentVolumeClaimNodeExpansionInProgress),
string(core.PersistentVolumeClaimNodeExpansionFailed))
// ValidatePersistentVolumeClaimStatusUpdate validates an update to status of a PersistentVolumeClaim
func ValidatePersistentVolumeClaimStatusUpdate(newPvc, oldPvc *core.PersistentVolumeClaim, validationOpts PersistentVolumeClaimSpecValidationOptions) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&newPvc.ObjectMeta, &oldPvc.ObjectMeta, field.NewPath("metadata"))
if len(newPvc.ResourceVersion) == 0 {
allErrs = append(allErrs, field.Required(field.NewPath("resourceVersion"), ""))
}
if len(newPvc.Spec.AccessModes) == 0 {
allErrs = append(allErrs, field.Required(field.NewPath("Spec", "accessModes"), ""))
}
capPath := field.NewPath("status", "capacity")
for r, qty := range newPvc.Status.Capacity {
allErrs = append(allErrs, validateBasicResource(qty, capPath.Key(string(r)))...)
}
if validationOpts.EnableRecoverFromExpansionFailure {
resizeStatusPath := field.NewPath("status", "resizeStatus")
if newPvc.Status.ResizeStatus != nil {
resizeStatus := *newPvc.Status.ResizeStatus
if !resizeStatusSet.Has(string(resizeStatus)) {
allErrs = append(allErrs, field.NotSupported(resizeStatusPath, resizeStatus, resizeStatusSet.List()))
}
}
allocPath := field.NewPath("status", "allocatedResources")
for r, qty := range newPvc.Status.AllocatedResources {
if r != core.ResourceStorage {
allErrs = append(allErrs, field.NotSupported(allocPath, r, []string{string(core.ResourceStorage)}))
continue
}
if errs := validateBasicResource(qty, allocPath.Key(string(r))); len(errs) > 0 {
allErrs = append(allErrs, errs...)
} else {
allErrs = append(allErrs, ValidateResourceQuantityValue(string(core.ResourceStorage), qty, allocPath.Key(string(r)))...)
}
}
}
return allErrs
}
var supportedPortProtocols = sets.NewString(string(core.ProtocolTCP), string(core.ProtocolUDP), string(core.ProtocolSCTP))
func validateContainerPorts(ports []core.ContainerPort, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
allNames := sets.String{}
for i, port := range ports {
idxPath := fldPath.Index(i)
if len(port.Name) > 0 {
if msgs := validation.IsValidPortName(port.Name); len(msgs) != 0 {
for i = range msgs {
allErrs = append(allErrs, field.Invalid(idxPath.Child("name"), port.Name, msgs[i]))
}
} else if allNames.Has(port.Name) {
allErrs = append(allErrs, field.Duplicate(idxPath.Child("name"), port.Name))
} else {
allNames.Insert(port.Name)
}
}
if port.ContainerPort == 0 {
allErrs = append(allErrs, field.Required(idxPath.Child("containerPort"), ""))
} else {
for _, msg := range validation.IsValidPortNum(int(port.ContainerPort)) {
allErrs = append(allErrs, field.Invalid(idxPath.Child("containerPort"), port.ContainerPort, msg))
}
}
if port.HostPort != 0 {
for _, msg := range validation.IsValidPortNum(int(port.HostPort)) {
allErrs = append(allErrs, field.Invalid(idxPath.Child("hostPort"), port.HostPort, msg))
}
}
if len(port.Protocol) == 0 {
allErrs = append(allErrs, field.Required(idxPath.Child("protocol"), ""))
} else if !supportedPortProtocols.Has(string(port.Protocol)) {
allErrs = append(allErrs, field.NotSupported(idxPath.Child("protocol"), port.Protocol, supportedPortProtocols.List()))
}
}
return allErrs
}
// ValidateEnv validates env vars
func ValidateEnv(vars []core.EnvVar, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
for i, ev := range vars {
idxPath := fldPath.Index(i)
if len(ev.Name) == 0 {
allErrs = append(allErrs, field.Required(idxPath.Child("name"), ""))
} else {
for _, msg := range validation.IsEnvVarName(ev.Name) {
allErrs = append(allErrs, field.Invalid(idxPath.Child("name"), ev.Name, msg))
}
}
allErrs = append(allErrs, validateEnvVarValueFrom(ev, idxPath.Child("valueFrom"), opts)...)
}
return allErrs
}
var validEnvDownwardAPIFieldPathExpressions = sets.NewString(
"metadata.name",
"metadata.namespace",
"metadata.uid",
"spec.nodeName",
"spec.serviceAccountName",
"status.hostIP",
"status.podIP",
"status.podIPs")
var validContainerResourceFieldPathExpressions = sets.NewString("limits.cpu", "limits.memory", "limits.ephemeral-storage", "requests.cpu", "requests.memory", "requests.ephemeral-storage")
// NOTE: this is only valid with DownwardAPIHugePages enabled
var validContainerResourceFieldPathPrefixes = sets.NewString()
var validContainerResourceFieldPathPrefixesWithDownwardAPIHugePages = sets.NewString(hugepagesRequestsPrefixDownwardAPI, hugepagesLimitsPrefixDownwardAPI)
const hugepagesRequestsPrefixDownwardAPI string = `requests.hugepages-`
const hugepagesLimitsPrefixDownwardAPI string = `limits.hugepages-`
func validateEnvVarValueFrom(ev core.EnvVar, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
if ev.ValueFrom == nil {
return allErrs
}
numSources := 0
if ev.ValueFrom.FieldRef != nil {
numSources++
allErrs = append(allErrs, validateObjectFieldSelector(ev.ValueFrom.FieldRef, &validEnvDownwardAPIFieldPathExpressions, fldPath.Child("fieldRef"))...)
}
if ev.ValueFrom.ResourceFieldRef != nil {
numSources++
localValidContainerResourceFieldPathPrefixes := validContainerResourceFieldPathPrefixes
if opts.AllowDownwardAPIHugePages {
localValidContainerResourceFieldPathPrefixes = validContainerResourceFieldPathPrefixesWithDownwardAPIHugePages
}
allErrs = append(allErrs, validateContainerResourceFieldSelector(ev.ValueFrom.ResourceFieldRef, &validContainerResourceFieldPathExpressions, &localValidContainerResourceFieldPathPrefixes, fldPath.Child("resourceFieldRef"), false)...)
}
if ev.ValueFrom.ConfigMapKeyRef != nil {
numSources++
allErrs = append(allErrs, validateConfigMapKeySelector(ev.ValueFrom.ConfigMapKeyRef, fldPath.Child("configMapKeyRef"))...)
}
if ev.ValueFrom.SecretKeyRef != nil {
numSources++
allErrs = append(allErrs, validateSecretKeySelector(ev.ValueFrom.SecretKeyRef, fldPath.Child("secretKeyRef"))...)
}
if numSources == 0 {
allErrs = append(allErrs, field.Invalid(fldPath, "", "must specify one of: `fieldRef`, `resourceFieldRef`, `configMapKeyRef` or `secretKeyRef`"))
} else if len(ev.Value) != 0 {
if numSources != 0 {
allErrs = append(allErrs, field.Invalid(fldPath, "", "may not be specified when `value` is not empty"))
}
} else if numSources > 1 {
allErrs = append(allErrs, field.Invalid(fldPath, "", "may not have more than one field specified at a time"))
}
return allErrs
}
func validateObjectFieldSelector(fs *core.ObjectFieldSelector, expressions *sets.String, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(fs.APIVersion) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("apiVersion"), ""))
return allErrs
}
if len(fs.FieldPath) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("fieldPath"), ""))
return allErrs
}
internalFieldPath, _, err := podshelper.ConvertDownwardAPIFieldLabel(fs.APIVersion, fs.FieldPath, "")
if err != nil {
allErrs = append(allErrs, field.Invalid(fldPath.Child("fieldPath"), fs.FieldPath, fmt.Sprintf("error converting fieldPath: %v", err)))
return allErrs
}
if path, subscript, ok := fieldpath.SplitMaybeSubscriptedPath(internalFieldPath); ok {
switch path {
case "metadata.annotations":
for _, msg := range validation.IsQualifiedName(strings.ToLower(subscript)) {
allErrs = append(allErrs, field.Invalid(fldPath, subscript, msg))
}
case "metadata.labels":
for _, msg := range validation.IsQualifiedName(subscript) {
allErrs = append(allErrs, field.Invalid(fldPath, subscript, msg))
}
default:
allErrs = append(allErrs, field.Invalid(fldPath, path, "does not support subscript"))
}
} else if !expressions.Has(path) {
allErrs = append(allErrs, field.NotSupported(fldPath.Child("fieldPath"), path, expressions.List()))
return allErrs
}
return allErrs
}
func validateContainerResourceFieldSelector(fs *core.ResourceFieldSelector, expressions *sets.String, prefixes *sets.String, fldPath *field.Path, volume bool) field.ErrorList {
allErrs := field.ErrorList{}
if volume && len(fs.ContainerName) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("containerName"), ""))
} else if len(fs.Resource) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("resource"), ""))
} else if !expressions.Has(fs.Resource) {
// check if the prefix is present
foundPrefix := false
if prefixes != nil {
for _, prefix := range prefixes.List() {
if strings.HasPrefix(fs.Resource, prefix) {
foundPrefix = true
}
}
}
if !foundPrefix {
allErrs = append(allErrs, field.NotSupported(fldPath.Child("resource"), fs.Resource, expressions.List()))
}
}
allErrs = append(allErrs, validateContainerResourceDivisor(fs.Resource, fs.Divisor, fldPath)...)
return allErrs
}
func ValidateEnvFrom(vars []core.EnvFromSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for i, ev := range vars {
idxPath := fldPath.Index(i)
if len(ev.Prefix) > 0 {
for _, msg := range validation.IsEnvVarName(ev.Prefix) {
allErrs = append(allErrs, field.Invalid(idxPath.Child("prefix"), ev.Prefix, msg))
}
}
numSources := 0
if ev.ConfigMapRef != nil {
numSources++
allErrs = append(allErrs, validateConfigMapEnvSource(ev.ConfigMapRef, idxPath.Child("configMapRef"))...)
}
if ev.SecretRef != nil {
numSources++
allErrs = append(allErrs, validateSecretEnvSource(ev.SecretRef, idxPath.Child("secretRef"))...)
}
if numSources == 0 {
allErrs = append(allErrs, field.Invalid(fldPath, "", "must specify one of: `configMapRef` or `secretRef`"))
} else if numSources > 1 {
allErrs = append(allErrs, field.Invalid(fldPath, "", "may not have more than one field specified at a time"))
}
}
return allErrs
}
func validateConfigMapEnvSource(configMapSource *core.ConfigMapEnvSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(configMapSource.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("name"), ""))
} else {
for _, msg := range ValidateConfigMapName(configMapSource.Name, true) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), configMapSource.Name, msg))
}
}
return allErrs
}
func validateSecretEnvSource(secretSource *core.SecretEnvSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(secretSource.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("name"), ""))
} else {
for _, msg := range ValidateSecretName(secretSource.Name, true) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), secretSource.Name, msg))
}
}
return allErrs
}
var validContainerResourceDivisorForCPU = sets.NewString("1m", "1")
var validContainerResourceDivisorForMemory = sets.NewString("1", "1k", "1M", "1G", "1T", "1P", "1E", "1Ki", "1Mi", "1Gi", "1Ti", "1Pi", "1Ei")
var validContainerResourceDivisorForHugePages = sets.NewString("1", "1k", "1M", "1G", "1T", "1P", "1E", "1Ki", "1Mi", "1Gi", "1Ti", "1Pi", "1Ei")
var validContainerResourceDivisorForEphemeralStorage = sets.NewString("1", "1k", "1M", "1G", "1T", "1P", "1E", "1Ki", "1Mi", "1Gi", "1Ti", "1Pi", "1Ei")
func validateContainerResourceDivisor(rName string, divisor resource.Quantity, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
unsetDivisor := resource.Quantity{}
if unsetDivisor.Cmp(divisor) == 0 {
return allErrs
}
switch rName {
case "limits.cpu", "requests.cpu":
if !validContainerResourceDivisorForCPU.Has(divisor.String()) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("divisor"), rName, "only divisor's values 1m and 1 are supported with the cpu resource"))
}
case "limits.memory", "requests.memory":
if !validContainerResourceDivisorForMemory.Has(divisor.String()) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("divisor"), rName, "only divisor's values 1, 1k, 1M, 1G, 1T, 1P, 1E, 1Ki, 1Mi, 1Gi, 1Ti, 1Pi, 1Ei are supported with the memory resource"))
}
case "limits.ephemeral-storage", "requests.ephemeral-storage":
if !validContainerResourceDivisorForEphemeralStorage.Has(divisor.String()) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("divisor"), rName, "only divisor's values 1, 1k, 1M, 1G, 1T, 1P, 1E, 1Ki, 1Mi, 1Gi, 1Ti, 1Pi, 1Ei are supported with the local ephemeral storage resource"))
}
}
if strings.HasPrefix(rName, hugepagesRequestsPrefixDownwardAPI) || strings.HasPrefix(rName, hugepagesLimitsPrefixDownwardAPI) {
if !validContainerResourceDivisorForHugePages.Has(divisor.String()) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("divisor"), rName, "only divisor's values 1, 1k, 1M, 1G, 1T, 1P, 1E, 1Ki, 1Mi, 1Gi, 1Ti, 1Pi, 1Ei are supported with the hugepages resource"))
}
}
return allErrs
}
func validateConfigMapKeySelector(s *core.ConfigMapKeySelector, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
nameFn := ValidateNameFunc(ValidateSecretName)
for _, msg := range nameFn(s.Name, false) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), s.Name, msg))
}
if len(s.Key) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("key"), ""))
} else {
for _, msg := range validation.IsConfigMapKey(s.Key) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("key"), s.Key, msg))
}
}
return allErrs
}
func validateSecretKeySelector(s *core.SecretKeySelector, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
nameFn := ValidateNameFunc(ValidateSecretName)
for _, msg := range nameFn(s.Name, false) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), s.Name, msg))
}
if len(s.Key) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("key"), ""))
} else {
for _, msg := range validation.IsConfigMapKey(s.Key) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("key"), s.Key, msg))
}
}
return allErrs
}
func GetVolumeMountMap(mounts []core.VolumeMount) map[string]string {
volmounts := make(map[string]string)
for _, mnt := range mounts {
volmounts[mnt.Name] = mnt.MountPath
}
return volmounts
}
func GetVolumeDeviceMap(devices []core.VolumeDevice) map[string]string {
volDevices := make(map[string]string)
for _, dev := range devices {
volDevices[dev.Name] = dev.DevicePath
}
return volDevices
}
func ValidateVolumeMounts(mounts []core.VolumeMount, voldevices map[string]string, volumes map[string]core.VolumeSource, container *core.Container, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
mountpoints := sets.NewString()
for i, mnt := range mounts {
idxPath := fldPath.Index(i)
if len(mnt.Name) == 0 {
allErrs = append(allErrs, field.Required(idxPath.Child("name"), ""))
}
if !IsMatchedVolume(mnt.Name, volumes) {
allErrs = append(allErrs, field.NotFound(idxPath.Child("name"), mnt.Name))
}
if len(mnt.MountPath) == 0 {
allErrs = append(allErrs, field.Required(idxPath.Child("mountPath"), ""))
}
if mountpoints.Has(mnt.MountPath) {
allErrs = append(allErrs, field.Invalid(idxPath.Child("mountPath"), mnt.MountPath, "must be unique"))
}
mountpoints.Insert(mnt.MountPath)
// check for overlap with VolumeDevice
if mountNameAlreadyExists(mnt.Name, voldevices) {
allErrs = append(allErrs, field.Invalid(idxPath.Child("name"), mnt.Name, "must not already exist in volumeDevices"))
}
if mountPathAlreadyExists(mnt.MountPath, voldevices) {
allErrs = append(allErrs, field.Invalid(idxPath.Child("mountPath"), mnt.MountPath, "must not already exist as a path in volumeDevices"))
}
if len(mnt.SubPath) > 0 {
allErrs = append(allErrs, validateLocalDescendingPath(mnt.SubPath, fldPath.Child("subPath"))...)
}
if len(mnt.SubPathExpr) > 0 {
if len(mnt.SubPath) > 0 {
allErrs = append(allErrs, field.Invalid(idxPath.Child("subPathExpr"), mnt.SubPathExpr, "subPathExpr and subPath are mutually exclusive"))
}
allErrs = append(allErrs, validateLocalDescendingPath(mnt.SubPathExpr, fldPath.Child("subPathExpr"))...)
}
if mnt.MountPropagation != nil {
allErrs = append(allErrs, validateMountPropagation(mnt.MountPropagation, container, fldPath.Child("mountPropagation"))...)
}
}
return allErrs
}
func ValidateVolumeDevices(devices []core.VolumeDevice, volmounts map[string]string, volumes map[string]core.VolumeSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
devicepath := sets.NewString()
devicename := sets.NewString()
for i, dev := range devices {
idxPath := fldPath.Index(i)
devName := dev.Name
devPath := dev.DevicePath
didMatch, isPVC := isMatchedDevice(devName, volumes)
if len(devName) == 0 {
allErrs = append(allErrs, field.Required(idxPath.Child("name"), ""))
}
if devicename.Has(devName) {
allErrs = append(allErrs, field.Invalid(idxPath.Child("name"), devName, "must be unique"))
}
// Must be based on PersistentVolumeClaim (PVC reference or generic ephemeral inline volume)
if didMatch && !isPVC {
allErrs = append(allErrs, field.Invalid(idxPath.Child("name"), devName, "can only use volume source type of PersistentVolumeClaim or Ephemeral for block mode"))
}
if !didMatch {
allErrs = append(allErrs, field.NotFound(idxPath.Child("name"), devName))
}
if len(devPath) == 0 {
allErrs = append(allErrs, field.Required(idxPath.Child("devicePath"), ""))
}
if devicepath.Has(devPath) {
allErrs = append(allErrs, field.Invalid(idxPath.Child("devicePath"), devPath, "must be unique"))
}
if len(devPath) > 0 && len(validatePathNoBacksteps(devPath, fldPath.Child("devicePath"))) > 0 {
allErrs = append(allErrs, field.Invalid(idxPath.Child("devicePath"), devPath, "can not contain backsteps ('..')"))
} else {
devicepath.Insert(devPath)
}
// check for overlap with VolumeMount
if deviceNameAlreadyExists(devName, volmounts) {
allErrs = append(allErrs, field.Invalid(idxPath.Child("name"), devName, "must not already exist in volumeMounts"))
}
if devicePathAlreadyExists(devPath, volmounts) {
allErrs = append(allErrs, field.Invalid(idxPath.Child("devicePath"), devPath, "must not already exist as a path in volumeMounts"))
}
if len(devName) > 0 {
devicename.Insert(devName)
}
}
return allErrs
}
func validateProbe(probe *core.Probe, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if probe == nil {
return allErrs
}
allErrs = append(allErrs, validateHandler(handlerFromProbe(&probe.ProbeHandler), fldPath)...)
allErrs = append(allErrs, ValidateNonnegativeField(int64(probe.InitialDelaySeconds), fldPath.Child("initialDelaySeconds"))...)
allErrs = append(allErrs, ValidateNonnegativeField(int64(probe.TimeoutSeconds), fldPath.Child("timeoutSeconds"))...)
allErrs = append(allErrs, ValidateNonnegativeField(int64(probe.PeriodSeconds), fldPath.Child("periodSeconds"))...)
allErrs = append(allErrs, ValidateNonnegativeField(int64(probe.SuccessThreshold), fldPath.Child("successThreshold"))...)
allErrs = append(allErrs, ValidateNonnegativeField(int64(probe.FailureThreshold), fldPath.Child("failureThreshold"))...)
if probe.TerminationGracePeriodSeconds != nil && *probe.TerminationGracePeriodSeconds <= 0 {
allErrs = append(allErrs, field.Invalid(fldPath.Child("terminationGracePeriodSeconds"), *probe.TerminationGracePeriodSeconds, "must be greater than 0"))
}
return allErrs
}
type commonHandler struct {
Exec *core.ExecAction
HTTPGet *core.HTTPGetAction
TCPSocket *core.TCPSocketAction
GRPC *core.GRPCAction
}
func handlerFromProbe(ph *core.ProbeHandler) commonHandler {
return commonHandler{
Exec: ph.Exec,
HTTPGet: ph.HTTPGet,
TCPSocket: ph.TCPSocket,
GRPC: ph.GRPC,
}
}
func handlerFromLifecycle(lh *core.LifecycleHandler) commonHandler {
return commonHandler{
Exec: lh.Exec,
HTTPGet: lh.HTTPGet,
TCPSocket: lh.TCPSocket,
}
}
func validateClientIPAffinityConfig(config *core.SessionAffinityConfig, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if config == nil {
allErrs = append(allErrs, field.Required(fldPath, fmt.Sprintf("when session affinity type is %s", core.ServiceAffinityClientIP)))
return allErrs
}
if config.ClientIP == nil {
allErrs = append(allErrs, field.Required(fldPath.Child("clientIP"), fmt.Sprintf("when session affinity type is %s", core.ServiceAffinityClientIP)))
return allErrs
}
if config.ClientIP.TimeoutSeconds == nil {
allErrs = append(allErrs, field.Required(fldPath.Child("clientIP").Child("timeoutSeconds"), fmt.Sprintf("when session affinity type is %s", core.ServiceAffinityClientIP)))
return allErrs
}
allErrs = append(allErrs, validateAffinityTimeout(config.ClientIP.TimeoutSeconds, fldPath.Child("clientIP").Child("timeoutSeconds"))...)
return allErrs
}
func validateAffinityTimeout(timeout *int32, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if *timeout <= 0 || *timeout > core.MaxClientIPServiceAffinitySeconds {
allErrs = append(allErrs, field.Invalid(fldPath, timeout, fmt.Sprintf("must be greater than 0 and less than %d", core.MaxClientIPServiceAffinitySeconds)))
}
return allErrs
}
// AccumulateUniqueHostPorts extracts each HostPort of each Container,
// accumulating the results and returning an error if any ports conflict.
func AccumulateUniqueHostPorts(containers []core.Container, accumulator *sets.String, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for ci, ctr := range containers {
idxPath := fldPath.Index(ci)
portsPath := idxPath.Child("ports")
for pi := range ctr.Ports {
idxPath := portsPath.Index(pi)
port := ctr.Ports[pi].HostPort
if port == 0 {
continue
}
str := fmt.Sprintf("%s/%s/%d", ctr.Ports[pi].Protocol, ctr.Ports[pi].HostIP, port)
if accumulator.Has(str) {
allErrs = append(allErrs, field.Duplicate(idxPath.Child("hostPort"), str))
} else {
accumulator.Insert(str)
}
}
}
return allErrs
}
// checkHostPortConflicts checks for colliding Port.HostPort values across
// a slice of containers.
func checkHostPortConflicts(containers []core.Container, fldPath *field.Path) field.ErrorList {
allPorts := sets.String{}
return AccumulateUniqueHostPorts(containers, &allPorts, fldPath)
}
func validateExecAction(exec *core.ExecAction, fldPath *field.Path) field.ErrorList {
allErrors := field.ErrorList{}
if len(exec.Command) == 0 {
allErrors = append(allErrors, field.Required(fldPath.Child("command"), ""))
}
return allErrors
}
var supportedHTTPSchemes = sets.NewString(string(core.URISchemeHTTP), string(core.URISchemeHTTPS))
func validateHTTPGetAction(http *core.HTTPGetAction, fldPath *field.Path) field.ErrorList {
allErrors := field.ErrorList{}
if len(http.Path) == 0 {
allErrors = append(allErrors, field.Required(fldPath.Child("path"), ""))
}
allErrors = append(allErrors, ValidatePortNumOrName(http.Port, fldPath.Child("port"))...)
if !supportedHTTPSchemes.Has(string(http.Scheme)) {
allErrors = append(allErrors, field.NotSupported(fldPath.Child("scheme"), http.Scheme, supportedHTTPSchemes.List()))
}
for _, header := range http.HTTPHeaders {
for _, msg := range validation.IsHTTPHeaderName(header.Name) {
allErrors = append(allErrors, field.Invalid(fldPath.Child("httpHeaders"), header.Name, msg))
}
}
return allErrors
}
func ValidatePortNumOrName(port intstr.IntOrString, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if port.Type == intstr.Int {
for _, msg := range validation.IsValidPortNum(port.IntValue()) {
allErrs = append(allErrs, field.Invalid(fldPath, port.IntValue(), msg))
}
} else if port.Type == intstr.String {
for _, msg := range validation.IsValidPortName(port.StrVal) {
allErrs = append(allErrs, field.Invalid(fldPath, port.StrVal, msg))
}
} else {
allErrs = append(allErrs, field.InternalError(fldPath, fmt.Errorf("unknown type: %v", port.Type)))
}
return allErrs
}
func validateTCPSocketAction(tcp *core.TCPSocketAction, fldPath *field.Path) field.ErrorList {
return ValidatePortNumOrName(tcp.Port, fldPath.Child("port"))
}
func validateGRPCAction(grpc *core.GRPCAction, fldPath *field.Path) field.ErrorList {
return ValidatePortNumOrName(intstr.FromInt(int(grpc.Port)), fldPath.Child("port"))
}
func validateHandler(handler commonHandler, fldPath *field.Path) field.ErrorList {
numHandlers := 0
allErrors := field.ErrorList{}
if handler.Exec != nil {
if numHandlers > 0 {
allErrors = append(allErrors, field.Forbidden(fldPath.Child("exec"), "may not specify more than 1 handler type"))
} else {
numHandlers++
allErrors = append(allErrors, validateExecAction(handler.Exec, fldPath.Child("exec"))...)
}
}
if handler.HTTPGet != nil {
if numHandlers > 0 {
allErrors = append(allErrors, field.Forbidden(fldPath.Child("httpGet"), "may not specify more than 1 handler type"))
} else {
numHandlers++
allErrors = append(allErrors, validateHTTPGetAction(handler.HTTPGet, fldPath.Child("httpGet"))...)
}
}
if handler.TCPSocket != nil {
if numHandlers > 0 {
allErrors = append(allErrors, field.Forbidden(fldPath.Child("tcpSocket"), "may not specify more than 1 handler type"))
} else {
numHandlers++
allErrors = append(allErrors, validateTCPSocketAction(handler.TCPSocket, fldPath.Child("tcpSocket"))...)
}
}
if handler.GRPC != nil {
if numHandlers > 0 {
allErrors = append(allErrors, field.Forbidden(fldPath.Child("grpc"), "may not specify more than 1 handler type"))
} else {
numHandlers++
allErrors = append(allErrors, validateGRPCAction(handler.GRPC, fldPath.Child("grpc"))...)
}
}
if numHandlers == 0 {
allErrors = append(allErrors, field.Required(fldPath, "must specify a handler type"))
}
return allErrors
}
func validateLifecycle(lifecycle *core.Lifecycle, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if lifecycle.PostStart != nil {
allErrs = append(allErrs, validateHandler(handlerFromLifecycle(lifecycle.PostStart), fldPath.Child("postStart"))...)
}
if lifecycle.PreStop != nil {
allErrs = append(allErrs, validateHandler(handlerFromLifecycle(lifecycle.PreStop), fldPath.Child("preStop"))...)
}
return allErrs
}
var supportedPullPolicies = sets.NewString(string(core.PullAlways), string(core.PullIfNotPresent), string(core.PullNever))
func validatePullPolicy(policy core.PullPolicy, fldPath *field.Path) field.ErrorList {
allErrors := field.ErrorList{}
switch policy {
case core.PullAlways, core.PullIfNotPresent, core.PullNever:
break
case "":
allErrors = append(allErrors, field.Required(fldPath, ""))
default:
allErrors = append(allErrors, field.NotSupported(fldPath, policy, supportedPullPolicies.List()))
}
return allErrors
}
func validateEphemeralContainers(ephemeralContainers []core.EphemeralContainer, containers, initContainers []core.Container, volumes map[string]core.VolumeSource, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
if len(ephemeralContainers) == 0 {
return allErrs
}
allNames := sets.String{}
for _, c := range containers {
allNames.Insert(c.Name)
}
for _, c := range initContainers {
allNames.Insert(c.Name)
}
for i, ec := range ephemeralContainers {
idxPath := fldPath.Index(i)
if ec.TargetContainerName != "" && !allNames.Has(ec.TargetContainerName) {
allErrs = append(allErrs, field.NotFound(idxPath.Child("targetContainerName"), ec.TargetContainerName))
}
if ec.Name == "" {
allErrs = append(allErrs, field.Required(idxPath, "ephemeralContainer requires a name"))
continue
}
// Using validateContainers() here isn't ideal because it adds an index to the error message that
// doesn't really exist for EphemeralContainers (i.e. ephemeralContainers[0].spec[0].name instead
// of ephemeralContainers[0].spec.name)
// TODO(verb): factor a validateContainer() out of validateContainers() to be used here
c := core.Container(ec.EphemeralContainerCommon)
allErrs = append(allErrs, validateContainers([]core.Container{c}, false, volumes, idxPath, opts)...)
// EphemeralContainers don't require the backwards-compatibility distinction between pod/podTemplate validation
allErrs = append(allErrs, validateContainersOnlyForPod([]core.Container{c}, idxPath)...)
if allNames.Has(ec.Name) {
allErrs = append(allErrs, field.Duplicate(idxPath.Child("name"), ec.Name))
} else {
allNames.Insert(ec.Name)
}
// Ephemeral Containers should not be relied upon for fundamental pod services, so fields such as
// Lifecycle, probes, resources and ports should be disallowed. This is implemented as a list
// of allowed fields so that new fields will be given consideration prior to inclusion in Ephemeral Containers.
allErrs = append(allErrs, validateFieldAllowList(ec.EphemeralContainerCommon, allowedEphemeralContainerFields, "cannot be set for an Ephemeral Container", idxPath)...)
// VolumeMount subpaths have the potential to leak resources since they're implemented with bind mounts
// that aren't cleaned up until the pod exits. Since they also imply that the container is being used
// as part of the workload, they're disallowed entirely.
for i, vm := range ec.VolumeMounts {
if vm.SubPath != "" {
allErrs = append(allErrs, field.Forbidden(idxPath.Child("volumeMounts").Index(i).Child("subPath"), "cannot be set for an Ephemeral Container"))
}
if vm.SubPathExpr != "" {
allErrs = append(allErrs, field.Forbidden(idxPath.Child("volumeMounts").Index(i).Child("subPathExpr"), "cannot be set for an Ephemeral Container"))
}
}
}
return allErrs
}
// validateFieldAcceptList checks that only allowed fields are set.
// The value must be a struct (not a pointer to a struct!).
func validateFieldAllowList(value interface{}, allowedFields map[string]bool, errorText string, fldPath *field.Path) field.ErrorList {
var allErrs field.ErrorList
reflectType, reflectValue := reflect.TypeOf(value), reflect.ValueOf(value)
for i := 0; i < reflectType.NumField(); i++ {
f := reflectType.Field(i)
if allowedFields[f.Name] {
continue
}
// Compare the value of this field to its zero value to determine if it has been set
if !reflect.DeepEqual(reflectValue.Field(i).Interface(), reflect.Zero(f.Type).Interface()) {
r, n := utf8.DecodeRuneInString(f.Name)
lcName := string(unicode.ToLower(r)) + f.Name[n:]
allErrs = append(allErrs, field.Forbidden(fldPath.Child(lcName), errorText))
}
}
return allErrs
}
func validateInitContainers(containers []core.Container, otherContainers []core.Container, deviceVolumes map[string]core.VolumeSource, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
var allErrs field.ErrorList
if len(containers) > 0 {
allErrs = append(allErrs, validateContainers(containers, true, deviceVolumes, fldPath, opts)...)
}
allNames := sets.String{}
for _, ctr := range otherContainers {
allNames.Insert(ctr.Name)
}
for i, ctr := range containers {
idxPath := fldPath.Index(i)
if allNames.Has(ctr.Name) {
allErrs = append(allErrs, field.Duplicate(idxPath.Child("name"), ctr.Name))
}
if len(ctr.Name) > 0 {
allNames.Insert(ctr.Name)
}
if ctr.Lifecycle != nil {
allErrs = append(allErrs, field.Invalid(idxPath.Child("lifecycle"), ctr.Lifecycle, "must not be set for init containers"))
}
if ctr.LivenessProbe != nil {
allErrs = append(allErrs, field.Invalid(idxPath.Child("livenessProbe"), ctr.LivenessProbe, "must not be set for init containers"))
}
if ctr.ReadinessProbe != nil {
allErrs = append(allErrs, field.Invalid(idxPath.Child("readinessProbe"), ctr.ReadinessProbe, "must not be set for init containers"))
}
if ctr.StartupProbe != nil {
allErrs = append(allErrs, field.Invalid(idxPath.Child("startupProbe"), ctr.StartupProbe, "must not be set for init containers"))
}
}
return allErrs
}
func validateContainers(containers []core.Container, isInitContainers bool, volumes map[string]core.VolumeSource, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
if len(containers) == 0 {
return append(allErrs, field.Required(fldPath, ""))
}
allNames := sets.String{}
for i, ctr := range containers {
idxPath := fldPath.Index(i)
namePath := idxPath.Child("name")
volMounts := GetVolumeMountMap(ctr.VolumeMounts)
volDevices := GetVolumeDeviceMap(ctr.VolumeDevices)
if len(ctr.Name) == 0 {
allErrs = append(allErrs, field.Required(namePath, ""))
} else {
allErrs = append(allErrs, ValidateDNS1123Label(ctr.Name, namePath)...)
}
if allNames.Has(ctr.Name) {
allErrs = append(allErrs, field.Duplicate(namePath, ctr.Name))
} else {
allNames.Insert(ctr.Name)
}
// TODO: do not validate leading and trailing whitespace to preserve backward compatibility.
// for example: https://github.com/openshift/origin/issues/14659 image = " " is special token in pod template
// others may have done similar
if len(ctr.Image) == 0 {
allErrs = append(allErrs, field.Required(idxPath.Child("image"), ""))
}
if ctr.Lifecycle != nil {
allErrs = append(allErrs, validateLifecycle(ctr.Lifecycle, idxPath.Child("lifecycle"))...)
}
allErrs = append(allErrs, validateProbe(ctr.LivenessProbe, idxPath.Child("livenessProbe"))...)
// Readiness-specific validation
if ctr.ReadinessProbe != nil && ctr.ReadinessProbe.TerminationGracePeriodSeconds != nil {
allErrs = append(allErrs, field.Invalid(idxPath.Child("readinessProbe", "terminationGracePeriodSeconds"), ctr.ReadinessProbe.TerminationGracePeriodSeconds, "must not be set for readinessProbes"))
}
allErrs = append(allErrs, validateProbe(ctr.StartupProbe, idxPath.Child("startupProbe"))...)
// Liveness-specific validation
if ctr.LivenessProbe != nil && ctr.LivenessProbe.SuccessThreshold != 1 {
allErrs = append(allErrs, field.Invalid(idxPath.Child("livenessProbe", "successThreshold"), ctr.LivenessProbe.SuccessThreshold, "must be 1"))
}
allErrs = append(allErrs, validateProbe(ctr.StartupProbe, idxPath.Child("startupProbe"))...)
// Startup-specific validation
if ctr.StartupProbe != nil && ctr.StartupProbe.SuccessThreshold != 1 {
allErrs = append(allErrs, field.Invalid(idxPath.Child("startupProbe", "successThreshold"), ctr.StartupProbe.SuccessThreshold, "must be 1"))
}
switch ctr.TerminationMessagePolicy {
case core.TerminationMessageReadFile, core.TerminationMessageFallbackToLogsOnError:
case "":
allErrs = append(allErrs, field.Required(idxPath.Child("terminationMessagePolicy"), "must be 'File' or 'FallbackToLogsOnError'"))
default:
allErrs = append(allErrs, field.Invalid(idxPath.Child("terminationMessagePolicy"), ctr.TerminationMessagePolicy, "must be 'File' or 'FallbackToLogsOnError'"))
}
allErrs = append(allErrs, validateProbe(ctr.ReadinessProbe, idxPath.Child("readinessProbe"))...)
allErrs = append(allErrs, validateContainerPorts(ctr.Ports, idxPath.Child("ports"))...)
allErrs = append(allErrs, ValidateEnv(ctr.Env, idxPath.Child("env"), opts)...)
allErrs = append(allErrs, ValidateEnvFrom(ctr.EnvFrom, idxPath.Child("envFrom"))...)
allErrs = append(allErrs, ValidateVolumeMounts(ctr.VolumeMounts, volDevices, volumes, &ctr, idxPath.Child("volumeMounts"))...)
allErrs = append(allErrs, ValidateVolumeDevices(ctr.VolumeDevices, volMounts, volumes, idxPath.Child("volumeDevices"))...)
allErrs = append(allErrs, validatePullPolicy(ctr.ImagePullPolicy, idxPath.Child("imagePullPolicy"))...)
allErrs = append(allErrs, ValidateResourceRequirements(&ctr.Resources, idxPath.Child("resources"), opts)...)
allErrs = append(allErrs, ValidateSecurityContext(ctr.SecurityContext, idxPath.Child("securityContext"))...)
}
if isInitContainers {
// check initContainers one by one since they are running in sequential order.
for _, initContainer := range containers {
allErrs = append(allErrs, checkHostPortConflicts([]core.Container{initContainer}, fldPath)...)
}
} else {
// Check for colliding ports across all containers.
allErrs = append(allErrs, checkHostPortConflicts(containers, fldPath)...)
}
return allErrs
}
func validateRestartPolicy(restartPolicy *core.RestartPolicy, fldPath *field.Path) field.ErrorList {
allErrors := field.ErrorList{}
switch *restartPolicy {
case core.RestartPolicyAlways, core.RestartPolicyOnFailure, core.RestartPolicyNever:
break
case "":
allErrors = append(allErrors, field.Required(fldPath, ""))
default:
validValues := []string{string(core.RestartPolicyAlways), string(core.RestartPolicyOnFailure), string(core.RestartPolicyNever)}
allErrors = append(allErrors, field.NotSupported(fldPath, *restartPolicy, validValues))
}
return allErrors
}
func ValidatePreemptionPolicy(preemptionPolicy *core.PreemptionPolicy, fldPath *field.Path) field.ErrorList {
allErrors := field.ErrorList{}
switch *preemptionPolicy {
case core.PreemptLowerPriority, core.PreemptNever:
case "":
allErrors = append(allErrors, field.Required(fldPath, ""))
default:
validValues := []string{string(core.PreemptLowerPriority), string(core.PreemptNever)}
allErrors = append(allErrors, field.NotSupported(fldPath, preemptionPolicy, validValues))
}
return allErrors
}
func validateDNSPolicy(dnsPolicy *core.DNSPolicy, fldPath *field.Path) field.ErrorList {
allErrors := field.ErrorList{}
switch *dnsPolicy {
case core.DNSClusterFirstWithHostNet, core.DNSClusterFirst, core.DNSDefault, core.DNSNone:
case "":
allErrors = append(allErrors, field.Required(fldPath, ""))
default:
validValues := []string{string(core.DNSClusterFirstWithHostNet), string(core.DNSClusterFirst), string(core.DNSDefault), string(core.DNSNone)}
allErrors = append(allErrors, field.NotSupported(fldPath, dnsPolicy, validValues))
}
return allErrors
}
var validFSGroupChangePolicies = sets.NewString(string(core.FSGroupChangeOnRootMismatch), string(core.FSGroupChangeAlways))
func validateFSGroupChangePolicy(fsGroupPolicy *core.PodFSGroupChangePolicy, fldPath *field.Path) field.ErrorList {
allErrors := field.ErrorList{}
if !validFSGroupChangePolicies.Has(string(*fsGroupPolicy)) {
allErrors = append(allErrors, field.NotSupported(fldPath, fsGroupPolicy, validFSGroupChangePolicies.List()))
}
return allErrors
}
const (
// Limits on various DNS parameters. These are derived from
// restrictions in Linux libc name resolution handling.
// Max number of DNS name servers.
MaxDNSNameservers = 3
// Expanded max number of domains in the search path list.
MaxDNSSearchPathsExpanded = 32
// Expanded max number of characters in the search path.
MaxDNSSearchListCharsExpanded = 2048
// Max number of domains in the search path list.
MaxDNSSearchPathsLegacy = 6
// Max number of characters in the search path list.
MaxDNSSearchListCharsLegacy = 256
)
func validateReadinessGates(readinessGates []core.PodReadinessGate, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for i, value := range readinessGates {
for _, msg := range validation.IsQualifiedName(string(value.ConditionType)) {
allErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child("conditionType"), string(value.ConditionType), msg))
}
}
return allErrs
}
func validatePodDNSConfig(dnsConfig *core.PodDNSConfig, dnsPolicy *core.DNSPolicy, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
// Validate DNSNone case. Must provide at least one DNS name server.
if dnsPolicy != nil && *dnsPolicy == core.DNSNone {
if dnsConfig == nil {
return append(allErrs, field.Required(fldPath, fmt.Sprintf("must provide `dnsConfig` when `dnsPolicy` is %s", core.DNSNone)))
}
if len(dnsConfig.Nameservers) == 0 {
return append(allErrs, field.Required(fldPath.Child("nameservers"), fmt.Sprintf("must provide at least one DNS nameserver when `dnsPolicy` is %s", core.DNSNone)))
}
}
if dnsConfig != nil {
// Validate nameservers.
if len(dnsConfig.Nameservers) > MaxDNSNameservers {
allErrs = append(allErrs, field.Invalid(fldPath.Child("nameservers"), dnsConfig.Nameservers, fmt.Sprintf("must not have more than %v nameservers", MaxDNSNameservers)))
}
for i, ns := range dnsConfig.Nameservers {
if ip := netutils.ParseIPSloppy(ns); ip == nil {
allErrs = append(allErrs, field.Invalid(fldPath.Child("nameservers").Index(i), ns, "must be valid IP address"))
}
}
// Validate searches.
maxDNSSearchPaths, maxDNSSearchListChars := MaxDNSSearchPathsLegacy, MaxDNSSearchListCharsLegacy
if opts.AllowExpandedDNSConfig {
maxDNSSearchPaths, maxDNSSearchListChars = MaxDNSSearchPathsExpanded, MaxDNSSearchListCharsExpanded
}
if len(dnsConfig.Searches) > maxDNSSearchPaths {
allErrs = append(allErrs, field.Invalid(fldPath.Child("searches"), dnsConfig.Searches, fmt.Sprintf("must not have more than %v search paths", maxDNSSearchPaths)))
}
// Include the space between search paths.
if len(strings.Join(dnsConfig.Searches, " ")) > maxDNSSearchListChars {
allErrs = append(allErrs, field.Invalid(fldPath.Child("searches"), dnsConfig.Searches, fmt.Sprintf("must not have more than %v characters (including spaces) in the search list", maxDNSSearchListChars)))
}
for i, search := range dnsConfig.Searches {
// it is fine to have a trailing dot
search = strings.TrimSuffix(search, ".")
allErrs = append(allErrs, ValidateDNS1123Subdomain(search, fldPath.Child("searches").Index(i))...)
}
// Validate options.
for i, option := range dnsConfig.Options {
if len(option.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("options").Index(i), "must not be empty"))
}
}
}
return allErrs
}
func validateHostNetwork(hostNetwork bool, containers []core.Container, fldPath *field.Path) field.ErrorList {
allErrors := field.ErrorList{}
if hostNetwork {
for i, container := range containers {
portsPath := fldPath.Index(i).Child("ports")
for i, port := range container.Ports {
idxPath := portsPath.Index(i)
if port.HostPort != port.ContainerPort {
allErrors = append(allErrors, field.Invalid(idxPath.Child("containerPort"), port.ContainerPort, "must match `hostPort` when `hostNetwork` is true"))
}
}
}
}
return allErrors
}
// validateImagePullSecrets checks to make sure the pull secrets are well
// formed. Right now, we only expect name to be set (it's the only field). If
// this ever changes and someone decides to set those fields, we'd like to
// know.
func validateImagePullSecrets(imagePullSecrets []core.LocalObjectReference, fldPath *field.Path) field.ErrorList {
allErrors := field.ErrorList{}
for i, currPullSecret := range imagePullSecrets {
idxPath := fldPath.Index(i)
strippedRef := core.LocalObjectReference{Name: currPullSecret.Name}
if !reflect.DeepEqual(strippedRef, currPullSecret) {
allErrors = append(allErrors, field.Invalid(idxPath, currPullSecret, "only name may be set"))
}
}
return allErrors
}
// validateAffinity checks if given affinities are valid
func validateAffinity(affinity *core.Affinity, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if affinity != nil {
if affinity.NodeAffinity != nil {
allErrs = append(allErrs, validateNodeAffinity(affinity.NodeAffinity, fldPath.Child("nodeAffinity"))...)
}
if affinity.PodAffinity != nil {
allErrs = append(allErrs, validatePodAffinity(affinity.PodAffinity, fldPath.Child("podAffinity"))...)
}
if affinity.PodAntiAffinity != nil {
allErrs = append(allErrs, validatePodAntiAffinity(affinity.PodAntiAffinity, fldPath.Child("podAntiAffinity"))...)
}
}
return allErrs
}
func validateTaintEffect(effect *core.TaintEffect, allowEmpty bool, fldPath *field.Path) field.ErrorList {
if !allowEmpty && len(*effect) == 0 {
return field.ErrorList{field.Required(fldPath, "")}
}
allErrors := field.ErrorList{}
switch *effect {
// TODO: Replace next line with subsequent commented-out line when implement TaintEffectNoScheduleNoAdmit.
case core.TaintEffectNoSchedule, core.TaintEffectPreferNoSchedule, core.TaintEffectNoExecute:
// case core.TaintEffectNoSchedule, core.TaintEffectPreferNoSchedule, core.TaintEffectNoScheduleNoAdmit, core.TaintEffectNoExecute:
default:
validValues := []string{
string(core.TaintEffectNoSchedule),
string(core.TaintEffectPreferNoSchedule),
string(core.TaintEffectNoExecute),
// TODO: Uncomment this block when implement TaintEffectNoScheduleNoAdmit.
// string(core.TaintEffectNoScheduleNoAdmit),
}
allErrors = append(allErrors, field.NotSupported(fldPath, *effect, validValues))
}
return allErrors
}
// validateOnlyAddedTolerations validates updated pod tolerations.
func validateOnlyAddedTolerations(newTolerations []core.Toleration, oldTolerations []core.Toleration, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for _, old := range oldTolerations {
found := false
oldTolerationClone := old.DeepCopy()
for _, newToleration := range newTolerations {
// assign to our clone before doing a deep equal so we can allow tolerationseconds to change.
oldTolerationClone.TolerationSeconds = newToleration.TolerationSeconds // +k8s:verify-mutation:reason=clone
if reflect.DeepEqual(*oldTolerationClone, newToleration) {
found = true
break
}
}
if !found {
allErrs = append(allErrs, field.Forbidden(fldPath, "existing toleration can not be modified except its tolerationSeconds"))
return allErrs
}
}
allErrs = append(allErrs, ValidateTolerations(newTolerations, fldPath)...)
return allErrs
}
func ValidateHostAliases(hostAliases []core.HostAlias, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for _, hostAlias := range hostAliases {
if ip := netutils.ParseIPSloppy(hostAlias.IP); ip == nil {
allErrs = append(allErrs, field.Invalid(fldPath.Child("ip"), hostAlias.IP, "must be valid IP address"))
}
for _, hostname := range hostAlias.Hostnames {
allErrs = append(allErrs, ValidateDNS1123Subdomain(hostname, fldPath.Child("hostnames"))...)
}
}
return allErrs
}
// ValidateTolerations tests if given tolerations have valid data.
func ValidateTolerations(tolerations []core.Toleration, fldPath *field.Path) field.ErrorList {
allErrors := field.ErrorList{}
for i, toleration := range tolerations {
idxPath := fldPath.Index(i)
// validate the toleration key
if len(toleration.Key) > 0 {
allErrors = append(allErrors, unversionedvalidation.ValidateLabelName(toleration.Key, idxPath.Child("key"))...)
}
// empty toleration key with Exists operator and empty value means match all taints
if len(toleration.Key) == 0 && toleration.Operator != core.TolerationOpExists {
allErrors = append(allErrors, field.Invalid(idxPath.Child("operator"), toleration.Operator,
"operator must be Exists when `key` is empty, which means \"match all values and all keys\""))
}
if toleration.TolerationSeconds != nil && toleration.Effect != core.TaintEffectNoExecute {
allErrors = append(allErrors, field.Invalid(idxPath.Child("effect"), toleration.Effect,
"effect must be 'NoExecute' when `tolerationSeconds` is set"))
}
// validate toleration operator and value
switch toleration.Operator {
// empty operator means Equal
case core.TolerationOpEqual, "":
if errs := validation.IsValidLabelValue(toleration.Value); len(errs) != 0 {
allErrors = append(allErrors, field.Invalid(idxPath.Child("operator"), toleration.Value, strings.Join(errs, ";")))
}
case core.TolerationOpExists:
if len(toleration.Value) > 0 {
allErrors = append(allErrors, field.Invalid(idxPath.Child("operator"), toleration, "value must be empty when `operator` is 'Exists'"))
}
default:
validValues := []string{string(core.TolerationOpEqual), string(core.TolerationOpExists)}
allErrors = append(allErrors, field.NotSupported(idxPath.Child("operator"), toleration.Operator, validValues))
}
// validate toleration effect, empty toleration effect means match all taint effects
if len(toleration.Effect) > 0 {
allErrors = append(allErrors, validateTaintEffect(&toleration.Effect, true, idxPath.Child("effect"))...)
}
}
return allErrors
}
// validateContainersOnlyForPod does additional validation for containers on a pod versus a pod template
// it only does additive validation of fields not covered in validateContainers
func validateContainersOnlyForPod(containers []core.Container, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for i, ctr := range containers {
idxPath := fldPath.Index(i)
if len(ctr.Image) != len(strings.TrimSpace(ctr.Image)) {
allErrs = append(allErrs, field.Invalid(idxPath.Child("image"), ctr.Image, "must not have leading or trailing whitespace"))
}
}
return allErrs
}
// PodValidationOptions contains the different settings for pod validation
type PodValidationOptions struct {
// Allow pod spec to use hugepages in downward API
AllowDownwardAPIHugePages bool
// Allow invalid pod-deletion-cost annotation value for backward compatibility.
AllowInvalidPodDeletionCost bool
// Allow pod spec to use non-integer multiple of huge page unit size
AllowIndivisibleHugePagesValues bool
// Allow hostProcess field to be set in windows security context
AllowWindowsHostProcessField bool
// Allow more DNSSearchPaths and longer DNSSearchListChars
AllowExpandedDNSConfig bool
// Allow OSField to be set in the pod spec
AllowOSField bool
// Allow sysctl name to contain a slash
AllowSysctlRegexContainSlash bool
}
// validatePodMetadataAndSpec tests if required fields in the pod.metadata and pod.spec are set,
// and is called by ValidatePodCreate and ValidatePodUpdate.
func validatePodMetadataAndSpec(pod *core.Pod, opts PodValidationOptions) field.ErrorList {
fldPath := field.NewPath("metadata")
allErrs := ValidateObjectMeta(&pod.ObjectMeta, true, ValidatePodName, fldPath)
allErrs = append(allErrs, ValidatePodSpecificAnnotations(pod.ObjectMeta.Annotations, &pod.Spec, fldPath.Child("annotations"), opts)...)
allErrs = append(allErrs, ValidatePodSpec(&pod.Spec, &pod.ObjectMeta, field.NewPath("spec"), opts)...)
// we do additional validation only pertinent for pods and not pod templates
// this was done to preserve backwards compatibility
specPath := field.NewPath("spec")
if pod.Spec.ServiceAccountName == "" {
for vi, volume := range pod.Spec.Volumes {
path := specPath.Child("volumes").Index(vi).Child("projected")
if volume.Projected != nil {
for si, source := range volume.Projected.Sources {
saPath := path.Child("sources").Index(si).Child("serviceAccountToken")
if source.ServiceAccountToken != nil {
allErrs = append(allErrs, field.Forbidden(saPath, "must not be specified when serviceAccountName is not set"))
}
}
}
}
}
allErrs = append(allErrs, validateContainersOnlyForPod(pod.Spec.Containers, specPath.Child("containers"))...)
allErrs = append(allErrs, validateContainersOnlyForPod(pod.Spec.InitContainers, specPath.Child("initContainers"))...)
return allErrs
}
// validatePodIPs validates IPs in pod status
func validatePodIPs(pod *core.Pod) field.ErrorList {
allErrs := field.ErrorList{}
podIPsField := field.NewPath("status", "podIPs")
// all PodIPs must be valid IPs
for i, podIP := range pod.Status.PodIPs {
for _, msg := range validation.IsValidIP(podIP.IP) {
allErrs = append(allErrs, field.Invalid(podIPsField.Index(i), podIP.IP, msg))
}
}
// if we have more than one Pod.PodIP then
// - validate for dual stack
// - validate for duplication
if len(pod.Status.PodIPs) > 1 {
podIPs := make([]string, 0, len(pod.Status.PodIPs))
for _, podIP := range pod.Status.PodIPs {
podIPs = append(podIPs, podIP.IP)
}
dualStack, err := netutils.IsDualStackIPStrings(podIPs)
if err != nil {
allErrs = append(allErrs, field.InternalError(podIPsField, fmt.Errorf("failed to check for dual stack with error:%v", err)))
}
// We only support one from each IP family (i.e. max two IPs in this list).
if !dualStack || len(podIPs) > 2 {
allErrs = append(allErrs, field.Invalid(podIPsField, pod.Status.PodIPs, "may specify no more than one IP for each IP family"))
}
// There should be no duplicates in list of Pod.PodIPs
seen := sets.String{} //:= make(map[string]int)
for i, podIP := range pod.Status.PodIPs {
if seen.Has(podIP.IP) {
allErrs = append(allErrs, field.Duplicate(podIPsField.Index(i), podIP))
}
seen.Insert(podIP.IP)
}
}
return allErrs
}
// ValidatePodSpec tests that the specified PodSpec has valid data.
// This includes checking formatting and uniqueness. It also canonicalizes the
// structure by setting default values and implementing any backwards-compatibility
// tricks.
// The pod metadata is needed to validate generic ephemeral volumes. It is optional
// and should be left empty unless the spec is from a real pod object.
func ValidatePodSpec(spec *core.PodSpec, podMeta *metav1.ObjectMeta, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
vols, vErrs := ValidateVolumes(spec.Volumes, podMeta, fldPath.Child("volumes"), opts)
allErrs = append(allErrs, vErrs...)
allErrs = append(allErrs, validateContainers(spec.Containers, false, vols, fldPath.Child("containers"), opts)...)
allErrs = append(allErrs, validateInitContainers(spec.InitContainers, spec.Containers, vols, fldPath.Child("initContainers"), opts)...)
allErrs = append(allErrs, validateEphemeralContainers(spec.EphemeralContainers, spec.Containers, spec.InitContainers, vols, fldPath.Child("ephemeralContainers"), opts)...)
allErrs = append(allErrs, validateRestartPolicy(&spec.RestartPolicy, fldPath.Child("restartPolicy"))...)
allErrs = append(allErrs, validateDNSPolicy(&spec.DNSPolicy, fldPath.Child("dnsPolicy"))...)
allErrs = append(allErrs, unversionedvalidation.ValidateLabels(spec.NodeSelector, fldPath.Child("nodeSelector"))...)
allErrs = append(allErrs, ValidatePodSecurityContext(spec.SecurityContext, spec, fldPath, fldPath.Child("securityContext"), opts)...)
allErrs = append(allErrs, validateImagePullSecrets(spec.ImagePullSecrets, fldPath.Child("imagePullSecrets"))...)
allErrs = append(allErrs, validateAffinity(spec.Affinity, fldPath.Child("affinity"))...)
allErrs = append(allErrs, validatePodDNSConfig(spec.DNSConfig, &spec.DNSPolicy, fldPath.Child("dnsConfig"), opts)...)
allErrs = append(allErrs, validateReadinessGates(spec.ReadinessGates, fldPath.Child("readinessGates"))...)
allErrs = append(allErrs, validateTopologySpreadConstraints(spec.TopologySpreadConstraints, fldPath.Child("topologySpreadConstraints"))...)
allErrs = append(allErrs, validateWindowsHostProcessPod(spec, fldPath, opts)...)
if len(spec.ServiceAccountName) > 0 {
for _, msg := range ValidateServiceAccountName(spec.ServiceAccountName, false) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("serviceAccountName"), spec.ServiceAccountName, msg))
}
}
if len(spec.NodeName) > 0 {
for _, msg := range ValidateNodeName(spec.NodeName, false) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("nodeName"), spec.NodeName, msg))
}
}
if spec.ActiveDeadlineSeconds != nil {
value := *spec.ActiveDeadlineSeconds
if value < 1 || value > math.MaxInt32 {
allErrs = append(allErrs, field.Invalid(fldPath.Child("activeDeadlineSeconds"), value, validation.InclusiveRangeError(1, math.MaxInt32)))
}
}
if len(spec.Hostname) > 0 {
allErrs = append(allErrs, ValidateDNS1123Label(spec.Hostname, fldPath.Child("hostname"))...)
}
if len(spec.Subdomain) > 0 {
allErrs = append(allErrs, ValidateDNS1123Label(spec.Subdomain, fldPath.Child("subdomain"))...)
}
if len(spec.Tolerations) > 0 {
allErrs = append(allErrs, ValidateTolerations(spec.Tolerations, fldPath.Child("tolerations"))...)
}
if len(spec.HostAliases) > 0 {
allErrs = append(allErrs, ValidateHostAliases(spec.HostAliases, fldPath.Child("hostAliases"))...)
}
if len(spec.PriorityClassName) > 0 {
for _, msg := range ValidatePriorityClassName(spec.PriorityClassName, false) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("priorityClassName"), spec.PriorityClassName, msg))
}
}
if spec.RuntimeClassName != nil {
allErrs = append(allErrs, ValidateRuntimeClassName(*spec.RuntimeClassName, fldPath.Child("runtimeClassName"))...)
}
if spec.PreemptionPolicy != nil {
allErrs = append(allErrs, ValidatePreemptionPolicy(spec.PreemptionPolicy, fldPath.Child("preemptionPolicy"))...)
}
if spec.Overhead != nil {
allErrs = append(allErrs, validateOverhead(spec.Overhead, fldPath.Child("overhead"), opts)...)
}
if spec.OS != nil {
osErrs := validateOS(spec, fldPath.Child("os"), opts)
switch {
case len(osErrs) > 0:
allErrs = append(allErrs, osErrs...)
case spec.OS.Name == core.Linux:
allErrs = append(allErrs, validateLinux(spec, fldPath)...)
case spec.OS.Name == core.Windows:
allErrs = append(allErrs, validateWindows(spec, fldPath)...)
}
}
return allErrs
}
func validateLinux(spec *core.PodSpec, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
securityContext := spec.SecurityContext
if securityContext != nil && securityContext.WindowsOptions != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("securityContext").Child("windowsOptions"), "windows options cannot be set for a linux pod"))
}
podshelper.VisitContainersWithPath(spec, fldPath, func(c *core.Container, cFldPath *field.Path) bool {
sc := c.SecurityContext
if sc != nil && sc.WindowsOptions != nil {
fldPath := cFldPath.Child("securityContext")
allErrs = append(allErrs, field.Forbidden(fldPath.Child("windowsOptions"), "windows options cannot be set for a linux pod"))
}
return true
})
return allErrs
}
func validateWindows(spec *core.PodSpec, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
securityContext := spec.SecurityContext
// validate Pod SecurityContext
if securityContext != nil {
if securityContext.SELinuxOptions != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("securityContext").Child("seLinuxOptions"), "cannot be set for a windows pod"))
}
if securityContext.HostPID {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("hostPID"), "cannot be set for a windows pod"))
}
if securityContext.HostIPC {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("hostIPC"), "cannot be set for a windows pod"))
}
if securityContext.SeccompProfile != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("securityContext").Child("seccompProfile"), "cannot be set for a windows pod"))
}
if securityContext.FSGroup != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("securityContext").Child("fsGroup"), "cannot be set for a windows pod"))
}
if securityContext.FSGroupChangePolicy != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("securityContext").Child("fsGroupChangePolicy"), "cannot be set for a windows pod"))
}
if len(securityContext.Sysctls) > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("securityContext").Child("sysctls"), "cannot be set for a windows pod"))
}
if securityContext.ShareProcessNamespace != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("shareProcessNamespace"), "cannot be set for a windows pod"))
}
if securityContext.RunAsUser != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("securityContext").Child("runAsUser"), "cannot be set for a windows pod"))
}
if securityContext.RunAsGroup != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("securityContext").Child("runAsGroup"), "cannot be set for a windows pod"))
}
if securityContext.SupplementalGroups != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("securityContext").Child("supplementalGroups"), "cannot be set for a windows pod"))
}
}
podshelper.VisitContainersWithPath(spec, fldPath, func(c *core.Container, cFldPath *field.Path) bool {
// validate container security context
sc := c.SecurityContext
// OS based podSecurityContext validation
// There is some naming overlap between Windows and Linux Security Contexts but all the Windows Specific options
// are set via securityContext.WindowsOptions which we validate below
// TODO: Think if we need to relax this restriction or some of the restrictions
if sc != nil {
fldPath := cFldPath.Child("securityContext")
if sc.SELinuxOptions != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("seLinuxOptions"), "cannot be set for a windows pod"))
}
if sc.SeccompProfile != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("seccompProfile"), "cannot be set for a windows pod"))
}
if sc.Capabilities != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("capabilities"), "cannot be set for a windows pod"))
}
if sc.ReadOnlyRootFilesystem != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("readOnlyRootFilesystem"), "cannot be set for a windows pod"))
}
if sc.Privileged != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("privileged"), "cannot be set for a windows pod"))
}
if sc.AllowPrivilegeEscalation != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("allowPrivilegeEscalation"), "cannot be set for a windows pod"))
}
if sc.ProcMount != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("procMount"), "cannot be set for a windows pod"))
}
if sc.RunAsUser != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("runAsUser"), "cannot be set for a windows pod"))
}
if sc.RunAsGroup != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("runAsGroup"), "cannot be set for a windows pod"))
}
}
return true
})
return allErrs
}
// ValidateNodeSelectorRequirement tests that the specified NodeSelectorRequirement fields has valid data
func ValidateNodeSelectorRequirement(rq core.NodeSelectorRequirement, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
switch rq.Operator {
case core.NodeSelectorOpIn, core.NodeSelectorOpNotIn:
if len(rq.Values) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("values"), "must be specified when `operator` is 'In' or 'NotIn'"))
}
case core.NodeSelectorOpExists, core.NodeSelectorOpDoesNotExist:
if len(rq.Values) > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("values"), "may not be specified when `operator` is 'Exists' or 'DoesNotExist'"))
}
case core.NodeSelectorOpGt, core.NodeSelectorOpLt:
if len(rq.Values) != 1 {
allErrs = append(allErrs, field.Required(fldPath.Child("values"), "must be specified single value when `operator` is 'Lt' or 'Gt'"))
}
default:
allErrs = append(allErrs, field.Invalid(fldPath.Child("operator"), rq.Operator, "not a valid selector operator"))
}
allErrs = append(allErrs, unversionedvalidation.ValidateLabelName(rq.Key, fldPath.Child("key"))...)
return allErrs
}
var nodeFieldSelectorValidators = map[string]func(string, bool) []string{
metav1.ObjectNameField: ValidateNodeName,
}
// ValidateNodeFieldSelectorRequirement tests that the specified NodeSelectorRequirement fields has valid data
func ValidateNodeFieldSelectorRequirement(req core.NodeSelectorRequirement, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
switch req.Operator {
case core.NodeSelectorOpIn, core.NodeSelectorOpNotIn:
if len(req.Values) != 1 {
allErrs = append(allErrs, field.Required(fldPath.Child("values"),
"must be only one value when `operator` is 'In' or 'NotIn' for node field selector"))
}
default:
allErrs = append(allErrs, field.Invalid(fldPath.Child("operator"), req.Operator, "not a valid selector operator"))
}
if vf, found := nodeFieldSelectorValidators[req.Key]; !found {
allErrs = append(allErrs, field.Invalid(fldPath.Child("key"), req.Key, "not a valid field selector key"))
} else {
for i, v := range req.Values {
for _, msg := range vf(v, false) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("values").Index(i), v, msg))
}
}
}
return allErrs
}
// ValidateNodeSelectorTerm tests that the specified node selector term has valid data
func ValidateNodeSelectorTerm(term core.NodeSelectorTerm, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for j, req := range term.MatchExpressions {
allErrs = append(allErrs, ValidateNodeSelectorRequirement(req, fldPath.Child("matchExpressions").Index(j))...)
}
for j, req := range term.MatchFields {
allErrs = append(allErrs, ValidateNodeFieldSelectorRequirement(req, fldPath.Child("matchFields").Index(j))...)
}
return allErrs
}
// ValidateNodeSelector tests that the specified nodeSelector fields has valid data
func ValidateNodeSelector(nodeSelector *core.NodeSelector, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
termFldPath := fldPath.Child("nodeSelectorTerms")
if len(nodeSelector.NodeSelectorTerms) == 0 {
return append(allErrs, field.Required(termFldPath, "must have at least one node selector term"))
}
for i, term := range nodeSelector.NodeSelectorTerms {
allErrs = append(allErrs, ValidateNodeSelectorTerm(term, termFldPath.Index(i))...)
}
return allErrs
}
// validateTopologySelectorLabelRequirement tests that the specified TopologySelectorLabelRequirement fields has valid data,
// and constructs a set containing all of its Values.
func validateTopologySelectorLabelRequirement(rq core.TopologySelectorLabelRequirement, fldPath *field.Path) (sets.String, field.ErrorList) {
allErrs := field.ErrorList{}
valueSet := make(sets.String)
valuesPath := fldPath.Child("values")
if len(rq.Values) == 0 {
allErrs = append(allErrs, field.Required(valuesPath, ""))
}
// Validate set property of Values field
for i, value := range rq.Values {
if valueSet.Has(value) {
allErrs = append(allErrs, field.Duplicate(valuesPath.Index(i), value))
}
valueSet.Insert(value)
}
allErrs = append(allErrs, unversionedvalidation.ValidateLabelName(rq.Key, fldPath.Child("key"))...)
return valueSet, allErrs
}
// ValidateTopologySelectorTerm tests that the specified topology selector term has valid data,
// and constructs a map representing the term in raw form.
func ValidateTopologySelectorTerm(term core.TopologySelectorTerm, fldPath *field.Path) (map[string]sets.String, field.ErrorList) {
allErrs := field.ErrorList{}
exprMap := make(map[string]sets.String)
exprPath := fldPath.Child("matchLabelExpressions")
// Allow empty MatchLabelExpressions, in case this field becomes optional in the future.
for i, req := range term.MatchLabelExpressions {
idxPath := exprPath.Index(i)
valueSet, exprErrs := validateTopologySelectorLabelRequirement(req, idxPath)
allErrs = append(allErrs, exprErrs...)
// Validate no duplicate keys exist.
if _, exists := exprMap[req.Key]; exists {
allErrs = append(allErrs, field.Duplicate(idxPath.Child("key"), req.Key))
}
exprMap[req.Key] = valueSet
}
return exprMap, allErrs
}
// ValidateAvoidPodsInNodeAnnotations tests that the serialized AvoidPods in Node.Annotations has valid data
func ValidateAvoidPodsInNodeAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
v1Avoids, err := schedulinghelper.GetAvoidPodsFromNodeAnnotations(annotations)
if err != nil {
allErrs = append(allErrs, field.Invalid(fldPath.Child("AvoidPods"), core.PreferAvoidPodsAnnotationKey, err.Error()))
return allErrs
}
var avoids core.AvoidPods
if err := corev1.Convert_v1_AvoidPods_To_core_AvoidPods(&v1Avoids, &avoids, nil); err != nil {
allErrs = append(allErrs, field.Invalid(fldPath.Child("AvoidPods"), core.PreferAvoidPodsAnnotationKey, err.Error()))
return allErrs
}
if len(avoids.PreferAvoidPods) != 0 {
for i, pa := range avoids.PreferAvoidPods {
idxPath := fldPath.Child(core.PreferAvoidPodsAnnotationKey).Index(i)
allErrs = append(allErrs, validatePreferAvoidPodsEntry(pa, idxPath)...)
}
}
return allErrs
}
// validatePreferAvoidPodsEntry tests if given PreferAvoidPodsEntry has valid data.
func validatePreferAvoidPodsEntry(avoidPodEntry core.PreferAvoidPodsEntry, fldPath *field.Path) field.ErrorList {
allErrors := field.ErrorList{}
if avoidPodEntry.PodSignature.PodController == nil {
allErrors = append(allErrors, field.Required(fldPath.Child("PodSignature"), ""))
} else {
if !*(avoidPodEntry.PodSignature.PodController.Controller) {
allErrors = append(allErrors,
field.Invalid(fldPath.Child("PodSignature").Child("PodController").Child("Controller"),
*(avoidPodEntry.PodSignature.PodController.Controller), "must point to a controller"))
}
}
return allErrors
}
// ValidatePreferredSchedulingTerms tests that the specified SoftNodeAffinity fields has valid data
func ValidatePreferredSchedulingTerms(terms []core.PreferredSchedulingTerm, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for i, term := range terms {
if term.Weight <= 0 || term.Weight > 100 {
allErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child("weight"), term.Weight, "must be in the range 1-100"))
}
allErrs = append(allErrs, ValidateNodeSelectorTerm(term.Preference, fldPath.Index(i).Child("preference"))...)
}
return allErrs
}
// validatePodAffinityTerm tests that the specified podAffinityTerm fields have valid data
func validatePodAffinityTerm(podAffinityTerm core.PodAffinityTerm, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(podAffinityTerm.LabelSelector, fldPath.Child("labelSelector"))...)
allErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(podAffinityTerm.NamespaceSelector, fldPath.Child("namespaceSelector"))...)
for _, name := range podAffinityTerm.Namespaces {
for _, msg := range ValidateNamespaceName(name, false) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("namespace"), name, msg))
}
}
if len(podAffinityTerm.TopologyKey) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("topologyKey"), "can not be empty"))
}
return append(allErrs, unversionedvalidation.ValidateLabelName(podAffinityTerm.TopologyKey, fldPath.Child("topologyKey"))...)
}
// validatePodAffinityTerms tests that the specified podAffinityTerms fields have valid data
func validatePodAffinityTerms(podAffinityTerms []core.PodAffinityTerm, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for i, podAffinityTerm := range podAffinityTerms {
allErrs = append(allErrs, validatePodAffinityTerm(podAffinityTerm, fldPath.Index(i))...)
}
return allErrs
}
// validateWeightedPodAffinityTerms tests that the specified weightedPodAffinityTerms fields have valid data
func validateWeightedPodAffinityTerms(weightedPodAffinityTerms []core.WeightedPodAffinityTerm, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for j, weightedTerm := range weightedPodAffinityTerms {
if weightedTerm.Weight <= 0 || weightedTerm.Weight > 100 {
allErrs = append(allErrs, field.Invalid(fldPath.Index(j).Child("weight"), weightedTerm.Weight, "must be in the range 1-100"))
}
allErrs = append(allErrs, validatePodAffinityTerm(weightedTerm.PodAffinityTerm, fldPath.Index(j).Child("podAffinityTerm"))...)
}
return allErrs
}
// validatePodAntiAffinity tests that the specified podAntiAffinity fields have valid data
func validatePodAntiAffinity(podAntiAffinity *core.PodAntiAffinity, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
// TODO:Uncomment below code once RequiredDuringSchedulingRequiredDuringExecution is implemented.
// if podAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution != nil {
// allErrs = append(allErrs, validatePodAffinityTerms(podAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution, false,
// fldPath.Child("requiredDuringSchedulingRequiredDuringExecution"))...)
//}
if podAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution != nil {
allErrs = append(allErrs, validatePodAffinityTerms(podAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution,
fldPath.Child("requiredDuringSchedulingIgnoredDuringExecution"))...)
}
if podAntiAffinity.PreferredDuringSchedulingIgnoredDuringExecution != nil {
allErrs = append(allErrs, validateWeightedPodAffinityTerms(podAntiAffinity.PreferredDuringSchedulingIgnoredDuringExecution,
fldPath.Child("preferredDuringSchedulingIgnoredDuringExecution"))...)
}
return allErrs
}
// validateNodeAffinity tests that the specified nodeAffinity fields have valid data
func validateNodeAffinity(na *core.NodeAffinity, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
// TODO: Uncomment the next three lines once RequiredDuringSchedulingRequiredDuringExecution is implemented.
// if na.RequiredDuringSchedulingRequiredDuringExecution != nil {
// allErrs = append(allErrs, ValidateNodeSelector(na.RequiredDuringSchedulingRequiredDuringExecution, fldPath.Child("requiredDuringSchedulingRequiredDuringExecution"))...)
// }
if na.RequiredDuringSchedulingIgnoredDuringExecution != nil {
allErrs = append(allErrs, ValidateNodeSelector(na.RequiredDuringSchedulingIgnoredDuringExecution, fldPath.Child("requiredDuringSchedulingIgnoredDuringExecution"))...)
}
if len(na.PreferredDuringSchedulingIgnoredDuringExecution) > 0 {
allErrs = append(allErrs, ValidatePreferredSchedulingTerms(na.PreferredDuringSchedulingIgnoredDuringExecution, fldPath.Child("preferredDuringSchedulingIgnoredDuringExecution"))...)
}
return allErrs
}
// validatePodAffinity tests that the specified podAffinity fields have valid data
func validatePodAffinity(podAffinity *core.PodAffinity, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
// TODO:Uncomment below code once RequiredDuringSchedulingRequiredDuringExecution is implemented.
// if podAffinity.RequiredDuringSchedulingRequiredDuringExecution != nil {
// allErrs = append(allErrs, validatePodAffinityTerms(podAffinity.RequiredDuringSchedulingRequiredDuringExecution, false,
// fldPath.Child("requiredDuringSchedulingRequiredDuringExecution"))...)
//}
if podAffinity.RequiredDuringSchedulingIgnoredDuringExecution != nil {
allErrs = append(allErrs, validatePodAffinityTerms(podAffinity.RequiredDuringSchedulingIgnoredDuringExecution,
fldPath.Child("requiredDuringSchedulingIgnoredDuringExecution"))...)
}
if podAffinity.PreferredDuringSchedulingIgnoredDuringExecution != nil {
allErrs = append(allErrs, validateWeightedPodAffinityTerms(podAffinity.PreferredDuringSchedulingIgnoredDuringExecution,
fldPath.Child("preferredDuringSchedulingIgnoredDuringExecution"))...)
}
return allErrs
}
func validateSeccompProfileField(sp *core.SeccompProfile, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if sp == nil {
return allErrs
}
if err := validateSeccompProfileType(fldPath.Child("type"), sp.Type); err != nil {
allErrs = append(allErrs, err)
}
if sp.Type == core.SeccompProfileTypeLocalhost {
if sp.LocalhostProfile == nil {
allErrs = append(allErrs, field.Required(fldPath.Child("localhostProfile"), "must be set when seccomp type is Localhost"))
} else {
allErrs = append(allErrs, validateLocalDescendingPath(*sp.LocalhostProfile, fldPath.Child("localhostProfile"))...)
}
} else {
if sp.LocalhostProfile != nil {
allErrs = append(allErrs, field.Invalid(fldPath.Child("localhostProfile"), sp, "can only be set when seccomp type is Localhost"))
}
}
return allErrs
}
func ValidateSeccompProfile(p string, fldPath *field.Path) field.ErrorList {
if p == core.SeccompProfileRuntimeDefault || p == core.DeprecatedSeccompProfileDockerDefault {
return nil
}
if p == v1.SeccompProfileNameUnconfined {
return nil
}
if strings.HasPrefix(p, v1.SeccompLocalhostProfileNamePrefix) {
return validateLocalDescendingPath(strings.TrimPrefix(p, v1.SeccompLocalhostProfileNamePrefix), fldPath)
}
return field.ErrorList{field.Invalid(fldPath, p, "must be a valid seccomp profile")}
}
func ValidateSeccompPodAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if p, exists := annotations[core.SeccompPodAnnotationKey]; exists {
allErrs = append(allErrs, ValidateSeccompProfile(p, fldPath.Child(core.SeccompPodAnnotationKey))...)
}
for k, p := range annotations {
if strings.HasPrefix(k, core.SeccompContainerAnnotationKeyPrefix) {
allErrs = append(allErrs, ValidateSeccompProfile(p, fldPath.Child(k))...)
}
}
return allErrs
}
// ValidateSeccompProfileType tests that the argument is a valid SeccompProfileType.
func validateSeccompProfileType(fldPath *field.Path, seccompProfileType core.SeccompProfileType) *field.Error {
switch seccompProfileType {
case core.SeccompProfileTypeLocalhost, core.SeccompProfileTypeRuntimeDefault, core.SeccompProfileTypeUnconfined:
return nil
case "":
return field.Required(fldPath, "type is required when seccompProfile is set")
default:
return field.NotSupported(fldPath, seccompProfileType, []string{string(core.SeccompProfileTypeLocalhost), string(core.SeccompProfileTypeRuntimeDefault), string(core.SeccompProfileTypeUnconfined)})
}
}
func ValidateAppArmorPodAnnotations(annotations map[string]string, spec *core.PodSpec, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for k, p := range annotations {
if !strings.HasPrefix(k, v1.AppArmorBetaContainerAnnotationKeyPrefix) {
continue
}
containerName := strings.TrimPrefix(k, v1.AppArmorBetaContainerAnnotationKeyPrefix)
if !podSpecHasContainer(spec, containerName) {
allErrs = append(allErrs, field.Invalid(fldPath.Key(k), containerName, "container not found"))
}
if err := ValidateAppArmorProfileFormat(p); err != nil {
allErrs = append(allErrs, field.Invalid(fldPath.Key(k), p, err.Error()))
}
}
return allErrs
}
func ValidateAppArmorProfileFormat(profile string) error {
if profile == "" || profile == v1.AppArmorBetaProfileRuntimeDefault || profile == v1.AppArmorBetaProfileNameUnconfined {
return nil
}
if !strings.HasPrefix(profile, v1.AppArmorBetaProfileNamePrefix) {
return fmt.Errorf("invalid AppArmor profile name: %q", profile)
}
return nil
}
func podSpecHasContainer(spec *core.PodSpec, containerName string) bool {
var hasContainer bool
podshelper.VisitContainersWithPath(spec, field.NewPath("spec"), func(c *core.Container, _ *field.Path) bool {
if c.Name == containerName {
hasContainer = true
return false
}
return true
})
return hasContainer
}
const (
// a sysctl segment regex, concatenated with dots to form a sysctl name
SysctlSegmentFmt string = "[a-z0-9]([-_a-z0-9]*[a-z0-9])?"
// a sysctl name regex
SysctlFmt string = "(" + SysctlSegmentFmt + "\\.)*" + SysctlSegmentFmt
// a sysctl name regex with slash allowed
SysctlContainSlashFmt string = "(" + SysctlSegmentFmt + "[\\./])*" + SysctlSegmentFmt
// the maximal length of a sysctl name
SysctlMaxLength int = 253
)
var sysctlRegexp = regexp.MustCompile("^" + SysctlFmt + "$")
var sysctlContainSlashRegexp = regexp.MustCompile("^" + SysctlContainSlashFmt + "$")
// IsValidSysctlName checks that the given string is a valid sysctl name,
// i.e. matches SysctlFmt (or SysctlContainSlashFmt if canContainSlash is true).
// More info:
// https://man7.org/linux/man-pages/man8/sysctl.8.html
// https://man7.org/linux/man-pages/man5/sysctl.d.5.html
func IsValidSysctlName(name string, canContainSlash bool) bool {
if len(name) > SysctlMaxLength {
return false
}
if canContainSlash {
return sysctlContainSlashRegexp.MatchString(name)
}
return sysctlRegexp.MatchString(name)
}
func getSysctlFmt(canContainSlash bool) string {
if canContainSlash {
// use relaxed validation everywhere in 1.24
return SysctlContainSlashFmt
}
// Will be removed in 1.24
return SysctlFmt
}
func validateSysctls(sysctls []core.Sysctl, fldPath *field.Path, allowSysctlRegexContainSlash bool) field.ErrorList {
allErrs := field.ErrorList{}
names := make(map[string]struct{})
for i, s := range sysctls {
if len(s.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Index(i).Child("name"), ""))
} else if !IsValidSysctlName(s.Name, allowSysctlRegexContainSlash) {
allErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child("name"), s.Name, fmt.Sprintf("must have at most %d characters and match regex %s", SysctlMaxLength, getSysctlFmt(allowSysctlRegexContainSlash))))
} else if _, ok := names[s.Name]; ok {
allErrs = append(allErrs, field.Duplicate(fldPath.Index(i).Child("name"), s.Name))
}
names[s.Name] = struct{}{}
}
return allErrs
}
// ValidatePodSecurityContext test that the specified PodSecurityContext has valid data.
func ValidatePodSecurityContext(securityContext *core.PodSecurityContext, spec *core.PodSpec, specPath, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
if securityContext != nil {
allErrs = append(allErrs, validateHostNetwork(securityContext.HostNetwork, spec.Containers, specPath.Child("containers"))...)
if securityContext.FSGroup != nil {
for _, msg := range validation.IsValidGroupID(*securityContext.FSGroup) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("fsGroup"), *(securityContext.FSGroup), msg))
}
}
if securityContext.RunAsUser != nil {
for _, msg := range validation.IsValidUserID(*securityContext.RunAsUser) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("runAsUser"), *(securityContext.RunAsUser), msg))
}
}
if securityContext.RunAsGroup != nil {
for _, msg := range validation.IsValidGroupID(*securityContext.RunAsGroup) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("runAsGroup"), *(securityContext.RunAsGroup), msg))
}
}
for g, gid := range securityContext.SupplementalGroups {
for _, msg := range validation.IsValidGroupID(gid) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("supplementalGroups").Index(g), gid, msg))
}
}
if securityContext.ShareProcessNamespace != nil && securityContext.HostPID && *securityContext.ShareProcessNamespace {
allErrs = append(allErrs, field.Invalid(fldPath.Child("shareProcessNamespace"), *securityContext.ShareProcessNamespace, "ShareProcessNamespace and HostPID cannot both be enabled"))
}
if len(securityContext.Sysctls) != 0 {
allErrs = append(allErrs, validateSysctls(securityContext.Sysctls, fldPath.Child("sysctls"), opts.AllowSysctlRegexContainSlash)...)
}
if securityContext.FSGroupChangePolicy != nil {
allErrs = append(allErrs, validateFSGroupChangePolicy(securityContext.FSGroupChangePolicy, fldPath.Child("fsGroupChangePolicy"))...)
}
allErrs = append(allErrs, validateSeccompProfileField(securityContext.SeccompProfile, fldPath.Child("seccompProfile"))...)
allErrs = append(allErrs, validateWindowsSecurityContextOptions(securityContext.WindowsOptions, fldPath.Child("windowsOptions"))...)
}
return allErrs
}
func ValidateContainerUpdates(newContainers, oldContainers []core.Container, fldPath *field.Path) (allErrs field.ErrorList, stop bool) {
allErrs = field.ErrorList{}
if len(newContainers) != len(oldContainers) {
//TODO: Pinpoint the specific container that causes the invalid error after we have strategic merge diff
allErrs = append(allErrs, field.Forbidden(fldPath, "pod updates may not add or remove containers"))
return allErrs, true
}
// validate updated container images
for i, ctr := range newContainers {
if len(ctr.Image) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Index(i).Child("image"), ""))
}
// this is only called from ValidatePodUpdate so its safe to check leading/trailing whitespace.
if len(strings.TrimSpace(ctr.Image)) != len(ctr.Image) {
allErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child("image"), ctr.Image, "must not have leading or trailing whitespace"))
}
}
return allErrs, false
}
// ValidatePodCreate validates a pod in the context of its initial create
func ValidatePodCreate(pod *core.Pod, opts PodValidationOptions) field.ErrorList {
allErrs := validatePodMetadataAndSpec(pod, opts)
fldPath := field.NewPath("spec")
// EphemeralContainers can only be set on update using the ephemeralcontainers subresource
if len(pod.Spec.EphemeralContainers) > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("ephemeralContainers"), "cannot be set on create"))
}
allErrs = append(allErrs, validateSeccompAnnotationsAndFields(pod.ObjectMeta, &pod.Spec, fldPath)...)
return allErrs
}
// ValidateSeccompAnnotationsAndFields iterates through all containers and ensure that when both seccompProfile and seccomp annotations exist they match.
func validateSeccompAnnotationsAndFields(objectMeta metav1.ObjectMeta, podSpec *core.PodSpec, specPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if podSpec.SecurityContext != nil && podSpec.SecurityContext.SeccompProfile != nil {
// If both seccomp annotations and fields are specified, the values must match.
if annotation, found := objectMeta.Annotations[v1.SeccompPodAnnotationKey]; found {
seccompPath := specPath.Child("securityContext").Child("seccompProfile")
err := validateSeccompAnnotationsAndFieldsMatch(annotation, podSpec.SecurityContext.SeccompProfile, seccompPath)
if err != nil {
allErrs = append(allErrs, err)
}
}
}
podshelper.VisitContainersWithPath(podSpec, specPath, func(c *core.Container, cFldPath *field.Path) bool {
var field *core.SeccompProfile
if c.SecurityContext != nil {
field = c.SecurityContext.SeccompProfile
}
if field == nil {
return true
}
key := v1.SeccompContainerAnnotationKeyPrefix + c.Name
if annotation, found := objectMeta.Annotations[key]; found {
seccompPath := cFldPath.Child("securityContext").Child("seccompProfile")
err := validateSeccompAnnotationsAndFieldsMatch(annotation, field, seccompPath)
if err != nil {
allErrs = append(allErrs, err)
}
}
return true
})
return allErrs
}
func validateSeccompAnnotationsAndFieldsMatch(annotationValue string, seccompField *core.SeccompProfile, fldPath *field.Path) *field.Error {
if seccompField == nil {
return nil
}
switch seccompField.Type {
case core.SeccompProfileTypeUnconfined:
if annotationValue != v1.SeccompProfileNameUnconfined {
return field.Forbidden(fldPath.Child("type"), "seccomp type in annotation and field must match")
}
case core.SeccompProfileTypeRuntimeDefault:
if annotationValue != v1.SeccompProfileRuntimeDefault && annotationValue != v1.DeprecatedSeccompProfileDockerDefault {
return field.Forbidden(fldPath.Child("type"), "seccomp type in annotation and field must match")
}
case core.SeccompProfileTypeLocalhost:
if !strings.HasPrefix(annotationValue, v1.SeccompLocalhostProfileNamePrefix) {
return field.Forbidden(fldPath.Child("type"), "seccomp type in annotation and field must match")
} else if seccompField.LocalhostProfile == nil || strings.TrimPrefix(annotationValue, v1.SeccompLocalhostProfileNamePrefix) != *seccompField.LocalhostProfile {
return field.Forbidden(fldPath.Child("localhostProfile"), "seccomp profile in annotation and field must match")
}
}
return nil
}
// ValidatePodUpdate tests to see if the update is legal for an end user to make. newPod is updated with fields
// that cannot be changed.
func ValidatePodUpdate(newPod, oldPod *core.Pod, opts PodValidationOptions) field.ErrorList {
fldPath := field.NewPath("metadata")
allErrs := ValidateObjectMetaUpdate(&newPod.ObjectMeta, &oldPod.ObjectMeta, fldPath)
allErrs = append(allErrs, validatePodMetadataAndSpec(newPod, opts)...)
allErrs = append(allErrs, ValidatePodSpecificAnnotationUpdates(newPod, oldPod, fldPath.Child("annotations"), opts)...)
specPath := field.NewPath("spec")
// validate updateable fields:
// 1. spec.containers[*].image
// 2. spec.initContainers[*].image
// 3. spec.activeDeadlineSeconds
// 4. spec.terminationGracePeriodSeconds
containerErrs, stop := ValidateContainerUpdates(newPod.Spec.Containers, oldPod.Spec.Containers, specPath.Child("containers"))
allErrs = append(allErrs, containerErrs...)
if stop {
return allErrs
}
containerErrs, stop = ValidateContainerUpdates(newPod.Spec.InitContainers, oldPod.Spec.InitContainers, specPath.Child("initContainers"))
allErrs = append(allErrs, containerErrs...)
if stop {
return allErrs
}
// validate updated spec.activeDeadlineSeconds. two types of updates are allowed:
// 1. from nil to a positive value
// 2. from a positive value to a lesser, non-negative value
if newPod.Spec.ActiveDeadlineSeconds != nil {
newActiveDeadlineSeconds := *newPod.Spec.ActiveDeadlineSeconds
if newActiveDeadlineSeconds < 0 || newActiveDeadlineSeconds > math.MaxInt32 {
allErrs = append(allErrs, field.Invalid(specPath.Child("activeDeadlineSeconds"), newActiveDeadlineSeconds, validation.InclusiveRangeError(0, math.MaxInt32)))
return allErrs
}
if oldPod.Spec.ActiveDeadlineSeconds != nil {
oldActiveDeadlineSeconds := *oldPod.Spec.ActiveDeadlineSeconds
if oldActiveDeadlineSeconds < newActiveDeadlineSeconds {
allErrs = append(allErrs, field.Invalid(specPath.Child("activeDeadlineSeconds"), newActiveDeadlineSeconds, "must be less than or equal to previous value"))
return allErrs
}
}
} else if oldPod.Spec.ActiveDeadlineSeconds != nil {
allErrs = append(allErrs, field.Invalid(specPath.Child("activeDeadlineSeconds"), newPod.Spec.ActiveDeadlineSeconds, "must not update from a positive integer to nil value"))
}
// Allow only additions to tolerations updates.
allErrs = append(allErrs, validateOnlyAddedTolerations(newPod.Spec.Tolerations, oldPod.Spec.Tolerations, specPath.Child("tolerations"))...)
// the last thing to check is pod spec equality. If the pod specs are equal, then we can simply return the errors we have
// so far and save the cost of a deep copy.
if apiequality.Semantic.DeepEqual(newPod.Spec, oldPod.Spec) {
return allErrs
}
// handle updateable fields by munging those fields prior to deep equal comparison.
mungedPodSpec := *newPod.Spec.DeepCopy()
// munge spec.containers[*].image
var newContainers []core.Container
for ix, container := range mungedPodSpec.Containers {
container.Image = oldPod.Spec.Containers[ix].Image // +k8s:verify-mutation:reason=clone
newContainers = append(newContainers, container)
}
mungedPodSpec.Containers = newContainers
// munge spec.initContainers[*].image
var newInitContainers []core.Container
for ix, container := range mungedPodSpec.InitContainers {
container.Image = oldPod.Spec.InitContainers[ix].Image // +k8s:verify-mutation:reason=clone
newInitContainers = append(newInitContainers, container)
}
mungedPodSpec.InitContainers = newInitContainers
// munge spec.activeDeadlineSeconds
mungedPodSpec.ActiveDeadlineSeconds = nil
if oldPod.Spec.ActiveDeadlineSeconds != nil {
activeDeadlineSeconds := *oldPod.Spec.ActiveDeadlineSeconds
mungedPodSpec.ActiveDeadlineSeconds = &activeDeadlineSeconds
}
// tolerations are checked before the deep copy, so munge those too
mungedPodSpec.Tolerations = oldPod.Spec.Tolerations // +k8s:verify-mutation:reason=clone
// Relax validation of immutable fields to allow it to be set to 1 if it was previously negative.
if oldPod.Spec.TerminationGracePeriodSeconds != nil && *oldPod.Spec.TerminationGracePeriodSeconds < 0 &&
mungedPodSpec.TerminationGracePeriodSeconds != nil && *mungedPodSpec.TerminationGracePeriodSeconds == 1 {
mungedPodSpec.TerminationGracePeriodSeconds = oldPod.Spec.TerminationGracePeriodSeconds // +k8s:verify-mutation:reason=clone
}
if !apiequality.Semantic.DeepEqual(mungedPodSpec, oldPod.Spec) {
// This diff isn't perfect, but it's a helluva lot better an "I'm not going to tell you what the difference is".
//TODO: Pinpoint the specific field that causes the invalid error after we have strategic merge diff
specDiff := cmp.Diff(oldPod.Spec, mungedPodSpec)
allErrs = append(allErrs, field.Forbidden(specPath, fmt.Sprintf("pod updates may not change fields other than `spec.containers[*].image`, `spec.initContainers[*].image`, `spec.activeDeadlineSeconds`, `spec.tolerations` (only additions to existing tolerations) or `spec.terminationGracePeriodSeconds` (allow it to be set to 1 if it was previously negative)\n%v", specDiff)))
}
return allErrs
}
// ValidateContainerStateTransition test to if any illegal container state transitions are being attempted
func ValidateContainerStateTransition(newStatuses, oldStatuses []core.ContainerStatus, fldpath *field.Path, restartPolicy core.RestartPolicy) field.ErrorList {
allErrs := field.ErrorList{}
// If we should always restart, containers are allowed to leave the terminated state
if restartPolicy == core.RestartPolicyAlways {
return allErrs
}
for i, oldStatus := range oldStatuses {
// Skip any container that is not terminated
if oldStatus.State.Terminated == nil {
continue
}
// Skip any container that failed but is allowed to restart
if oldStatus.State.Terminated.ExitCode != 0 && restartPolicy == core.RestartPolicyOnFailure {
continue
}
for _, newStatus := range newStatuses {
if oldStatus.Name == newStatus.Name && newStatus.State.Terminated == nil {
allErrs = append(allErrs, field.Forbidden(fldpath.Index(i).Child("state"), "may not be transitioned to non-terminated state"))
}
}
}
return allErrs
}
// ValidatePodStatusUpdate checks for changes to status that shouldn't occur in normal operation.
func ValidatePodStatusUpdate(newPod, oldPod *core.Pod, opts PodValidationOptions) field.ErrorList {
fldPath := field.NewPath("metadata")
allErrs := ValidateObjectMetaUpdate(&newPod.ObjectMeta, &oldPod.ObjectMeta, fldPath)
allErrs = append(allErrs, ValidatePodSpecificAnnotationUpdates(newPod, oldPod, fldPath.Child("annotations"), opts)...)
allErrs = append(allErrs, validatePodConditions(newPod.Status.Conditions, fldPath.Child("conditions"))...)
fldPath = field.NewPath("status")
if newPod.Spec.NodeName != oldPod.Spec.NodeName {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("nodeName"), "may not be changed directly"))
}
if newPod.Status.NominatedNodeName != oldPod.Status.NominatedNodeName && len(newPod.Status.NominatedNodeName) > 0 {
for _, msg := range ValidateNodeName(newPod.Status.NominatedNodeName, false) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("nominatedNodeName"), newPod.Status.NominatedNodeName, msg))
}
}
// If pod should not restart, make sure the status update does not transition
// any terminated containers to a non-terminated state.
allErrs = append(allErrs, ValidateContainerStateTransition(newPod.Status.ContainerStatuses, oldPod.Status.ContainerStatuses, fldPath.Child("containerStatuses"), oldPod.Spec.RestartPolicy)...)
allErrs = append(allErrs, ValidateContainerStateTransition(newPod.Status.InitContainerStatuses, oldPod.Status.InitContainerStatuses, fldPath.Child("initContainerStatuses"), oldPod.Spec.RestartPolicy)...)
// The kubelet will never restart ephemeral containers, so treat them like they have an implicit RestartPolicyNever.
allErrs = append(allErrs, ValidateContainerStateTransition(newPod.Status.EphemeralContainerStatuses, oldPod.Status.EphemeralContainerStatuses, fldPath.Child("ephemeralContainerStatuses"), core.RestartPolicyNever)...)
if newIPErrs := validatePodIPs(newPod); len(newIPErrs) > 0 {
allErrs = append(allErrs, newIPErrs...)
}
return allErrs
}
// validatePodConditions tests if the custom pod conditions are valid.
func validatePodConditions(conditions []core.PodCondition, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
systemConditions := sets.NewString(string(core.PodScheduled), string(core.PodReady), string(core.PodInitialized))
for i, condition := range conditions {
if systemConditions.Has(string(condition.Type)) {
continue
}
for _, msg := range validation.IsQualifiedName(string(condition.Type)) {
allErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child("Type"), string(condition.Type), msg))
}
}
return allErrs
}
// ValidatePodEphemeralContainersUpdate tests that a user update to EphemeralContainers is valid.
// newPod and oldPod must only differ in their EphemeralContainers.
func ValidatePodEphemeralContainersUpdate(newPod, oldPod *core.Pod, opts PodValidationOptions) field.ErrorList {
// Part 1: Validate newPod's spec and updates to metadata
fldPath := field.NewPath("metadata")
allErrs := ValidateObjectMetaUpdate(&newPod.ObjectMeta, &oldPod.ObjectMeta, fldPath)
allErrs = append(allErrs, validatePodMetadataAndSpec(newPod, opts)...)
allErrs = append(allErrs, ValidatePodSpecificAnnotationUpdates(newPod, oldPod, fldPath.Child("annotations"), opts)...)
// Part 2: Validate that the changes between oldPod.Spec.EphemeralContainers and
// newPod.Spec.EphemeralContainers are allowed.
//
// Existing EphemeralContainers may not be changed. Order isn't preserved by patch, so check each individually.
newContainerIndex := make(map[string]*core.EphemeralContainer)
specPath := field.NewPath("spec").Child("ephemeralContainers")
for i := range newPod.Spec.EphemeralContainers {
newContainerIndex[newPod.Spec.EphemeralContainers[i].Name] = &newPod.Spec.EphemeralContainers[i]
}
for _, old := range oldPod.Spec.EphemeralContainers {
if new, ok := newContainerIndex[old.Name]; !ok {
allErrs = append(allErrs, field.Forbidden(specPath, fmt.Sprintf("existing ephemeral containers %q may not be removed\n", old.Name)))
} else if !apiequality.Semantic.DeepEqual(old, *new) {
specDiff := cmp.Diff(old, *new)
allErrs = append(allErrs, field.Forbidden(specPath, fmt.Sprintf("existing ephemeral containers %q may not be changed\n%v", old.Name, specDiff)))
}
}
return allErrs
}
// ValidatePodBinding tests if required fields in the pod binding are legal.
func ValidatePodBinding(binding *core.Binding) field.ErrorList {
allErrs := field.ErrorList{}
if len(binding.Target.Kind) != 0 && binding.Target.Kind != "Node" {
// TODO: When validation becomes versioned, this gets more complicated.
allErrs = append(allErrs, field.NotSupported(field.NewPath("target", "kind"), binding.Target.Kind, []string{"Node", "<empty>"}))
}
if len(binding.Target.Name) == 0 {
// TODO: When validation becomes versioned, this gets more complicated.
allErrs = append(allErrs, field.Required(field.NewPath("target", "name"), ""))
}
return allErrs
}
// ValidatePodTemplate tests if required fields in the pod template are set.
func ValidatePodTemplate(pod *core.PodTemplate, opts PodValidationOptions) field.ErrorList {
allErrs := ValidateObjectMeta(&pod.ObjectMeta, true, ValidatePodName, field.NewPath("metadata"))
allErrs = append(allErrs, ValidatePodTemplateSpec(&pod.Template, field.NewPath("template"), opts)...)
return allErrs
}
// ValidatePodTemplateUpdate tests to see if the update is legal for an end user to make. newPod is updated with fields
// that cannot be changed.
func ValidatePodTemplateUpdate(newPod, oldPod *core.PodTemplate, opts PodValidationOptions) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&newPod.ObjectMeta, &oldPod.ObjectMeta, field.NewPath("metadata"))
allErrs = append(allErrs, ValidatePodTemplateSpec(&newPod.Template, field.NewPath("template"), opts)...)
return allErrs
}
var supportedSessionAffinityType = sets.NewString(string(core.ServiceAffinityClientIP), string(core.ServiceAffinityNone))
var supportedServiceType = sets.NewString(string(core.ServiceTypeClusterIP), string(core.ServiceTypeNodePort),
string(core.ServiceTypeLoadBalancer), string(core.ServiceTypeExternalName))
var supportedServiceInternalTrafficPolicy = sets.NewString(string(core.ServiceInternalTrafficPolicyCluster), string(core.ServiceExternalTrafficPolicyTypeLocal))
var supportedServiceIPFamily = sets.NewString(string(core.IPv4Protocol), string(core.IPv6Protocol))
var supportedServiceIPFamilyPolicy = sets.NewString(string(core.IPFamilyPolicySingleStack), string(core.IPFamilyPolicyPreferDualStack), string(core.IPFamilyPolicyRequireDualStack))
// ValidateService tests if required fields/annotations of a Service are valid.
func ValidateService(service *core.Service) field.ErrorList {
allErrs := ValidateObjectMeta(&service.ObjectMeta, true, ValidateServiceName, field.NewPath("metadata"))
specPath := field.NewPath("spec")
if len(service.Spec.Ports) == 0 && !isHeadlessService(service) && service.Spec.Type != core.ServiceTypeExternalName {
allErrs = append(allErrs, field.Required(specPath.Child("ports"), ""))
}
switch service.Spec.Type {
case core.ServiceTypeLoadBalancer:
for ix := range service.Spec.Ports {
port := &service.Spec.Ports[ix]
// This is a workaround for broken cloud environments that
// over-open firewalls. Hopefully it can go away when more clouds
// understand containers better.
if port.Port == ports.KubeletPort {
portPath := specPath.Child("ports").Index(ix)
allErrs = append(allErrs, field.Invalid(portPath, port.Port, fmt.Sprintf("may not expose port %v externally since it is used by kubelet", ports.KubeletPort)))
}
}
if isHeadlessService(service) {
allErrs = append(allErrs, field.Invalid(specPath.Child("clusterIPs").Index(0), service.Spec.ClusterIPs[0], "may not be set to 'None' for LoadBalancer services"))
}
case core.ServiceTypeNodePort:
if isHeadlessService(service) {
allErrs = append(allErrs, field.Invalid(specPath.Child("clusterIPs").Index(0), service.Spec.ClusterIPs[0], "may not be set to 'None' for NodePort services"))
}
case core.ServiceTypeExternalName:
// must have len(.spec.ClusterIPs) == 0 // note: strategy sets ClusterIPs based on ClusterIP
if len(service.Spec.ClusterIPs) > 0 {
allErrs = append(allErrs, field.Forbidden(specPath.Child("clusterIPs"), "may not be set for ExternalName services"))
}
// must have nil families and nil policy
if len(service.Spec.IPFamilies) > 0 {
allErrs = append(allErrs, field.Forbidden(specPath.Child("ipFamilies"), "may not be set for ExternalName services"))
}
if service.Spec.IPFamilyPolicy != nil {
allErrs = append(allErrs, field.Forbidden(specPath.Child("ipFamilyPolicy"), "may not be set for ExternalName services"))
}
// The value (a CNAME) may have a trailing dot to denote it as fully qualified
cname := strings.TrimSuffix(service.Spec.ExternalName, ".")
if len(cname) > 0 {
allErrs = append(allErrs, ValidateDNS1123Subdomain(cname, specPath.Child("externalName"))...)
} else {
allErrs = append(allErrs, field.Required(specPath.Child("externalName"), ""))
}
}
allPortNames := sets.String{}
portsPath := specPath.Child("ports")
for i := range service.Spec.Ports {
portPath := portsPath.Index(i)
allErrs = append(allErrs, validateServicePort(&service.Spec.Ports[i], len(service.Spec.Ports) > 1, isHeadlessService(service), &allPortNames, portPath)...)
}
if service.Spec.Selector != nil {
allErrs = append(allErrs, unversionedvalidation.ValidateLabels(service.Spec.Selector, specPath.Child("selector"))...)
}
if len(service.Spec.SessionAffinity) == 0 {
allErrs = append(allErrs, field.Required(specPath.Child("sessionAffinity"), ""))
} else if !supportedSessionAffinityType.Has(string(service.Spec.SessionAffinity)) {
allErrs = append(allErrs, field.NotSupported(specPath.Child("sessionAffinity"), service.Spec.SessionAffinity, supportedSessionAffinityType.List()))
}
if service.Spec.SessionAffinity == core.ServiceAffinityClientIP {
allErrs = append(allErrs, validateClientIPAffinityConfig(service.Spec.SessionAffinityConfig, specPath.Child("sessionAffinityConfig"))...)
} else if service.Spec.SessionAffinity == core.ServiceAffinityNone {
if service.Spec.SessionAffinityConfig != nil {
allErrs = append(allErrs, field.Forbidden(specPath.Child("sessionAffinityConfig"), fmt.Sprintf("must not be set when session affinity is %s", string(core.ServiceAffinityNone))))
}
}
// dualstack <-> ClusterIPs <-> ipfamilies
allErrs = append(allErrs, ValidateServiceClusterIPsRelatedFields(service)...)
ipPath := specPath.Child("externalIPs")
for i, ip := range service.Spec.ExternalIPs {
idxPath := ipPath.Index(i)
if msgs := validation.IsValidIP(ip); len(msgs) != 0 {
for i := range msgs {
allErrs = append(allErrs, field.Invalid(idxPath, ip, msgs[i]))
}
} else {
allErrs = append(allErrs, ValidateNonSpecialIP(ip, idxPath)...)
}
}
if len(service.Spec.Type) == 0 {
allErrs = append(allErrs, field.Required(specPath.Child("type"), ""))
} else if !supportedServiceType.Has(string(service.Spec.Type)) {
allErrs = append(allErrs, field.NotSupported(specPath.Child("type"), service.Spec.Type, supportedServiceType.List()))
}
if service.Spec.Type == core.ServiceTypeClusterIP {
portsPath := specPath.Child("ports")
for i := range service.Spec.Ports {
portPath := portsPath.Index(i)
if service.Spec.Ports[i].NodePort != 0 {
allErrs = append(allErrs, field.Forbidden(portPath.Child("nodePort"), "may not be used when `type` is 'ClusterIP'"))
}
}
}
// Check for duplicate NodePorts, considering (protocol,port) pairs
portsPath = specPath.Child("ports")
nodePorts := make(map[core.ServicePort]bool)
for i := range service.Spec.Ports {
port := &service.Spec.Ports[i]
if port.NodePort == 0 {
continue
}
portPath := portsPath.Index(i)
var key core.ServicePort
key.Protocol = port.Protocol
key.NodePort = port.NodePort
_, found := nodePorts[key]
if found {
allErrs = append(allErrs, field.Duplicate(portPath.Child("nodePort"), port.NodePort))
}
nodePorts[key] = true
}
// Check for duplicate Ports, considering (protocol,port) pairs
portsPath = specPath.Child("ports")
ports := make(map[core.ServicePort]bool)
for i, port := range service.Spec.Ports {
portPath := portsPath.Index(i)
key := core.ServicePort{Protocol: port.Protocol, Port: port.Port}
_, found := ports[key]
if found {
allErrs = append(allErrs, field.Duplicate(portPath, key))
}
ports[key] = true
}
// Validate SourceRange field and annotation
_, ok := service.Annotations[core.AnnotationLoadBalancerSourceRangesKey]
if len(service.Spec.LoadBalancerSourceRanges) > 0 || ok {
var fieldPath *field.Path
var val string
if len(service.Spec.LoadBalancerSourceRanges) > 0 {
fieldPath = specPath.Child("LoadBalancerSourceRanges")
val = fmt.Sprintf("%v", service.Spec.LoadBalancerSourceRanges)
} else {
fieldPath = field.NewPath("metadata", "annotations").Key(core.AnnotationLoadBalancerSourceRangesKey)
val = service.Annotations[core.AnnotationLoadBalancerSourceRangesKey]
}
if service.Spec.Type != core.ServiceTypeLoadBalancer {
allErrs = append(allErrs, field.Forbidden(fieldPath, "may only be used when `type` is 'LoadBalancer'"))
}
_, err := apiservice.GetLoadBalancerSourceRanges(service)
if err != nil {
allErrs = append(allErrs, field.Invalid(fieldPath, val, "must be a list of IP ranges. For example, 10.240.0.0/24,10.250.0.0/24 "))
}
}
if service.Spec.AllocateLoadBalancerNodePorts != nil && service.Spec.Type != core.ServiceTypeLoadBalancer {
allErrs = append(allErrs, field.Forbidden(specPath.Child("allocateLoadBalancerNodePorts"), "may only be used when `type` is 'LoadBalancer'"))
}
if service.Spec.Type == core.ServiceTypeLoadBalancer && service.Spec.AllocateLoadBalancerNodePorts == nil {
allErrs = append(allErrs, field.Required(field.NewPath("allocateLoadBalancerNodePorts"), ""))
}
// validate LoadBalancerClass field
allErrs = append(allErrs, validateLoadBalancerClassField(nil, service)...)
// external traffic policy fields
allErrs = append(allErrs, validateServiceExternalTrafficPolicy(service)...)
// internal traffic policy field
allErrs = append(allErrs, validateServiceInternalTrafficFieldsValue(service)...)
return allErrs
}
func validateServicePort(sp *core.ServicePort, requireName, isHeadlessService bool, allNames *sets.String, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if requireName && len(sp.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("name"), ""))
} else if len(sp.Name) != 0 {
allErrs = append(allErrs, ValidateDNS1123Label(sp.Name, fldPath.Child("name"))...)
if allNames.Has(sp.Name) {
allErrs = append(allErrs, field.Duplicate(fldPath.Child("name"), sp.Name))
} else {
allNames.Insert(sp.Name)
}
}
for _, msg := range validation.IsValidPortNum(int(sp.Port)) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("port"), sp.Port, msg))
}
if len(sp.Protocol) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("protocol"), ""))
} else if !supportedPortProtocols.Has(string(sp.Protocol)) {
allErrs = append(allErrs, field.NotSupported(fldPath.Child("protocol"), sp.Protocol, supportedPortProtocols.List()))
}
allErrs = append(allErrs, ValidatePortNumOrName(sp.TargetPort, fldPath.Child("targetPort"))...)
if sp.AppProtocol != nil {
for _, msg := range validation.IsQualifiedName(*sp.AppProtocol) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("appProtocol"), sp.AppProtocol, msg))
}
}
// in the v1 API, targetPorts on headless services were tolerated.
// once we have version-specific validation, we can reject this on newer API versions, but until then, we have to tolerate it for compatibility.
//
// if isHeadlessService {
// if sp.TargetPort.Type == intstr.String || (sp.TargetPort.Type == intstr.Int && sp.Port != sp.TargetPort.IntValue()) {
// allErrs = append(allErrs, field.Invalid(fldPath.Child("targetPort"), sp.TargetPort, "must be equal to the value of 'port' when clusterIP = None"))
// }
// }
return allErrs
}
func needsExternalTrafficPolicy(svc *api.Service) bool {
return svc.Spec.Type == core.ServiceTypeLoadBalancer || svc.Spec.Type == core.ServiceTypeNodePort
}
var validExternalTrafficPolicies = sets.NewString(
string(core.ServiceExternalTrafficPolicyTypeCluster),
string(core.ServiceExternalTrafficPolicyTypeLocal))
func validateServiceExternalTrafficPolicy(service *core.Service) field.ErrorList {
allErrs := field.ErrorList{}
fldPath := field.NewPath("spec")
if !needsExternalTrafficPolicy(service) {
if service.Spec.ExternalTrafficPolicy != "" {
allErrs = append(allErrs, field.Invalid(fldPath.Child("externalTrafficPolicy"), service.Spec.ExternalTrafficPolicy,
"may only be set when `type` is 'NodePort' or 'LoadBalancer'"))
}
} else {
if service.Spec.ExternalTrafficPolicy == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("externalTrafficPolicy"), ""))
} else if !validExternalTrafficPolicies.Has(string(service.Spec.ExternalTrafficPolicy)) {
allErrs = append(allErrs, field.NotSupported(fldPath.Child("externalTrafficPolicy"),
service.Spec.ExternalTrafficPolicy, validExternalTrafficPolicies.List()))
}
}
if !apiservice.NeedsHealthCheck(service) {
if service.Spec.HealthCheckNodePort != 0 {
allErrs = append(allErrs, field.Invalid(fldPath.Child("healthCheckNodePort"), service.Spec.HealthCheckNodePort,
"may only be set when `type` is 'LoadBalancer' and `externalTrafficPolicy` is 'Local'"))
}
} else {
if service.Spec.HealthCheckNodePort == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("healthCheckNodePort"), ""))
} else {
for _, msg := range validation.IsValidPortNum(int(service.Spec.HealthCheckNodePort)) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("healthCheckNodePort"), service.Spec.HealthCheckNodePort, msg))
}
}
}
return allErrs
}
func validateServiceExternalTrafficFieldsUpdate(before, after *api.Service) field.ErrorList {
allErrs := field.ErrorList{}
if apiservice.NeedsHealthCheck(before) && apiservice.NeedsHealthCheck(after) {
if after.Spec.HealthCheckNodePort != before.Spec.HealthCheckNodePort {
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "healthCheckNodePort"), "field is immutable"))
}
}
return allErrs
}
// validateServiceInternalTrafficFieldsValue validates InternalTraffic related
// spec have legal value.
func validateServiceInternalTrafficFieldsValue(service *core.Service) field.ErrorList {
allErrs := field.ErrorList{}
if utilfeature.DefaultFeatureGate.Enabled(features.ServiceInternalTrafficPolicy) {
if service.Spec.InternalTrafficPolicy == nil {
// We do not forbid internalTrafficPolicy on other Service types because of historical reasons.
// We did not check that before it went beta and we don't want to invalidate existing stored objects.
if service.Spec.Type == core.ServiceTypeNodePort ||
service.Spec.Type == core.ServiceTypeLoadBalancer || service.Spec.Type == core.ServiceTypeClusterIP {
allErrs = append(allErrs, field.Required(field.NewPath("spec").Child("internalTrafficPolicy"), ""))
}
}
}
if service.Spec.InternalTrafficPolicy != nil && !supportedServiceInternalTrafficPolicy.Has(string(*service.Spec.InternalTrafficPolicy)) {
allErrs = append(allErrs, field.NotSupported(field.NewPath("spec").Child("internalTrafficPolicy"), *service.Spec.InternalTrafficPolicy, supportedServiceInternalTrafficPolicy.List()))
}
return allErrs
}
// ValidateServiceCreate validates Services as they are created.
func ValidateServiceCreate(service *core.Service) field.ErrorList {
return ValidateService(service)
}
// ValidateServiceUpdate tests if required fields in the service are set during an update
func ValidateServiceUpdate(service, oldService *core.Service) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&service.ObjectMeta, &oldService.ObjectMeta, field.NewPath("metadata"))
// User can upgrade (add another clusterIP or ipFamily)
// can downgrade (remove secondary clusterIP or ipFamily)
// but *CAN NOT* change primary/secondary clusterIP || ipFamily *UNLESS*
// they are changing from/to/ON ExternalName
upgradeDowngradeClusterIPsErrs := validateUpgradeDowngradeClusterIPs(oldService, service)
allErrs = append(allErrs, upgradeDowngradeClusterIPsErrs...)
upgradeDowngradeIPFamiliesErrs := validateUpgradeDowngradeIPFamilies(oldService, service)
allErrs = append(allErrs, upgradeDowngradeIPFamiliesErrs...)
upgradeDowngradeLoadBalancerClassErrs := validateLoadBalancerClassField(oldService, service)
allErrs = append(allErrs, upgradeDowngradeLoadBalancerClassErrs...)
allErrs = append(allErrs, validateServiceExternalTrafficFieldsUpdate(oldService, service)...)
return append(allErrs, ValidateService(service)...)
}
// ValidateServiceStatusUpdate tests if required fields in the Service are set when updating status.
func ValidateServiceStatusUpdate(service, oldService *core.Service) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&service.ObjectMeta, &oldService.ObjectMeta, field.NewPath("metadata"))
allErrs = append(allErrs, ValidateLoadBalancerStatus(&service.Status.LoadBalancer, field.NewPath("status", "loadBalancer"))...)
return allErrs
}
// ValidateReplicationController tests if required fields in the replication controller are set.
func ValidateReplicationController(controller *core.ReplicationController, opts PodValidationOptions) field.ErrorList {
allErrs := ValidateObjectMeta(&controller.ObjectMeta, true, ValidateReplicationControllerName, field.NewPath("metadata"))
allErrs = append(allErrs, ValidateReplicationControllerSpec(&controller.Spec, field.NewPath("spec"), opts)...)
return allErrs
}
// ValidateReplicationControllerUpdate tests if required fields in the replication controller are set.
func ValidateReplicationControllerUpdate(controller, oldController *core.ReplicationController, opts PodValidationOptions) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&controller.ObjectMeta, &oldController.ObjectMeta, field.NewPath("metadata"))
allErrs = append(allErrs, ValidateReplicationControllerSpec(&controller.Spec, field.NewPath("spec"), opts)...)
return allErrs
}
// ValidateReplicationControllerStatusUpdate tests if required fields in the replication controller are set.
func ValidateReplicationControllerStatusUpdate(controller, oldController *core.ReplicationController) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&controller.ObjectMeta, &oldController.ObjectMeta, field.NewPath("metadata"))
allErrs = append(allErrs, ValidateReplicationControllerStatus(controller.Status, field.NewPath("status"))...)
return allErrs
}
func ValidateReplicationControllerStatus(status core.ReplicationControllerStatus, statusPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, ValidateNonnegativeField(int64(status.Replicas), statusPath.Child("replicas"))...)
allErrs = append(allErrs, ValidateNonnegativeField(int64(status.FullyLabeledReplicas), statusPath.Child("fullyLabeledReplicas"))...)
allErrs = append(allErrs, ValidateNonnegativeField(int64(status.ReadyReplicas), statusPath.Child("readyReplicas"))...)
allErrs = append(allErrs, ValidateNonnegativeField(int64(status.AvailableReplicas), statusPath.Child("availableReplicas"))...)
allErrs = append(allErrs, ValidateNonnegativeField(int64(status.ObservedGeneration), statusPath.Child("observedGeneration"))...)
msg := "cannot be greater than status.replicas"
if status.FullyLabeledReplicas > status.Replicas {
allErrs = append(allErrs, field.Invalid(statusPath.Child("fullyLabeledReplicas"), status.FullyLabeledReplicas, msg))
}
if status.ReadyReplicas > status.Replicas {
allErrs = append(allErrs, field.Invalid(statusPath.Child("readyReplicas"), status.ReadyReplicas, msg))
}
if status.AvailableReplicas > status.Replicas {
allErrs = append(allErrs, field.Invalid(statusPath.Child("availableReplicas"), status.AvailableReplicas, msg))
}
if status.AvailableReplicas > status.ReadyReplicas {
allErrs = append(allErrs, field.Invalid(statusPath.Child("availableReplicas"), status.AvailableReplicas, "cannot be greater than readyReplicas"))
}
return allErrs
}
// Validates that the given selector is non-empty.
func ValidateNonEmptySelector(selectorMap map[string]string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
selector := labels.Set(selectorMap).AsSelector()
if selector.Empty() {
allErrs = append(allErrs, field.Required(fldPath, ""))
}
return allErrs
}
// Validates the given template and ensures that it is in accordance with the desired selector and replicas.
func ValidatePodTemplateSpecForRC(template *core.PodTemplateSpec, selectorMap map[string]string, replicas int32, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
if template == nil {
allErrs = append(allErrs, field.Required(fldPath, ""))
} else {
selector := labels.Set(selectorMap).AsSelector()
if !selector.Empty() {
// Verify that the RC selector matches the labels in template.
labels := labels.Set(template.Labels)
if !selector.Matches(labels) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("metadata", "labels"), template.Labels, "`selector` does not match template `labels`"))
}
}
allErrs = append(allErrs, ValidatePodTemplateSpec(template, fldPath, opts)...)
if replicas > 1 {
allErrs = append(allErrs, ValidateReadOnlyPersistentDisks(template.Spec.Volumes, fldPath.Child("spec", "volumes"))...)
}
// RestartPolicy has already been first-order validated as per ValidatePodTemplateSpec().
if template.Spec.RestartPolicy != core.RestartPolicyAlways {
allErrs = append(allErrs, field.NotSupported(fldPath.Child("spec", "restartPolicy"), template.Spec.RestartPolicy, []string{string(core.RestartPolicyAlways)}))
}
if template.Spec.ActiveDeadlineSeconds != nil {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("spec", "activeDeadlineSeconds"), "activeDeadlineSeconds in ReplicationController is not Supported"))
}
}
return allErrs
}
// ValidateReplicationControllerSpec tests if required fields in the replication controller spec are set.
func ValidateReplicationControllerSpec(spec *core.ReplicationControllerSpec, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, ValidateNonnegativeField(int64(spec.MinReadySeconds), fldPath.Child("minReadySeconds"))...)
allErrs = append(allErrs, ValidateNonEmptySelector(spec.Selector, fldPath.Child("selector"))...)
allErrs = append(allErrs, ValidateNonnegativeField(int64(spec.Replicas), fldPath.Child("replicas"))...)
allErrs = append(allErrs, ValidatePodTemplateSpecForRC(spec.Template, spec.Selector, spec.Replicas, fldPath.Child("template"), opts)...)
return allErrs
}
// ValidatePodTemplateSpec validates the spec of a pod template
func ValidatePodTemplateSpec(spec *core.PodTemplateSpec, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, unversionedvalidation.ValidateLabels(spec.Labels, fldPath.Child("labels"))...)
allErrs = append(allErrs, ValidateAnnotations(spec.Annotations, fldPath.Child("annotations"))...)
allErrs = append(allErrs, ValidatePodSpecificAnnotations(spec.Annotations, &spec.Spec, fldPath.Child("annotations"), opts)...)
allErrs = append(allErrs, ValidatePodSpec(&spec.Spec, nil, fldPath.Child("spec"), opts)...)
allErrs = append(allErrs, validateSeccompAnnotationsAndFields(spec.ObjectMeta, &spec.Spec, fldPath.Child("spec"))...)
if len(spec.Spec.EphemeralContainers) > 0 {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("spec", "ephemeralContainers"), "ephemeral containers not allowed in pod template"))
}
return allErrs
}
func ValidateReadOnlyPersistentDisks(volumes []core.Volume, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for i := range volumes {
vol := &volumes[i]
idxPath := fldPath.Index(i)
if vol.GCEPersistentDisk != nil {
if !vol.GCEPersistentDisk.ReadOnly {
allErrs = append(allErrs, field.Invalid(idxPath.Child("gcePersistentDisk", "readOnly"), false, "must be true for replicated pods > 1; GCE PD can only be mounted on multiple machines if it is read-only"))
}
}
// TODO: What to do for AWS? It doesn't support replicas
}
return allErrs
}
// ValidateTaintsInNodeAnnotations tests that the serialized taints in Node.Annotations has valid data
func ValidateTaintsInNodeAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
taints, err := helper.GetTaintsFromNodeAnnotations(annotations)
if err != nil {
allErrs = append(allErrs, field.Invalid(fldPath, core.TaintsAnnotationKey, err.Error()))
return allErrs
}
if len(taints) > 0 {
allErrs = append(allErrs, validateNodeTaints(taints, fldPath.Child(core.TaintsAnnotationKey))...)
}
return allErrs
}
// validateNodeTaints tests if given taints have valid data.
func validateNodeTaints(taints []core.Taint, fldPath *field.Path) field.ErrorList {
allErrors := field.ErrorList{}
uniqueTaints := map[core.TaintEffect]sets.String{}
for i, currTaint := range taints {
idxPath := fldPath.Index(i)
// validate the taint key
allErrors = append(allErrors, unversionedvalidation.ValidateLabelName(currTaint.Key, idxPath.Child("key"))...)
// validate the taint value
if errs := validation.IsValidLabelValue(currTaint.Value); len(errs) != 0 {
allErrors = append(allErrors, field.Invalid(idxPath.Child("value"), currTaint.Value, strings.Join(errs, ";")))
}
// validate the taint effect
allErrors = append(allErrors, validateTaintEffect(&currTaint.Effect, false, idxPath.Child("effect"))...)
// validate if taint is unique by <key, effect>
if len(uniqueTaints[currTaint.Effect]) > 0 && uniqueTaints[currTaint.Effect].Has(currTaint.Key) {
duplicatedError := field.Duplicate(idxPath, currTaint)
duplicatedError.Detail = "taints must be unique by key and effect pair"
allErrors = append(allErrors, duplicatedError)
continue
}
// add taint to existingTaints for uniqueness check
if len(uniqueTaints[currTaint.Effect]) == 0 {
uniqueTaints[currTaint.Effect] = sets.String{}
}
uniqueTaints[currTaint.Effect].Insert(currTaint.Key)
}
return allErrors
}
func ValidateNodeSpecificAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if annotations[core.TaintsAnnotationKey] != "" {
allErrs = append(allErrs, ValidateTaintsInNodeAnnotations(annotations, fldPath)...)
}
if annotations[core.PreferAvoidPodsAnnotationKey] != "" {
allErrs = append(allErrs, ValidateAvoidPodsInNodeAnnotations(annotations, fldPath)...)
}
return allErrs
}
// ValidateNode tests if required fields in the node are set.
func ValidateNode(node *core.Node) field.ErrorList {
fldPath := field.NewPath("metadata")
allErrs := ValidateObjectMeta(&node.ObjectMeta, false, ValidateNodeName, fldPath)
allErrs = append(allErrs, ValidateNodeSpecificAnnotations(node.ObjectMeta.Annotations, fldPath.Child("annotations"))...)
if len(node.Spec.Taints) > 0 {
allErrs = append(allErrs, validateNodeTaints(node.Spec.Taints, fldPath.Child("taints"))...)
}
// Only validate spec.
// All status fields are optional and can be updated later.
// That said, if specified, we need to ensure they are valid.
allErrs = append(allErrs, ValidateNodeResources(node)...)
// validate PodCIDRS only if we need to
if len(node.Spec.PodCIDRs) > 0 {
podCIDRsField := field.NewPath("spec", "podCIDRs")
// all PodCIDRs should be valid ones
for idx, value := range node.Spec.PodCIDRs {
if _, err := ValidateCIDR(value); err != nil {
allErrs = append(allErrs, field.Invalid(podCIDRsField.Index(idx), node.Spec.PodCIDRs, "must be valid CIDR"))
}
}
// if more than PodCIDR then
// - validate for dual stack
// - validate for duplication
if len(node.Spec.PodCIDRs) > 1 {
dualStack, err := netutils.IsDualStackCIDRStrings(node.Spec.PodCIDRs)
if err != nil {
allErrs = append(allErrs, field.InternalError(podCIDRsField, fmt.Errorf("invalid PodCIDRs. failed to check with dual stack with error:%v", err)))
}
if !dualStack || len(node.Spec.PodCIDRs) > 2 {
allErrs = append(allErrs, field.Invalid(podCIDRsField, node.Spec.PodCIDRs, "may specify no more than one CIDR for each IP family"))
}
// PodCIDRs must not contain duplicates
seen := sets.String{}
for i, value := range node.Spec.PodCIDRs {
if seen.Has(value) {
allErrs = append(allErrs, field.Duplicate(podCIDRsField.Index(i), value))
}
seen.Insert(value)
}
}
}
return allErrs
}
// ValidateNodeResources is used to make sure a node has valid capacity and allocatable values.
func ValidateNodeResources(node *core.Node) field.ErrorList {
allErrs := field.ErrorList{}
// Validate resource quantities in capacity.
for k, v := range node.Status.Capacity {
resPath := field.NewPath("status", "capacity", string(k))
allErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...)
}
// Validate resource quantities in allocatable.
for k, v := range node.Status.Allocatable {
resPath := field.NewPath("status", "allocatable", string(k))
allErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...)
}
return allErrs
}
// ValidateNodeUpdate tests to make sure a node update can be applied. Modifies oldNode.
func ValidateNodeUpdate(node, oldNode *core.Node) field.ErrorList {
fldPath := field.NewPath("metadata")
allErrs := ValidateObjectMetaUpdate(&node.ObjectMeta, &oldNode.ObjectMeta, fldPath)
allErrs = append(allErrs, ValidateNodeSpecificAnnotations(node.ObjectMeta.Annotations, fldPath.Child("annotations"))...)
// TODO: Enable the code once we have better core object.status update model. Currently,
// anyone can update node status.
// if !apiequality.Semantic.DeepEqual(node.Status, core.NodeStatus{}) {
// allErrs = append(allErrs, field.Invalid("status", node.Status, "must be empty"))
// }
allErrs = append(allErrs, ValidateNodeResources(node)...)
// Validate no duplicate addresses in node status.
addresses := make(map[core.NodeAddress]bool)
for i, address := range node.Status.Addresses {
if _, ok := addresses[address]; ok {
allErrs = append(allErrs, field.Duplicate(field.NewPath("status", "addresses").Index(i), address))
}
addresses[address] = true
}
// Allow the controller manager to assign a CIDR to a node if it doesn't have one.
if len(oldNode.Spec.PodCIDRs) > 0 {
// compare the entire slice
if len(oldNode.Spec.PodCIDRs) != len(node.Spec.PodCIDRs) {
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "podCIDRs"), "node updates may not change podCIDR except from \"\" to valid"))
} else {
for idx, value := range oldNode.Spec.PodCIDRs {
if value != node.Spec.PodCIDRs[idx] {
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "podCIDRs"), "node updates may not change podCIDR except from \"\" to valid"))
}
}
}
}
// Allow controller manager updating provider ID when not set
if len(oldNode.Spec.ProviderID) > 0 && oldNode.Spec.ProviderID != node.Spec.ProviderID {
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "providerID"), "node updates may not change providerID except from \"\" to valid"))
}
if node.Spec.ConfigSource != nil {
allErrs = append(allErrs, validateNodeConfigSourceSpec(node.Spec.ConfigSource, field.NewPath("spec", "configSource"))...)
}
if node.Status.Config != nil {
allErrs = append(allErrs, validateNodeConfigStatus(node.Status.Config, field.NewPath("status", "config"))...)
}
// update taints
if len(node.Spec.Taints) > 0 {
allErrs = append(allErrs, validateNodeTaints(node.Spec.Taints, fldPath.Child("taints"))...)
}
if node.Spec.DoNotUseExternalID != oldNode.Spec.DoNotUseExternalID {
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "externalID"), "may not be updated"))
}
// status and metadata are allowed change (barring restrictions above), so separately test spec field.
// spec only has a few fields, so check the ones we don't allow changing
// 1. PodCIDRs - immutable after first set - checked above
// 2. ProviderID - immutable after first set - checked above
// 3. Unschedulable - allowed to change
// 4. Taints - allowed to change
// 5. ConfigSource - allowed to change (and checked above)
// 6. DoNotUseExternalID - immutable - checked above
return allErrs
}
// validation specific to Node.Spec.ConfigSource
func validateNodeConfigSourceSpec(source *core.NodeConfigSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
count := int(0)
if source.ConfigMap != nil {
count++
allErrs = append(allErrs, validateConfigMapNodeConfigSourceSpec(source.ConfigMap, fldPath.Child("configMap"))...)
}
// add more subfields here in the future as they are added to NodeConfigSource
// exactly one reference subfield must be non-nil
if count != 1 {
allErrs = append(allErrs, field.Invalid(fldPath, source, "exactly one reference subfield must be non-nil"))
}
return allErrs
}
// validation specific to Node.Spec.ConfigSource.ConfigMap
func validateConfigMapNodeConfigSourceSpec(source *core.ConfigMapNodeConfigSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
// uid and resourceVersion must not be set in spec
if string(source.UID) != "" {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("uid"), "uid must not be set in spec"))
}
if source.ResourceVersion != "" {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("resourceVersion"), "resourceVersion must not be set in spec"))
}
return append(allErrs, validateConfigMapNodeConfigSource(source, fldPath)...)
}
// validation specififc to Node.Status.Config
func validateNodeConfigStatus(status *core.NodeConfigStatus, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if status.Assigned != nil {
allErrs = append(allErrs, validateNodeConfigSourceStatus(status.Assigned, fldPath.Child("assigned"))...)
}
if status.Active != nil {
allErrs = append(allErrs, validateNodeConfigSourceStatus(status.Active, fldPath.Child("active"))...)
}
if status.LastKnownGood != nil {
allErrs = append(allErrs, validateNodeConfigSourceStatus(status.LastKnownGood, fldPath.Child("lastKnownGood"))...)
}
return allErrs
}
// validation specific to Node.Status.Config.(Active|Assigned|LastKnownGood)
func validateNodeConfigSourceStatus(source *core.NodeConfigSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
count := int(0)
if source.ConfigMap != nil {
count++
allErrs = append(allErrs, validateConfigMapNodeConfigSourceStatus(source.ConfigMap, fldPath.Child("configMap"))...)
}
// add more subfields here in the future as they are added to NodeConfigSource
// exactly one reference subfield must be non-nil
if count != 1 {
allErrs = append(allErrs, field.Invalid(fldPath, source, "exactly one reference subfield must be non-nil"))
}
return allErrs
}
// validation specific to Node.Status.Config.(Active|Assigned|LastKnownGood).ConfigMap
func validateConfigMapNodeConfigSourceStatus(source *core.ConfigMapNodeConfigSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
// uid and resourceVersion must be set in status
if string(source.UID) == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("uid"), "uid must be set in status"))
}
if source.ResourceVersion == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("resourceVersion"), "resourceVersion must be set in status"))
}
return append(allErrs, validateConfigMapNodeConfigSource(source, fldPath)...)
}
// common validation
func validateConfigMapNodeConfigSource(source *core.ConfigMapNodeConfigSource, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
// validate target configmap namespace
if source.Namespace == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("namespace"), "namespace must be set"))
} else {
for _, msg := range ValidateNameFunc(ValidateNamespaceName)(source.Namespace, false) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("namespace"), source.Namespace, msg))
}
}
// validate target configmap name
if source.Name == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("name"), "name must be set"))
} else {
for _, msg := range ValidateNameFunc(ValidateConfigMapName)(source.Name, false) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), source.Name, msg))
}
}
// validate kubeletConfigKey against rules for configMap key names
if source.KubeletConfigKey == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("kubeletConfigKey"), "kubeletConfigKey must be set"))
} else {
for _, msg := range validation.IsConfigMapKey(source.KubeletConfigKey) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("kubeletConfigKey"), source.KubeletConfigKey, msg))
}
}
return allErrs
}
// Validate compute resource typename.
// Refer to docs/design/resources.md for more details.
func validateResourceName(value string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for _, msg := range validation.IsQualifiedName(value) {
allErrs = append(allErrs, field.Invalid(fldPath, value, msg))
}
if len(allErrs) != 0 {
return allErrs
}
if len(strings.Split(value, "/")) == 1 {
if !helper.IsStandardResourceName(value) {
return append(allErrs, field.Invalid(fldPath, value, "must be a standard resource type or fully qualified"))
}
}
return allErrs
}
// Validate container resource name
// Refer to docs/design/resources.md for more details.
func validateContainerResourceName(value string, fldPath *field.Path) field.ErrorList {
allErrs := validateResourceName(value, fldPath)
if len(strings.Split(value, "/")) == 1 {
if !helper.IsStandardContainerResourceName(value) {
return append(allErrs, field.Invalid(fldPath, value, "must be a standard resource for containers"))
}
} else if !helper.IsNativeResource(core.ResourceName(value)) {
if !helper.IsExtendedResourceName(core.ResourceName(value)) {
return append(allErrs, field.Invalid(fldPath, value, "doesn't follow extended resource name standard"))
}
}
return allErrs
}
// Validate resource names that can go in a resource quota
// Refer to docs/design/resources.md for more details.
func ValidateResourceQuotaResourceName(value string, fldPath *field.Path) field.ErrorList {
allErrs := validateResourceName(value, fldPath)
if len(strings.Split(value, "/")) == 1 {
if !helper.IsStandardQuotaResourceName(value) {
return append(allErrs, field.Invalid(fldPath, value, isInvalidQuotaResource))
}
}
return allErrs
}
// Validate limit range types
func validateLimitRangeTypeName(value string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for _, msg := range validation.IsQualifiedName(value) {
allErrs = append(allErrs, field.Invalid(fldPath, value, msg))
}
if len(allErrs) != 0 {
return allErrs
}
if len(strings.Split(value, "/")) == 1 {
if !helper.IsStandardLimitRangeType(value) {
return append(allErrs, field.Invalid(fldPath, value, "must be a standard limit type or fully qualified"))
}
}
return allErrs
}
// Validate limit range resource name
// limit types (other than Pod/Container) could contain storage not just cpu or memory
func validateLimitRangeResourceName(limitType core.LimitType, value string, fldPath *field.Path) field.ErrorList {
switch limitType {
case core.LimitTypePod, core.LimitTypeContainer:
return validateContainerResourceName(value, fldPath)
default:
return validateResourceName(value, fldPath)
}
}
// ValidateLimitRange tests if required fields in the LimitRange are set.
func ValidateLimitRange(limitRange *core.LimitRange) field.ErrorList {
allErrs := ValidateObjectMeta(&limitRange.ObjectMeta, true, ValidateLimitRangeName, field.NewPath("metadata"))
// ensure resource names are properly qualified per docs/design/resources.md
limitTypeSet := map[core.LimitType]bool{}
fldPath := field.NewPath("spec", "limits")
for i := range limitRange.Spec.Limits {
idxPath := fldPath.Index(i)
limit := &limitRange.Spec.Limits[i]
allErrs = append(allErrs, validateLimitRangeTypeName(string(limit.Type), idxPath.Child("type"))...)
_, found := limitTypeSet[limit.Type]
if found {
allErrs = append(allErrs, field.Duplicate(idxPath.Child("type"), limit.Type))
}
limitTypeSet[limit.Type] = true
keys := sets.String{}
min := map[string]resource.Quantity{}
max := map[string]resource.Quantity{}
defaults := map[string]resource.Quantity{}
defaultRequests := map[string]resource.Quantity{}
maxLimitRequestRatios := map[string]resource.Quantity{}
for k, q := range limit.Max {
allErrs = append(allErrs, validateLimitRangeResourceName(limit.Type, string(k), idxPath.Child("max").Key(string(k)))...)
keys.Insert(string(k))
max[string(k)] = q
}
for k, q := range limit.Min {
allErrs = append(allErrs, validateLimitRangeResourceName(limit.Type, string(k), idxPath.Child("min").Key(string(k)))...)
keys.Insert(string(k))
min[string(k)] = q
}
if limit.Type == core.LimitTypePod {
if len(limit.Default) > 0 {
allErrs = append(allErrs, field.Forbidden(idxPath.Child("default"), "may not be specified when `type` is 'Pod'"))
}
if len(limit.DefaultRequest) > 0 {
allErrs = append(allErrs, field.Forbidden(idxPath.Child("defaultRequest"), "may not be specified when `type` is 'Pod'"))
}
} else {
for k, q := range limit.Default {
allErrs = append(allErrs, validateLimitRangeResourceName(limit.Type, string(k), idxPath.Child("default").Key(string(k)))...)
keys.Insert(string(k))
defaults[string(k)] = q
}
for k, q := range limit.DefaultRequest {
allErrs = append(allErrs, validateLimitRangeResourceName(limit.Type, string(k), idxPath.Child("defaultRequest").Key(string(k)))...)
keys.Insert(string(k))
defaultRequests[string(k)] = q
}
}
if limit.Type == core.LimitTypePersistentVolumeClaim {
_, minQuantityFound := limit.Min[core.ResourceStorage]
_, maxQuantityFound := limit.Max[core.ResourceStorage]
if !minQuantityFound && !maxQuantityFound {
allErrs = append(allErrs, field.Required(idxPath.Child("limits"), "either minimum or maximum storage value is required, but neither was provided"))
}
}
for k, q := range limit.MaxLimitRequestRatio {
allErrs = append(allErrs, validateLimitRangeResourceName(limit.Type, string(k), idxPath.Child("maxLimitRequestRatio").Key(string(k)))...)
keys.Insert(string(k))
maxLimitRequestRatios[string(k)] = q
}
for k := range keys {
minQuantity, minQuantityFound := min[k]
maxQuantity, maxQuantityFound := max[k]
defaultQuantity, defaultQuantityFound := defaults[k]
defaultRequestQuantity, defaultRequestQuantityFound := defaultRequests[k]
maxRatio, maxRatioFound := maxLimitRequestRatios[k]
if minQuantityFound && maxQuantityFound && minQuantity.Cmp(maxQuantity) > 0 {
allErrs = append(allErrs, field.Invalid(idxPath.Child("min").Key(string(k)), minQuantity, fmt.Sprintf("min value %s is greater than max value %s", minQuantity.String(), maxQuantity.String())))
}
if defaultRequestQuantityFound && minQuantityFound && minQuantity.Cmp(defaultRequestQuantity) > 0 {
allErrs = append(allErrs, field.Invalid(idxPath.Child("defaultRequest").Key(string(k)), defaultRequestQuantity, fmt.Sprintf("min value %s is greater than default request value %s", minQuantity.String(), defaultRequestQuantity.String())))
}
if defaultRequestQuantityFound && maxQuantityFound && defaultRequestQuantity.Cmp(maxQuantity) > 0 {
allErrs = append(allErrs, field.Invalid(idxPath.Child("defaultRequest").Key(string(k)), defaultRequestQuantity, fmt.Sprintf("default request value %s is greater than max value %s", defaultRequestQuantity.String(), maxQuantity.String())))
}
if defaultRequestQuantityFound && defaultQuantityFound && defaultRequestQuantity.Cmp(defaultQuantity) > 0 {
allErrs = append(allErrs, field.Invalid(idxPath.Child("defaultRequest").Key(string(k)), defaultRequestQuantity, fmt.Sprintf("default request value %s is greater than default limit value %s", defaultRequestQuantity.String(), defaultQuantity.String())))
}
if defaultQuantityFound && minQuantityFound && minQuantity.Cmp(defaultQuantity) > 0 {
allErrs = append(allErrs, field.Invalid(idxPath.Child("default").Key(string(k)), minQuantity, fmt.Sprintf("min value %s is greater than default value %s", minQuantity.String(), defaultQuantity.String())))
}
if defaultQuantityFound && maxQuantityFound && defaultQuantity.Cmp(maxQuantity) > 0 {
allErrs = append(allErrs, field.Invalid(idxPath.Child("default").Key(string(k)), maxQuantity, fmt.Sprintf("default value %s is greater than max value %s", defaultQuantity.String(), maxQuantity.String())))
}
if maxRatioFound && maxRatio.Cmp(*resource.NewQuantity(1, resource.DecimalSI)) < 0 {
allErrs = append(allErrs, field.Invalid(idxPath.Child("maxLimitRequestRatio").Key(string(k)), maxRatio, fmt.Sprintf("ratio %s is less than 1", maxRatio.String())))
}
if maxRatioFound && minQuantityFound && maxQuantityFound {
maxRatioValue := float64(maxRatio.Value())
minQuantityValue := minQuantity.Value()
maxQuantityValue := maxQuantity.Value()
if maxRatio.Value() < resource.MaxMilliValue && minQuantityValue < resource.MaxMilliValue && maxQuantityValue < resource.MaxMilliValue {
maxRatioValue = float64(maxRatio.MilliValue()) / 1000
minQuantityValue = minQuantity.MilliValue()
maxQuantityValue = maxQuantity.MilliValue()
}
maxRatioLimit := float64(maxQuantityValue) / float64(minQuantityValue)
if maxRatioValue > maxRatioLimit {
allErrs = append(allErrs, field.Invalid(idxPath.Child("maxLimitRequestRatio").Key(string(k)), maxRatio, fmt.Sprintf("ratio %s is greater than max/min = %f", maxRatio.String(), maxRatioLimit)))
}
}
// for GPU, hugepages and other resources that are not allowed to overcommit,
// the default value and defaultRequest value must match if both are specified
if !helper.IsOvercommitAllowed(core.ResourceName(k)) && defaultQuantityFound && defaultRequestQuantityFound && defaultQuantity.Cmp(defaultRequestQuantity) != 0 {
allErrs = append(allErrs, field.Invalid(idxPath.Child("defaultRequest").Key(string(k)), defaultRequestQuantity, fmt.Sprintf("default value %s must equal to defaultRequest value %s in %s", defaultQuantity.String(), defaultRequestQuantity.String(), k)))
}
}
}
return allErrs
}
// ValidateServiceAccount tests if required fields in the ServiceAccount are set.
func ValidateServiceAccount(serviceAccount *core.ServiceAccount) field.ErrorList {
allErrs := ValidateObjectMeta(&serviceAccount.ObjectMeta, true, ValidateServiceAccountName, field.NewPath("metadata"))
return allErrs
}
// ValidateServiceAccountUpdate tests if required fields in the ServiceAccount are set.
func ValidateServiceAccountUpdate(newServiceAccount, oldServiceAccount *core.ServiceAccount) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&newServiceAccount.ObjectMeta, &oldServiceAccount.ObjectMeta, field.NewPath("metadata"))
allErrs = append(allErrs, ValidateServiceAccount(newServiceAccount)...)
return allErrs
}
// ValidateSecret tests if required fields in the Secret are set.
func ValidateSecret(secret *core.Secret) field.ErrorList {
allErrs := ValidateObjectMeta(&secret.ObjectMeta, true, ValidateSecretName, field.NewPath("metadata"))
dataPath := field.NewPath("data")
totalSize := 0
for key, value := range secret.Data {
for _, msg := range validation.IsConfigMapKey(key) {
allErrs = append(allErrs, field.Invalid(dataPath.Key(key), key, msg))
}
totalSize += len(value)
}
if totalSize > core.MaxSecretSize {
allErrs = append(allErrs, field.TooLong(dataPath, "", core.MaxSecretSize))
}
switch secret.Type {
case core.SecretTypeServiceAccountToken:
// Only require Annotations[kubernetes.io/service-account.name]
// Additional fields (like Annotations[kubernetes.io/service-account.uid] and Data[token]) might be contributed later by a controller loop
if value := secret.Annotations[core.ServiceAccountNameKey]; len(value) == 0 {
allErrs = append(allErrs, field.Required(field.NewPath("metadata", "annotations").Key(core.ServiceAccountNameKey), ""))
}
case core.SecretTypeOpaque, "":
// no-op
case core.SecretTypeDockercfg:
dockercfgBytes, exists := secret.Data[core.DockerConfigKey]
if !exists {
allErrs = append(allErrs, field.Required(dataPath.Key(core.DockerConfigKey), ""))
break
}
// make sure that the content is well-formed json.
if err := json.Unmarshal(dockercfgBytes, &map[string]interface{}{}); err != nil {
allErrs = append(allErrs, field.Invalid(dataPath.Key(core.DockerConfigKey), "<secret contents redacted>", err.Error()))
}
case core.SecretTypeDockerConfigJSON:
dockerConfigJSONBytes, exists := secret.Data[core.DockerConfigJSONKey]
if !exists {
allErrs = append(allErrs, field.Required(dataPath.Key(core.DockerConfigJSONKey), ""))
break
}
// make sure that the content is well-formed json.
if err := json.Unmarshal(dockerConfigJSONBytes, &map[string]interface{}{}); err != nil {
allErrs = append(allErrs, field.Invalid(dataPath.Key(core.DockerConfigJSONKey), "<secret contents redacted>", err.Error()))
}
case core.SecretTypeBasicAuth:
_, usernameFieldExists := secret.Data[core.BasicAuthUsernameKey]
_, passwordFieldExists := secret.Data[core.BasicAuthPasswordKey]
// username or password might be empty, but the field must be present
if !usernameFieldExists && !passwordFieldExists {
allErrs = append(allErrs, field.Required(dataPath.Key(core.BasicAuthUsernameKey), ""))
allErrs = append(allErrs, field.Required(dataPath.Key(core.BasicAuthPasswordKey), ""))
break
}
case core.SecretTypeSSHAuth:
if len(secret.Data[core.SSHAuthPrivateKey]) == 0 {
allErrs = append(allErrs, field.Required(dataPath.Key(core.SSHAuthPrivateKey), ""))
break
}
case core.SecretTypeTLS:
if _, exists := secret.Data[core.TLSCertKey]; !exists {
allErrs = append(allErrs, field.Required(dataPath.Key(core.TLSCertKey), ""))
}
if _, exists := secret.Data[core.TLSPrivateKeyKey]; !exists {
allErrs = append(allErrs, field.Required(dataPath.Key(core.TLSPrivateKeyKey), ""))
}
// TODO: Verify that the key matches the cert.
default:
// no-op
}
return allErrs
}
// ValidateSecretUpdate tests if required fields in the Secret are set.
func ValidateSecretUpdate(newSecret, oldSecret *core.Secret) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&newSecret.ObjectMeta, &oldSecret.ObjectMeta, field.NewPath("metadata"))
allErrs = append(allErrs, ValidateImmutableField(newSecret.Type, oldSecret.Type, field.NewPath("type"))...)
if oldSecret.Immutable != nil && *oldSecret.Immutable {
if newSecret.Immutable == nil || !*newSecret.Immutable {
allErrs = append(allErrs, field.Forbidden(field.NewPath("immutable"), "field is immutable when `immutable` is set"))
}
if !reflect.DeepEqual(newSecret.Data, oldSecret.Data) {
allErrs = append(allErrs, field.Forbidden(field.NewPath("data"), "field is immutable when `immutable` is set"))
}
// We don't validate StringData, as it was already converted back to Data
// before validation is happening.
}
allErrs = append(allErrs, ValidateSecret(newSecret)...)
return allErrs
}
// ValidateConfigMapName can be used to check whether the given ConfigMap name is valid.
// Prefix indicates this name will be used as part of generation, in which case
// trailing dashes are allowed.
var ValidateConfigMapName = apimachineryvalidation.NameIsDNSSubdomain
// ValidateConfigMap tests whether required fields in the ConfigMap are set.
func ValidateConfigMap(cfg *core.ConfigMap) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, ValidateObjectMeta(&cfg.ObjectMeta, true, ValidateConfigMapName, field.NewPath("metadata"))...)
totalSize := 0
for key, value := range cfg.Data {
for _, msg := range validation.IsConfigMapKey(key) {
allErrs = append(allErrs, field.Invalid(field.NewPath("data").Key(key), key, msg))
}
// check if we have a duplicate key in the other bag
if _, isValue := cfg.BinaryData[key]; isValue {
msg := "duplicate of key present in binaryData"
allErrs = append(allErrs, field.Invalid(field.NewPath("data").Key(key), key, msg))
}
totalSize += len(value)
}
for key, value := range cfg.BinaryData {
for _, msg := range validation.IsConfigMapKey(key) {
allErrs = append(allErrs, field.Invalid(field.NewPath("binaryData").Key(key), key, msg))
}
totalSize += len(value)
}
if totalSize > core.MaxSecretSize {
// pass back "" to indicate that the error refers to the whole object.
allErrs = append(allErrs, field.TooLong(field.NewPath(""), cfg, core.MaxSecretSize))
}
return allErrs
}
// ValidateConfigMapUpdate tests if required fields in the ConfigMap are set.
func ValidateConfigMapUpdate(newCfg, oldCfg *core.ConfigMap) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, ValidateObjectMetaUpdate(&newCfg.ObjectMeta, &oldCfg.ObjectMeta, field.NewPath("metadata"))...)
if oldCfg.Immutable != nil && *oldCfg.Immutable {
if newCfg.Immutable == nil || !*newCfg.Immutable {
allErrs = append(allErrs, field.Forbidden(field.NewPath("immutable"), "field is immutable when `immutable` is set"))
}
if !reflect.DeepEqual(newCfg.Data, oldCfg.Data) {
allErrs = append(allErrs, field.Forbidden(field.NewPath("data"), "field is immutable when `immutable` is set"))
}
if !reflect.DeepEqual(newCfg.BinaryData, oldCfg.BinaryData) {
allErrs = append(allErrs, field.Forbidden(field.NewPath("binaryData"), "field is immutable when `immutable` is set"))
}
}
allErrs = append(allErrs, ValidateConfigMap(newCfg)...)
return allErrs
}
func validateBasicResource(quantity resource.Quantity, fldPath *field.Path) field.ErrorList {
if quantity.Value() < 0 {
return field.ErrorList{field.Invalid(fldPath, quantity.Value(), "must be a valid resource quantity")}
}
return field.ErrorList{}
}
// Validates resource requirement spec.
func ValidateResourceRequirements(requirements *core.ResourceRequirements, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
limPath := fldPath.Child("limits")
reqPath := fldPath.Child("requests")
limContainsCPUOrMemory := false
reqContainsCPUOrMemory := false
limContainsHugePages := false
reqContainsHugePages := false
supportedQoSComputeResources := sets.NewString(string(core.ResourceCPU), string(core.ResourceMemory))
for resourceName, quantity := range requirements.Limits {
fldPath := limPath.Key(string(resourceName))
// Validate resource name.
allErrs = append(allErrs, validateContainerResourceName(string(resourceName), fldPath)...)
// Validate resource quantity.
allErrs = append(allErrs, ValidateResourceQuantityValue(string(resourceName), quantity, fldPath)...)
if helper.IsHugePageResourceName(resourceName) {
limContainsHugePages = true
if err := validateResourceQuantityHugePageValue(resourceName, quantity, opts); err != nil {
allErrs = append(allErrs, field.Invalid(fldPath, quantity.String(), err.Error()))
}
}
if supportedQoSComputeResources.Has(string(resourceName)) {
limContainsCPUOrMemory = true
}
}
for resourceName, quantity := range requirements.Requests {
fldPath := reqPath.Key(string(resourceName))
// Validate resource name.
allErrs = append(allErrs, validateContainerResourceName(string(resourceName), fldPath)...)
// Validate resource quantity.
allErrs = append(allErrs, ValidateResourceQuantityValue(string(resourceName), quantity, fldPath)...)
// Check that request <= limit.
limitQuantity, exists := requirements.Limits[resourceName]
if exists {
// For non overcommitable resources, not only requests can't exceed limits, they also can't be lower, i.e. must be equal.
if quantity.Cmp(limitQuantity) != 0 && !helper.IsOvercommitAllowed(resourceName) {
allErrs = append(allErrs, field.Invalid(reqPath, quantity.String(), fmt.Sprintf("must be equal to %s limit", resourceName)))
} else if quantity.Cmp(limitQuantity) > 0 {
allErrs = append(allErrs, field.Invalid(reqPath, quantity.String(), fmt.Sprintf("must be less than or equal to %s limit", resourceName)))
}
} else if !helper.IsOvercommitAllowed(resourceName) {
allErrs = append(allErrs, field.Required(limPath, "Limit must be set for non overcommitable resources"))
}
if helper.IsHugePageResourceName(resourceName) {
reqContainsHugePages = true
if err := validateResourceQuantityHugePageValue(resourceName, quantity, opts); err != nil {
allErrs = append(allErrs, field.Invalid(fldPath, quantity.String(), err.Error()))
}
}
if supportedQoSComputeResources.Has(string(resourceName)) {
reqContainsCPUOrMemory = true
}
}
if !limContainsCPUOrMemory && !reqContainsCPUOrMemory && (reqContainsHugePages || limContainsHugePages) {
allErrs = append(allErrs, field.Forbidden(fldPath, "HugePages require cpu or memory"))
}
return allErrs
}
func validateResourceQuantityHugePageValue(name core.ResourceName, quantity resource.Quantity, opts PodValidationOptions) error {
if !helper.IsHugePageResourceName(name) {
return nil
}
if !opts.AllowIndivisibleHugePagesValues && !helper.IsHugePageResourceValueDivisible(name, quantity) {
return fmt.Errorf("%s is not positive integer multiple of %s", quantity.String(), name)
}
return nil
}
// validateResourceQuotaScopes ensures that each enumerated hard resource constraint is valid for set of scopes
func validateResourceQuotaScopes(resourceQuotaSpec *core.ResourceQuotaSpec, fld *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(resourceQuotaSpec.Scopes) == 0 {
return allErrs
}
hardLimits := sets.NewString()
for k := range resourceQuotaSpec.Hard {
hardLimits.Insert(string(k))
}
fldPath := fld.Child("scopes")
scopeSet := sets.NewString()
for _, scope := range resourceQuotaSpec.Scopes {
if !helper.IsStandardResourceQuotaScope(string(scope)) {
allErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.Scopes, "unsupported scope"))
}
for _, k := range hardLimits.List() {
if helper.IsStandardQuotaResourceName(k) && !helper.IsResourceQuotaScopeValidForResource(scope, k) {
allErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.Scopes, "unsupported scope applied to resource"))
}
}
scopeSet.Insert(string(scope))
}
invalidScopePairs := []sets.String{
sets.NewString(string(core.ResourceQuotaScopeBestEffort), string(core.ResourceQuotaScopeNotBestEffort)),
sets.NewString(string(core.ResourceQuotaScopeTerminating), string(core.ResourceQuotaScopeNotTerminating)),
}
for _, invalidScopePair := range invalidScopePairs {
if scopeSet.HasAll(invalidScopePair.List()...) {
allErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.Scopes, "conflicting scopes"))
}
}
return allErrs
}
// validateScopedResourceSelectorRequirement tests that the match expressions has valid data
func validateScopedResourceSelectorRequirement(resourceQuotaSpec *core.ResourceQuotaSpec, fld *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
hardLimits := sets.NewString()
for k := range resourceQuotaSpec.Hard {
hardLimits.Insert(string(k))
}
fldPath := fld.Child("matchExpressions")
scopeSet := sets.NewString()
for _, req := range resourceQuotaSpec.ScopeSelector.MatchExpressions {
if !helper.IsStandardResourceQuotaScope(string(req.ScopeName)) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("scopeName"), req.ScopeName, "unsupported scope"))
}
for _, k := range hardLimits.List() {
if helper.IsStandardQuotaResourceName(k) && !helper.IsResourceQuotaScopeValidForResource(req.ScopeName, k) {
allErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.ScopeSelector, "unsupported scope applied to resource"))
}
}
switch req.ScopeName {
case core.ResourceQuotaScopeBestEffort, core.ResourceQuotaScopeNotBestEffort, core.ResourceQuotaScopeTerminating, core.ResourceQuotaScopeNotTerminating, core.ResourceQuotaScopeCrossNamespacePodAffinity:
if req.Operator != core.ScopeSelectorOpExists {
allErrs = append(allErrs, field.Invalid(fldPath.Child("operator"), req.Operator,
"must be 'Exist' when scope is any of ResourceQuotaScopeTerminating, ResourceQuotaScopeNotTerminating, ResourceQuotaScopeBestEffort, ResourceQuotaScopeNotBestEffort or ResourceQuotaScopeCrossNamespacePodAffinity"))
}
}
switch req.Operator {
case core.ScopeSelectorOpIn, core.ScopeSelectorOpNotIn:
if len(req.Values) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("values"),
"must be at least one value when `operator` is 'In' or 'NotIn' for scope selector"))
}
case core.ScopeSelectorOpExists, core.ScopeSelectorOpDoesNotExist:
if len(req.Values) != 0 {
allErrs = append(allErrs, field.Invalid(fldPath.Child("values"), req.Values,
"must be no value when `operator` is 'Exist' or 'DoesNotExist' for scope selector"))
}
default:
allErrs = append(allErrs, field.Invalid(fldPath.Child("operator"), req.Operator, "not a valid selector operator"))
}
scopeSet.Insert(string(req.ScopeName))
}
invalidScopePairs := []sets.String{
sets.NewString(string(core.ResourceQuotaScopeBestEffort), string(core.ResourceQuotaScopeNotBestEffort)),
sets.NewString(string(core.ResourceQuotaScopeTerminating), string(core.ResourceQuotaScopeNotTerminating)),
}
for _, invalidScopePair := range invalidScopePairs {
if scopeSet.HasAll(invalidScopePair.List()...) {
allErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.Scopes, "conflicting scopes"))
}
}
return allErrs
}
// validateScopeSelector tests that the specified scope selector has valid data
func validateScopeSelector(resourceQuotaSpec *core.ResourceQuotaSpec, fld *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if resourceQuotaSpec.ScopeSelector == nil {
return allErrs
}
allErrs = append(allErrs, validateScopedResourceSelectorRequirement(resourceQuotaSpec, fld.Child("scopeSelector"))...)
return allErrs
}
// ValidateResourceQuota tests if required fields in the ResourceQuota are set.
func ValidateResourceQuota(resourceQuota *core.ResourceQuota) field.ErrorList {
allErrs := ValidateObjectMeta(&resourceQuota.ObjectMeta, true, ValidateResourceQuotaName, field.NewPath("metadata"))
allErrs = append(allErrs, ValidateResourceQuotaSpec(&resourceQuota.Spec, field.NewPath("spec"))...)
allErrs = append(allErrs, ValidateResourceQuotaStatus(&resourceQuota.Status, field.NewPath("status"))...)
return allErrs
}
func ValidateResourceQuotaStatus(status *core.ResourceQuotaStatus, fld *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
fldPath := fld.Child("hard")
for k, v := range status.Hard {
resPath := fldPath.Key(string(k))
allErrs = append(allErrs, ValidateResourceQuotaResourceName(string(k), resPath)...)
allErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...)
}
fldPath = fld.Child("used")
for k, v := range status.Used {
resPath := fldPath.Key(string(k))
allErrs = append(allErrs, ValidateResourceQuotaResourceName(string(k), resPath)...)
allErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...)
}
return allErrs
}
func ValidateResourceQuotaSpec(resourceQuotaSpec *core.ResourceQuotaSpec, fld *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
fldPath := fld.Child("hard")
for k, v := range resourceQuotaSpec.Hard {
resPath := fldPath.Key(string(k))
allErrs = append(allErrs, ValidateResourceQuotaResourceName(string(k), resPath)...)
allErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...)
}
allErrs = append(allErrs, validateResourceQuotaScopes(resourceQuotaSpec, fld)...)
allErrs = append(allErrs, validateScopeSelector(resourceQuotaSpec, fld)...)
return allErrs
}
// ValidateResourceQuantityValue enforces that specified quantity is valid for specified resource
func ValidateResourceQuantityValue(resource string, value resource.Quantity, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, ValidateNonnegativeQuantity(value, fldPath)...)
if helper.IsIntegerResourceName(resource) {
if value.MilliValue()%int64(1000) != int64(0) {
allErrs = append(allErrs, field.Invalid(fldPath, value, isNotIntegerErrorMsg))
}
}
return allErrs
}
// ValidateResourceQuotaUpdate tests to see if the update is legal for an end user to make.
func ValidateResourceQuotaUpdate(newResourceQuota, oldResourceQuota *core.ResourceQuota) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&newResourceQuota.ObjectMeta, &oldResourceQuota.ObjectMeta, field.NewPath("metadata"))
allErrs = append(allErrs, ValidateResourceQuotaSpec(&newResourceQuota.Spec, field.NewPath("spec"))...)
// ensure scopes cannot change, and that resources are still valid for scope
fldPath := field.NewPath("spec", "scopes")
oldScopes := sets.NewString()
newScopes := sets.NewString()
for _, scope := range newResourceQuota.Spec.Scopes {
newScopes.Insert(string(scope))
}
for _, scope := range oldResourceQuota.Spec.Scopes {
oldScopes.Insert(string(scope))
}
if !oldScopes.Equal(newScopes) {
allErrs = append(allErrs, field.Invalid(fldPath, newResourceQuota.Spec.Scopes, fieldImmutableErrorMsg))
}
return allErrs
}
// ValidateResourceQuotaStatusUpdate tests to see if the status update is legal for an end user to make.
func ValidateResourceQuotaStatusUpdate(newResourceQuota, oldResourceQuota *core.ResourceQuota) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&newResourceQuota.ObjectMeta, &oldResourceQuota.ObjectMeta, field.NewPath("metadata"))
if len(newResourceQuota.ResourceVersion) == 0 {
allErrs = append(allErrs, field.Required(field.NewPath("resourceVersion"), ""))
}
fldPath := field.NewPath("status", "hard")
for k, v := range newResourceQuota.Status.Hard {
resPath := fldPath.Key(string(k))
allErrs = append(allErrs, ValidateResourceQuotaResourceName(string(k), resPath)...)
allErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...)
}
fldPath = field.NewPath("status", "used")
for k, v := range newResourceQuota.Status.Used {
resPath := fldPath.Key(string(k))
allErrs = append(allErrs, ValidateResourceQuotaResourceName(string(k), resPath)...)
allErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...)
}
return allErrs
}
// ValidateNamespace tests if required fields are set.
func ValidateNamespace(namespace *core.Namespace) field.ErrorList {
allErrs := ValidateObjectMeta(&namespace.ObjectMeta, false, ValidateNamespaceName, field.NewPath("metadata"))
for i := range namespace.Spec.Finalizers {
allErrs = append(allErrs, validateFinalizerName(string(namespace.Spec.Finalizers[i]), field.NewPath("spec", "finalizers"))...)
}
return allErrs
}
// Validate finalizer names
func validateFinalizerName(stringValue string, fldPath *field.Path) field.ErrorList {
allErrs := apimachineryvalidation.ValidateFinalizerName(stringValue, fldPath)
allErrs = append(allErrs, validateKubeFinalizerName(stringValue, fldPath)...)
return allErrs
}
// validateKubeFinalizerName checks for "standard" names of legacy finalizer
func validateKubeFinalizerName(stringValue string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(strings.Split(stringValue, "/")) == 1 {
if !helper.IsStandardFinalizerName(stringValue) {
return append(allErrs, field.Invalid(fldPath, stringValue, "name is neither a standard finalizer name nor is it fully qualified"))
}
}
return allErrs
}
// ValidateNamespaceUpdate tests to make sure a namespace update can be applied.
func ValidateNamespaceUpdate(newNamespace *core.Namespace, oldNamespace *core.Namespace) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&newNamespace.ObjectMeta, &oldNamespace.ObjectMeta, field.NewPath("metadata"))
return allErrs
}
// ValidateNamespaceStatusUpdate tests to see if the update is legal for an end user to make.
func ValidateNamespaceStatusUpdate(newNamespace, oldNamespace *core.Namespace) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&newNamespace.ObjectMeta, &oldNamespace.ObjectMeta, field.NewPath("metadata"))
if newNamespace.DeletionTimestamp.IsZero() {
if newNamespace.Status.Phase != core.NamespaceActive {
allErrs = append(allErrs, field.Invalid(field.NewPath("status", "Phase"), newNamespace.Status.Phase, "may only be 'Active' if `deletionTimestamp` is empty"))
}
} else {
if newNamespace.Status.Phase != core.NamespaceTerminating {
allErrs = append(allErrs, field.Invalid(field.NewPath("status", "Phase"), newNamespace.Status.Phase, "may only be 'Terminating' if `deletionTimestamp` is not empty"))
}
}
return allErrs
}
// ValidateNamespaceFinalizeUpdate tests to see if the update is legal for an end user to make.
func ValidateNamespaceFinalizeUpdate(newNamespace, oldNamespace *core.Namespace) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&newNamespace.ObjectMeta, &oldNamespace.ObjectMeta, field.NewPath("metadata"))
fldPath := field.NewPath("spec", "finalizers")
for i := range newNamespace.Spec.Finalizers {
idxPath := fldPath.Index(i)
allErrs = append(allErrs, validateFinalizerName(string(newNamespace.Spec.Finalizers[i]), idxPath)...)
}
return allErrs
}
// ValidateEndpoints validates Endpoints on create and update.
func ValidateEndpoints(endpoints *core.Endpoints) field.ErrorList {
allErrs := ValidateObjectMeta(&endpoints.ObjectMeta, true, ValidateEndpointsName, field.NewPath("metadata"))
allErrs = append(allErrs, ValidateEndpointsSpecificAnnotations(endpoints.Annotations, field.NewPath("annotations"))...)
allErrs = append(allErrs, validateEndpointSubsets(endpoints.Subsets, field.NewPath("subsets"))...)
return allErrs
}
// ValidateEndpointsCreate validates Endpoints on create.
func ValidateEndpointsCreate(endpoints *core.Endpoints) field.ErrorList {
return ValidateEndpoints(endpoints)
}
// ValidateEndpointsUpdate validates Endpoints on update. NodeName changes are
// allowed during update to accommodate the case where nodeIP or PodCIDR is
// reused. An existing endpoint ip will have a different nodeName if this
// happens.
func ValidateEndpointsUpdate(newEndpoints, oldEndpoints *core.Endpoints) field.ErrorList {
allErrs := ValidateObjectMetaUpdate(&newEndpoints.ObjectMeta, &oldEndpoints.ObjectMeta, field.NewPath("metadata"))
allErrs = append(allErrs, ValidateEndpoints(newEndpoints)...)
return allErrs
}
func validateEndpointSubsets(subsets []core.EndpointSubset, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for i := range subsets {
ss := &subsets[i]
idxPath := fldPath.Index(i)
// EndpointSubsets must include endpoint address. For headless service, we allow its endpoints not to have ports.
if len(ss.Addresses) == 0 && len(ss.NotReadyAddresses) == 0 {
//TODO: consider adding a RequiredOneOf() error for this and similar cases
allErrs = append(allErrs, field.Required(idxPath, "must specify `addresses` or `notReadyAddresses`"))
}
for addr := range ss.Addresses {
allErrs = append(allErrs, validateEndpointAddress(&ss.Addresses[addr], idxPath.Child("addresses").Index(addr))...)
}
for addr := range ss.NotReadyAddresses {
allErrs = append(allErrs, validateEndpointAddress(&ss.NotReadyAddresses[addr], idxPath.Child("notReadyAddresses").Index(addr))...)
}
for port := range ss.Ports {
allErrs = append(allErrs, validateEndpointPort(&ss.Ports[port], len(ss.Ports) > 1, idxPath.Child("ports").Index(port))...)
}
}
return allErrs
}
func validateEndpointAddress(address *core.EndpointAddress, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for _, msg := range validation.IsValidIP(address.IP) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("ip"), address.IP, msg))
}
if len(address.Hostname) > 0 {
allErrs = append(allErrs, ValidateDNS1123Label(address.Hostname, fldPath.Child("hostname"))...)
}
// During endpoint update, verify that NodeName is a DNS subdomain and transition rules allow the update
if address.NodeName != nil {
for _, msg := range ValidateNodeName(*address.NodeName, false) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("nodeName"), *address.NodeName, msg))
}
}
allErrs = append(allErrs, ValidateNonSpecialIP(address.IP, fldPath.Child("ip"))...)
return allErrs
}
// ValidateNonSpecialIP is used to validate Endpoints, EndpointSlices, and
// external IPs. Specifically, this disallows unspecified and loopback addresses
// are nonsensical and link-local addresses tend to be used for node-centric
// purposes (e.g. metadata service).
//
// IPv6 references
// - https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
// - https://www.iana.org/assignments/ipv6-multicast-addresses/ipv6-multicast-addresses.xhtml
func ValidateNonSpecialIP(ipAddress string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
ip := netutils.ParseIPSloppy(ipAddress)
if ip == nil {
allErrs = append(allErrs, field.Invalid(fldPath, ipAddress, "must be a valid IP address"))
return allErrs
}
if ip.IsUnspecified() {
allErrs = append(allErrs, field.Invalid(fldPath, ipAddress, fmt.Sprintf("may not be unspecified (%v)", ipAddress)))
}
if ip.IsLoopback() {
allErrs = append(allErrs, field.Invalid(fldPath, ipAddress, "may not be in the loopback range (127.0.0.0/8, ::1/128)"))
}
if ip.IsLinkLocalUnicast() {
allErrs = append(allErrs, field.Invalid(fldPath, ipAddress, "may not be in the link-local range (169.254.0.0/16, fe80::/10)"))
}
if ip.IsLinkLocalMulticast() {
allErrs = append(allErrs, field.Invalid(fldPath, ipAddress, "may not be in the link-local multicast range (224.0.0.0/24, ff02::/10)"))
}
return allErrs
}
func validateEndpointPort(port *core.EndpointPort, requireName bool, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if requireName && len(port.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("name"), ""))
} else if len(port.Name) != 0 {
allErrs = append(allErrs, ValidateDNS1123Label(port.Name, fldPath.Child("name"))...)
}
for _, msg := range validation.IsValidPortNum(int(port.Port)) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("port"), port.Port, msg))
}
if len(port.Protocol) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("protocol"), ""))
} else if !supportedPortProtocols.Has(string(port.Protocol)) {
allErrs = append(allErrs, field.NotSupported(fldPath.Child("protocol"), port.Protocol, supportedPortProtocols.List()))
}
if port.AppProtocol != nil {
for _, msg := range validation.IsQualifiedName(*port.AppProtocol) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("appProtocol"), port.AppProtocol, msg))
}
}
return allErrs
}
// ValidateSecurityContext ensures the security context contains valid settings
func ValidateSecurityContext(sc *core.SecurityContext, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
//this should only be true for testing since SecurityContext is defaulted by the core
if sc == nil {
return allErrs
}
if sc.Privileged != nil {
if *sc.Privileged && !capabilities.Get().AllowPrivileged {
allErrs = append(allErrs, field.Forbidden(fldPath.Child("privileged"), "disallowed by cluster policy"))
}
}
if sc.RunAsUser != nil {
for _, msg := range validation.IsValidUserID(*sc.RunAsUser) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("runAsUser"), *sc.RunAsUser, msg))
}
}
if sc.RunAsGroup != nil {
for _, msg := range validation.IsValidGroupID(*sc.RunAsGroup) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("runAsGroup"), *sc.RunAsGroup, msg))
}
}
if sc.ProcMount != nil {
if err := ValidateProcMountType(fldPath.Child("procMount"), *sc.ProcMount); err != nil {
allErrs = append(allErrs, err)
}
}
allErrs = append(allErrs, validateSeccompProfileField(sc.SeccompProfile, fldPath.Child("seccompProfile"))...)
if sc.AllowPrivilegeEscalation != nil && !*sc.AllowPrivilegeEscalation {
if sc.Privileged != nil && *sc.Privileged {
allErrs = append(allErrs, field.Invalid(fldPath, sc, "cannot set `allowPrivilegeEscalation` to false and `privileged` to true"))
}
if sc.Capabilities != nil {
for _, cap := range sc.Capabilities.Add {
if string(cap) == "CAP_SYS_ADMIN" {
allErrs = append(allErrs, field.Invalid(fldPath, sc, "cannot set `allowPrivilegeEscalation` to false and `capabilities.Add` CAP_SYS_ADMIN"))
}
}
}
}
allErrs = append(allErrs, validateWindowsSecurityContextOptions(sc.WindowsOptions, fldPath.Child("windowsOptions"))...)
return allErrs
}
// maxGMSACredentialSpecLength is the max length, in bytes, for the actual contents
// of a GMSA cred spec. In general, those shouldn't be more than a few hundred bytes,
// so we want to give plenty of room here while still providing an upper bound.
// The runAsUserName field will be used to execute the given container's entrypoint, and
// it can be formatted as "DOMAIN/USER", where the DOMAIN is optional, maxRunAsUserNameDomainLength
// is the max character length for the user's DOMAIN, and maxRunAsUserNameUserLength
// is the max character length for the USER itself. Both the DOMAIN and USER have their
// own restrictions, and more information about them can be found here:
// https://support.microsoft.com/en-us/help/909264/naming-conventions-in-active-directory-for-computers-domains-sites-and
// https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-2000-server/bb726984(v=technet.10)
const (
maxGMSACredentialSpecLengthInKiB = 64
maxGMSACredentialSpecLength = maxGMSACredentialSpecLengthInKiB * 1024
maxRunAsUserNameDomainLength = 256
maxRunAsUserNameUserLength = 104
)
var (
// control characters are not permitted in the runAsUserName field.
ctrlRegex = regexp.MustCompile(`[[:cntrl:]]+`)
// a valid NetBios Domain name cannot start with a dot, has at least 1 character,
// at most 15 characters, and it cannot the characters: \ / : * ? " < > |
validNetBiosRegex = regexp.MustCompile(`^[^\\/:\*\?"<>|\.][^\\/:\*\?"<>|]{0,14}$`)
// a valid DNS name contains only alphanumeric characters, dots, and dashes.
dnsLabelFormat = `[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?`
dnsSubdomainFormat = fmt.Sprintf(`^%s(?:\.%s)*$`, dnsLabelFormat, dnsLabelFormat)
validWindowsUserDomainDNSRegex = regexp.MustCompile(dnsSubdomainFormat)
// a username is invalid if it contains the characters: " / \ [ ] : ; | = , + * ? < > @
// or it contains only dots or spaces.
invalidUserNameCharsRegex = regexp.MustCompile(`["/\\:;|=,\+\*\?<>@\[\]]`)
invalidUserNameDotsSpacesRegex = regexp.MustCompile(`^[\. ]+$`)
)
func validateWindowsSecurityContextOptions(windowsOptions *core.WindowsSecurityContextOptions, fieldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if windowsOptions == nil {
return allErrs
}
if windowsOptions.GMSACredentialSpecName != nil {
// gmsaCredentialSpecName must be the name of a custom resource
for _, msg := range validation.IsDNS1123Subdomain(*windowsOptions.GMSACredentialSpecName) {
allErrs = append(allErrs, field.Invalid(fieldPath.Child("gmsaCredentialSpecName"), windowsOptions.GMSACredentialSpecName, msg))
}
}
if windowsOptions.GMSACredentialSpec != nil {
if l := len(*windowsOptions.GMSACredentialSpec); l == 0 {
allErrs = append(allErrs, field.Invalid(fieldPath.Child("gmsaCredentialSpec"), windowsOptions.GMSACredentialSpec, "gmsaCredentialSpec cannot be an empty string"))
} else if l > maxGMSACredentialSpecLength {
errMsg := fmt.Sprintf("gmsaCredentialSpec size must be under %d KiB", maxGMSACredentialSpecLengthInKiB)
allErrs = append(allErrs, field.Invalid(fieldPath.Child("gmsaCredentialSpec"), windowsOptions.GMSACredentialSpec, errMsg))
}
}
if windowsOptions.RunAsUserName != nil {
if l := len(*windowsOptions.RunAsUserName); l == 0 {
allErrs = append(allErrs, field.Invalid(fieldPath.Child("runAsUserName"), windowsOptions.RunAsUserName, "runAsUserName cannot be an empty string"))
} else if ctrlRegex.MatchString(*windowsOptions.RunAsUserName) {
errMsg := "runAsUserName cannot contain control characters"
allErrs = append(allErrs, field.Invalid(fieldPath.Child("runAsUserName"), windowsOptions.RunAsUserName, errMsg))
} else if parts := strings.Split(*windowsOptions.RunAsUserName, "\\"); len(parts) > 2 {
errMsg := "runAsUserName cannot contain more than one backslash"
allErrs = append(allErrs, field.Invalid(fieldPath.Child("runAsUserName"), windowsOptions.RunAsUserName, errMsg))
} else {
var (
hasDomain = false
domain = ""
user string
)
if len(parts) == 1 {
user = parts[0]
} else {
hasDomain = true
domain = parts[0]
user = parts[1]
}
if len(domain) >= maxRunAsUserNameDomainLength {
errMsg := fmt.Sprintf("runAsUserName's Domain length must be under %d characters", maxRunAsUserNameDomainLength)
allErrs = append(allErrs, field.Invalid(fieldPath.Child("runAsUserName"), windowsOptions.RunAsUserName, errMsg))
}
if hasDomain && !(validNetBiosRegex.MatchString(domain) || validWindowsUserDomainDNSRegex.MatchString(domain)) {
errMsg := "runAsUserName's Domain doesn't match the NetBios nor the DNS format"
allErrs = append(allErrs, field.Invalid(fieldPath.Child("runAsUserName"), windowsOptions.RunAsUserName, errMsg))
}
if l := len(user); l == 0 {
errMsg := "runAsUserName's User cannot be empty"
allErrs = append(allErrs, field.Invalid(fieldPath.Child("runAsUserName"), windowsOptions.RunAsUserName, errMsg))
} else if l > maxRunAsUserNameUserLength {
errMsg := fmt.Sprintf("runAsUserName's User length must not be longer than %d characters", maxRunAsUserNameUserLength)
allErrs = append(allErrs, field.Invalid(fieldPath.Child("runAsUserName"), windowsOptions.RunAsUserName, errMsg))
}
if invalidUserNameDotsSpacesRegex.MatchString(user) {
errMsg := `runAsUserName's User cannot contain only periods or spaces`
allErrs = append(allErrs, field.Invalid(fieldPath.Child("runAsUserName"), windowsOptions.RunAsUserName, errMsg))
}
if invalidUserNameCharsRegex.MatchString(user) {
errMsg := `runAsUserName's User cannot contain the following characters: "/\:;|=,+*?<>@[]`
allErrs = append(allErrs, field.Invalid(fieldPath.Child("runAsUserName"), windowsOptions.RunAsUserName, errMsg))
}
}
}
return allErrs
}
func validateWindowsHostProcessPod(podSpec *core.PodSpec, fieldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
// Keep track of container and hostProcess container count for validate
containerCount := 0
hostProcessContainerCount := 0
var podHostProcess *bool
if podSpec.SecurityContext != nil && podSpec.SecurityContext.WindowsOptions != nil {
podHostProcess = podSpec.SecurityContext.WindowsOptions.HostProcess
}
if !opts.AllowWindowsHostProcessField && podHostProcess != nil {
// Do not allow pods to persist data that sets hostProcess (true or false)
errMsg := "not allowed when feature gate 'WindowsHostProcessContainers' is not enabled"
allErrs = append(allErrs, field.Forbidden(fieldPath.Child("securityContext", "windowsOptions", "hostProcess"), errMsg))
return allErrs
}
hostNetwork := false
if podSpec.SecurityContext != nil {
hostNetwork = podSpec.SecurityContext.HostNetwork
}
podshelper.VisitContainersWithPath(podSpec, fieldPath, func(c *core.Container, cFieldPath *field.Path) bool {
containerCount++
var containerHostProcess *bool = nil
if c.SecurityContext != nil && c.SecurityContext.WindowsOptions != nil {
containerHostProcess = c.SecurityContext.WindowsOptions.HostProcess
}
if !opts.AllowWindowsHostProcessField && containerHostProcess != nil {
// Do not allow pods to persist data that sets hostProcess (true or false)
errMsg := "not allowed when feature gate 'WindowsHostProcessContainers' is not enabled"
allErrs = append(allErrs, field.Forbidden(cFieldPath.Child("securityContext", "windowsOptions", "hostProcess"), errMsg))
}
if podHostProcess != nil && containerHostProcess != nil && *podHostProcess != *containerHostProcess {
errMsg := fmt.Sprintf("pod hostProcess value must be identical if both are specified, was %v", *podHostProcess)
allErrs = append(allErrs, field.Invalid(cFieldPath.Child("securityContext", "windowsOptions", "hostProcess"), *containerHostProcess, errMsg))
}
switch {
case containerHostProcess != nil && *containerHostProcess:
// Container explitly sets hostProcess=true
hostProcessContainerCount++
case containerHostProcess == nil && podHostProcess != nil && *podHostProcess:
// Container inherits hostProcess=true from pod settings
hostProcessContainerCount++
}
return true
})
if hostProcessContainerCount > 0 {
// Fail Pod validation if feature is not enabled (unless podspec already exists and contains HostProcess fields) instead of dropping fields based on PRR reivew.
if !opts.AllowWindowsHostProcessField {
errMsg := "pod must not contain Windows hostProcess containers when feature gate 'WindowsHostProcessContainers' is not enabled"
allErrs = append(allErrs, field.Forbidden(fieldPath, errMsg))
return allErrs
}
// At present, if a Windows Pods contains any HostProcess containers than all containers must be
// HostProcess containers (explicitly set or inherited).
if hostProcessContainerCount != containerCount {
errMsg := "If pod contains any hostProcess containers then all containers must be HostProcess containers"
allErrs = append(allErrs, field.Invalid(fieldPath, "", errMsg))
}
// At present Windows Pods which contain HostProcess containers must also set HostNetwork.
if !hostNetwork {
errMsg := "hostNetwork must be true if pod contains any hostProcess containers"
allErrs = append(allErrs, field.Invalid(fieldPath.Child("hostNetwork"), hostNetwork, errMsg))
}
if !capabilities.Get().AllowPrivileged {
errMsg := "hostProcess containers are disallowed by cluster policy"
allErrs = append(allErrs, field.Forbidden(fieldPath, errMsg))
}
}
return allErrs
}
// validateOS validates the OS field within pod spec
func validateOS(podSpec *core.PodSpec, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {
allErrs := field.ErrorList{}
os := podSpec.OS
if os == nil {
return allErrs
}
if !opts.AllowOSField {
return append(allErrs, field.Forbidden(fldPath, "cannot be set when IdentifyPodOS feature is not enabled"))
}
if len(os.Name) == 0 {
return append(allErrs, field.Required(fldPath.Child("name"), "cannot be empty"))
}
osName := string(os.Name)
if !validOS.Has(osName) {
allErrs = append(allErrs, field.NotSupported(fldPath, osName, validOS.List()))
}
return allErrs
}
func ValidatePodLogOptions(opts *core.PodLogOptions) field.ErrorList {
allErrs := field.ErrorList{}
if opts.TailLines != nil && *opts.TailLines < 0 {
allErrs = append(allErrs, field.Invalid(field.NewPath("tailLines"), *opts.TailLines, isNegativeErrorMsg))
}
if opts.LimitBytes != nil && *opts.LimitBytes < 1 {
allErrs = append(allErrs, field.Invalid(field.NewPath("limitBytes"), *opts.LimitBytes, "must be greater than 0"))
}
switch {
case opts.SinceSeconds != nil && opts.SinceTime != nil:
allErrs = append(allErrs, field.Forbidden(field.NewPath(""), "at most one of `sinceTime` or `sinceSeconds` may be specified"))
case opts.SinceSeconds != nil:
if *opts.SinceSeconds < 1 {
allErrs = append(allErrs, field.Invalid(field.NewPath("sinceSeconds"), *opts.SinceSeconds, "must be greater than 0"))
}
}
return allErrs
}
// ValidateLoadBalancerStatus validates required fields on a LoadBalancerStatus
func ValidateLoadBalancerStatus(status *core.LoadBalancerStatus, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for i, ingress := range status.Ingress {
idxPath := fldPath.Child("ingress").Index(i)
if len(ingress.IP) > 0 {
if isIP := (netutils.ParseIPSloppy(ingress.IP) != nil); !isIP {
allErrs = append(allErrs, field.Invalid(idxPath.Child("ip"), ingress.IP, "must be a valid IP address"))
}
}
if len(ingress.Hostname) > 0 {
for _, msg := range validation.IsDNS1123Subdomain(ingress.Hostname) {
allErrs = append(allErrs, field.Invalid(idxPath.Child("hostname"), ingress.Hostname, msg))
}
if isIP := (netutils.ParseIPSloppy(ingress.Hostname) != nil); isIP {
allErrs = append(allErrs, field.Invalid(idxPath.Child("hostname"), ingress.Hostname, "must be a DNS name, not an IP address"))
}
}
}
return allErrs
}
// validateVolumeNodeAffinity tests that the PersistentVolume.NodeAffinity has valid data
// returns:
// - true if volumeNodeAffinity is set
// - errorList if there are validation errors
func validateVolumeNodeAffinity(nodeAffinity *core.VolumeNodeAffinity, fldPath *field.Path) (bool, field.ErrorList) {
allErrs := field.ErrorList{}
if nodeAffinity == nil {
return false, allErrs
}
if nodeAffinity.Required != nil {
allErrs = append(allErrs, ValidateNodeSelector(nodeAffinity.Required, fldPath.Child("required"))...)
} else {
allErrs = append(allErrs, field.Required(fldPath.Child("required"), "must specify required node constraints"))
}
return true, allErrs
}
// ValidateCIDR validates whether a CIDR matches the conventions expected by net.ParseCIDR
func ValidateCIDR(cidr string) (*net.IPNet, error) {
_, net, err := netutils.ParseCIDRSloppy(cidr)
if err != nil {
return nil, err
}
return net, nil
}
func IsDecremented(update, old *int32) bool {
if update == nil && old != nil {
return true
}
if update == nil || old == nil {
return false
}
return *update < *old
}
// ValidateProcMountType tests that the argument is a valid ProcMountType.
func ValidateProcMountType(fldPath *field.Path, procMountType core.ProcMountType) *field.Error {
switch procMountType {
case core.DefaultProcMount, core.UnmaskedProcMount:
return nil
default:
return field.NotSupported(fldPath, procMountType, []string{string(core.DefaultProcMount), string(core.UnmaskedProcMount)})
}
}
var (
supportedScheduleActions = sets.NewString(string(core.DoNotSchedule), string(core.ScheduleAnyway))
)
// validateTopologySpreadConstraints validates given TopologySpreadConstraints.
func validateTopologySpreadConstraints(constraints []core.TopologySpreadConstraint, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
for i, constraint := range constraints {
subFldPath := fldPath.Index(i)
if err := ValidateMaxSkew(subFldPath.Child("maxSkew"), constraint.MaxSkew); err != nil {
allErrs = append(allErrs, err)
}
if err := ValidateTopologyKey(subFldPath.Child("topologyKey"), constraint.TopologyKey); err != nil {
allErrs = append(allErrs, err)
}
if err := ValidateWhenUnsatisfiable(subFldPath.Child("whenUnsatisfiable"), constraint.WhenUnsatisfiable); err != nil {
allErrs = append(allErrs, err)
}
// tuple {topologyKey, whenUnsatisfiable} denotes one kind of spread constraint
if err := ValidateSpreadConstraintNotRepeat(subFldPath.Child("{topologyKey, whenUnsatisfiable}"), constraint, constraints[i+1:]); err != nil {
allErrs = append(allErrs, err)
}
}
return allErrs
}
// ValidateMaxSkew tests that the argument is a valid MaxSkew.
func ValidateMaxSkew(fldPath *field.Path, maxSkew int32) *field.Error {
if maxSkew <= 0 {
return field.Invalid(fldPath, maxSkew, isNotPositiveErrorMsg)
}
return nil
}
// ValidateTopologyKey tests that the argument is a valid TopologyKey.
func ValidateTopologyKey(fldPath *field.Path, topologyKey string) *field.Error {
if len(topologyKey) == 0 {
return field.Required(fldPath, "can not be empty")
}
return nil
}
// ValidateWhenUnsatisfiable tests that the argument is a valid UnsatisfiableConstraintAction.
func ValidateWhenUnsatisfiable(fldPath *field.Path, action core.UnsatisfiableConstraintAction) *field.Error {
if !supportedScheduleActions.Has(string(action)) {
return field.NotSupported(fldPath, action, supportedScheduleActions.List())
}
return nil
}
// ValidateSpreadConstraintNotRepeat tests that if `constraint` duplicates with `existingConstraintPairs`
// on TopologyKey and WhenUnsatisfiable fields.
func ValidateSpreadConstraintNotRepeat(fldPath *field.Path, constraint core.TopologySpreadConstraint, restingConstraints []core.TopologySpreadConstraint) *field.Error {
for _, restingConstraint := range restingConstraints {
if constraint.TopologyKey == restingConstraint.TopologyKey &&
constraint.WhenUnsatisfiable == restingConstraint.WhenUnsatisfiable {
return field.Duplicate(fldPath, fmt.Sprintf("{%v, %v}", constraint.TopologyKey, constraint.WhenUnsatisfiable))
}
}
return nil
}
// ValidateServiceClusterIPsRelatedFields validates .spec.ClusterIPs,,
// .spec.IPFamilies, .spec.ipFamilyPolicy. This is exported because it is used
// during IP init and allocation.
func ValidateServiceClusterIPsRelatedFields(service *core.Service) field.ErrorList {
// ClusterIP, ClusterIPs, IPFamilyPolicy and IPFamilies are validated prior (all must be unset) for ExternalName service
if service.Spec.Type == core.ServiceTypeExternalName {
return field.ErrorList{}
}
allErrs := field.ErrorList{}
hasInvalidIPs := false
specPath := field.NewPath("spec")
clusterIPsField := specPath.Child("clusterIPs")
ipFamiliesField := specPath.Child("ipFamilies")
ipFamilyPolicyField := specPath.Child("ipFamilyPolicy")
// Make sure ClusterIP and ClusterIPs are synced. For most cases users can
// just manage one or the other and we'll handle the rest (see PrepareFor*
// in strategy).
if len(service.Spec.ClusterIP) != 0 {
// If ClusterIP is set, ClusterIPs[0] must match.
if len(service.Spec.ClusterIPs) == 0 {
allErrs = append(allErrs, field.Required(clusterIPsField, ""))
} else if service.Spec.ClusterIPs[0] != service.Spec.ClusterIP {
allErrs = append(allErrs, field.Invalid(clusterIPsField, service.Spec.ClusterIPs, "first value must match `clusterIP`"))
}
} else { // ClusterIP == ""
// If ClusterIP is not set, ClusterIPs must also be unset.
if len(service.Spec.ClusterIPs) != 0 {
allErrs = append(allErrs, field.Invalid(clusterIPsField, service.Spec.ClusterIPs, "must be empty when `clusterIP` is not specified"))
}
}
// ipfamilies stand alone validation
// must be either IPv4 or IPv6
seen := sets.String{}
for i, ipFamily := range service.Spec.IPFamilies {
if !supportedServiceIPFamily.Has(string(ipFamily)) {
allErrs = append(allErrs, field.NotSupported(ipFamiliesField.Index(i), ipFamily, supportedServiceIPFamily.List()))
}
// no duplicate check also ensures that ipfamilies is dualstacked, in any order
if seen.Has(string(ipFamily)) {
allErrs = append(allErrs, field.Duplicate(ipFamiliesField.Index(i), ipFamily))
}
seen.Insert(string(ipFamily))
}
// IPFamilyPolicy stand alone validation
//note: nil is ok, defaulted in alloc check registry/core/service/*
if service.Spec.IPFamilyPolicy != nil {
// must have a supported value
if !supportedServiceIPFamilyPolicy.Has(string(*(service.Spec.IPFamilyPolicy))) {
allErrs = append(allErrs, field.NotSupported(ipFamilyPolicyField, service.Spec.IPFamilyPolicy, supportedServiceIPFamilyPolicy.List()))
}
}
// clusterIPs stand alone validation
// valid ips with None and empty string handling
// duplication check is done as part of DualStackvalidation below
for i, clusterIP := range service.Spec.ClusterIPs {
// valid at first location only. if and only if len(clusterIPs) == 1
if i == 0 && clusterIP == core.ClusterIPNone {
if len(service.Spec.ClusterIPs) > 1 {
hasInvalidIPs = true
allErrs = append(allErrs, field.Invalid(clusterIPsField, service.Spec.ClusterIPs, "'None' must be the first and only value"))
}
continue
}
// is it valid ip?
errorMessages := validation.IsValidIP(clusterIP)
hasInvalidIPs = (len(errorMessages) != 0) || hasInvalidIPs
for _, msg := range errorMessages {
allErrs = append(allErrs, field.Invalid(clusterIPsField.Index(i), clusterIP, msg))
}
}
// max two
if len(service.Spec.ClusterIPs) > 2 {
allErrs = append(allErrs, field.Invalid(clusterIPsField, service.Spec.ClusterIPs, "may only hold up to 2 values"))
}
// at this stage if there is an invalid ip or misplaced none/empty string
// it will skew the error messages (bad index || dualstackness of already bad ips). so we
// stop here if there are errors in clusterIPs validation
if hasInvalidIPs {
return allErrs
}
// must be dual stacked ips if they are more than one ip
if len(service.Spec.ClusterIPs) > 1 /* meaning: it does not have a None or empty string */ {
dualStack, err := netutils.IsDualStackIPStrings(service.Spec.ClusterIPs)
if err != nil { // though we check for that earlier. safe > sorry
allErrs = append(allErrs, field.InternalError(clusterIPsField, fmt.Errorf("failed to check for dual stack with error:%v", err)))
}
// We only support one from each IP family (i.e. max two IPs in this list).
if !dualStack {
allErrs = append(allErrs, field.Invalid(clusterIPsField, service.Spec.ClusterIPs, "may specify no more than one IP for each IP family"))
}
}
// match clusterIPs to their families, if they were provided
if !isHeadlessService(service) && len(service.Spec.ClusterIPs) > 0 && len(service.Spec.IPFamilies) > 0 {
for i, ip := range service.Spec.ClusterIPs {
if i > (len(service.Spec.IPFamilies) - 1) {
break // no more families to check
}
// 4=>6
if service.Spec.IPFamilies[i] == core.IPv4Protocol && netutils.IsIPv6String(ip) {
allErrs = append(allErrs, field.Invalid(clusterIPsField.Index(i), ip, fmt.Sprintf("expected an IPv4 value as indicated by `ipFamilies[%v]`", i)))
}
// 6=>4
if service.Spec.IPFamilies[i] == core.IPv6Protocol && !netutils.IsIPv6String(ip) {
allErrs = append(allErrs, field.Invalid(clusterIPsField.Index(i), ip, fmt.Sprintf("expected an IPv6 value as indicated by `ipFamilies[%v]`", i)))
}
}
}
return allErrs
}
// specific validation for clusterIPs in cases of user upgrading or downgrading to/from dualstack
func validateUpgradeDowngradeClusterIPs(oldService, service *core.Service) field.ErrorList {
allErrs := make(field.ErrorList, 0)
// bail out early for ExternalName
if service.Spec.Type == core.ServiceTypeExternalName || oldService.Spec.Type == core.ServiceTypeExternalName {
return allErrs
}
newIsHeadless := isHeadlessService(service)
oldIsHeadless := isHeadlessService(oldService)
if oldIsHeadless && newIsHeadless {
return allErrs
}
switch {
// no change in ClusterIP lengths
// compare each
case len(oldService.Spec.ClusterIPs) == len(service.Spec.ClusterIPs):
for i, ip := range oldService.Spec.ClusterIPs {
if ip != service.Spec.ClusterIPs[i] {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "clusterIPs").Index(i), service.Spec.ClusterIPs, "may not change once set"))
}
}
// something has been released (downgraded)
case len(oldService.Spec.ClusterIPs) > len(service.Spec.ClusterIPs):
// primary ClusterIP has been released
if len(service.Spec.ClusterIPs) == 0 {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "clusterIPs").Index(0), service.Spec.ClusterIPs, "primary clusterIP can not be unset"))
}
// test if primary clusterIP has changed
if len(oldService.Spec.ClusterIPs) > 0 &&
len(service.Spec.ClusterIPs) > 0 &&
service.Spec.ClusterIPs[0] != oldService.Spec.ClusterIPs[0] {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "clusterIPs").Index(0), service.Spec.ClusterIPs, "may not change once set"))
}
// test if secondary ClusterIP has been released. has this service been downgraded correctly?
// user *must* set IPFamilyPolicy == SingleStack
if len(service.Spec.ClusterIPs) == 1 {
if service.Spec.IPFamilyPolicy == nil || *(service.Spec.IPFamilyPolicy) != core.IPFamilyPolicySingleStack {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "ipFamilyPolicy"), service.Spec.IPFamilyPolicy, "must be set to 'SingleStack' when releasing the secondary clusterIP"))
}
}
case len(oldService.Spec.ClusterIPs) < len(service.Spec.ClusterIPs):
// something has been added (upgraded)
// test if primary clusterIP has changed
if len(oldService.Spec.ClusterIPs) > 0 &&
service.Spec.ClusterIPs[0] != oldService.Spec.ClusterIPs[0] {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "clusterIPs").Index(0), service.Spec.ClusterIPs, "may not change once set"))
}
// we don't check for Policy == RequireDualStack here since, Validation/Creation func takes care of it
}
return allErrs
}
// specific validation for ipFamilies in cases of user upgrading or downgrading to/from dualstack
func validateUpgradeDowngradeIPFamilies(oldService, service *core.Service) field.ErrorList {
allErrs := make(field.ErrorList, 0)
// bail out early for ExternalName
if service.Spec.Type == core.ServiceTypeExternalName || oldService.Spec.Type == core.ServiceTypeExternalName {
return allErrs
}
oldIsHeadless := isHeadlessService(oldService)
newIsHeadless := isHeadlessService(service)
// if changed to/from headless, then bail out
if newIsHeadless != oldIsHeadless {
return allErrs
}
// headless can change families
if newIsHeadless {
return allErrs
}
switch {
case len(oldService.Spec.IPFamilies) == len(service.Spec.IPFamilies):
// no change in ClusterIP lengths
// compare each
for i, ip := range oldService.Spec.IPFamilies {
if ip != service.Spec.IPFamilies[i] {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "ipFamilies").Index(0), service.Spec.IPFamilies, "may not change once set"))
}
}
case len(oldService.Spec.IPFamilies) > len(service.Spec.IPFamilies):
// something has been released (downgraded)
// test if primary ipfamily has been released
if len(service.Spec.ClusterIPs) == 0 {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "ipFamilies").Index(0), service.Spec.IPFamilies, "primary ipFamily can not be unset"))
}
// test if primary ipFamily has changed
if len(service.Spec.IPFamilies) > 0 &&
service.Spec.IPFamilies[0] != oldService.Spec.IPFamilies[0] {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "ipFamilies").Index(0), service.Spec.ClusterIPs, "may not change once set"))
}
// test if secondary IPFamily has been released. has this service been downgraded correctly?
// user *must* set IPFamilyPolicy == SingleStack
if len(service.Spec.IPFamilies) == 1 {
if service.Spec.IPFamilyPolicy == nil || *(service.Spec.IPFamilyPolicy) != core.IPFamilyPolicySingleStack {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "ipFamilyPolicy"), service.Spec.IPFamilyPolicy, "must be set to 'SingleStack' when releasing the secondary ipFamily"))
}
}
case len(oldService.Spec.IPFamilies) < len(service.Spec.IPFamilies):
// something has been added (upgraded)
// test if primary ipFamily has changed
if len(oldService.Spec.IPFamilies) > 0 &&
len(service.Spec.IPFamilies) > 0 &&
service.Spec.IPFamilies[0] != oldService.Spec.IPFamilies[0] {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "ipFamilies").Index(0), service.Spec.ClusterIPs, "may not change once set"))
}
// we don't check for Policy == RequireDualStack here since, Validation/Creation func takes care of it
}
return allErrs
}
func isHeadlessService(service *core.Service) bool {
return service != nil &&
len(service.Spec.ClusterIPs) == 1 &&
service.Spec.ClusterIPs[0] == core.ClusterIPNone
}
// validateLoadBalancerClassField validation for loadBalancerClass
func validateLoadBalancerClassField(oldService, service *core.Service) field.ErrorList {
allErrs := make(field.ErrorList, 0)
if oldService != nil {
// validate update op
if isTypeLoadBalancer(oldService) && isTypeLoadBalancer(service) {
// old and new are both LoadBalancer
if !sameLoadBalancerClass(oldService, service) {
// can't change loadBalancerClass
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "loadBalancerClass"), service.Spec.LoadBalancerClass, "may not change once set"))
}
}
}
if isTypeLoadBalancer(service) {
// check LoadBalancerClass format
if service.Spec.LoadBalancerClass != nil {
allErrs = append(allErrs, ValidateQualifiedName(*service.Spec.LoadBalancerClass, field.NewPath("spec", "loadBalancerClass"))...)
}
} else {
// check if LoadBalancerClass set for non LoadBalancer type of service
if service.Spec.LoadBalancerClass != nil {
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "loadBalancerClass"), "may only be used when `type` is 'LoadBalancer'"))
}
}
return allErrs
}
// isTypeLoadBalancer tests service type is loadBalancer or not
func isTypeLoadBalancer(service *core.Service) bool {
return service.Spec.Type == core.ServiceTypeLoadBalancer
}
// sameLoadBalancerClass check two services have the same loadBalancerClass or not
func sameLoadBalancerClass(oldService, service *core.Service) bool {
if oldService.Spec.LoadBalancerClass == nil && service.Spec.LoadBalancerClass == nil {
return true
}
if oldService.Spec.LoadBalancerClass == nil || service.Spec.LoadBalancerClass == nil {
return false
}
return *oldService.Spec.LoadBalancerClass == *service.Spec.LoadBalancerClass
}
| humblec/kubernetes | pkg/apis/core/validation/validation.go | GO | apache-2.0 | 298,748 |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'div', 'de-ch', {
IdInputLabel: 'Kennung',
advisoryTitleInputLabel: 'Tooltip',
cssClassInputLabel: 'Formatvorlagenklasse',
edit: 'Div bearbeiten',
inlineStyleInputLabel: 'Inline Stil',
langDirLTRLabel: 'Links nach Rechs (LTR)',
langDirLabel: 'Sprachrichtung',
langDirRTLLabel: 'Rechs nach Links (RTL)',
languageCodeInputLabel: 'Sprachcode',
remove: 'Div entfernen',
styleSelectLabel: 'Stil',
title: 'Div Container erzeugen',
toolbar: 'Div Container erzeugen'
} );
| ldilov/uidb | plugins/ckeditor/plugins/div/lang/de-ch.js | JavaScript | apache-2.0 | 649 |
# -*- coding: utf-8 -*-
"""Fake data generator.
To use:
1. Install fake-factory.
pip install fake-factory
2. Create your OSF user account
3. Run the script, passing in your username (email).
::
python3 -m scripts.create_fakes --user fred@cos.io
This will create 3 fake public projects, each with 3 fake contributors (with
you as the creator).
To create a project with a complex component structure, pass in a list representing the depth you would
like each component to contain.
Examples:
python3 -m scripts.create_fakes -u fred@cos --components '[1, 1, 1, 1]' --nprojects 1
...will create a project with 4 components.
python3 -m scripts.create_fakes -u fred@cos --components '4' --nprojects 1
...will create a project with a series of components, 4 levels deep.
python3 -m scripts.create_fakes -u fred@cos --components '[1, [1, 1]]' --nprojects 1
...will create a project with two top level components, and one with a depth of 2 components.
python3 -m scripts.create_fakes -u fred@cos --nprojects 3 --preprint True
...will create 3 preprints with the default provider osf
python3 -m scripts.create_fakes -u fred@cos --nprojects 3 --preprint True --preprintprovider osf,test_provider
...will create 3 preprints with the providers osf and test_provider
"""
from __future__ import print_function, absolute_import
import ast
import sys
import mock
import argparse
import logging
import django
import pytz
from faker import Factory
from faker.providers import BaseProvider
django.setup()
from framework.auth import Auth
from osf_tests.factories import UserFactory, ProjectFactory, NodeFactory, RegistrationFactory, PreprintFactory, PreprintProviderFactory, fake_email
from osf import models
from website.app import init_app
class Sciencer(BaseProvider):
# Science term Faker Provider created by @csheldonhess
# https://github.com/csheldonhess/FakeConsumer/blob/master/faker/providers/science.py
word_list = ('abiosis', 'abrade', 'absorption', 'acceleration', 'accumulation',
'acid', 'acidic', 'activist', 'adaptation', 'agonistic', 'agrarian', 'airborne',
'alchemist', 'alignment', 'allele', 'alluvial', 'alveoli', 'ambiparous',
'amphibian', 'amplitude', 'analysis', 'ancestor', 'anodize', 'anomaly',
'anther', 'antigen', 'apiary', 'apparatus', 'application', 'approximation',
'aquatic', 'aquifer', 'arboreal', 'archaeology', 'artery', 'assessment',
'asteroid', 'atmosphere', 'atomic', 'atrophy', 'attenuate', 'aven', 'aviary',
'axis', 'bacteria', 'balance', 'bases', 'biome', 'biosphere', 'black hole',
'blight', 'buoyancy', 'calcium', 'canopy', 'capacity', 'capillary', 'carapace',
'carcinogen', 'catalyst', 'cauldron', 'celestial', 'cells', 'centigrade',
'centimeter', 'centrifugal', 'chemical reaction', 'chemicals', 'chemistry',
'chlorophyll', 'choked', 'chromosome', 'chronic', 'churn', 'classification',
'climate', 'cloud', 'comet', 'composition', 'compound', 'compression',
'condensation', 'conditions', 'conduction', 'conductivity', 'conservation',
'constant', 'constellation', 'continental', 'convection', 'convention', 'cool',
'core', 'cosmic', 'crater', 'creature', 'crepuscular', 'crystals', 'cycle', 'cytoplasm',
'dampness', 'data', 'decay', 'decibel', 'deciduous', 'defoliate', 'density',
'denude', 'dependency', 'deposits', 'depth', 'desiccant', 'detritus',
'development', 'digestible', 'diluted', 'direction', 'disappearance', 'discovery',
'dislodge', 'displace', 'dissection', 'dissolution', 'dissolve', 'distance',
'diurnal', 'diverse', 'doldrums', 'dynamics', 'earthquake', 'eclipse', 'ecology',
'ecosystem', 'electricity', 'elements', 'elevation', 'embryo', 'endangered',
'endocrine', 'energy', 'entropy', 'environment', 'enzyme', 'epidermis', 'epoch',
'equilibrium', 'equine', 'erosion', 'essential', 'estuary', 'ethical', 'evaporation',
'event', 'evidence', 'evolution', 'examination', 'existence', 'expansion',
'experiment', 'exploration ', 'extinction', 'extreme', 'facet', 'fault', 'fauna',
'feldspar', 'fermenting', 'fission', 'fissure', 'flora', 'flourish', 'flowstone',
'foliage', 'food chain', 'forage', 'force', 'forecast', 'forensics', 'formations',
'fossil fuel', 'frequency', 'friction', 'fungi', 'fusion', 'galaxy', 'gastric',
'geo-science', 'geothermal', 'germination', 'gestation', 'global', 'gravitation',
'green', 'greenhouse effect', 'grotto', 'groundwater', 'habitat', 'heat', 'heavens',
'hemisphere', 'hemoglobin', 'herpetologist', 'hormones', 'host', 'humidity', 'hyaline',
'hydrogen', 'hydrology', 'hypothesis', 'ichthyology', 'illumination', 'imagination',
'impact of', 'impulse', 'incandescent', 'indigenous', 'inertia', 'inevitable', 'inherit',
'inquiry', 'insoluble', 'instinct', 'instruments', 'integrity', 'intelligence',
'interacts with', 'interdependence', 'interplanetary', 'invertebrate', 'investigation',
'invisible', 'ions', 'irradiate', 'isobar', 'isotope', 'joule', 'jungle', 'jurassic',
'jutting', 'kilometer', 'kinetics', 'kingdom', 'knot', 'laser', 'latitude', 'lava',
'lethal', 'life', 'lift', 'light', 'limestone', 'lipid', 'lithosphere', 'load',
'lodestone', 'luminous', 'luster', 'magma', 'magnet', 'magnetism', 'mangrove', 'mantle',
'marine', 'marsh', 'mass', 'matter', 'measurements', 'mechanical', 'meiosis', 'meridian',
'metamorphosis', 'meteor', 'microbes', 'microcosm', 'migration', 'millennia', 'minerals',
'modulate', 'moisture', 'molecule', 'molten', 'monograph', 'monolith', 'motion',
'movement', 'mutant', 'mutation', 'mysterious', 'natural', 'navigable', 'navigation',
'negligence', 'nervous system', 'nesting', 'neutrons', 'niche', 'nocturnal',
'nuclear energy', 'numerous', 'nurture', 'obsidian', 'ocean', 'oceanography', 'omnivorous',
'oolites (cave pearls)', 'opaque', 'orbit', 'organ', 'organism', 'ornithology',
'osmosis', 'oxygen', 'paleontology', 'parallax', 'particle', 'penumbra',
'percolate', 'permafrost', 'permutation', 'petrify', 'petrograph', 'phenomena',
'physical property', 'planetary', 'plasma', 'polar', 'pole', 'pollination',
'polymer', 'population', 'precipitation', 'predator', 'prehensile', 'preservation',
'preserve', 'pressure', 'primate', 'pristine', 'probe', 'process', 'propagation',
'properties', 'protected', 'proton', 'pulley', 'qualitative data', 'quantum', 'quark',
'quarry', 'radiation', 'radioactivity', 'rain forest', 'ratio', 'reaction', 'reagent',
'realm', 'redwoods', 'reeds', 'reflection', 'refraction', 'relationships between', 'reptile',
'research', 'resistance', 'resonate', 'rookery', 'rubble', 'runoff', 'salinity', 'sandbar',
'satellite', 'saturation', 'scientific investigation', 'scientist\'s', 'sea floor', 'season',
'sedentary', 'sediment', 'sedimentary', 'seepage', 'seismic', 'sensors', 'shard',
'similarity', 'solar', 'soluble', 'solvent', 'sonic', 'sound', 'source', 'species',
'spectacular', 'spectrum', 'speed', 'sphere', 'spring', 'stage', 'stalactite',
'stalagmites', 'stimulus', 'substance', 'subterranean', 'sulfuric acid', 'surface',
'survival', 'swamp', 'sylvan', 'symbiosis', 'symbol', 'synergy', 'synthesis', 'taiga',
'taxidermy', 'technology', 'tectonics', 'temperate', 'temperature', 'terrestrial',
'thermals', 'thermometer', 'thrust', 'torque', 'toxin', 'trade winds', 'pterodactyl',
'transformation tremors', 'tropical', 'umbra', 'unbelievable', 'underwater', 'unearth',
'unique', 'unite', 'unity', 'universal', 'unpredictable', 'unusual', 'ursine', 'vacuole',
'valuable', 'vapor', 'variable', 'variety', 'vast', 'velocity', 'ventifact', 'verdant',
'vespiary', 'viable', 'vibration', 'virus', 'viscosity', 'visible', 'vista', 'vital',
'vitreous', 'volt', 'volume', 'vulpine', 'wave', 'wax', 'weather', 'westerlies', 'wetlands',
'whitewater', 'xeriscape', 'xylem', 'yield', 'zero-impact', 'zone', 'zygote', 'achieving',
'acquisition of', 'an alternative', 'analysis of', 'approach toward', 'area', 'aspects of',
'assessment of', 'assuming', 'authority', 'available', 'benefit of', 'circumstantial',
'commentary', 'components', 'concept of', 'consistent', 'corresponding', 'criteria',
'data', 'deduction', 'demonstrating', 'derived', 'distribution', 'dominant', 'elements',
'equation', 'estimate', 'evaluation', 'factors', 'features', 'final', 'function',
'initial', 'instance ', 'interpretation of', 'maintaining ', 'method', 'perceived',
'percent', 'period', 'positive', 'potential', 'previous', 'primary', 'principle',
'procedure', 'process', 'range', 'region', 'relevant', 'required', 'research',
'resources', 'response', 'role', 'section', 'select', 'significant ', 'similar',
'source', 'specific', 'strategies', 'structure', 'theory', 'transfer', 'variables',
'corvidae', 'passerine', 'Pica pica', 'Chinchilla lanigera', 'Nymphicus hollandicus',
'Melopsittacus undulatus', )
def science_word(cls):
"""
:example 'Lorem'
"""
return cls.random_element(cls.word_list)
def science_words(cls, nb=3):
"""
Generate an array of random words
:example array('Lorem', 'ipsum', 'dolor')
:param nb how many words to return
"""
return [cls.science_word() for _ in range(0, nb)]
def science_sentence(cls, nb_words=6, variable_nb_words=True):
"""
Generate a random sentence
:example 'Lorem ipsum dolor sit amet.'
:param nb_words around how many words the sentence should contain
:param variable_nb_words set to false if you want exactly $nbWords returned,
otherwise $nbWords may vary by +/-40% with a minimum of 1
"""
if nb_words <= 0:
return ''
if variable_nb_words:
nb_words = cls.randomize_nb_elements(nb_words)
words = cls.science_words(nb_words)
words[0] = words[0].title()
return ' '.join(words) + '.'
def science_sentences(cls, nb=3):
"""
Generate an array of sentences
:example array('Lorem ipsum dolor sit amet.', 'Consectetur adipisicing eli.')
:param nb how many sentences to return
:return list
"""
return [cls.science_sentence() for _ in range(0, nb)]
def science_paragraph(cls, nb_sentences=3, variable_nb_sentences=True):
"""
Generate a single paragraph
:example 'Sapiente sunt omnis. Ut pariatur ad autem ducimus et. Voluptas rem voluptas sint modi dolorem amet.'
:param nb_sentences around how many sentences the paragraph should contain
:param variable_nb_sentences set to false if you want exactly $nbSentences returned,
otherwise $nbSentences may vary by +/-40% with a minimum of 1
:return string
"""
if nb_sentences <= 0:
return ''
if variable_nb_sentences:
nb_sentences = cls.randomize_nb_elements(nb_sentences)
return ' '.join(cls.science_sentences(nb_sentences))
def science_paragraphs(cls, nb=3):
"""
Generate an array of paragraphs
:example array($paragraph1, $paragraph2, $paragraph3)
:param nb how many paragraphs to return
:return array
"""
return [cls.science_paragraph() for _ in range(0, nb)]
def science_text(cls, max_nb_chars=200):
"""
Generate a text string.
Depending on the $maxNbChars, returns a string made of words, sentences, or paragraphs.
:example 'Sapiente sunt omnis. Ut pariatur ad autem ducimus et. Voluptas rem voluptas sint modi dolorem amet.'
:param max_nb_chars Maximum number of characters the text should contain (minimum 5)
:return string
"""
text = []
if max_nb_chars < 5:
raise ValueError('text() can only generate text of at least 5 characters')
if max_nb_chars < 25:
# join words
while not text:
size = 0
# determine how many words are needed to reach the $max_nb_chars once;
while size < max_nb_chars:
word = (' ' if size else '') + cls.science_word()
text.append(word)
size += len(word)
text.pop()
text[0] = text[0][0].upper() + text[0][1:]
last_index = len(text) - 1
text[last_index] += '.'
elif max_nb_chars < 100:
# join sentences
while not text:
size = 0
# determine how many sentences are needed to reach the $max_nb_chars once
while size < max_nb_chars:
sentence = (' ' if size else '') + cls.science_sentence()
text.append(sentence)
size += len(sentence)
text.pop()
else:
# join paragraphs
while not text:
size = 0
# determine how many paragraphs are needed to reach the $max_nb_chars once
while size < max_nb_chars:
paragraph = ('\n' if size else '') + cls.science_paragraph()
text.append(paragraph)
size += len(paragraph)
text.pop()
return ''.join(text)
logger = logging.getLogger('create_fakes')
SILENT_LOGGERS = [
'factory',
'website.mails',
]
for logger_name in SILENT_LOGGERS:
logging.getLogger(logger_name).setLevel(logging.CRITICAL)
fake = Factory.create()
fake.add_provider(Sciencer)
def create_fake_user():
email = fake_email()
name = fake.name()
user = UserFactory(username=email, fullname=name,
is_registered=True, emails=[email],
date_registered=fake.date_time(tzinfo=pytz.UTC),
)
user.set_password('faker123')
user.save()
logger.info('Created user: {0} <{1}>'.format(user.fullname, user.username))
return user
def parse_args():
parser = argparse.ArgumentParser(description='Create fake data.')
parser.add_argument('-u', '--user', dest='user', required=True)
parser.add_argument('--nusers', dest='n_users', type=int, default=3)
parser.add_argument('--nprojects', dest='n_projects', type=int, default=3)
parser.add_argument('-c', '--components', dest='n_components', type=evaluate_argument, default='0')
parser.add_argument('-p', '--privacy', dest='privacy', type=str, default='private', choices=['public', 'private'])
parser.add_argument('-n', '--name', dest='name', type=str, default=None)
parser.add_argument('-t', '--tags', dest='n_tags', type=int, default=5)
parser.add_argument('--presentation', dest='presentation_name', type=str, default=None)
parser.add_argument('-r', '--registration', dest='is_registration', type=bool, default=False)
parser.add_argument('-pre', '--preprint', dest='is_preprint', type=bool, default=False)
parser.add_argument('-preprovider', '--preprintprovider', dest='preprint_provider', type=str, default=None)
return parser.parse_args()
def evaluate_argument(string):
return ast.literal_eval(string)
def create_fake_project(creator, n_users, privacy, n_components, name, n_tags, presentation_name, is_registration, is_preprint, preprint_provider):
auth = Auth(user=creator)
project_title = name if name else fake.science_sentence()
if is_preprint:
provider = None
if preprint_provider:
try:
provider = models.PreprintProvider.objects.get(_id=provider)
except models.PreprintProvider.DoesNotExist:
pass
if not provider:
provider = PreprintProviderFactory(name=fake.science_word())
privacy = 'public'
mock_change_identifier_preprints = mock.patch('website.identifiers.client.CrossRefClient.update_identifier')
mock_change_identifier_preprints.start()
project = PreprintFactory(title=project_title, description=fake.science_paragraph(), creator=creator, provider=provider)
node = project.node
elif is_registration:
project = RegistrationFactory(title=project_title, description=fake.science_paragraph(), creator=creator)
node = project
else:
project = ProjectFactory(title=project_title, description=fake.science_paragraph(), creator=creator)
node = project
node.set_privacy(privacy)
for _ in range(n_users):
contrib = create_fake_user()
node.add_contributor(contrib, auth=auth)
if isinstance(n_components, int):
for _ in range(n_components):
NodeFactory(parent=node, title=fake.science_sentence(), description=fake.science_paragraph(),
creator=creator)
elif isinstance(n_components, list):
render_generations_from_node_structure_list(node, creator, n_components)
for _ in range(n_tags):
node.add_tag(fake.science_word(), auth=auth)
if presentation_name is not None:
node.add_tag(presentation_name, auth=auth)
node.add_tag('poster', auth=auth)
node.save()
project.save()
logger.info('Created project: {0}'.format(node.title))
return project
def render_generations_from_parent(parent, creator, num_generations):
current_gen = parent
for generation in range(0, num_generations):
next_gen = NodeFactory(
parent=current_gen,
creator=creator,
title=fake.science_sentence(),
description=fake.science_paragraph()
)
current_gen = next_gen
return current_gen
def render_generations_from_node_structure_list(parent, creator, node_structure_list):
new_parent = None
for node_number in node_structure_list:
if isinstance(node_number, list):
render_generations_from_node_structure_list(new_parent or parent, creator, node_number)
else:
new_parent = render_generations_from_parent(parent, creator, node_number)
return new_parent
def main():
args = parse_args()
creator = models.OSFUser.objects.get(username=args.user)
for i in range(args.n_projects):
name = args.name + str(i) if args.name else ''
create_fake_project(creator, args.n_users, args.privacy, args.n_components, name, args.n_tags,
args.presentation_name, args.is_registration, args.is_preprint, args.preprint_provider)
print('Created {n} fake projects.'.format(n=args.n_projects))
sys.exit(0)
if __name__ == '__main__':
init_app(set_backends=True, routes=False)
main()
| Johnetordoff/osf.io | scripts/create_fakes.py | Python | apache-2.0 | 19,763 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.builder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
/**
* <p>
* Assists in implementing {@link Diffable#diff(Object)} methods.
* </p>
*
* <p>
* To use this class, write code as follows:
* </p>
*
* <pre>
* public class Person implements Diffable<Person> {
* String name;
* int age;
* boolean smoker;
*
* ...
*
* public DiffResult diff(Person obj) {
* // No need for null check, as NullPointerException correct if obj is null
* return new DiffBuilder(this, obj, ToStringStyle.SHORT_PREFIX_STYLE)
* .append("name", this.name, obj.name)
* .append("age", this.age, obj.age)
* .append("smoker", this.smoker, obj.smoker)
* .build();
* }
* }
* </pre>
*
* <p>
* The {@code ToStringStyle} passed to the constructor is embedded in the
* returned {@code DiffResult} and influences the style of the
* {@code DiffResult.toString()} method. This style choice can be overridden by
* calling {@link DiffResult#toString(ToStringStyle)}.
* </p>
*
* @since 3.3
* @version $Id: DiffBuilder.java 1565245 2014-02-06 13:39:50Z sebb $
* @see Diffable
* @see Diff
* @see DiffResult
* @see ToStringStyle
*/
public class DiffBuilder implements Builder<DiffResult> {
private final List<Diff<?>> diffs;
private final boolean objectsTriviallyEqual;
private final Object left;
private final Object right;
private final ToStringStyle style;
/**
* <p>
* Constructs a builder for the specified objects with the specified style.
* </p>
*
* <p>
* If {@code lhs == rhs} or {@code lhs.equals(rhs)} then the builder will
* not evaluate any calls to {@code append(...)} and will return an empty
* {@link DiffResult} when {@link #build()} is executed.
* </p>
*
* @param lhs
* {@code this} object
* @param rhs
* the object to diff against
* @param style
* the style will use when outputting the objects, {@code null}
* uses the default
* @throws IllegalArgumentException
* if {@code lhs} or {@code rhs} is {@code null}
*/
public DiffBuilder(final Object lhs, final Object rhs,
final ToStringStyle style) {
if (lhs == null) {
throw new IllegalArgumentException("lhs cannot be null");
}
if (rhs == null) {
throw new IllegalArgumentException("rhs cannot be null");
}
this.diffs = new ArrayList<Diff<?>>();
this.left = lhs;
this.right = rhs;
this.style = style;
// Don't compare any fields if objects equal
this.objectsTriviallyEqual = (lhs == rhs || lhs.equals(rhs));
}
/**
* <p>
* Test if two {@code boolean}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code boolean}
* @param rhs
* the right hand {@code boolean}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final boolean lhs,
final boolean rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (lhs != rhs) {
diffs.add(new Diff<Boolean>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Boolean getLeft() {
return Boolean.valueOf(lhs);
}
@Override
public Boolean getRight() {
return Boolean.valueOf(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code boolean[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code boolean[]}
* @param rhs
* the right hand {@code boolean[]}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final boolean[] lhs,
final boolean[] rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Boolean[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Boolean[] getLeft() {
return ArrayUtils.toObject(lhs);
}
@Override
public Boolean[] getRight() {
return ArrayUtils.toObject(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code byte}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code byte}
* @param rhs
* the right hand {@code byte}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final byte lhs,
final byte rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (lhs != rhs) {
diffs.add(new Diff<Byte>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Byte getLeft() {
return Byte.valueOf(lhs);
}
@Override
public Byte getRight() {
return Byte.valueOf(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code byte[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code byte[]}
* @param rhs
* the right hand {@code byte[]}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final byte[] lhs,
final byte[] rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Byte[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Byte[] getLeft() {
return ArrayUtils.toObject(lhs);
}
@Override
public Byte[] getRight() {
return ArrayUtils.toObject(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code char}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code char}
* @param rhs
* the right hand {@code char}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final char lhs,
final char rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (lhs != rhs) {
diffs.add(new Diff<Character>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Character getLeft() {
return Character.valueOf(lhs);
}
@Override
public Character getRight() {
return Character.valueOf(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code char[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code char[]}
* @param rhs
* the right hand {@code char[]}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final char[] lhs,
final char[] rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Character[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Character[] getLeft() {
return ArrayUtils.toObject(lhs);
}
@Override
public Character[] getRight() {
return ArrayUtils.toObject(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code double}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code double}
* @param rhs
* the right hand {@code double}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final double lhs,
final double rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (Double.doubleToLongBits(lhs) != Double.doubleToLongBits(rhs)) {
diffs.add(new Diff<Double>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Double getLeft() {
return Double.valueOf(lhs);
}
@Override
public Double getRight() {
return Double.valueOf(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code double[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code double[]}
* @param rhs
* the right hand {@code double[]}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final double[] lhs,
final double[] rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Double[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Double[] getLeft() {
return ArrayUtils.toObject(lhs);
}
@Override
public Double[] getRight() {
return ArrayUtils.toObject(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code float}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code float}
* @param rhs
* the right hand {@code float}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final float lhs,
final float rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (Float.floatToIntBits(lhs) != Float.floatToIntBits(rhs)) {
diffs.add(new Diff<Float>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Float getLeft() {
return Float.valueOf(lhs);
}
@Override
public Float getRight() {
return Float.valueOf(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code float[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code float[]}
* @param rhs
* the right hand {@code float[]}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final float[] lhs,
final float[] rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Float[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Float[] getLeft() {
return ArrayUtils.toObject(lhs);
}
@Override
public Float[] getRight() {
return ArrayUtils.toObject(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code int}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code int}
* @param rhs
* the right hand {@code int}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final int lhs,
final int rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (lhs != rhs) {
diffs.add(new Diff<Integer>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Integer getLeft() {
return Integer.valueOf(lhs);
}
@Override
public Integer getRight() {
return Integer.valueOf(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code int[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code int[]}
* @param rhs
* the right hand {@code int[]}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final int[] lhs,
final int[] rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Integer[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Integer[] getLeft() {
return ArrayUtils.toObject(lhs);
}
@Override
public Integer[] getRight() {
return ArrayUtils.toObject(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code long}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code long}
* @param rhs
* the right hand {@code long}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final long lhs,
final long rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (lhs != rhs) {
diffs.add(new Diff<Long>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Long getLeft() {
return Long.valueOf(lhs);
}
@Override
public Long getRight() {
return Long.valueOf(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code long[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code long[]}
* @param rhs
* the right hand {@code long[]}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final long[] lhs,
final long[] rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Long[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Long[] getLeft() {
return ArrayUtils.toObject(lhs);
}
@Override
public Long[] getRight() {
return ArrayUtils.toObject(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code short}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code short}
* @param rhs
* the right hand {@code short}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final short lhs,
final short rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (lhs != rhs) {
diffs.add(new Diff<Short>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Short getLeft() {
return Short.valueOf(lhs);
}
@Override
public Short getRight() {
return Short.valueOf(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code short[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code short[]}
* @param rhs
* the right hand {@code short[]}
* @return this
* @throws IllegalArgumentException
* if field name is {@code null}
*/
public DiffBuilder append(final String fieldName, final short[] lhs,
final short[] rhs) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Short[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Short[] getLeft() {
return ArrayUtils.toObject(lhs);
}
@Override
public Short[] getRight() {
return ArrayUtils.toObject(rhs);
}
});
}
return this;
}
/**
* <p>
* Test if two {@code Objects}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code Object}
* @param rhs
* the right hand {@code Object}
* @return this
*/
public DiffBuilder append(final String fieldName, final Object lhs,
final Object rhs) {
if (objectsTriviallyEqual) {
return this;
}
if (lhs == rhs) {
return this;
}
Object objectToTest;
if (lhs != null) {
objectToTest = lhs;
} else {
// rhs cannot be null, as lhs != rhs
objectToTest = rhs;
}
if (objectToTest.getClass().isArray()) {
if (objectToTest instanceof boolean[]) {
return append(fieldName, (boolean[]) lhs, (boolean[]) rhs);
}
if (objectToTest instanceof byte[]) {
return append(fieldName, (byte[]) lhs, (byte[]) rhs);
}
if (objectToTest instanceof char[]) {
return append(fieldName, (char[]) lhs, (char[]) rhs);
}
if (objectToTest instanceof double[]) {
return append(fieldName, (double[]) lhs, (double[]) rhs);
}
if (objectToTest instanceof float[]) {
return append(fieldName, (float[]) lhs, (float[]) rhs);
}
if (objectToTest instanceof int[]) {
return append(fieldName, (int[]) lhs, (int[]) rhs);
}
if (objectToTest instanceof long[]) {
return append(fieldName, (long[]) lhs, (long[]) rhs);
}
if (objectToTest instanceof short[]) {
return append(fieldName, (short[]) lhs, (short[]) rhs);
}
return append(fieldName, (Object[]) lhs, (Object[]) rhs);
}
// Not array type
diffs.add(new Diff<Object>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Object getLeft() {
return lhs;
}
@Override
public Object getRight() {
return rhs;
}
});
return this;
}
/**
* <p>
* Test if two {@code Object[]}s are equal.
* </p>
*
* @param fieldName
* the field name
* @param lhs
* the left hand {@code Object[]}
* @param rhs
* the right hand {@code Object[]}
* @return this
*/
public DiffBuilder append(final String fieldName, final Object[] lhs,
final Object[] rhs) {
if (objectsTriviallyEqual) {
return this;
}
if (!Arrays.equals(lhs, rhs)) {
diffs.add(new Diff<Object[]>(fieldName) {
private static final long serialVersionUID = 1L;
@Override
public Object[] getLeft() {
return lhs;
}
@Override
public Object[] getRight() {
return rhs;
}
});
}
return this;
}
/**
* <p>
* Builds a {@link DiffResult} based on the differences appended to this
* builder.
* </p>
*
* @return a {@code DiffResult} containing the differences between the two
* objects.
*/
@Override
public DiffResult build() {
return new DiffResult(left, right, diffs, style);
}
}
| MeRPG/EndHQ-Libraries | src/org/apache/commons/lang3/builder/DiffBuilder.java | Java | apache-2.0 | 26,079 |
/*
* Copyright 2016 SimplifyOps, Inc. (http://simplifyops.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 com.dtolabs.rundeck.core.utils;
import org.apache.commons.lang.text.StrMatcher;
import java.util.*;
/**
* Tokenizer for strings delimited by spaces, allowing quoted strings with either single or double quotes, and escaped
* quote values within those strings by doubling the quote character. Delimiters are not returned in the tokens, and
* runs of delimiters can be quelled. All chars in a quoted section are returned, even blanks.
* Implements {@link Iterable} and {@link Iterator}.
*
*/
public class QuotedStringTokenizer implements Iterator<String>, Iterable<String> {
private char[] string;
private int pos;
private Queue<String> buffer;
private StrMatcher delimiterMatcher;
private StrMatcher quoteMatcher;
private StrMatcher whitespaceMatcher;
private boolean quashDelimiters;
public QuotedStringTokenizer(String string) {
this(string.toCharArray(), 0);
}
public QuotedStringTokenizer(char[] chars, int pos) {
this.string = chars;
this.pos = pos;
buffer = new ArrayDeque<String>();
delimiterMatcher = StrMatcher.trimMatcher();
quoteMatcher = StrMatcher.quoteMatcher();
whitespaceMatcher = StrMatcher.trimMatcher();
quashDelimiters=true;
readNext();
}
public static String[] tokenizeToArray(String string) {
List<String> strings = collectTokens(string);
return strings.toArray(new String[strings.size()]);
}
public static List<String> tokenizeToList(String string) {
return collectTokens(string);
}
public static Iterable<String> tokenize(String string) {
return new QuotedStringTokenizer(string);
}
private static List<String> collectTokens(String string) {
ArrayList<String> strings = new ArrayList<String>();
for (String s : new QuotedStringTokenizer(string)) {
strings.add(s);
}
return strings;
}
@Override
public boolean hasNext() {
return !buffer.isEmpty();
}
@Override
public String next() {
String remove = buffer.remove();
readNext();
return remove;
}
private void readNext() {
pos = readNextToken(string, pos, buffer);
}
private int readNextToken(char[] chars, int pos, Collection<String> tokens) {
if (pos >= chars.length) {
return -1;
}
int ws = whitespaceMatcher.isMatch(chars, pos);
if (ws > 0) {
pos += ws;
}
if (pos >= chars.length) {
return -1;
}
int delim = delimiterMatcher.isMatch(chars, pos);
if (delim > 0) {
if (quashDelimiters) {
pos = consumeDelimiters(chars, pos, delim);
} else {
addToken(buffer, "");
return pos + delim;
}
}
int quote = quoteMatcher.isMatch(chars, pos);
return readQuotedToken(chars, pos, tokens, quote);
}
private int consumeDelimiters(char[] chars, int start, int delim) {
while (delim > 0 && start < chars.length - delim) {
start += delim;
delim = delimiterMatcher.isMatch(chars, start);
}
return start;
}
private int readQuotedToken(char[] chars, int start, Collection<String> tokens, int quotesize) {
int pos = start;
StringBuilder tchars = new StringBuilder();
boolean quoting = quotesize > 0;
if (quoting) {
pos += quotesize;
}
while (pos < chars.length) {
if (quoting) {
if (charsMatch(chars, start, pos, quotesize)) {
//matches the quoting char
//if next token is the same quote, it is an escaped quote
if (charsMatch(chars, start, pos + quotesize, quotesize)) {
//token the quote
tchars.append(new String(chars, pos, quotesize));
pos += 2 * quotesize;
continue;
}
//end of quoting
quoting = false;
pos += quotesize;
continue;
}
//append char
tchars.append(chars[pos++]);
} else {
int delim = delimiterMatcher.isMatch(chars, pos);
if (delim > 0) {
if (quashDelimiters) {
pos = consumeDelimiters(chars, pos, delim);
addToken(tokens, tchars.toString());
return pos;
} else {
addToken(tokens, tchars.toString());
return pos + delim;
}
}
if (quotesize > 0 && charsMatch(chars, start, pos, quotesize)) {
//new quote
quoting = true;
pos += quotesize;
continue;
}
//append char
tchars.append(chars[pos++]);
}
}
addToken(tokens, tchars.toString());
return pos;
}
/**
* @return true if two sequences of chars match within the array.
*
* @param chars char set
* @param pos1 position 1
* @param pos2 position 2
* @param len2 length to compare
*
*/
private boolean charsMatch(char[] chars, int pos1, int pos2, int len2) {
return charsMatch(chars, pos1, len2, pos2, len2);
}
/**
* @return true if two sequences of chars match within the array.
*
* @param chars char set
* @param pos1 pos 1
* @param len1 length 1
* @param pos2 pos 2
* @param len2 length 2
*
*/
private boolean charsMatch(char[] chars, int pos1, int len1, int pos2, int len2) {
if (len1 != len2) {
return false;
}
if (pos1 + len1 > chars.length || pos2 + len2 > chars.length) {
return false;
}
for (int i = 0; i < len1; i++) {
if (chars[pos1 + i] != chars[pos2 + i]) {
return false;
}
}
return true;
}
private void addToken(Collection<String> buffer, String token) {
buffer.add(token);
}
@Override
public void remove() {
}
@Override
public Iterator<String> iterator() {
return this;
}
}
| variacode/rundeck | core/src/main/java/com/dtolabs/rundeck/core/utils/QuotedStringTokenizer.java | Java | apache-2.0 | 7,149 |
export class Class {
#field: any
}
const task: Class = {} as unknown;
| alexeagle/TypeScript | tests/cases/compiler/privateFieldAssignabilityFromUnknown.ts | TypeScript | apache-2.0 | 78 |
#
# Author:: Noah Kantrowitz <noah@opscode.com>
# Cookbook Name:: application_python
# Resource:: django
#
# Copyright:: 2011, Opscode, Inc <legal@opscode.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.
#
include ApplicationCookbook::ResourceBase
attribute :database_master_role, :kind_of => [String, NilClass], :default => nil
attribute :packages, :kind_of => [Array, Hash], :default => []
attribute :requirements, :kind_of => [NilClass, String, FalseClass], :default => nil
attribute :legacy_database_settings, :kind_of => [TrueClass, FalseClass], :default => false
attribute :settings, :kind_of => Hash, :default => {}
# Actually defaults to "settings.py.erb", but nil means it wasn't set by the user
attribute :settings_template, :kind_of => [String, NilClass], :default => nil
attribute :local_settings_file, :kind_of => String, :default => 'local_settings.py'
attribute :debug, :kind_of => [TrueClass, FalseClass], :default => false
attribute :collectstatic, :kind_of => [TrueClass, FalseClass, String], :default => false
def local_settings_base
local_settings_file.split(/[\\\/]/).last
end
def virtualenv
"#{path}/shared/env"
end
def database(*args, &block)
@database ||= Mash.new
@database.update(options_block(*args, &block))
@database
end
| noradaiko/application_python | resources/django.rb | Ruby | apache-2.0 | 1,767 |
/*
* IzPack - Copyright 2001-2013 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2013 Tim Anderson
*
* 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.izforge.izpack.panels.userinput.console.title;
import com.izforge.izpack.api.handler.Prompt;
import com.izforge.izpack.panels.userinput.console.ConsoleField;
import com.izforge.izpack.panels.userinput.field.Field;
import com.izforge.izpack.util.Console;
/**
* Console title field.
*
* @author Tim Anderson
*/
public class ConsoleTitleField extends ConsoleField
{
/**
* Constructs a {@code ConsoleTitleField}.
*
* @param field the field
* @param console the console
*/
public ConsoleTitleField(Field field, Console console, Prompt prompt)
{
super(field, console, prompt);
}
/**
* Displays the field.
*
* @return {@code true}
*/
@Override
public boolean display()
{
String title = getField().getLabel(true);
if (title != null) {
println(title);
println("");
}
return true;
}
}
| maichler/izpack | izpack-panel/src/main/java/com/izforge/izpack/panels/userinput/console/title/ConsoleTitleField.java | Java | apache-2.0 | 1,665 |
/*
* Copyright 2015 JBoss, by Red Hat, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uberfire.ext.wires.bpmn.client.resources.i18n;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.Messages;
public interface BpmnEditorConstants
extends
Messages {
public static final BpmnEditorConstants INSTANCE = GWT.create( BpmnEditorConstants.class );
String bpmnResourceTypeDescription();
String bpmnPerspectiveTitle();
String bpmnExplorerTitle();
String bpmnExplorerNoFilesFound();
String bpmnExplorerNoFilesOpen();
String bpmnExplorerFileUrl();
String bpmnEditorTitle();
} | dgutierr/uberfire-extensions | uberfire-wires/uberfire-wires-bpmn/uberfire-wires-bpmn-client/src/main/java/org/uberfire/ext/wires/bpmn/client/resources/i18n/BpmnEditorConstants.java | Java | apache-2.0 | 1,180 |
/*
* 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.drill.exec.physical.impl.common;
import org.apache.drill.shaded.guava.com.google.common.collect.Lists;
import org.apache.calcite.rel.core.JoinRelType;
import org.apache.drill.common.config.DrillConfig;
import org.apache.drill.common.expression.FieldReference;
import org.apache.drill.common.expression.LogicalExpression;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.common.logical.data.JoinCondition;
import org.apache.drill.common.logical.data.NamedExpression;
import org.apache.drill.common.types.TypeProtos;
import org.apache.drill.common.types.Types;
import org.apache.drill.exec.ExecConstants;
import org.apache.drill.exec.memory.BufferAllocator;
import org.apache.drill.exec.ops.FragmentContext;
import org.apache.drill.exec.ops.OperatorContext;
import org.apache.drill.exec.physical.config.HashJoinPOP;
import org.apache.drill.exec.physical.impl.MockRecordBatch;
import org.apache.drill.exec.physical.impl.aggregate.SpilledRecordBatch;
import org.apache.drill.exec.physical.impl.join.HashJoinMemoryCalculator;
import org.apache.drill.exec.physical.impl.join.HashJoinMemoryCalculatorImpl;
import org.apache.drill.exec.physical.impl.join.JoinUtils;
import org.apache.drill.exec.physical.impl.spill.SpillSet;
import org.apache.drill.exec.planner.logical.DrillJoinRel;
import org.apache.drill.exec.proto.ExecProtos;
import org.apache.drill.exec.proto.UserBitShared;
import org.apache.drill.exec.record.BatchSchema;
import org.apache.drill.exec.record.CloseableRecordBatch;
import org.apache.drill.exec.record.MaterializedField;
import org.apache.drill.exec.record.RecordBatch;
import org.apache.drill.test.BaseDirTestWatcher;
import org.apache.drill.test.BaseTest;
import org.apache.drill.test.OperatorFixture;
import org.apache.drill.exec.physical.rowSet.DirectRowSet;
import org.apache.drill.exec.physical.rowSet.RowSet;
import org.apache.drill.exec.physical.rowSet.RowSetBuilder;
import org.apache.drill.test.rowSet.RowSetComparison;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import java.util.List;
public class HashPartitionTest extends BaseTest {
@Rule
public final BaseDirTestWatcher dirTestWatcher = new BaseDirTestWatcher();
@Test
public void noSpillBuildSideTest() throws Exception
{
new HashPartitionFixture().run(new HashPartitionTestCase() {
private RowSet buildRowSet;
private RowSet probeRowSet;
@Override
public CloseableRecordBatch createBuildBatch(BatchSchema schema, FragmentContext context) {
buildRowSet = new RowSetBuilder(context.getAllocator(), schema)
.addRow(1, "green")
.addRow(3, "red")
.addRow(2, "blue")
.build();
return new MockRecordBatch.Builder().
sendData(buildRowSet).
build(context);
}
@Override
public void createResultBuildBatch(BatchSchema schema, FragmentContext context) {
}
@Override
public CloseableRecordBatch createProbeBatch(BatchSchema schema, FragmentContext context) {
probeRowSet = new RowSetBuilder(context.getAllocator(), schema)
.addRow(.5f, "yellow")
.addRow(1.5f, "blue")
.addRow(2.5f, "black")
.build();
return new MockRecordBatch.Builder().
sendData(probeRowSet).
build(context);
}
@Override
public void run(SpillSet spillSet,
BatchSchema buildSchema,
BatchSchema probeSchema,
RecordBatch buildBatch,
RecordBatch probeBatch,
ChainedHashTable baseHashTable,
FragmentContext context,
OperatorContext operatorContext) throws Exception {
final HashPartition hashPartition = new HashPartition(context,
context.getAllocator(),
baseHashTable,
buildBatch,
probeBatch, false, 10,
spillSet,
0,
0,
2); // only '1' has a special treatment
final HashJoinMemoryCalculator.BuildSidePartitioning noopCalc = new HashJoinMemoryCalculatorImpl.NoopBuildSidePartitioningImpl();
hashPartition.appendInnerRow(buildBatch.getContainer(), 0, 10, noopCalc);
hashPartition.appendInnerRow(buildBatch.getContainer(), 1, 11, noopCalc);
hashPartition.appendInnerRow(buildBatch.getContainer(), 2, 12, noopCalc);
hashPartition.completeAnInnerBatch(false, false);
hashPartition.buildContainersHashTableAndHelper();
{
int compositeIndex = hashPartition.probeForKey(0, 16);
Assert.assertEquals(-1, compositeIndex);
}
{
int compositeIndex = hashPartition.probeForKey(1, 12);
int startIndex = hashPartition.getStartIndex(compositeIndex).getLeft();
int nextIndex = hashPartition.getNextIndex(startIndex);
Assert.assertEquals(2, startIndex);
Assert.assertEquals(-1, nextIndex);
}
{
int compositeIndex = hashPartition.probeForKey(2, 15);
Assert.assertEquals(-1, compositeIndex);
}
buildRowSet.clear();
probeRowSet.clear();
hashPartition.close();
}
});
}
@Test
public void spillSingleIncompleteBatchBuildSideTest() throws Exception
{
new HashPartitionFixture().run(new HashPartitionTestCase() {
private RowSet buildRowSet;
private RowSet probeRowSet;
private RowSet actualBuildRowSet;
@Override
public CloseableRecordBatch createBuildBatch(BatchSchema schema, FragmentContext context) {
buildRowSet = new RowSetBuilder(context.getAllocator(), schema)
.addRow(1, "green")
.addRow(3, "red")
.addRow(2, "blue")
.build();
return new MockRecordBatch.Builder().
sendData(buildRowSet).
build(context);
}
@Override
public void createResultBuildBatch(BatchSchema schema, FragmentContext context) {
final BatchSchema newSchema = BatchSchema.newBuilder()
.addFields(schema)
.addField(MaterializedField.create(HashPartition.HASH_VALUE_COLUMN_NAME, HashPartition.HVtype))
.build();
actualBuildRowSet = new RowSetBuilder(context.getAllocator(), newSchema)
.addRow(1, "green", 10)
.addRow(3, "red", 11)
.addRow(2, "blue", 12)
.build();
}
@Override
public CloseableRecordBatch createProbeBatch(BatchSchema schema, FragmentContext context) {
probeRowSet = new RowSetBuilder(context.getAllocator(), schema)
.addRow(.5f, "yellow")
.addRow(1.5f, "blue")
.addRow(2.5f, "black")
.build();
return new MockRecordBatch.Builder().
sendData(probeRowSet).
build(context);
}
@Override
public void run(SpillSet spillSet,
BatchSchema buildSchema,
BatchSchema probeSchema,
RecordBatch buildBatch,
RecordBatch probeBatch,
ChainedHashTable baseHashTable,
FragmentContext context,
OperatorContext operatorContext) {
final HashPartition hashPartition = new HashPartition(context,
context.getAllocator(),
baseHashTable,
buildBatch,
probeBatch, false, 10,
spillSet,
0,
0,
2);
final HashJoinMemoryCalculator.BuildSidePartitioning noopCalc = new HashJoinMemoryCalculatorImpl.NoopBuildSidePartitioningImpl();
hashPartition.appendInnerRow(buildBatch.getContainer(), 0, 10, noopCalc);
hashPartition.appendInnerRow(buildBatch.getContainer(), 1, 11, noopCalc);
hashPartition.appendInnerRow(buildBatch.getContainer(), 2, 12, noopCalc);
hashPartition.completeAnInnerBatch(false, false);
hashPartition.spillThisPartition();
final String spillFile = hashPartition.getSpillFile();
final int batchesCount = hashPartition.getPartitionBatchesCount();
hashPartition.closeWriter();
SpilledRecordBatch spilledBuildBatch = new SpilledRecordBatch(spillFile, batchesCount, context, buildSchema, operatorContext, spillSet);
final RowSet actual = DirectRowSet.fromContainer(spilledBuildBatch.getContainer());
new RowSetComparison(actualBuildRowSet).verify(actual);
spilledBuildBatch.close();
buildRowSet.clear();
actualBuildRowSet.clear();
probeRowSet.clear();
hashPartition.close();
}
});
}
public class HashPartitionFixture {
public void run(HashPartitionTestCase testCase) throws Exception {
try (OperatorFixture operatorFixture = new OperatorFixture.Builder(HashPartitionTest.this.dirTestWatcher).build()) {
final FragmentContext context = operatorFixture.getFragmentContext();
final HashJoinPOP pop = new HashJoinPOP(null, null, null, JoinRelType.FULL, null);
final OperatorContext operatorContext = operatorFixture.operatorContext(pop);
final DrillConfig config = context.getConfig();
final BufferAllocator allocator = operatorFixture.allocator();
final UserBitShared.QueryId queryId = UserBitShared.QueryId.newBuilder()
.setPart1(1L)
.setPart2(2L)
.build();
final ExecProtos.FragmentHandle fragmentHandle = ExecProtos.FragmentHandle.newBuilder()
.setQueryId(queryId)
.setMinorFragmentId(1)
.setMajorFragmentId(2)
.build();
final SpillSet spillSet = new SpillSet(config, fragmentHandle, pop);
// Create build batch
MaterializedField buildColA = MaterializedField.create("buildColA", Types.required(TypeProtos.MinorType.INT));
MaterializedField buildColB = MaterializedField.create("buildColB", Types.required(TypeProtos.MinorType.VARCHAR));
List<MaterializedField> buildCols = Lists.newArrayList(buildColA, buildColB);
final BatchSchema buildSchema = new BatchSchema(BatchSchema.SelectionVectorMode.NONE, buildCols);
final CloseableRecordBatch buildBatch = testCase.createBuildBatch(buildSchema, operatorContext.getFragmentContext());
buildBatch.next();
testCase.createResultBuildBatch(buildSchema, operatorContext.getFragmentContext());
// Create probe batch
MaterializedField probeColA = MaterializedField.create("probeColA", Types.required(TypeProtos.MinorType.FLOAT4));
MaterializedField probeColB = MaterializedField.create("probeColB", Types.required(TypeProtos.MinorType.VARCHAR));
List<MaterializedField> probeCols = Lists.newArrayList(probeColA, probeColB);
final BatchSchema probeSchema = new BatchSchema(BatchSchema.SelectionVectorMode.NONE, probeCols);
final CloseableRecordBatch probeBatch = testCase.createProbeBatch(probeSchema, operatorContext.getFragmentContext());
probeBatch.next();
final LogicalExpression buildColExpression = SchemaPath.getSimplePath(buildColB.getName());
final LogicalExpression probeColExpression = SchemaPath.getSimplePath(probeColB.getName());
final JoinCondition condition = new JoinCondition(DrillJoinRel.EQUALITY_CONDITION, probeColExpression, buildColExpression);
final List<Comparator> comparators = Lists.newArrayList(JoinUtils.checkAndReturnSupportedJoinComparator(condition));
final List<NamedExpression> buildExpressions = Lists.newArrayList(new NamedExpression(buildColExpression, new FieldReference("build_side_0")));
final List<NamedExpression> probeExpressions = Lists.newArrayList(new NamedExpression(probeColExpression, new FieldReference("probe_side_0")));
final int hashTableSize = (int) context.getOptions().getOption(ExecConstants.MIN_HASH_TABLE_SIZE);
final HashTableConfig htConfig = new HashTableConfig(hashTableSize, HashTable.DEFAULT_LOAD_FACTOR, buildExpressions, probeExpressions, comparators);
final ChainedHashTable baseHashTable = new ChainedHashTable(htConfig, context, allocator, buildBatch, probeBatch, null);
baseHashTable.updateIncoming(buildBatch, probeBatch);
testCase.run(spillSet, buildSchema, probeSchema, buildBatch, probeBatch, baseHashTable, context, operatorContext);
buildBatch.close();
probeBatch.close();
}
}
}
interface HashPartitionTestCase {
CloseableRecordBatch createBuildBatch(BatchSchema schema, FragmentContext context);
void createResultBuildBatch(BatchSchema schema, FragmentContext context);
CloseableRecordBatch createProbeBatch(BatchSchema schema, FragmentContext context);
void run(SpillSet spillSet,
BatchSchema buildSchema,
BatchSchema probeSchema,
RecordBatch buildBatch,
RecordBatch probeBatch,
ChainedHashTable baseHashTable,
FragmentContext context,
OperatorContext operatorContext) throws Exception;
}
}
| johnnywale/drill | exec/java-exec/src/test/java/org/apache/drill/exec/physical/impl/common/HashPartitionTest.java | Java | apache-2.0 | 13,922 |
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.andes.listeners;
/**
* This is an interface that declares the method where external parties
* can define andes server pre-shutdown work that needs to be done by extending this.
*/
public interface BrokerLifecycleListener {
/**
* Method declaration for pre-shutdown work
*
*/
public void onShuttingdown();
/**
* Method declaration for post-shutdown work
*
*/
public void onShutdown();
}
| hastef88/carbon-business-messaging | components/andes/org.wso2.carbon.andes/src/main/java/org/wso2/carbon/andes/listeners/BrokerLifecycleListener.java | Java | apache-2.0 | 1,101 |
/**
* Copyright 2005-2014 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.kim.impl.group;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.kuali.rice.kim.api.group.GroupMember;
import org.kuali.rice.kim.api.group.GroupMemberContract;
import org.kuali.rice.kim.impl.membership.AbstractMemberBo;
import org.kuali.rice.krad.data.jpa.PortableSequenceGenerator;
import javax.persistence.Cacheable;
@Entity
@Cacheable(false)
@Table(name = "KRIM_GRP_MBR_T")
public class GroupMemberBo extends AbstractMemberBo implements GroupMemberContract {
private static final long serialVersionUID = 6773749266062306217L;
@PortableSequenceGenerator(name = "KRIM_GRP_MBR_ID_S")
@GeneratedValue(generator = "KRIM_GRP_MBR_ID_S")
@Id
@Column(name = "GRP_MBR_ID")
private String id;
@Column(name = "GRP_ID")
private String groupId;
public static GroupMember to(GroupMemberBo bo) {
if (bo == null) {
return null;
}
return GroupMember.Builder.create(bo).build();
}
public static GroupMemberBo from(GroupMember im) {
if (im == null) {
return null;
}
GroupMemberBo bo = new GroupMemberBo();
bo.setId(im.getId());
bo.setGroupId(im.getGroupId());
bo.setMemberId(im.getMemberId());
bo.setTypeCode(im.getType().getCode());
bo.setActiveFromDateValue(im.getActiveFromDate() == null ? null : new Timestamp(im.getActiveFromDate().getMillis()));
bo.setActiveToDateValue(im.getActiveToDate() == null ? null : new Timestamp(im.getActiveToDate().getMillis()));
bo.setVersionNumber(im.getVersionNumber());
bo.setObjectId(im.getObjectId());
return bo;
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
}
| mztaylor/rice-git | rice-middleware/kim/kim-impl/src/main/java/org/kuali/rice/kim/impl/group/GroupMemberBo.java | Java | apache-2.0 | 2,735 |
/*global define, $, console, window, history, tizen*/
/**
* Init page module
*/
define({
name: 'views/audioPage',
def: function viewsAudioPage() {
'use strict';
var appControl = null,
appControlReplyCallback = null;
function onLaunchSuccess() {
console.log('launchAppControl', 'onLaunchSuccess');
}
function onLaunchError() {
console.error('launchAppControl', 'onLaunchError');
}
function launch() {
if (typeof tizen !== 'undefined') {
return;
}
tizen.application.launchAppControl(
appControl,
"com.samsung.w-voicerecorder",
onLaunchSuccess,
onLaunchError,
appControlReplyCallback
);
}
function init() {
if (typeof tizen !== 'undefined' && typeof tizen.ApplicationControl === 'function') {
appControl = new tizen.ApplicationControl(
"http://tizen.org/appcontrol/operation/create_content",
null,
"audio/amr",
null
);
} else {
console.warn('tizen.ApplicationControl not available');
}
appControlReplyCallback = {
// callee sent a reply
onsuccess: function onsuccess(data) {
var i = 0,
key = "http://tizen.org/appcontrol/data/selected";
for (i; i < data.length; i += 1) {
if (data[i].key == key) {
console.log('selected image is ' + data[i].value[0]);
}
}
},
// callee returned failure
onfailure: function onfailure() {
console.error('The launch application control failed');
}
};
}
return {
init: init,
launch: launch
};
}
});
| cwz920716/jalangi2 | tests/evernote/js/views/audioPage.js | JavaScript | apache-2.0 | 2,117 |
/**
* @license
* Copyright 2015 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.
*/
/**
* @fileoverview Implements an OpenPGP key generator using ECC keys.
*/
goog.provide('e2e.openpgp.KeyGenerator');
goog.require('e2e');
goog.require('e2e.Hkdf');
goog.require('e2e.algorithm.KeyLocations');
goog.require('e2e.asymmetric.keygenerator');
goog.require('e2e.async.Result');
goog.require('e2e.cipher.Algorithm');
goog.require('e2e.error.InvalidArgumentsError');
goog.require('e2e.hash.Sha256');
goog.require('e2e.openpgp');
goog.require('e2e.openpgp.DummyS2k');
goog.require('e2e.openpgp.EncryptedCipher');
goog.require('e2e.openpgp.Mpi');
goog.require('e2e.openpgp.block.TransferablePublicKey');
goog.require('e2e.openpgp.block.TransferableSecretKey');
goog.require('e2e.openpgp.error.UnsupportedError');
goog.require('e2e.openpgp.packet.PublicKey');
goog.require('e2e.openpgp.packet.PublicSubkey');
goog.require('e2e.openpgp.packet.SecretKey');
goog.require('e2e.openpgp.packet.SecretSubkey');
goog.require('e2e.openpgp.packet.Signature');
goog.require('e2e.openpgp.packet.SignatureSub');
goog.require('e2e.openpgp.packet.UserId');
goog.require('e2e.random');
goog.require('e2e.signer.Algorithm');
goog.require('goog.array');
/**
* Implements an OpenPGP key generator
* @constructor
*/
e2e.openpgp.KeyGenerator = function() {};
/**
* ECC key generation seed
* @type {?e2e.ByteArray}
* @private
*/
e2e.openpgp.KeyGenerator.prototype.eccSeed_;
/**
* Number of keys generated from ECC generation seed
* @type {?number}
* @private
*/
e2e.openpgp.KeyGenerator.prototype.eccCount_;
/**
* Size in bytes for the ECC key generation seed.
* @const
*/
e2e.openpgp.KeyGenerator.ECC_SEED_SIZE = 16;
/**
* Returns the ECC key generation seed and key count backup data.
* @return {!e2e.openpgp.KeyringBackupInfo}
*/
e2e.openpgp.KeyGenerator.prototype.getGeneratorState = function() {
return {
seed: this.eccSeed_,
count: this.eccCount_
};
};
/**
* Initializes the ECC key generation seed and key count.
* @param {e2e.openpgp.KeyringBackupInfo} backupInfo
*/
e2e.openpgp.KeyGenerator.prototype.setGeneratorState = function(backupInfo) {
if (goog.isDefAndNotNull(backupInfo) && backupInfo.count % 2) {
throw new e2e.error.InvalidArgumentsError('Keys must be restored in pairs');
}
this.eccSeed_ = goog.isDefAndNotNull(backupInfo) ? (backupInfo.seed ||
null) : null;
this.eccCount_ = goog.isDefAndNotNull(backupInfo) ? (backupInfo.count ||
null) : null;
};
/**
* Generates and imports to the key ring a master signing key and a subordinate
* encryption key.
* @param {string} email The email to associate the key with.
* @param {!e2e.signer.Algorithm} keyAlgo Algorithm of the master key.
* It must be one of the digital signature algorithms.
* @param {number} keyLength Length in bits of the master key.
* @param {e2e.cipher.Algorithm} subkeyAlgo Algorithm of the subkey.
* It must be one of the cipher algorithms.
* @param {number} subkeyLength Length in bits of the subkey.
* @param {!e2e.algorithm.KeyLocations=} opt_keyLocation Where should the key be
* stored? (default to JS)
* @return {e2e.async.Result.<!Array.<!e2e.openpgp.block.TransferableKey>>}
* The generated public key and secret key in an array.
*/
e2e.openpgp.KeyGenerator.prototype.generateKey = function(email,
keyAlgo,
keyLength,
subkeyAlgo,
subkeyLength,
opt_keyLocation) {
var keyData = {
'pubKey': new Array(),
'privKey': new Array()
};
if (!goog.isDef(opt_keyLocation)) {
opt_keyLocation = e2e.algorithm.KeyLocations.JAVASCRIPT;
}
if (opt_keyLocation == e2e.algorithm.KeyLocations.JAVASCRIPT) {
var fingerprint;
if (keyAlgo == e2e.signer.Algorithm.ECDSA &&
keyLength == 256) {
var ecdsa = e2e.asymmetric.keygenerator.newEcdsaWithP256(
this.getNextKey_(keyLength));
this.extractKeyData_(keyData, ecdsa);
fingerprint = keyData.pubKey[0].fingerprint;
}
if (subkeyAlgo == e2e.cipher.Algorithm.ECDH &&
subkeyLength == 256) {
var ecdh = e2e.asymmetric.keygenerator.newEcdhWithP256(
this.getNextKey_(subkeyLength));
this.extractKeyData_(keyData, ecdh, true);
}
return e2e.async.Result.toResult(this.certifyKeys_(email, keyData));
} else if (opt_keyLocation == e2e.algorithm.KeyLocations.WEB_CRYPTO) {
if (keyAlgo == e2e.signer.Algorithm.RSA) {
if ((keyLength != 4096 && keyLength != 8192) ||
subkeyAlgo != e2e.cipher.Algorithm.RSA || subkeyLength != keyLength) {
throw new e2e.openpgp.error.UnsupportedError(
'WebCrypto RSA keyLength must be 4096 or 8192');
}
return e2e.asymmetric.keygenerator.newWebCryptoRsaKeys(
keyLength).addCallback(
function(ciphers) {
this.extractKeyData_(keyData, ciphers[0]);
this.extractKeyData_(keyData, ciphers[1]);
return this.certifyKeys_(email, keyData);
});
}
} else if (opt_keyLocation == e2e.algorithm.KeyLocations.HARDWARE) {
// TODO(user): https://code.google.com/p/end-to-end/issues/detail?id=130
throw new e2e.openpgp.error.UnsupportedError(
'Hardware keygen not supported yet');
}
// Should never happen.
throw new e2e.openpgp.error.UnsupportedError(
'Unsupported key type or length.');
};
/**
* @param {string} email The email to associate the key with.
* @param {{privKey: Array, pubKey: Array}} keyData
* @return {!Array.<!e2e.openpgp.block.TransferableKey>}
* @private
*/
e2e.openpgp.KeyGenerator.prototype.certifyKeys_ = function(email, keyData) {
if (keyData['pubKey'].length == 2 && keyData['privKey'].length == 2) {
// TODO(evn): Move this code to a .construct.
var primaryKey = keyData['privKey'][0];
var uid = new e2e.openpgp.packet.UserId(email);
uid.certifyBy(primaryKey);
keyData['privKey'][1].bindTo(
primaryKey,
e2e.openpgp.packet.Signature.SignatureType.SUBKEY,
e2e.openpgp.packet.SignatureSub.KeyFlags.ENCRYPT_COMMUNICATION |
e2e.openpgp.packet.SignatureSub.KeyFlags.ENCRYPT_STORAGE);
keyData['pubKey'][1].bindTo(
primaryKey,
e2e.openpgp.packet.Signature.SignatureType.SUBKEY,
e2e.openpgp.packet.SignatureSub.KeyFlags.ENCRYPT_COMMUNICATION |
e2e.openpgp.packet.SignatureSub.KeyFlags.ENCRYPT_STORAGE
);
var privKeyBlock = new e2e.openpgp.block.TransferableSecretKey();
privKeyBlock.keyPacket = primaryKey;
privKeyBlock.addUnverifiedSubKey(keyData['privKey'][1]);
privKeyBlock.addUnverifiedUserId(uid);
var pubKeyBlock = new e2e.openpgp.block.TransferablePublicKey();
pubKeyBlock.keyPacket = keyData['pubKey'][0];
pubKeyBlock.addUnverifiedSubKey(keyData['pubKey'][1]);
pubKeyBlock.addUnverifiedUserId(uid);
privKeyBlock.processSignatures();
pubKeyBlock.processSignatures();
return [pubKeyBlock, privKeyBlock];
}
// Should never happen.
throw new e2e.openpgp.error.UnsupportedError(
'Unsupported key type or length.');
};
/**
* Extracts serialized key data contained in a crypto object.
* @param {{privKey: Array, pubKey: Array}} keyData The map
* to store the extracted data.
* @param {!e2e.cipher.Cipher|!e2e.signer.Signer} cryptor
* The crypto object to extract key material.
* @param {boolean=} opt_subKey Whether the key is a subkey. Defaults to false.
* @param {boolean=} opt_isJS Whether the key material is stored in JS.
* Default to true.
* @private
*/
e2e.openpgp.KeyGenerator.prototype.extractKeyData_ = function(
keyData, cryptor, opt_subKey, opt_isJS) {
var version = 0x04;
var timestamp = 0;
var publicConstructor = opt_subKey ?
e2e.openpgp.packet.PublicSubkey : e2e.openpgp.packet.PublicKey;
var secretConstructor = opt_subKey ?
e2e.openpgp.packet.SecretSubkey : e2e.openpgp.packet.SecretKey;
var pubKey = new publicConstructor(
version, timestamp, cryptor);
var serializedPubKey = pubKey.serializePacketBody();
if (!goog.isDef(opt_isJS)) {
opt_isJS = true;
}
var serializedPrivKey;
if (opt_isJS) {
// privKey is MPI, needs to serialize to get the right byte array.
var privKey = e2e.openpgp.Mpi.serialize(cryptor.getKey()['privKey']);
serializedPrivKey = goog.array.flatten(
serializedPubKey,
/* key is not encrypted individually. */
e2e.openpgp.EncryptedCipher.KeyDerivationType.PLAINTEXT,
privKey,
e2e.openpgp.calculateNumericChecksum(privKey));
} else {
// Use dummy s2k
var s2k = new e2e.openpgp.DummyS2k(new e2e.hash.Sha256,
[0x45, 0x32, 0x45],
e2e.openpgp.DummyS2k.E2E_modes.WEB_CRYPTO);
serializedPrivKey = goog.array.flatten(
serializedPubKey,
e2e.openpgp.EncryptedCipher.KeyDerivationType.S2K_CHECKSUM,
s2k.serialize(), [0], [0]);
}
privKey = secretConstructor.parse(serializedPrivKey);
privKey.cipher.unlockKey();
keyData['privKey'].push(privKey);
keyData['pubKey'].push(
publicConstructor.parse(serializedPubKey));
};
/**
* Generates the next key in the sequence based on the ECC generation seed
* @param {number} keyLength Length in bits of the key.
* @private
* @return {!e2e.ByteArray} Deterministic privKey based on ECC seed.
*/
e2e.openpgp.KeyGenerator.prototype.getNextKey_ = function(keyLength) {
if (!this.eccSeed_) {
this.eccSeed_ = e2e.random.getRandomBytes(
e2e.openpgp.KeyGenerator.ECC_SEED_SIZE);
this.eccCount_ = 0;
}
if (++this.eccCount_ > 0x7F) {
throw new e2e.openpgp.error.UnsupportedError('Too many ECC keys generated');
}
if (keyLength % 8) {
throw new e2e.openpgp.error.UnsupportedError(
'Key length is not a multiple of 8');
}
return new e2e.Hkdf(new e2e.hash.Sha256()).getHKDF(this.eccSeed_,
e2e.dwordArrayToByteArray([this.eccCount_]), keyLength / 8);
};
| adhintz/end-to-end | src/javascript/crypto/e2e/openpgp/keygenerator.js | JavaScript | apache-2.0 | 10,724 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.io.keyStorage;
import com.intellij.util.Processor;
import com.intellij.util.io.InlineKeyDescriptor;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
public class InlinedKeyStorage<Data> implements AppendableObjectStorage<Data> {
private final InlineKeyDescriptor<Data> myDescriptor;
public InlinedKeyStorage(@NotNull InlineKeyDescriptor<Data> descriptor) {
myDescriptor = descriptor;
}
@Override
public Data read(int addr) throws IOException {
return myDescriptor.fromInt(addr);
}
@Override
public boolean processAll(@NotNull Processor<? super Data> processor) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public int append(Data value) throws IOException {
return myDescriptor.toInt(value);
}
@Override
public boolean checkBytesAreTheSame(int addr, Data value) {
return false;
}
@Override
public void lockRead() {
throw new UnsupportedOperationException();
}
@Override
public void unlockRead() {
throw new UnsupportedOperationException();
}
@Override
public void lockWrite() {
throw new UnsupportedOperationException();
}
@Override
public void unlockWrite() {
throw new UnsupportedOperationException();
}
@Override
public int getCurrentLength() {
throw new UnsupportedOperationException();
}
@Override
public boolean isDirty() {
return false;
}
@Override
public void force() {
}
@Override
public void close() throws IOException {
}
}
| zdary/intellij-community | platform/util/src/com/intellij/util/io/keyStorage/InlinedKeyStorage.java | Java | apache-2.0 | 1,695 |
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.android.result;
import com.google.zxing.client.android.R;
import com.google.zxing.client.result.AddressBookParsedResult;
import com.google.zxing.client.result.ParsedResult;
import android.app.Activity;
import android.telephony.PhoneNumberUtils;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.StyleSpan;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Handles address book entries.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class AddressBookResultHandler extends ResultHandler {
private static final DateFormat[] DATE_FORMATS = {
new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH),
new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH),
new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH),
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH),
};
static {
for (DateFormat format : DATE_FORMATS) {
format.setLenient(false);
}
}
private static final int[] BUTTON_TEXTS = {
R.string.button_add_contact,
R.string.button_show_map,
R.string.button_dial,
R.string.button_email,
};
private final boolean[] fields;
private int buttonCount;
// This takes all the work out of figuring out which buttons/actions should be in which
// positions, based on which fields are present in this barcode.
private int mapIndexToAction(int index) {
if (index < buttonCount) {
int count = -1;
for (int x = 0; x < MAX_BUTTON_COUNT; x++) {
if (fields[x]) {
count++;
}
if (count == index) {
return x;
}
}
}
return -1;
}
public AddressBookResultHandler(Activity activity, ParsedResult result) {
super(activity, result);
AddressBookParsedResult addressResult = (AddressBookParsedResult) result;
String[] addresses = addressResult.getAddresses();
boolean hasAddress = addresses != null && addresses.length > 0 && addresses[0].length() > 0;
String[] phoneNumbers = addressResult.getPhoneNumbers();
boolean hasPhoneNumber = phoneNumbers != null && phoneNumbers.length > 0;
String[] emails = addressResult.getEmails();
boolean hasEmailAddress = emails != null && emails.length > 0;
fields = new boolean[MAX_BUTTON_COUNT];
fields[0] = true; // Add contact is always available
fields[1] = hasAddress;
fields[2] = hasPhoneNumber;
fields[3] = hasEmailAddress;
buttonCount = 0;
for (int x = 0; x < MAX_BUTTON_COUNT; x++) {
if (fields[x]) {
buttonCount++;
}
}
}
@Override
public int getButtonCount() {
return buttonCount;
}
@Override
public int getButtonText(int index) {
return BUTTON_TEXTS[mapIndexToAction(index)];
}
@Override
public void handleButtonPress(int index) {
AddressBookParsedResult addressResult = (AddressBookParsedResult) getResult();
String[] addresses = addressResult.getAddresses();
String address1 = addresses == null || addresses.length < 1 ? null : addresses[0];
String[] addressTypes = addressResult.getAddressTypes();
String address1Type = addressTypes == null || addressTypes.length < 1 ? null : addressTypes[0];
int action = mapIndexToAction(index);
switch (action) {
case 0:
addContact(addressResult.getNames(),
addressResult.getPronunciation(),
addressResult.getPhoneNumbers(),
addressResult.getPhoneTypes(),
addressResult.getEmails(),
addressResult.getEmailTypes(),
addressResult.getNote(),
addressResult.getInstantMessenger(),
address1,
address1Type,
addressResult.getOrg(),
addressResult.getTitle(),
addressResult.getURL(),
addressResult.getBirthday());
break;
case 1:
String[] names = addressResult.getNames();
String title = names != null ? names[0] : null;
searchMap(address1, title);
break;
case 2:
dialPhone(addressResult.getPhoneNumbers()[0]);
break;
case 3:
sendEmail(addressResult.getEmails()[0], null, null);
break;
default:
break;
}
}
private static Date parseDate(String s) {
for (DateFormat currentFormat : DATE_FORMATS) {
try {
return currentFormat.parse(s);
} catch (ParseException e) {
// continue
}
}
return null;
}
// Overriden so we can hyphenate phone numbers, format birthdays, and bold the name.
@Override
public CharSequence getDisplayContents() {
AddressBookParsedResult result = (AddressBookParsedResult) getResult();
StringBuilder contents = new StringBuilder(100);
ParsedResult.maybeAppend(result.getNames(), contents);
int namesLength = contents.length();
String pronunciation = result.getPronunciation();
if (pronunciation != null && pronunciation.length() > 0) {
contents.append("\n(");
contents.append(pronunciation);
contents.append(')');
}
ParsedResult.maybeAppend(result.getTitle(), contents);
ParsedResult.maybeAppend(result.getOrg(), contents);
ParsedResult.maybeAppend(result.getAddresses(), contents);
String[] numbers = result.getPhoneNumbers();
if (numbers != null) {
for (String number : numbers) {
ParsedResult.maybeAppend(PhoneNumberUtils.formatNumber(number), contents);
}
}
ParsedResult.maybeAppend(result.getEmails(), contents);
ParsedResult.maybeAppend(result.getURL(), contents);
String birthday = result.getBirthday();
if (birthday != null && birthday.length() > 0) {
Date date = parseDate(birthday);
if (date != null) {
ParsedResult.maybeAppend(DateFormat.getDateInstance(DateFormat.MEDIUM).format(date.getTime()), contents);
}
}
ParsedResult.maybeAppend(result.getNote(), contents);
if (namesLength > 0) {
// Bold the full name to make it stand out a bit.
Spannable styled = new SpannableString(contents.toString());
styled.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, namesLength, 0);
return styled;
} else {
return contents.toString();
}
}
@Override
public int getDisplayTitle() {
return R.string.result_address_book;
}
}
| kerwinxu/barcodeManager | zxing/android/src/com/google/zxing/client/android/result/AddressBookResultHandler.java | Java | bsd-2-clause | 7,135 |
class RakeCompletion < Formula
desc "Bash completion for Rake"
homepage "https://github.com/JoeNyland/rake-completion"
url "https://github.com/JoeNyland/rake-completion/archive/v1.0.1.tar.gz"
sha256 "085801e62cb240311d77885778a603f649b3fd5d85ee279691d1d00bc060bba6"
license "MIT"
bottle do
sha256 cellar: :any_skip_relocation, all: "6d5a9f29cceb2470b61d563fc7d9d762e0a8b73f8e052d99103fad25e6301f62"
end
def install
bash_completion.install "rake.sh" => "rake"
end
test do
assert_match "-F _rakecomplete",
shell_output("bash -c 'source #{bash_completion}/rake && complete -p rake'")
end
end
| sjackman/homebrew-core | Formula/rake-completion.rb | Ruby | bsd-2-clause | 632 |
import jinja2
from django_jinja import library
from kitsune.sumo import parser
from kitsune.wiki.diff import BetterHtmlDiff
@library.global_function
def diff_table(content_from, content_to):
"""Creates an HTML diff of the passed in content_from and content_to."""
html_diff = BetterHtmlDiff()
diff = html_diff.make_table(content_from.splitlines(), content_to.splitlines(), context=True)
return jinja2.Markup(diff)
@library.global_function
def generate_video(v):
return jinja2.Markup(parser.generate_video(v))
| mythmon/kitsune | kitsune/wiki/templatetags/jinja_helpers.py | Python | bsd-3-clause | 534 |
<?php
use bedezign\yii2\audit\Audit;
use yii\helpers\Html;
use yii\grid\GridView;
use bedezign\yii2\audit\models\AuditEntrySearch;
/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('audit', 'Entries');
$this->params['breadcrumbs'][] = ['label' => Yii::t('audit', 'Audit'), 'url' => ['default/index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="audit-entry-index">
<h1><?= Html::encode($this->title) ?></h1>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\ActionColumn', 'template' => '{view}'],
'id',
[
'attribute' => 'user_id',
'label' => Yii::t('audit', 'User'),
'class' => 'yii\grid\DataColumn',
'value' => function ($data) {
return Audit::getInstance()->getUserIdentifier($data->user_id);
},
'format' => 'raw',
],
'ip',
[
'filter' => AuditEntrySearch::methodFilter(),
'attribute' => 'request_method',
],
[
'filter' => [1 => \Yii::t('audit', 'Yes'), 0 => \Yii::t('audit', 'No')],
'attribute' => 'ajax',
'value' => function($data) {
return $data->ajax ? Yii::t('audit', 'Yes') : Yii::t('audit', 'No');
},
],
[
'class' => 'yii\grid\DataColumn',
'attribute' => 'route',
'filter' => AuditEntrySearch::routeFilter(),
'format' => 'html',
'value' => function ($data) {
return HTML::tag('span', '', [
'title' => \yii\helpers\Url::to([$data->route]),
'class' => 'glyphicon glyphicon-link'
]) . ' ' . $data->route;
},
],
[
'attribute' => 'duration',
'format' => 'decimal',
'contentOptions' => ['class' => 'text-right', 'width' => '100px'],
],
[
'attribute' => 'memory_max',
'format' => 'shortsize',
'contentOptions' => ['class' => 'text-right', 'width' => '100px'],
],
[
'attribute' => 'trails',
'value' => function ($data) {
return $data->trails ? count($data->trails) : '';
},
'contentOptions' => ['class' => 'text-right'],
],
[
'attribute' => 'mails',
'value' => function ($data) {
return $data->mails ? count($data->mails) : '';
},
'contentOptions' => ['class' => 'text-right'],
],
[
'attribute' => 'javascripts',
'value' => function ($data) {
return $data->javascripts ? count($data->javascripts) : '';
},
'contentOptions' => ['class' => 'text-right'],
],
[
'attribute' => 'errors',
'value' => function ($data) {
return $data->linkedErrors ? count($data->linkedErrors) : '';
},
'contentOptions' => ['class' => 'text-right'],
],
[
'attribute' => 'created',
'options' => ['width' => '150px'],
],
],
]); ?>
</div>
| hung101/kbs | vendor/bedezign/yii2-audit/src/views/entry/index.php | PHP | bsd-3-clause | 3,690 |
from __future__ import division, absolute_import, print_function
import re
import os
import sys
import warnings
import platform
import tempfile
from subprocess import Popen, PIPE, STDOUT
from numpy.distutils.fcompiler import FCompiler
from numpy.distutils.exec_command import exec_command
from numpy.distutils.misc_util import msvc_runtime_library
from numpy.distutils.compat import get_exception
compilers = ['GnuFCompiler', 'Gnu95FCompiler']
TARGET_R = re.compile("Target: ([a-zA-Z0-9_\-]*)")
# XXX: handle cross compilation
def is_win64():
return sys.platform == "win32" and platform.architecture()[0] == "64bit"
if is_win64():
#_EXTRAFLAGS = ["-fno-leading-underscore"]
_EXTRAFLAGS = []
else:
_EXTRAFLAGS = []
class GnuFCompiler(FCompiler):
compiler_type = 'gnu'
compiler_aliases = ('g77',)
description = 'GNU Fortran 77 compiler'
def gnu_version_match(self, version_string):
"""Handle the different versions of GNU fortran compilers"""
# Strip warning(s) that may be emitted by gfortran
while version_string.startswith('gfortran: warning'):
version_string = version_string[version_string.find('\n')+1:]
# Gfortran versions from after 2010 will output a simple string
# (usually "x.y", "x.y.z" or "x.y.z-q") for ``-dumpversion``; older
# gfortrans may still return long version strings (``-dumpversion`` was
# an alias for ``--version``)
if len(version_string) <= 20:
# Try to find a valid version string
m = re.search(r'([0-9.]+)', version_string)
if m:
# g77 provides a longer version string that starts with GNU
# Fortran
if version_string.startswith('GNU Fortran'):
return ('g77', m.group(1))
# gfortran only outputs a version string such as #.#.#, so check
# if the match is at the start of the string
elif m.start() == 0:
return ('gfortran', m.group(1))
else:
# Output probably from --version, try harder:
m = re.search(r'GNU Fortran\s+95.*?([0-9-.]+)', version_string)
if m:
return ('gfortran', m.group(1))
m = re.search(r'GNU Fortran.*?\-?([0-9-.]+)', version_string)
if m:
v = m.group(1)
if v.startswith('0') or v.startswith('2') or v.startswith('3'):
# the '0' is for early g77's
return ('g77', v)
else:
# at some point in the 4.x series, the ' 95' was dropped
# from the version string
return ('gfortran', v)
# If still nothing, raise an error to make the problem easy to find.
err = 'A valid Fortran version was not found in this string:\n'
raise ValueError(err + version_string)
def version_match(self, version_string):
v = self.gnu_version_match(version_string)
if not v or v[0] != 'g77':
return None
return v[1]
possible_executables = ['g77', 'f77']
executables = {
'version_cmd' : [None, "-dumpversion"],
'compiler_f77' : [None, "-g", "-Wall", "-fno-second-underscore"],
'compiler_f90' : None, # Use --fcompiler=gnu95 for f90 codes
'compiler_fix' : None,
'linker_so' : [None, "-g", "-Wall"],
'archiver' : ["ar", "-cr"],
'ranlib' : ["ranlib"],
'linker_exe' : [None, "-g", "-Wall"]
}
module_dir_switch = None
module_include_switch = None
# Cygwin: f771: warning: -fPIC ignored for target (all code is
# position independent)
if os.name != 'nt' and sys.platform != 'cygwin':
pic_flags = ['-fPIC']
# use -mno-cygwin for g77 when Python is not Cygwin-Python
if sys.platform == 'win32':
for key in ['version_cmd', 'compiler_f77', 'linker_so', 'linker_exe']:
executables[key].append('-mno-cygwin')
g2c = 'g2c'
suggested_f90_compiler = 'gnu95'
def get_flags_linker_so(self):
opt = self.linker_so[1:]
if sys.platform == 'darwin':
target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', None)
# If MACOSX_DEPLOYMENT_TARGET is set, we simply trust the value
# and leave it alone. But, distutils will complain if the
# environment's value is different from the one in the Python
# Makefile used to build Python. We let disutils handle this
# error checking.
if not target:
# If MACOSX_DEPLOYMENT_TARGET is not set in the environment,
# we try to get it first from the Python Makefile and then we
# fall back to setting it to 10.3 to maximize the set of
# versions we can work with. This is a reasonable default
# even when using the official Python dist and those derived
# from it.
import distutils.sysconfig as sc
g = {}
try:
get_makefile_filename = sc.get_makefile_filename
except AttributeError:
pass # i.e. PyPy
else:
filename = get_makefile_filename()
sc.parse_makefile(filename, g)
target = g.get('MACOSX_DEPLOYMENT_TARGET', '10.3')
os.environ['MACOSX_DEPLOYMENT_TARGET'] = target
if target == '10.3':
s = 'Env. variable MACOSX_DEPLOYMENT_TARGET set to 10.3'
warnings.warn(s, stacklevel=2)
opt.extend(['-undefined', 'dynamic_lookup', '-bundle'])
else:
opt.append("-shared")
if sys.platform.startswith('sunos'):
# SunOS often has dynamically loaded symbols defined in the
# static library libg2c.a The linker doesn't like this. To
# ignore the problem, use the -mimpure-text flag. It isn't
# the safest thing, but seems to work. 'man gcc' says:
# ".. Instead of using -mimpure-text, you should compile all
# source code with -fpic or -fPIC."
opt.append('-mimpure-text')
return opt
def get_libgcc_dir(self):
status, output = exec_command(self.compiler_f77 +
['-print-libgcc-file-name'],
use_tee=0)
if not status:
return os.path.dirname(output)
return None
def get_library_dirs(self):
opt = []
if sys.platform[:5] != 'linux':
d = self.get_libgcc_dir()
if d:
# if windows and not cygwin, libg2c lies in a different folder
if sys.platform == 'win32' and not d.startswith('/usr/lib'):
d = os.path.normpath(d)
path = os.path.join(d, "lib%s.a" % self.g2c)
if not os.path.exists(path):
root = os.path.join(d, *((os.pardir,)*4))
d2 = os.path.abspath(os.path.join(root, 'lib'))
path = os.path.join(d2, "lib%s.a" % self.g2c)
if os.path.exists(path):
opt.append(d2)
opt.append(d)
return opt
def get_libraries(self):
opt = []
d = self.get_libgcc_dir()
if d is not None:
g2c = self.g2c + '-pic'
f = self.static_lib_format % (g2c, self.static_lib_extension)
if not os.path.isfile(os.path.join(d, f)):
g2c = self.g2c
else:
g2c = self.g2c
if g2c is not None:
opt.append(g2c)
c_compiler = self.c_compiler
if sys.platform == 'win32' and c_compiler and \
c_compiler.compiler_type == 'msvc':
# the following code is not needed (read: breaks) when using MinGW
# in case want to link F77 compiled code with MSVC
opt.append('gcc')
runtime_lib = msvc_runtime_library()
if runtime_lib:
opt.append(runtime_lib)
if sys.platform == 'darwin':
opt.append('cc_dynamic')
return opt
def get_flags_debug(self):
return ['-g']
def get_flags_opt(self):
v = self.get_version()
if v and v <= '3.3.3':
# With this compiler version building Fortran BLAS/LAPACK
# with -O3 caused failures in lib.lapack heevr,syevr tests.
opt = ['-O2']
else:
opt = ['-O3']
opt.append('-funroll-loops')
return opt
def _c_arch_flags(self):
""" Return detected arch flags from CFLAGS """
from distutils import sysconfig
try:
cflags = sysconfig.get_config_vars()['CFLAGS']
except KeyError:
return []
arch_re = re.compile(r"-arch\s+(\w+)")
arch_flags = []
for arch in arch_re.findall(cflags):
arch_flags += ['-arch', arch]
return arch_flags
def get_flags_arch(self):
return []
def runtime_library_dir_option(self, dir):
sep = ',' if sys.platform == 'darwin' else '='
return '-Wl,-rpath%s"%s"' % (sep, dir)
class Gnu95FCompiler(GnuFCompiler):
compiler_type = 'gnu95'
compiler_aliases = ('gfortran',)
description = 'GNU Fortran 95 compiler'
def version_match(self, version_string):
v = self.gnu_version_match(version_string)
if not v or v[0] != 'gfortran':
return None
v = v[1]
if v >= '4.':
# gcc-4 series releases do not support -mno-cygwin option
pass
else:
# use -mno-cygwin flag for gfortran when Python is not
# Cygwin-Python
if sys.platform == 'win32':
for key in ['version_cmd', 'compiler_f77', 'compiler_f90',
'compiler_fix', 'linker_so', 'linker_exe']:
self.executables[key].append('-mno-cygwin')
return v
possible_executables = ['gfortran', 'f95']
executables = {
'version_cmd' : ["<F90>", "-dumpversion"],
'compiler_f77' : [None, "-Wall", "-g", "-ffixed-form",
"-fno-second-underscore"] + _EXTRAFLAGS,
'compiler_f90' : [None, "-Wall", "-g",
"-fno-second-underscore"] + _EXTRAFLAGS,
'compiler_fix' : [None, "-Wall", "-g","-ffixed-form",
"-fno-second-underscore"] + _EXTRAFLAGS,
'linker_so' : ["<F90>", "-Wall", "-g"],
'archiver' : ["ar", "-cr"],
'ranlib' : ["ranlib"],
'linker_exe' : [None, "-Wall"]
}
module_dir_switch = '-J'
module_include_switch = '-I'
g2c = 'gfortran'
def _universal_flags(self, cmd):
"""Return a list of -arch flags for every supported architecture."""
if not sys.platform == 'darwin':
return []
arch_flags = []
# get arches the C compiler gets.
c_archs = self._c_arch_flags()
if "i386" in c_archs:
c_archs[c_archs.index("i386")] = "i686"
# check the arches the Fortran compiler supports, and compare with
# arch flags from C compiler
for arch in ["ppc", "i686", "x86_64", "ppc64"]:
if _can_target(cmd, arch) and arch in c_archs:
arch_flags.extend(["-arch", arch])
return arch_flags
def get_flags(self):
flags = GnuFCompiler.get_flags(self)
arch_flags = self._universal_flags(self.compiler_f90)
if arch_flags:
flags[:0] = arch_flags
return flags
def get_flags_linker_so(self):
flags = GnuFCompiler.get_flags_linker_so(self)
arch_flags = self._universal_flags(self.linker_so)
if arch_flags:
flags[:0] = arch_flags
return flags
def get_library_dirs(self):
opt = GnuFCompiler.get_library_dirs(self)
if sys.platform == 'win32':
c_compiler = self.c_compiler
if c_compiler and c_compiler.compiler_type == "msvc":
target = self.get_target()
if target:
d = os.path.normpath(self.get_libgcc_dir())
root = os.path.join(d, *((os.pardir,)*4))
path = os.path.join(root, "lib")
mingwdir = os.path.normpath(path)
if os.path.exists(os.path.join(mingwdir, "libmingwex.a")):
opt.append(mingwdir)
return opt
def get_libraries(self):
opt = GnuFCompiler.get_libraries(self)
if sys.platform == 'darwin':
opt.remove('cc_dynamic')
if sys.platform == 'win32':
c_compiler = self.c_compiler
if c_compiler and c_compiler.compiler_type == "msvc":
if "gcc" in opt:
i = opt.index("gcc")
opt.insert(i+1, "mingwex")
opt.insert(i+1, "mingw32")
# XXX: fix this mess, does not work for mingw
if is_win64():
c_compiler = self.c_compiler
if c_compiler and c_compiler.compiler_type == "msvc":
return []
else:
pass
return opt
def get_target(self):
status, output = exec_command(self.compiler_f77 +
['-v'],
use_tee=0)
if not status:
m = TARGET_R.search(output)
if m:
return m.group(1)
return ""
def get_flags_opt(self):
if is_win64():
return ['-O0']
else:
return GnuFCompiler.get_flags_opt(self)
def _can_target(cmd, arch):
"""Return true if the architecture supports the -arch flag"""
newcmd = cmd[:]
fid, filename = tempfile.mkstemp(suffix=".f")
os.close(fid)
try:
d = os.path.dirname(filename)
output = os.path.splitext(filename)[0] + ".o"
try:
newcmd.extend(["-arch", arch, "-c", filename])
p = Popen(newcmd, stderr=STDOUT, stdout=PIPE, cwd=d)
p.communicate()
return p.returncode == 0
finally:
if os.path.exists(output):
os.remove(output)
finally:
os.remove(filename)
return False
if __name__ == '__main__':
from distutils import log
log.set_verbosity(2)
compiler = GnuFCompiler()
compiler.customize()
print(compiler.get_version())
try:
compiler = Gnu95FCompiler()
compiler.customize()
print(compiler.get_version())
except Exception:
msg = get_exception()
print(msg)
| maniteja123/numpy | numpy/distutils/fcompiler/gnu.py | Python | bsd-3-clause | 14,957 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @package Zend_Loader
*/
namespace Zend\Loader;
use ArrayIterator;
use IteratorAggregate;
use Traversable;
/**
* Plugin class locator interface
*
* @category Zend
* @package Zend_Loader
*/
class PluginClassLoader implements PluginClassLocator
{
/**
* List of plugin name => class name pairs
* @var array
*/
protected $plugins = array();
/**
* Static map allow global seeding of plugin loader
* @var array
*/
protected static $staticMap = array();
/**
* Constructor
*
* @param null|array|Traversable $map If provided, seeds the loader with a map
*/
public function __construct($map = null)
{
// Merge in static overrides
if (!empty(static::$staticMap)) {
$this->registerPlugins(static::$staticMap);
}
// Merge in constructor arguments
if ($map !== null) {
$this->registerPlugins($map);
}
}
/**
* Add a static map of plugins
*
* A null value will clear the static map.
*
* @param null|array|Traversable $map
* @throws Exception\InvalidArgumentException
* @return void
*/
public static function addStaticMap($map)
{
if (null === $map) {
static::$staticMap = array();
return;
}
if (!is_array($map) && !$map instanceof \Traversable) {
throw new Exception\InvalidArgumentException('Expects an array or Traversable object');
}
foreach ($map as $key => $value) {
static::$staticMap[$key] = $value;
}
}
/**
* Register a class to a given short name
*
* @param string $shortName
* @param string $className
* @return PluginClassLoader
*/
public function registerPlugin($shortName, $className)
{
$this->plugins[strtolower($shortName)] = $className;
return $this;
}
/**
* Register many plugins at once
*
* If $map is a string, assumes that the map is the class name of a
* Traversable object (likely a ShortNameLocator); it will then instantiate
* this class and use it to register plugins.
*
* If $map is an array or Traversable object, it will iterate it to
* register plugin names/classes.
*
* For all other arguments, or if the string $map is not a class or not a
* Traversable class, an exception will be raised.
*
* @param string|array|Traversable $map
* @return PluginClassLoader
* @throws Exception\InvalidArgumentException
*/
public function registerPlugins($map)
{
if (is_string($map)) {
if (!class_exists($map)) {
throw new Exception\InvalidArgumentException('Map class provided is invalid');
}
$map = new $map;
}
if (is_array($map)) {
$map = new ArrayIterator($map);
}
if (!$map instanceof Traversable) {
throw new Exception\InvalidArgumentException('Map provided is invalid; must be traversable');
}
// iterator_apply doesn't work as expected with IteratorAggregate
if ($map instanceof IteratorAggregate) {
$map = $map->getIterator();
}
foreach ($map as $name => $class) {
if (is_int($name) || is_numeric($name)) {
if (!is_object($class) && class_exists($class)) {
$class = new $class();
}
if ($class instanceof Traversable) {
$this->registerPlugins($class);
continue;
}
}
$this->registerPlugin($name, $class);
}
return $this;
}
/**
* Unregister a short name lookup
*
* @param mixed $shortName
* @return PluginClassLoader
*/
public function unregisterPlugin($shortName)
{
$lookup = strtolower($shortName);
if (array_key_exists($lookup, $this->plugins)) {
unset($this->plugins[$lookup]);
}
return $this;
}
/**
* Get a list of all registered plugins
*
* @return array|Traversable
*/
public function getRegisteredPlugins()
{
return $this->plugins;
}
/**
* Whether or not a plugin by a specific name has been registered
*
* @param string $name
* @return bool
*/
public function isLoaded($name)
{
$lookup = strtolower($name);
return isset($this->plugins[$lookup]);
}
/**
* Return full class name for a named helper
*
* @param string $name
* @return string|false
*/
public function getClassName($name)
{
return $this->load($name);
}
/**
* Load a helper via the name provided
*
* @param string $name
* @return string|false
*/
public function load($name)
{
if (!$this->isLoaded($name)) {
return false;
}
return $this->plugins[strtolower($name)];
}
/**
* Defined by IteratorAggregate
*
* Returns an instance of ArrayIterator, containing a map of
* all plugins
*
* @return ArrayIterator
*/
public function getIterator()
{
return new ArrayIterator($this->plugins);
}
}
| altira/AltiraIDE | vendor/zendframework/zendframework/library/Zend/Loader/PluginClassLoader.php | PHP | bsd-3-clause | 5,685 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/url/url_search_params.h"
#include <algorithm>
#include <utility>
#include "third_party/blink/renderer/bindings/core/v8/v8_union_usvstring_usvstringsequencesequence_usvstringusvstringrecord.h"
#include "third_party/blink/renderer/core/url/dom_url.h"
#include "third_party/blink/renderer/platform/bindings/exception_messages.h"
#include "third_party/blink/renderer/platform/network/form_data_encoder.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/wtf/text/text_encoding.h"
namespace blink {
namespace {
class URLSearchParamsIterationSource final
: public PairIterable<String, IDLString, String, IDLString>::
IterationSource {
public:
explicit URLSearchParamsIterationSource(URLSearchParams* params)
: params_(params), current_(0) {}
bool Next(ScriptState*,
String& key,
String& value,
ExceptionState&) override {
if (current_ >= params_->Params().size())
return false;
key = params_->Params()[current_].first;
value = params_->Params()[current_].second;
current_++;
return true;
}
void Trace(Visitor* visitor) const override {
visitor->Trace(params_);
PairIterable<String, IDLString, String, IDLString>::IterationSource::Trace(
visitor);
}
private:
Member<URLSearchParams> params_;
wtf_size_t current_;
};
bool CompareParams(const std::pair<String, String>& a,
const std::pair<String, String>& b) {
return WTF::CodeUnitCompareLessThan(a.first, b.first);
}
} // namespace
URLSearchParams* URLSearchParams::Create(const URLSearchParamsInit* init,
ExceptionState& exception_state) {
DCHECK(init);
switch (init->GetContentType()) {
case URLSearchParamsInit::ContentType::kUSVString: {
const String& query_string = init->GetAsUSVString();
if (query_string.StartsWith('?'))
return MakeGarbageCollected<URLSearchParams>(query_string.Substring(1));
return MakeGarbageCollected<URLSearchParams>(query_string);
}
case URLSearchParamsInit::ContentType::kUSVStringSequenceSequence:
return URLSearchParams::Create(init->GetAsUSVStringSequenceSequence(),
exception_state);
case URLSearchParamsInit::ContentType::kUSVStringUSVStringRecord:
return URLSearchParams::Create(init->GetAsUSVStringUSVStringRecord(),
exception_state);
}
NOTREACHED();
return nullptr;
}
URLSearchParams* URLSearchParams::Create(const Vector<Vector<String>>& init,
ExceptionState& exception_state) {
URLSearchParams* instance = MakeGarbageCollected<URLSearchParams>(String());
if (!init.size())
return instance;
for (unsigned i = 0; i < init.size(); ++i) {
const Vector<String>& pair = init[i];
if (pair.size() != 2) {
exception_state.ThrowTypeError(ExceptionMessages::FailedToConstruct(
"URLSearchParams",
"Sequence initializer must only contain pair elements"));
return nullptr;
}
instance->AppendWithoutUpdate(pair[0], pair[1]);
}
return instance;
}
URLSearchParams::URLSearchParams(const String& query_string, DOMURL* url_object)
: url_object_(url_object) {
if (!query_string.IsEmpty())
SetInputWithoutUpdate(query_string);
}
URLSearchParams* URLSearchParams::Create(
const Vector<std::pair<String, String>>& init,
ExceptionState& exception_state) {
URLSearchParams* instance = MakeGarbageCollected<URLSearchParams>(String());
if (init.IsEmpty())
return instance;
for (const auto& item : init)
instance->AppendWithoutUpdate(item.first, item.second);
return instance;
}
URLSearchParams::~URLSearchParams() = default;
void URLSearchParams::Trace(Visitor* visitor) const {
visitor->Trace(url_object_);
ScriptWrappable::Trace(visitor);
}
#if DCHECK_IS_ON()
DOMURL* URLSearchParams::UrlObject() const {
return url_object_;
}
#endif
void URLSearchParams::RunUpdateSteps() {
if (!url_object_)
return;
if (url_object_->IsInUpdate())
return;
url_object_->SetSearchInternal(toString());
}
static String DecodeString(String input) {
// |DecodeURLMode::kUTF8| is used because "UTF-8 decode without BOM" should
// be performed (see https://url.spec.whatwg.org/#concept-urlencoded-parser).
return DecodeURLEscapeSequences(input.Replace('+', ' '),
DecodeURLMode::kUTF8);
}
void URLSearchParams::SetInputWithoutUpdate(const String& query_string) {
params_.clear();
wtf_size_t start = 0;
wtf_size_t query_string_length = query_string.length();
while (start < query_string_length) {
wtf_size_t name_start = start;
wtf_size_t name_value_end = query_string.find('&', start);
if (name_value_end == kNotFound)
name_value_end = query_string_length;
if (name_value_end > start) {
wtf_size_t end_of_name = query_string.find('=', start);
if (end_of_name == kNotFound || end_of_name > name_value_end)
end_of_name = name_value_end;
String name = DecodeString(
query_string.Substring(name_start, end_of_name - name_start));
String value;
if (end_of_name != name_value_end)
value = DecodeString(query_string.Substring(
end_of_name + 1, name_value_end - end_of_name - 1));
if (value.IsNull())
value = "";
AppendWithoutUpdate(name, value);
}
start = name_value_end + 1;
}
}
String URLSearchParams::toString() const {
Vector<char> encoded_data;
EncodeAsFormData(encoded_data);
return String(encoded_data.data(), encoded_data.size());
}
void URLSearchParams::AppendWithoutUpdate(const String& name,
const String& value) {
params_.push_back(std::make_pair(name, value));
}
void URLSearchParams::append(const String& name, const String& value) {
AppendWithoutUpdate(name, value);
RunUpdateSteps();
}
void URLSearchParams::deleteAllWithName(const String& name) {
for (wtf_size_t i = 0; i < params_.size();) {
if (params_[i].first == name)
params_.EraseAt(i);
else
i++;
}
RunUpdateSteps();
}
String URLSearchParams::get(const String& name) const {
for (const auto& param : params_) {
if (param.first == name)
return param.second;
}
return String();
}
Vector<String> URLSearchParams::getAll(const String& name) const {
Vector<String> result;
for (const auto& param : params_) {
if (param.first == name)
result.push_back(param.second);
}
return result;
}
bool URLSearchParams::has(const String& name) const {
for (const auto& param : params_) {
if (param.first == name)
return true;
}
return false;
}
void URLSearchParams::set(const String& name, const String& value) {
bool found_match = false;
for (wtf_size_t i = 0; i < params_.size();) {
// If there are any name-value whose name is 'name', set
// the value of the first such name-value pair to 'value'
// and remove the others.
if (params_[i].first == name) {
if (!found_match) {
params_[i++].second = value;
found_match = true;
} else {
params_.EraseAt(i);
}
} else {
i++;
}
}
// Otherwise, append a new name-value pair to the list.
if (!found_match)
append(name, value);
else
RunUpdateSteps();
}
void URLSearchParams::sort() {
std::stable_sort(params_.begin(), params_.end(), CompareParams);
RunUpdateSteps();
}
void URLSearchParams::EncodeAsFormData(Vector<char>& encoded_data) const {
for (const auto& param : params_)
FormDataEncoder::AddKeyValuePairAsFormData(
encoded_data, param.first.Utf8(), param.second.Utf8(),
EncodedFormData::kFormURLEncoded, FormDataEncoder::kDoNotNormalizeCRLF);
}
scoped_refptr<EncodedFormData> URLSearchParams::ToEncodedFormData() const {
Vector<char> encoded_data;
EncodeAsFormData(encoded_data);
return EncodedFormData::Create(encoded_data.data(), encoded_data.size());
}
PairIterable<String, IDLString, String, IDLString>::IterationSource*
URLSearchParams::StartIteration(ScriptState*, ExceptionState&) {
return MakeGarbageCollected<URLSearchParamsIterationSource>(this);
}
} // namespace blink
| chromium/chromium | third_party/blink/renderer/core/url/url_search_params.cc | C++ | bsd-3-clause | 8,516 |
"""
Create movie from MEG inverse solution
=======================================
Data were computed using mne-python (http://martinos.org/mne)
"""
import os
import numpy as np
from surfer import Brain
from surfer.io import read_stc
print(__doc__)
"""
create Brain object for visualization
"""
brain = Brain('fsaverage', 'split', 'inflated', size=(800, 400))
"""
read and display MNE dSPM inverse solution
"""
stc_fname = os.path.join('example_data', 'meg_source_estimate-%s.stc')
for hemi in ['lh', 'rh']:
stc = read_stc(stc_fname % hemi)
data = stc['data']
times = np.arange(data.shape[1]) * stc['tstep'] + stc['tmin']
brain.add_data(data, colormap='hot', vertices=stc['vertices'],
smoothing_steps=10, time=times, hemi=hemi,
time_label=lambda t: '%s ms' % int(round(t * 1e3)))
"""
scale colormap
"""
brain.scale_data_colormap(fmin=13, fmid=18, fmax=22, transparent=True)
"""
Save a movie. Use a large value for time_dilation because the sample stc only
covers 30 ms.
"""
brain.save_movie('example_current.mov', time_dilation=30)
brain.close()
| diego0020/PySurfer | examples/save_movie.py | Python | bsd-3-clause | 1,110 |
# $Id$
"""Mixins that are useful for classes using vtk_kit.
@author: Charl P. Botha <http://cpbotha.net/>
"""
from external.vtkPipeline.ConfigVtkObj import ConfigVtkObj
from external.vtkPipeline.vtkMethodParser import VtkMethodParser
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin # temporary
import module_utils # temporary, most of this should be in utils.
import re
import types
import utils
#########################################################################
class PickleVTKObjectsModuleMixin(object):
"""This mixin will pickle the state of all vtk objects whose binding
attribute names have been added to self._vtkObjects, e.g. if you have
a self._imageMath, '_imageMath' should be in the list.
Your module has to derive from module_base as well so that it has a
self._config!
Remember to call the __init__ of this class with the list of attribute
strings representing vtk objects that you want pickled. All the objects
have to exist and be initially configured by then.
Remember to call close() when your child class close()s.
"""
def __init__(self, vtkObjectNames):
# you have to add the NAMES of the objects that you want pickled
# to this list.
self._vtkObjectNames = vtkObjectNames
self.statePattern = re.compile ("To[A-Z0-9]")
# make sure that the state of the vtkObjectNames objects is
# encapsulated in the initial _config
self.logic_to_config()
def close(self):
# make sure we get rid of these bindings as well
del self._vtkObjectNames
def logic_to_config(self):
parser = VtkMethodParser()
for vtkObjName in self._vtkObjectNames:
# pickled data: a list with toggle_methods, state_methods and
# get_set_methods as returned by the vtkMethodParser. Each of
# these is a list of tuples with the name of the method (as
# returned by the vtkMethodParser) and the value; in the case
# of the stateMethods, we use the whole stateGroup instead of
# just a single name
vtkObjPD = [[], [], []]
vtkObj = getattr(self, vtkObjName)
parser.parse_methods(vtkObj)
# parser now has toggle_methods(), state_methods() and
# get_set_methods();
# toggle_methods: ['BlaatOn', 'AbortExecuteOn']
# state_methods: [['SetBlaatToOne', 'SetBlaatToTwo'],
# ['SetMaatToThree', 'SetMaatToFive']]
# get_set_methods: ['NumberOfThreads', 'Progress']
for method in parser.toggle_methods():
# if you query ReleaseDataFlag on a filter with 0 outputs,
# VTK yields an error
if vtkObj.GetNumberOfOutputPorts() == 0 and \
method == 'ReleaseDataFlagOn':
continue
# we need to snip the 'On' off
val = eval("vtkObj.Get%s()" % (method[:-2],))
vtkObjPD[0].append((method, val))
for stateGroup in parser.state_methods():
# we search up to the To
end = self.statePattern.search (stateGroup[0]).start ()
# so we turn SetBlaatToOne to GetBlaat
get_m = 'G'+stateGroup[0][1:end]
# we're going to have to be more clever when we set_config...
# use a similar trick to get_state in vtkMethodParser
val = eval('vtkObj.%s()' % (get_m,))
vtkObjPD[1].append((stateGroup, val))
for method in parser.get_set_methods():
val = eval('vtkObj.Get%s()' % (method,))
vtkObjPD[2].append((method, val))
# finally set the pickle data in the correct position
setattr(self._config, vtkObjName, vtkObjPD)
def config_to_logic(self):
# go through at least the attributes in self._vtkObjectNames
for vtkObjName in self._vtkObjectNames:
try:
vtkObjPD = getattr(self._config, vtkObjName)
vtkObj = getattr(self, vtkObjName)
except AttributeError:
print "PickleVTKObjectsModuleMixin: %s not available " \
"in self._config OR in self. Skipping." % (vtkObjName,)
else:
for method, val in vtkObjPD[0]:
if val:
eval('vtkObj.%s()' % (method,))
else:
# snip off the On
eval('vtkObj.%sOff()' % (method[:-2],))
for stateGroup, val in vtkObjPD[1]:
# keep on calling the methods in stategroup until
# the getter returns a value == val.
end = self.statePattern.search(stateGroup[0]).start()
getMethod = 'G'+stateGroup[0][1:end]
for i in range(len(stateGroup)):
m = stateGroup[i]
eval('vtkObj.%s()' % (m,))
tempVal = eval('vtkObj.%s()' % (getMethod,))
if tempVal == val:
# success! break out of the for loop
break
for method, val in vtkObjPD[2]:
try:
eval('vtkObj.Set%s(val)' % (method,))
except TypeError:
if type(val) in [types.TupleType, types.ListType]:
# sometimes VTK wants the separate elements
# and not the tuple / list
eval("vtkObj.Set%s(*val)"%(method,))
else:
# re-raise the exception if it wasn't a
# tuple/list
raise
#########################################################################
# note that the pickle mixin comes first, as its config_to_logic/logic_to_config
# should be chosen over that of noConfig
class SimpleVTKClassModuleBase(PickleVTKObjectsModuleMixin,
IntrospectModuleMixin,
ModuleBase):
"""Use this base to make a DeVIDE module that wraps a single VTK
object. The state of the VTK object will be saved when the network
is.
You only have to override the __init__ method and call the __init__
of this class with the desired parameters.
The __doc__ string of your module class will be replaced with the
__doc__ string of the encapsulated VTK class (and will thus be
shown if the user requests module help). If you don't want this,
call the ctor with replaceDoc=False.
inputFunctions is a list of the complete methods that have to be called
on the encapsulated VTK class, e.g. ['SetInput1(inputStream)',
'SetInput1(inputStream)']. The same goes for outputFunctions, except that
there's no inputStream involved. Use None in both cases if you want
the default to be used (SetInput(), GetOutput()).
"""
def __init__(self, module_manager, vtkObjectBinding, progressText,
inputDescriptions, outputDescriptions,
replaceDoc=True,
inputFunctions=None, outputFunctions=None):
self._viewFrame = None
self._configVtkObj = None
# first these two mixins
ModuleBase.__init__(self, module_manager)
self._theFilter = vtkObjectBinding
if replaceDoc:
myMessage = "<em>"\
"This is a special DeVIDE module that very simply " \
"wraps a single VTK class. In general, the " \
"complete state of the class will be saved along " \
"with the rest of the network. The documentation " \
"below is that of the wrapped VTK class:</em>"
self.__doc__ = '%s\n\n%s' % (myMessage, self._theFilter.__doc__)
# now that we have the object, init the pickle mixin so
# that the state of this object will be saved
PickleVTKObjectsModuleMixin.__init__(self, ['_theFilter'])
# make progress hooks for the object
module_utils.setup_vtk_object_progress(self, self._theFilter,
progressText)
self._inputDescriptions = inputDescriptions
self._outputDescriptions = outputDescriptions
self._inputFunctions = inputFunctions
self._outputFunctions = outputFunctions
def _createViewFrame(self):
parentWindow = self._module_manager.get_module_view_parent_window()
import resources.python.defaultModuleViewFrame
reload(resources.python.defaultModuleViewFrame)
dMVF = resources.python.defaultModuleViewFrame.defaultModuleViewFrame
viewFrame = module_utils.instantiate_module_view_frame(
self, self._module_manager, dMVF)
# ConfigVtkObj parent not important, we're passing frame + panel
# this should populate the sizer with a new sizer7
# params: noParent, noRenwin, vtk_obj, frame, panel
self._configVtkObj = ConfigVtkObj(None, None,
self._theFilter,
viewFrame, viewFrame.viewFramePanel)
module_utils.create_standard_object_introspection(
self, viewFrame, viewFrame.viewFramePanel,
{'Module (self)' : self}, None)
# we don't want the Execute button to be default... else stuff gets
# executed with every enter in the command window (at least in Doze)
module_utils.create_eoca_buttons(self, viewFrame,
viewFrame.viewFramePanel,
False)
self._viewFrame = viewFrame
return viewFrame
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
PickleVTKObjectsModuleMixin.close(self)
IntrospectModuleMixin.close(self)
if self._viewFrame is not None:
self._configVtkObj.close()
self._viewFrame.Destroy()
ModuleBase.close(self)
# get rid of our binding to the vtkObject
del self._theFilter
def get_output_descriptions(self):
return self._outputDescriptions
def get_output(self, idx):
# this will only every be invoked if your get_output_descriptions has
# 1 or more elements
if self._outputFunctions:
return eval('self._theFilter.%s' % (self._outputFunctions[idx],))
else:
return self._theFilter.GetOutput()
def get_input_descriptions(self):
return self._inputDescriptions
def set_input(self, idx, inputStream):
# this will only be called for a certain idx if you've specified that
# many elements in your get_input_descriptions
if self._inputFunctions:
exec('self._theFilter.%s' %
(self._inputFunctions[idx]))
else:
if idx == 0:
self._theFilter.SetInput(inputStream)
else:
self._theFilter.SetInput(idx, inputStream)
def execute_module(self):
# it could be a writer, in that case, call the Write method.
if hasattr(self._theFilter, 'Write') and \
callable(self._theFilter.Write):
self._theFilter.Write()
else:
self._theFilter.Update()
def streaming_execute_module(self):
"""All VTK classes should be streamable.
"""
# it could be a writer, in that case, call the Write method.
if hasattr(self._theFilter, 'Write') and \
callable(self._theFilter.Write):
self._theFilter.Write()
else:
self._theFilter.Update()
def view(self):
if self._viewFrame is None:
# we have an initial config populated with stuff and in sync
# with theFilter. The viewFrame will also be in sync with the
# filter
self._viewFrame = self._createViewFrame()
self._viewFrame.Show(True)
self._viewFrame.Raise()
def config_to_view(self):
# the pickleVTKObjectsModuleMixin does logic <-> config
# so when the user clicks "sync", logic_to_config is called
# which transfers picklable state from the LOGIC to the CONFIG
# then we do double the work and call update_gui, which transfers
# the same state from the LOGIC straight up to the VIEW
self._configVtkObj.update_gui()
def view_to_config(self):
# same thing here: user clicks "apply", view_to_config is called which
# zaps UI changes straight to the LOGIC. Then we have to call
# logic_to_config explicitly which brings the info back up to the
# config... i.e. view -> logic -> config
# after that, config_to_logic is called which transfers all state AGAIN
# from the config to the logic
self._configVtkObj.apply_changes()
self.logic_to_config()
#########################################################################
| nagyistoce/devide | module_kits/vtk_kit/mixins.py | Python | bsd-3-clause | 13,612 |
// Copyright (C) 2006 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.
// Author: Jim Meehan
#include <iostream>
#include <sstream>
#include <cassert>
#include "phonenumbers/utf/unicodetext.h"
//#include "base/logging.h"
#include "phonenumbers/utf/stringpiece.h"
//#include "utf/stringprintf.h"
#include "phonenumbers/utf/utf.h"
#include "phonenumbers/utf/unilib.h"
using std::stringstream;
using std::max;
using std::hex;
using std::dec;
using std::cerr;
using std::endl;
static int CodepointDistance(const char* start, const char* end) {
int n = 0;
// Increment n on every non-trail-byte.
for (const char* p = start; p < end; ++p) {
n += (*reinterpret_cast<const signed char*>(p) >= -0x40);
}
return n;
}
static int CodepointCount(const char* utf8, int len) {
return CodepointDistance(utf8, utf8 + len);
}
UnicodeText::const_iterator::difference_type
distance(const UnicodeText::const_iterator& first,
const UnicodeText::const_iterator& last) {
return CodepointDistance(first.it_, last.it_);
}
// ---------- Utility ----------
static int ConvertToInterchangeValid(char* start, int len) {
// This routine is called only when we've discovered that a UTF-8 buffer
// that was passed to CopyUTF8, TakeOwnershipOfUTF8, or PointToUTF8
// was not interchange valid. This indicates a bug in the caller, and
// a LOG(WARNING) is done in that case.
// This is similar to CoerceToInterchangeValid, but it replaces each
// structurally valid byte with a space, and each non-interchange
// character with a space, even when that character requires more
// than one byte in UTF8. E.g., "\xEF\xB7\x90" (U+FDD0) is
// structurally valid UTF8, but U+FDD0 is not an interchange-valid
// code point. The result should contain one space, not three.
//
// Since the conversion never needs to write more data than it
// reads, it is safe to change the buffer in place. It returns the
// number of bytes written.
char* const in = start;
char* out = start;
char* const end = start + len;
while (start < end) {
int good = UniLib::SpanInterchangeValid(start, end - start);
if (good > 0) {
if (out != start) {
memmove(out, start, good);
}
out += good;
start += good;
if (start == end) {
break;
}
}
// Is the current string invalid UTF8 or just non-interchange UTF8?
char32 rune;
int n;
if (isvalidcharntorune(start, end - start, &rune, &n)) {
// structurally valid UTF8, but not interchange valid
start += n; // Skip over the whole character.
} else { // bad UTF8
start += 1; // Skip over just one byte
}
*out++ = ' ';
}
return out - in;
}
// *************** Data representation **********
// Note: the copy constructor is undefined.
// After reserve(), resize(), or clear(), we're an owner, not an alias.
void UnicodeText::Repr::reserve(int new_capacity) {
// If there's already enough capacity, and we're an owner, do nothing.
if (capacity_ >= new_capacity && ours_) return;
// Otherwise, allocate a new buffer.
capacity_ = max(new_capacity, (3 * capacity_) / 2 + 20);
char* new_data = new char[capacity_];
// If there is an old buffer, copy it into the new buffer.
if (data_) {
memcpy(new_data, data_, size_);
if (ours_) delete[] data_; // If we owned the old buffer, free it.
}
data_ = new_data;
ours_ = true; // We own the new buffer.
// size_ is unchanged.
}
void UnicodeText::Repr::resize(int new_size) {
if (new_size == 0) {
clear();
} else {
if (!ours_ || new_size > capacity_) reserve(new_size);
// Clear the memory in the expanded part.
if (size_ < new_size) memset(data_ + size_, 0, new_size - size_);
size_ = new_size;
ours_ = true;
}
}
// This implementation of clear() deallocates the buffer if we're an owner.
// That's not strictly necessary; we could just set size_ to 0.
void UnicodeText::Repr::clear() {
if (ours_) delete[] data_;
data_ = NULL;
size_ = capacity_ = 0;
ours_ = true;
}
void UnicodeText::Repr::Copy(const char* data, int size) {
resize(size);
memcpy(data_, data, size);
}
void UnicodeText::Repr::TakeOwnershipOf(char* data, int size, int capacity) {
if (data == data_) return; // We already own this memory. (Weird case.)
if (ours_ && data_) delete[] data_; // If we owned the old buffer, free it.
data_ = data;
size_ = size;
capacity_ = capacity;
ours_ = true;
}
void UnicodeText::Repr::PointTo(const char* data, int size) {
if (ours_ && data_) delete[] data_; // If we owned the old buffer, free it.
data_ = const_cast<char*>(data);
size_ = size;
capacity_ = size;
ours_ = false;
}
void UnicodeText::Repr::append(const char* bytes, int byte_length) {
reserve(size_ + byte_length);
memcpy(data_ + size_, bytes, byte_length);
size_ += byte_length;
}
string UnicodeText::Repr::DebugString() const {
stringstream ss;
ss << "{Repr " << hex << this << " data=" << data_ << " size=" << dec
<< size_ << " capacity=" << capacity_ << " "
<< (ours_ ? "Owned" : "Alias") << "}";
string result;
ss >> result;
return result;
}
// *************** UnicodeText ******************
// ----- Constructors -----
// Default constructor
UnicodeText::UnicodeText() {
}
// Copy constructor
UnicodeText::UnicodeText(const UnicodeText& src) {
Copy(src);
}
// Substring constructor
UnicodeText::UnicodeText(const UnicodeText::const_iterator& first,
const UnicodeText::const_iterator& last) {
assert(first <= last && "Incompatible iterators");
repr_.append(first.it_, last.it_ - first.it_);
}
string UnicodeText::UTF8Substring(const const_iterator& first,
const const_iterator& last) {
assert(first <= last && "Incompatible iterators");
return string(first.it_, last.it_ - first.it_);
}
// ----- Copy -----
UnicodeText& UnicodeText::operator=(const UnicodeText& src) {
if (this != &src) {
Copy(src);
}
return *this;
}
UnicodeText& UnicodeText::Copy(const UnicodeText& src) {
repr_.Copy(src.repr_.data_, src.repr_.size_);
return *this;
}
UnicodeText& UnicodeText::CopyUTF8(const char* buffer, int byte_length) {
repr_.Copy(buffer, byte_length);
if (!UniLib:: IsInterchangeValid(buffer, byte_length)) {
cerr << "UTF-8 buffer is not interchange-valid." << endl;
repr_.size_ = ConvertToInterchangeValid(repr_.data_, byte_length);
}
return *this;
}
UnicodeText& UnicodeText::UnsafeCopyUTF8(const char* buffer,
int byte_length) {
repr_.Copy(buffer, byte_length);
return *this;
}
// ----- TakeOwnershipOf -----
UnicodeText& UnicodeText::TakeOwnershipOfUTF8(char* buffer,
int byte_length,
int byte_capacity) {
repr_.TakeOwnershipOf(buffer, byte_length, byte_capacity);
if (!UniLib:: IsInterchangeValid(buffer, byte_length)) {
cerr << "UTF-8 buffer is not interchange-valid." << endl;
repr_.size_ = ConvertToInterchangeValid(repr_.data_, byte_length);
}
return *this;
}
UnicodeText& UnicodeText::UnsafeTakeOwnershipOfUTF8(char* buffer,
int byte_length,
int byte_capacity) {
repr_.TakeOwnershipOf(buffer, byte_length, byte_capacity);
return *this;
}
// ----- PointTo -----
UnicodeText& UnicodeText::PointToUTF8(const char* buffer, int byte_length) {
if (UniLib:: IsInterchangeValid(buffer, byte_length)) {
repr_.PointTo(buffer, byte_length);
} else {
cerr << "UTF-8 buffer is not interchange-valid." << endl;
repr_.Copy(buffer, byte_length);
repr_.size_ = ConvertToInterchangeValid(repr_.data_, byte_length);
}
return *this;
}
UnicodeText& UnicodeText::UnsafePointToUTF8(const char* buffer,
int byte_length) {
repr_.PointTo(buffer, byte_length);
return *this;
}
UnicodeText& UnicodeText::PointTo(const UnicodeText& src) {
repr_.PointTo(src.repr_.data_, src.repr_.size_);
return *this;
}
UnicodeText& UnicodeText::PointTo(const const_iterator &first,
const const_iterator &last) {
assert(first <= last && " Incompatible iterators");
repr_.PointTo(first.utf8_data(), last.utf8_data() - first.utf8_data());
return *this;
}
// ----- Append -----
UnicodeText& UnicodeText::append(const UnicodeText& u) {
repr_.append(u.repr_.data_, u.repr_.size_);
return *this;
}
UnicodeText& UnicodeText::append(const const_iterator& first,
const const_iterator& last) {
assert(first <= last && "Incompatible iterators");
repr_.append(first.it_, last.it_ - first.it_);
return *this;
}
UnicodeText& UnicodeText::UnsafeAppendUTF8(const char* utf8, int len) {
repr_.append(utf8, len);
return *this;
}
// ----- substring searching -----
UnicodeText::const_iterator UnicodeText::find(const UnicodeText& look,
const_iterator start_pos) const {
assert(start_pos.utf8_data() >= utf8_data());
assert(start_pos.utf8_data() <= utf8_data() + utf8_length());
return UnsafeFind(look, start_pos);
}
UnicodeText::const_iterator UnicodeText::find(const UnicodeText& look) const {
return UnsafeFind(look, begin());
}
UnicodeText::const_iterator UnicodeText::UnsafeFind(
const UnicodeText& look, const_iterator start_pos) const {
// Due to the magic of the UTF8 encoding, searching for a sequence of
// letters is equivalent to substring search.
StringPiece searching(utf8_data(), utf8_length());
StringPiece look_piece(look.utf8_data(), look.utf8_length());
StringPiece::size_type found =
searching.find(look_piece, start_pos.utf8_data() - utf8_data());
if (found == StringPiece::npos) return end();
return const_iterator(utf8_data() + found);
}
bool UnicodeText::HasReplacementChar() const {
// Equivalent to:
// UnicodeText replacement_char;
// replacement_char.push_back(0xFFFD);
// return find(replacement_char) != end();
StringPiece searching(utf8_data(), utf8_length());
StringPiece looking_for("\xEF\xBF\xBD", 3);
return searching.find(looking_for) != StringPiece::npos;
}
// ----- other methods -----
// Clear operator
void UnicodeText::clear() {
repr_.clear();
}
// Destructor
UnicodeText::~UnicodeText() {}
void UnicodeText::push_back(char32 c) {
if (UniLib::IsValidCodepoint(c)) {
char buf[UTFmax];
int len = runetochar(buf, &c);
if (UniLib::IsInterchangeValid(buf, len)) {
repr_.append(buf, len);
} else {
cerr << "Unicode value 0x" << hex << c
<< " is not valid for interchange" << endl;
repr_.append(" ", 1);
}
} else {
cerr << "Illegal Unicode value: 0x" << hex << c << endl;
repr_.append(" ", 1);
}
}
int UnicodeText::size() const {
return CodepointCount(repr_.data_, repr_.size_);
}
bool operator==(const UnicodeText& lhs, const UnicodeText& rhs) {
if (&lhs == &rhs) return true;
if (lhs.repr_.size_ != rhs.repr_.size_) return false;
return memcmp(lhs.repr_.data_, rhs.repr_.data_, lhs.repr_.size_) == 0;
}
string UnicodeText::DebugString() const {
stringstream ss;
ss << "{UnicodeText " << hex << this << dec << " chars="
<< size() << " repr=" << repr_.DebugString() << "}";
#if 0
return StringPrintf("{UnicodeText %p chars=%d repr=%s}",
this,
size(),
repr_.DebugString().c_str());
#endif
string result;
ss >> result;
return result;
}
// ******************* UnicodeText::const_iterator *********************
// The implementation of const_iterator would be nicer if it
// inherited from boost::iterator_facade
// (http://boost.org/libs/iterator/doc/iterator_facade.html).
UnicodeText::const_iterator::const_iterator() : it_(0) {}
UnicodeText::const_iterator::const_iterator(const const_iterator& other)
: it_(other.it_) {
}
UnicodeText::const_iterator&
UnicodeText::const_iterator::operator=(const const_iterator& other) {
if (&other != this)
it_ = other.it_;
return *this;
}
UnicodeText::const_iterator UnicodeText::begin() const {
return const_iterator(repr_.data_);
}
UnicodeText::const_iterator UnicodeText::end() const {
return const_iterator(repr_.data_ + repr_.size_);
}
bool operator<(const UnicodeText::const_iterator& lhs,
const UnicodeText::const_iterator& rhs) {
return lhs.it_ < rhs.it_;
}
char32 UnicodeText::const_iterator::operator*() const {
// (We could call chartorune here, but that does some
// error-checking, and we're guaranteed that our data is valid
// UTF-8. Also, we expect this routine to be called very often. So
// for speed, we do the calculation ourselves.)
// Convert from UTF-8
uint8 byte1 = static_cast<uint8>(it_[0]);
if (byte1 < 0x80)
return byte1;
uint8 byte2 = static_cast<uint8>(it_[1]);
if (byte1 < 0xE0)
return ((byte1 & 0x1F) << 6)
| (byte2 & 0x3F);
uint8 byte3 = static_cast<uint8>(it_[2]);
if (byte1 < 0xF0)
return ((byte1 & 0x0F) << 12)
| ((byte2 & 0x3F) << 6)
| (byte3 & 0x3F);
uint8 byte4 = static_cast<uint8>(it_[3]);
return ((byte1 & 0x07) << 18)
| ((byte2 & 0x3F) << 12)
| ((byte3 & 0x3F) << 6)
| (byte4 & 0x3F);
}
UnicodeText::const_iterator& UnicodeText::const_iterator::operator++() {
it_ += UniLib::OneCharLen(it_);
return *this;
}
UnicodeText::const_iterator& UnicodeText::const_iterator::operator--() {
while (UniLib::IsTrailByte(*--it_)) { }
return *this;
}
int UnicodeText::const_iterator::get_utf8(char* utf8_output) const {
utf8_output[0] = it_[0];
if (static_cast<unsigned char>(it_[0]) < 0x80)
return 1;
utf8_output[1] = it_[1];
if (static_cast<unsigned char>(it_[0]) < 0xE0)
return 2;
utf8_output[2] = it_[2];
if (static_cast<unsigned char>(it_[0]) < 0xF0)
return 3;
utf8_output[3] = it_[3];
return 4;
}
UnicodeText::const_iterator UnicodeText::MakeIterator(const char* p) const {
assert(p != NULL);
const char* start = utf8_data();
int len = utf8_length();
const char* end = start + len;
assert(p >= start);
assert(p <= end);
assert(p == end || !UniLib::IsTrailByte(*p));
return const_iterator(p);
}
string UnicodeText::const_iterator::DebugString() const {
stringstream ss;
ss << "{iter " << hex << it_ << "}";
string result;
ss >> result;
return result;
}
| leighpauls/k2cro4 | third_party/libphonenumber/src/phonenumbers/utf/unicodetext.cc | C++ | bsd-3-clause | 15,052 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* 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@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Pdf
* @subpackage Fonts
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Internally used classes */
require_once 'Zend/Pdf/Element/Array.php';
require_once 'Zend/Pdf/Element/Dictionary.php';
require_once 'Zend/Pdf/Element/Name.php';
require_once 'Zend/Pdf/Element/Numeric.php';
require_once 'Zend/Pdf/Element/String.php';
/** Zend_Pdf_Resource_Font */
require_once 'Zend/Pdf/Resource/Font.php';
/**
* Adobe PDF CIDFont font object implementation
*
* A CIDFont program contains glyph descriptions that are accessed using a CID as
* the character selector. There are two types of CIDFont. A Type 0 CIDFont contains
* glyph descriptions based on Adobe’s Type 1 font format, whereas those in a
* Type 2 CIDFont are based on the TrueType font format.
*
* A CIDFont dictionary is a PDF object that contains information about a CIDFont program.
* Although its Type value is Font, a CIDFont is not actually a font. It does not have an Encoding
* entry, it cannot be listed in the Font subdictionary of a resource dictionary, and it cannot be
* used as the operand of the Tf operator. It is used only as a descendant of a Type 0 font.
* The CMap in the Type 0 font is what defines the encoding that maps character codes to CIDs
* in the CIDFont.
*
* Font objects should be normally be obtained from the factory methods
* {@link Zend_Pdf_Font::fontWithName} and {@link Zend_Pdf_Font::fontWithPath}.
*
* @package Zend_Pdf
* @subpackage Fonts
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Pdf_Resource_Font_CidFont extends Zend_Pdf_Resource_Font
{
/**
* Object representing the font's cmap (character to glyph map).
* @var Zend_Pdf_Cmap
*/
protected $_cmap = null;
/**
* Array containing the widths of each character that have entries in used character map.
*
* @var array
*/
protected $_charWidths = null;
/**
* Width for characters missed in the font
*
* @var integer
*/
protected $_missingCharWidth = 0;
/**
* Object constructor
*
* @param Zend_Pdf_FileParser_Font_OpenType $fontParser Font parser object
* containing OpenType file.
* @param integer $embeddingOptions Options for font embedding.
* @throws Zend_Pdf_Exception
*/
public function __construct(Zend_Pdf_FileParser_Font_OpenType $fontParser)
{
parent::__construct();
$fontParser->parse();
/* Object properties */
$this->_fontNames = $fontParser->names;
$this->_isBold = $fontParser->isBold;
$this->_isItalic = $fontParser->isItalic;
$this->_isMonospaced = $fontParser->isMonospaced;
$this->_underlinePosition = $fontParser->underlinePosition;
$this->_underlineThickness = $fontParser->underlineThickness;
$this->_strikePosition = $fontParser->strikePosition;
$this->_strikeThickness = $fontParser->strikeThickness;
$this->_unitsPerEm = $fontParser->unitsPerEm;
$this->_ascent = $fontParser->ascent;
$this->_descent = $fontParser->descent;
$this->_lineGap = $fontParser->lineGap;
$this->_cmap = $fontParser->cmap;
/* Resource dictionary */
$baseFont = $this->getFontName(Zend_Pdf_Font::NAME_POSTSCRIPT, 'en', 'UTF-8');
$this->_resource->BaseFont = new Zend_Pdf_Element_Name($baseFont);
/**
* Prepare widths array.
*/
/* Constract characters widths array using font CMap and glyphs widths array */
$glyphWidths = $fontParser->glyphWidths;
$charGlyphs = $this->_cmap->getCoveredCharactersGlyphs();
$charWidths = array();
foreach ($charGlyphs as $charCode => $glyph) {
$charWidths[$charCode] = $glyphWidths[$glyph];
}
$this->_charWidths = $charWidths;
$this->_missingCharWidth = $glyphWidths[0];
/* Width array optimization. Step1: extract default value */
$widthFrequencies = array_count_values($charWidths);
$defaultWidth = null;
$defaultWidthFrequency = -1;
foreach ($widthFrequencies as $width => $frequency) {
if ($frequency > $defaultWidthFrequency) {
$defaultWidth = $width;
$defaultWidthFrequency = $frequency;
}
}
// Store default value in the font dictionary
$this->_resource->DW = new Zend_Pdf_Element_Numeric($this->toEmSpace($defaultWidth));
// Remove characters which corresponds to default width from the widths array
$defWidthChars = array_keys($charWidths, $defaultWidth);
foreach ($defWidthChars as $charCode) {
unset($charWidths[$charCode]);
}
// Order cheracter widths aray by character codes
ksort($charWidths, SORT_NUMERIC);
/* Width array optimization. Step2: Compact character codes sequences */
$lastCharCode = -1;
$widthsSequences = array();
foreach ($charWidths as $charCode => $width) {
if ($lastCharCode == -1) {
$charCodesSequense = array();
$sequenceStartCode = $charCode;
} else if ($charCode != $lastCharCode + 1) {
// New chracters sequence detected
$widthsSequences[$sequenceStartCode] = $charCodesSequense;
$charCodesSequense = array();
$sequenceStartCode = $charCode;
}
$charCodesSequense[] = $width;
$lastCharCode = $charCode;
}
// Save last sequence, if widths array is not empty (it may happens for monospaced fonts)
if (count($charWidths) != 0) {
$widthsSequences[$sequenceStartCode] = $charCodesSequense;
}
$pdfCharsWidths = array();
foreach ($widthsSequences as $startCode => $widthsSequence) {
/* Width array optimization. Step3: Compact widths sequences */
$pdfWidths = array();
$lastWidth = -1;
$widthsInSequence = 0;
foreach ($widthsSequence as $width) {
if ($lastWidth != $width) {
// New width is detected
if ($widthsInSequence != 0) {
// Previous width value was a part of the widths sequence. Save it as 'c_1st c_last w'.
$pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($startCode); // First character code
$pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($startCode + $widthsInSequence - 1); // Last character code
$pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($this->toEmSpace($lastWidth)); // Width
// Reset widths sequence
$startCode = $startCode + $widthsInSequence;
$widthsInSequence = 0;
}
// Collect new width
$pdfWidths[] = new Zend_Pdf_Element_Numeric($this->toEmSpace($width));
$lastWidth = $width;
} else {
// Width is equal to previous
if (count($pdfWidths) != 0) {
// We already have some widths collected
// So, we've just detected new widths sequence
// Remove last element from widths list, since it's a part of widths sequence
array_pop($pdfWidths);
// and write the rest if it's not empty
if (count($pdfWidths) != 0) {
// Save it as 'c_1st [w1 w2 ... wn]'.
$pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($startCode); // First character code
$pdfCharsWidths[] = new Zend_Pdf_Element_Array($pdfWidths); // Widths array
// Reset widths collection
$startCode += count($pdfWidths);
$pdfWidths = array();
}
$widthsInSequence = 2;
} else {
// Continue widths sequence
$widthsInSequence++;
}
}
}
// Check if we have widths collection or widths sequence to wite it down
if (count($pdfWidths) != 0) {
// We have some widths collected
// Save it as 'c_1st [w1 w2 ... wn]'.
$pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($startCode); // First character code
$pdfCharsWidths[] = new Zend_Pdf_Element_Array($pdfWidths); // Widths array
} else if ($widthsInSequence != 0){
// We have widths sequence
// Save it as 'c_1st c_last w'.
$pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($startCode); // First character code
$pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($startCode + $widthsInSequence - 1); // Last character code
$pdfCharsWidths[] = new Zend_Pdf_Element_Numeric($this->toEmSpace($lastWidth)); // Width
}
}
/* Create the Zend_Pdf_Element_Array object and add it to the font's
* object factory and resource dictionary.
*/
$widthsArrayElement = new Zend_Pdf_Element_Array($pdfCharsWidths);
$widthsObject = $this->_objectFactory->newObject($widthsArrayElement);
$this->_resource->W = $widthsObject;
/* CIDSystemInfo dictionary */
$cidSystemInfo = new Zend_Pdf_Element_Dictionary();
$cidSystemInfo->Registry = new Zend_Pdf_Element_String('Adobe');
$cidSystemInfo->Ordering = new Zend_Pdf_Element_String('UCS');
$cidSystemInfo->Supplement = new Zend_Pdf_Element_Numeric(0);
$cidSystemInfoObject = $this->_objectFactory->newObject($cidSystemInfo);
$this->_resource->CIDSystemInfo = $cidSystemInfoObject;
}
/**
* Returns an array of glyph numbers corresponding to the Unicode characters.
*
* If a particular character doesn't exist in this font, the special 'missing
* character glyph' will be substituted.
*
* See also {@link glyphNumberForCharacter()}.
*
* @param array $characterCodes Array of Unicode character codes (code points).
* @return array Array of glyph numbers.
*/
public function glyphNumbersForCharacters($characterCodes)
{
/**
* CIDFont object is not actually a font. It does not have an Encoding entry,
* it cannot be listed in the Font subdictionary of a resource dictionary, and
* it cannot be used as the operand of the Tf operator.
*
* Throw an exception.
*/
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('CIDFont PDF objects could not be used as the operand of the text drawing operators');
}
/**
* Returns the glyph number corresponding to the Unicode character.
*
* If a particular character doesn't exist in this font, the special 'missing
* character glyph' will be substituted.
*
* See also {@link glyphNumbersForCharacters()} which is optimized for bulk
* operations.
*
* @param integer $characterCode Unicode character code (code point).
* @return integer Glyph number.
*/
public function glyphNumberForCharacter($characterCode)
{
/**
* CIDFont object is not actually a font. It does not have an Encoding entry,
* it cannot be listed in the Font subdictionary of a resource dictionary, and
* it cannot be used as the operand of the Tf operator.
*
* Throw an exception.
*/
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('CIDFont PDF objects could not be used as the operand of the text drawing operators');
}
/**
* Returns a number between 0 and 1 inclusive that indicates the percentage
* of characters in the string which are covered by glyphs in this font.
*
* Since no one font will contain glyphs for the entire Unicode character
* range, this method can be used to help locate a suitable font when the
* actual contents of the string are not known.
*
* Note that some fonts lie about the characters they support. Additionally,
* fonts don't usually contain glyphs for control characters such as tabs
* and line breaks, so it is rare that you will get back a full 1.0 score.
* The resulting value should be considered informational only.
*
* @param string $string
* @param string $charEncoding (optional) Character encoding of source text.
* If omitted, uses 'current locale'.
* @return float
*/
public function getCoveredPercentage($string, $charEncoding = '')
{
/* Convert the string to UTF-16BE encoding so we can match the string's
* character codes to those found in the cmap.
*/
if ($charEncoding != 'UTF-16BE') {
$string = iconv($charEncoding, 'UTF-16BE', $string);
}
$charCount = iconv_strlen($string, 'UTF-16BE');
if ($charCount == 0) {
return 0;
}
/* Calculate the score by doing a lookup for each character.
*/
$score = 0;
$maxIndex = strlen($string);
for ($i = 0; $i < $maxIndex; $i++) {
/**
* @todo Properly handle characters encoded as surrogate pairs.
*/
$charCode = (ord($string[$i]) << 8) | ord($string[++$i]);
/* This could probably be optimized a bit with a binary search...
*/
if (isset($this->_charWidths[$charCode])) {
$score++;
}
}
return $score / $charCount;
}
/**
* Returns the widths of the Chars.
*
* The widths are expressed in the font's glyph space. You are responsible
* for converting to user space as necessary. See {@link unitsPerEm()}.
*
* See also {@link widthForChar()}.
*
* @param array &$glyphNumbers Array of glyph numbers.
* @return array Array of glyph widths (integers).
*/
public function widthsForChars($charCodes)
{
$widths = array();
foreach ($charCodes as $key => $charCode) {
if (!isset($this->_charWidths[$charCode])) {
$widths[$key] = $this->_missingCharWidth;
} else {
$widths[$key] = $this->_charWidths[$charCode];
}
}
return $widths;
}
/**
* Returns the width of the character.
*
* Like {@link widthsForChars()} but used for one char at a time.
*
* @param integer $charCode
* @return integer
*/
public function widthForChar($charCode)
{
if (!isset($this->_charWidths[$charCode])) {
return $this->_missingCharWidth;
}
return $this->_charWidths[$charCode];
}
/**
* Returns the widths of the glyphs.
*
* @param array &$glyphNumbers Array of glyph numbers.
* @return array Array of glyph widths (integers).
* @throws Zend_Pdf_Exception
*/
public function widthsForGlyphs($glyphNumbers)
{
/**
* CIDFont object is not actually a font. It does not have an Encoding entry,
* it cannot be listed in the Font subdictionary of a resource dictionary, and
* it cannot be used as the operand of the Tf operator.
*
* Throw an exception.
*/
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('CIDFont PDF objects could not be used as the operand of the text drawing operators');
}
/**
* Returns the width of the glyph.
*
* Like {@link widthsForGlyphs()} but used for one glyph at a time.
*
* @param integer $glyphNumber
* @return integer
* @throws Zend_Pdf_Exception
*/
public function widthForGlyph($glyphNumber)
{
/**
* CIDFont object is not actually a font. It does not have an Encoding entry,
* it cannot be listed in the Font subdictionary of a resource dictionary, and
* it cannot be used as the operand of the Tf operator.
*
* Throw an exception.
*/
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('CIDFont PDF objects could not be used as the operand of the text drawing operators');
}
/**
* Convert string to the font encoding.
*
* @param string $string
* @param string $charEncoding Character encoding of source text.
* @return string
* @throws Zend_Pdf_Exception
* */
public function encodeString($string, $charEncoding)
{
/**
* CIDFont object is not actually a font. It does not have an Encoding entry,
* it cannot be listed in the Font subdictionary of a resource dictionary, and
* it cannot be used as the operand of the Tf operator.
*
* Throw an exception.
*/
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('CIDFont PDF objects could not be used as the operand of the text drawing operators');
}
/**
* Convert string from the font encoding.
*
* @param string $string
* @param string $charEncoding Character encoding of resulting text.
* @return string
* @throws Zend_Pdf_Exception
*/
public function decodeString($string, $charEncoding)
{
/**
* CIDFont object is not actually a font. It does not have an Encoding entry,
* it cannot be listed in the Font subdictionary of a resource dictionary, and
* it cannot be used as the operand of the Tf operator.
*
* Throw an exception.
*/
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception('CIDFont PDF objects could not be used as the operand of the text drawing operators');
}
}
| jupeter/zf1 | library/Zend/Pdf/Resource/Font/CidFont.php | PHP | bsd-3-clause | 19,099 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/webshare/win/fake_data_transfer_manager.h"
#include <wrl/module.h>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/win/core_winrt_util.h"
#include "base/win/scoped_hstring.h"
#include "base/win/vector.h"
#include "base/win/windows_version.h"
#include "testing/gtest/include/gtest/gtest.h"
using ABI::Windows::ApplicationModel::DataTransfer::DataPackage;
using ABI::Windows::ApplicationModel::DataTransfer::DataPackageOperation;
using ABI::Windows::ApplicationModel::DataTransfer::DataRequestedEventArgs;
using ABI::Windows::ApplicationModel::DataTransfer::DataTransferManager;
using ABI::Windows::ApplicationModel::DataTransfer::IDataPackage;
using ABI::Windows::ApplicationModel::DataTransfer::IDataPackage2;
using ABI::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet;
using ABI::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet3;
using ABI::Windows::ApplicationModel::DataTransfer::IDataPackageView;
using ABI::Windows::ApplicationModel::DataTransfer::IDataProviderHandler;
using ABI::Windows::ApplicationModel::DataTransfer::IDataRequest;
using ABI::Windows::ApplicationModel::DataTransfer::IDataRequestDeferral;
using ABI::Windows::ApplicationModel::DataTransfer::IDataRequestedEventArgs;
using ABI::Windows::ApplicationModel::DataTransfer::IDataTransferManager;
using ABI::Windows::ApplicationModel::DataTransfer::OperationCompletedEventArgs;
using ABI::Windows::ApplicationModel::DataTransfer::
TargetApplicationChosenEventArgs;
using ABI::Windows::Foundation::DateTime;
using ABI::Windows::Foundation::ITypedEventHandler;
using ABI::Windows::Foundation::IUriRuntimeClass;
using ABI::Windows::Foundation::Collections::IIterable;
using ABI::Windows::Foundation::Collections::IIterator;
using ABI::Windows::Foundation::Collections::IMap;
using ABI::Windows::Foundation::Collections::IVector;
using ABI::Windows::Storage::IStorageFile;
using ABI::Windows::Storage::IStorageItem;
using ABI::Windows::Storage::Streams::IRandomAccessStreamReference;
using ABI::Windows::Storage::Streams::RandomAccessStreamReference;
using Microsoft::WRL::ActivationFactory;
using Microsoft::WRL::ComPtr;
using Microsoft::WRL::Make;
using Microsoft::WRL::RuntimeClass;
using Microsoft::WRL::RuntimeClassFlags;
using Microsoft::WRL::WinRtClassicComMix;
namespace ABI {
namespace Windows {
namespace Foundation {
namespace Collections {
// Define template specializations for the types used.
template <>
struct __declspec(uuid("AF82EEF9-F786-475D-A3EB-929AEB6F0689"))
IObservableVector<HSTRING> : IObservableVector_impl<HSTRING> {};
template <>
struct __declspec(uuid("1ED11184-03B9-4911-875C-9682969C732A"))
VectorChangedEventHandler<HSTRING>
: VectorChangedEventHandler_impl<HSTRING> {};
} // namespace Collections
} // namespace Foundation
} // namespace Windows
} // namespace ABI
namespace webshare {
namespace {
class FakeDataPackagePropertySet final
: public RuntimeClass<RuntimeClassFlags<WinRtClassicComMix>,
IDataPackagePropertySet,
IDataPackagePropertySet3> {
public:
FakeDataPackagePropertySet(
FakeDataTransferManager::DataRequestedContent& data_requested_content)
: data_requested_content_(data_requested_content) {}
FakeDataPackagePropertySet(const FakeDataPackagePropertySet&) = delete;
FakeDataPackagePropertySet& operator=(const FakeDataPackagePropertySet&) =
delete;
~FakeDataPackagePropertySet() final {
// Though it is technically legal for consuming code to hold on to the
// FileTypes past the lifetime of the DataPackagePropertySet, there is
// no good reason to do so, so any lingering references presumably point
// to a coding error.
if (file_types_)
EXPECT_EQ(0u, file_types_.Reset());
}
// IDataPackagePropertySet
IFACEMETHODIMP get_ApplicationListingUri(IUriRuntimeClass** value) final {
NOTREACHED();
return E_NOTIMPL;
}
IFACEMETHODIMP get_ApplicationName(HSTRING* value) final {
NOTREACHED();
return E_NOTIMPL;
}
IFACEMETHODIMP get_Description(HSTRING* value) final {
NOTREACHED();
return E_NOTIMPL;
}
IFACEMETHODIMP get_FileTypes(IVector<HSTRING>** value) final {
if (!file_types_)
file_types_ = Make<base::win::Vector<HSTRING>>();
auto hr = file_types_->QueryInterface(IID_PPV_ARGS(value));
EXPECT_HRESULT_SUCCEEDED(hr);
return hr;
}
IFACEMETHODIMP get_Thumbnail(IRandomAccessStreamReference** value) final {
NOTREACHED();
return E_NOTIMPL;
}
IFACEMETHODIMP get_Title(HSTRING* value) final {
NOTREACHED();
return E_NOTIMPL;
}
IFACEMETHODIMP put_ApplicationListingUri(IUriRuntimeClass* value) final {
return S_OK;
}
IFACEMETHODIMP put_ApplicationName(HSTRING value) final { return S_OK; }
IFACEMETHODIMP put_Description(HSTRING value) final { return S_OK; }
IFACEMETHODIMP put_Thumbnail(IRandomAccessStreamReference* value) final {
return S_OK;
}
IFACEMETHODIMP put_Title(HSTRING value) final {
base::win::ScopedHString wrapped_value(value);
data_requested_content_.title = wrapped_value.GetAsUTF8();
return S_OK;
}
// IDataPackagePropertySet3
IFACEMETHODIMP get_EnterpriseId(HSTRING* value) final {
NOTREACHED();
return E_NOTIMPL;
}
IFACEMETHODIMP put_EnterpriseId(HSTRING value) final { return S_OK; }
private:
FakeDataTransferManager::DataRequestedContent& data_requested_content_;
ComPtr<base::win::Vector<HSTRING>> file_types_;
};
class FakeDataPackage final
: public RuntimeClass<RuntimeClassFlags<WinRtClassicComMix>,
IDataPackage,
IDataPackage2> {
public:
FakeDataPackage(
FakeDataTransferManager::DataRequestedContent& data_requested_content)
: data_requested_content_(data_requested_content) {}
FakeDataPackage(const FakeDataPackage&) = delete;
FakeDataPackage& operator=(const FakeDataPackage&) = delete;
~FakeDataPackage() final {
// Though it is technically legal for consuming code to hold on to the
// DataPackagePropertySet past the lifetime of the DataPackage, there is
// no good reason to do so, so any lingering references presumably point
// to a coding error.
if (properties_)
EXPECT_EQ(0u, properties_.Reset());
}
// IDataPackage
IFACEMETHODIMP add_Destroyed(
ITypedEventHandler<DataPackage*, IInspectable*>* handler,
EventRegistrationToken* token) final {
NOTREACHED();
return E_NOTIMPL;
}
IFACEMETHODIMP add_OperationCompleted(
ITypedEventHandler<DataPackage*, OperationCompletedEventArgs*>* handler,
EventRegistrationToken* token) final {
NOTREACHED();
return E_NOTIMPL;
}
IFACEMETHODIMP GetView(IDataPackageView** result) final {
NOTREACHED();
return E_NOTIMPL;
}
IFACEMETHODIMP get_Properties(IDataPackagePropertySet** value) final {
if (!properties_)
properties_ = Make<FakeDataPackagePropertySet>(data_requested_content_);
auto hr = properties_->QueryInterface(IID_PPV_ARGS(value));
EXPECT_HRESULT_SUCCEEDED(hr);
return hr;
}
IFACEMETHODIMP get_RequestedOperation(DataPackageOperation* value) final {
NOTREACHED();
return E_NOTIMPL;
}
IFACEMETHODIMP get_ResourceMap(
IMap<HSTRING, RandomAccessStreamReference*>** value) final {
NOTREACHED();
return E_NOTIMPL;
}
IFACEMETHODIMP put_RequestedOperation(DataPackageOperation value) final {
return S_OK;
}
IFACEMETHODIMP remove_Destroyed(EventRegistrationToken token) final {
NOTREACHED();
return E_NOTIMPL;
}
IFACEMETHODIMP remove_OperationCompleted(EventRegistrationToken token) final {
NOTREACHED();
return E_NOTIMPL;
}
IFACEMETHODIMP SetBitmap(IRandomAccessStreamReference* value) final {
return S_OK;
}
IFACEMETHODIMP SetData(HSTRING formatId, IInspectable* value) final {
return S_OK;
}
IFACEMETHODIMP SetDataProvider(HSTRING formatId,
IDataProviderHandler* delayRenderer) final {
return S_OK;
}
IFACEMETHODIMP SetHtmlFormat(HSTRING value) final { return S_OK; }
IFACEMETHODIMP SetRtf(HSTRING value) final { return S_OK; }
IFACEMETHODIMP SetText(HSTRING value) final {
base::win::ScopedHString wrapped_value(value);
data_requested_content_.text = wrapped_value.GetAsUTF8();
return S_OK;
}
IFACEMETHODIMP SetStorageItems(IIterable<IStorageItem*>* value,
boolean readOnly) final {
EXPECT_TRUE(readOnly);
return SetStorageItemsReadOnly(value);
}
IFACEMETHODIMP SetStorageItemsReadOnly(
IIterable<IStorageItem*>* value) final {
ComPtr<IIterator<IStorageItem*>> iterator;
HRESULT hr = value->First(&iterator);
if (FAILED(hr))
return hr;
boolean has_current;
hr = iterator->get_HasCurrent(&has_current);
if (FAILED(hr))
return hr;
while (has_current == TRUE) {
ComPtr<IStorageItem> storage_item;
hr = iterator->get_Current(&storage_item);
if (FAILED(hr))
return hr;
HSTRING name;
hr = storage_item->get_Name(&name);
base::win::ScopedHString wrapped_name(name);
if (FAILED(hr))
return hr;
ComPtr<IStorageFile> storage_file;
hr = storage_item.As(&storage_file);
if (FAILED(hr))
return hr;
FakeDataTransferManager::DataRequestedFile file;
file.name = wrapped_name.GetAsUTF8();
file.file = storage_file;
data_requested_content_.files.push_back(std::move(file));
hr = iterator->MoveNext(&has_current);
if (FAILED(hr))
return hr;
}
return S_OK;
}
IFACEMETHODIMP SetUri(IUriRuntimeClass* value) final { return S_OK; }
// IDataPackage2
IFACEMETHODIMP SetApplicationLink(IUriRuntimeClass* value) final {
return S_OK;
}
IFACEMETHODIMP SetWebLink(IUriRuntimeClass* value) final {
HSTRING raw_uri;
value->get_RawUri(&raw_uri);
base::win::ScopedHString wrapped_value(raw_uri);
data_requested_content_.uri = wrapped_value.GetAsUTF8();
return S_OK;
}
private:
FakeDataTransferManager::DataRequestedContent& data_requested_content_;
ComPtr<IDataPackagePropertySet> properties_;
};
class FakeDataRequest final
: public RuntimeClass<RuntimeClassFlags<WinRtClassicComMix>, IDataRequest> {
public:
struct FakeDataRequestDeferral final
: public RuntimeClass<RuntimeClassFlags<WinRtClassicComMix>,
IDataRequestDeferral> {
public:
explicit FakeDataRequestDeferral(FakeDataRequest* data_request)
: data_request_(data_request) {}
FakeDataRequestDeferral(const FakeDataRequestDeferral&) = delete;
FakeDataRequestDeferral& operator=(const FakeDataRequestDeferral&) = delete;
// IDataRequestDeferral
IFACEMETHODIMP Complete() final {
data_request_->RunPostDataRequestedCallbackImpl();
return S_OK;
}
private:
ComPtr<FakeDataRequest> data_request_;
};
FakeDataRequest(FakeDataTransferManager::PostDataRequestedCallback
post_data_requested_callback)
: post_data_requested_callback_(post_data_requested_callback) {}
FakeDataRequest(const FakeDataRequest&) = delete;
FakeDataRequest& operator=(const FakeDataRequest&) = delete;
~FakeDataRequest() final = default;
// IDataRequest
IFACEMETHODIMP FailWithDisplayText(HSTRING value) final {
NOTREACHED();
return E_NOTIMPL;
}
IFACEMETHODIMP get_Data(IDataPackage** value) final {
if (!data_package_)
data_package_ = Make<FakeDataPackage>(data_requested_content_);
auto hr = data_package_->QueryInterface(IID_PPV_ARGS(value));
EXPECT_HRESULT_SUCCEEDED(hr);
return hr;
}
IFACEMETHODIMP
get_Deadline(DateTime* value) final {
NOTREACHED();
return E_NOTIMPL;
}
IFACEMETHODIMP GetDeferral(IDataRequestDeferral** value) final {
if (!data_request_deferral_)
data_request_deferral_ = Make<FakeDataRequestDeferral>(this);
auto hr = data_request_deferral_->QueryInterface(IID_PPV_ARGS(value));
EXPECT_HRESULT_SUCCEEDED(hr);
return hr;
}
IFACEMETHODIMP put_Data(IDataPackage* value) final {
data_package_ = value;
return S_OK;
}
void RunPostDataRequestedCallback() {
// If there is not a deferral trigger the callback right away, otherwise it
// will be triggered when the deferral is complete
if (!data_request_deferral_)
RunPostDataRequestedCallbackImpl();
}
private:
void RunPostDataRequestedCallbackImpl() {
post_data_requested_callback_.Run(data_requested_content_);
}
ComPtr<IDataPackage> data_package_;
ComPtr<FakeDataRequestDeferral> data_request_deferral_;
FakeDataTransferManager::DataRequestedContent data_requested_content_;
FakeDataTransferManager::PostDataRequestedCallback
post_data_requested_callback_;
};
class FakeDataRequestedEventArgs final
: public RuntimeClass<RuntimeClassFlags<WinRtClassicComMix>,
IDataRequestedEventArgs> {
public:
FakeDataRequestedEventArgs(FakeDataTransferManager::PostDataRequestedCallback
post_data_requested_callback)
: post_data_requested_callback_(post_data_requested_callback) {}
FakeDataRequestedEventArgs(const FakeDataRequestedEventArgs&) = delete;
FakeDataRequestedEventArgs& operator=(const FakeDataRequestedEventArgs&) =
delete;
~FakeDataRequestedEventArgs() final = default;
// IDataRequestedEventArgs
IFACEMETHODIMP get_Request(IDataRequest** value) final {
if (!data_request_)
data_request_ = Make<FakeDataRequest>(post_data_requested_callback_);
auto hr = data_request_->QueryInterface(IID_PPV_ARGS(value));
EXPECT_HRESULT_SUCCEEDED(hr);
return hr;
}
void RunPostDataRequestedCallback() {
if (data_request_)
data_request_->RunPostDataRequestedCallback();
}
private:
ComPtr<FakeDataRequest> data_request_;
FakeDataTransferManager::PostDataRequestedCallback
post_data_requested_callback_;
};
} // namespace
// static
bool FakeDataTransferManager::IsSupportedEnvironment() {
return base::win::GetVersion() >= base::win::Version::WIN10;
}
FakeDataTransferManager::FakeDataTransferManager() {
post_data_requested_callback_ = base::DoNothing();
}
FakeDataTransferManager::~FakeDataTransferManager() = default;
FakeDataTransferManager::DataRequestedFile::DataRequestedFile() = default;
FakeDataTransferManager::DataRequestedFile::DataRequestedFile(
FakeDataTransferManager::DataRequestedFile&&) = default;
FakeDataTransferManager::DataRequestedFile::~DataRequestedFile() = default;
FakeDataTransferManager::DataRequestedContent::DataRequestedContent() = default;
FakeDataTransferManager::DataRequestedContent::~DataRequestedContent() =
default;
IFACEMETHODIMP
FakeDataTransferManager::add_DataRequested(
ITypedEventHandler<DataTransferManager*, DataRequestedEventArgs*>*
event_handler,
EventRegistrationToken* event_cookie) {
DataRequestedHandlerEntry entry;
entry.event_handler = event_handler;
entry.token_value = ++latest_token_value_;
data_requested_event_handlers_.push_back(std::move(entry));
event_cookie->value = latest_token_value_;
return S_OK;
}
IFACEMETHODIMP
FakeDataTransferManager::remove_DataRequested(
EventRegistrationToken event_cookie) {
auto it = data_requested_event_handlers_.begin();
while (it != data_requested_event_handlers_.end()) {
if (it->token_value == event_cookie.value) {
data_requested_event_handlers_.erase(it);
return S_OK;
}
it++;
}
ADD_FAILURE() << "remove_DataRequested called for untracked token";
return E_FAIL;
}
IFACEMETHODIMP FakeDataTransferManager::add_TargetApplicationChosen(
ITypedEventHandler<DataTransferManager*, TargetApplicationChosenEventArgs*>*
eventHandler,
EventRegistrationToken* event_cookie) {
NOTREACHED();
return E_NOTIMPL;
}
IFACEMETHODIMP
FakeDataTransferManager::remove_TargetApplicationChosen(
EventRegistrationToken event_cookie) {
NOTREACHED();
return E_NOTIMPL;
}
base::OnceClosure FakeDataTransferManager::GetDataRequestedInvoker() {
if (data_requested_event_handlers_.empty()) {
ADD_FAILURE()
<< "GetDataRequestedInvoker called with no event handler registered";
return base::DoNothing();
}
// Though multiple handlers may be registered for this event, only the
// latest is invoked by the OS and then the event is considered handled.
auto handler = data_requested_event_handlers_.back().event_handler;
ComPtr<FakeDataTransferManager> self = this;
return base::BindOnce(
[](ComPtr<FakeDataTransferManager> self,
ComPtr<ITypedEventHandler<DataTransferManager*,
DataRequestedEventArgs*>> handler) {
auto event_args = Make<FakeDataRequestedEventArgs>(
self->post_data_requested_callback_);
handler->Invoke(self.Get(), event_args.Get());
event_args->RunPostDataRequestedCallback();
},
self, handler);
}
bool FakeDataTransferManager::HasDataRequestedListener() {
return !data_requested_event_handlers_.empty();
}
void FakeDataTransferManager::SetPostDataRequestedCallback(
PostDataRequestedCallback post_data_requested_callback) {
post_data_requested_callback_ = std::move(post_data_requested_callback);
}
FakeDataTransferManager::DataRequestedHandlerEntry::
DataRequestedHandlerEntry() = default;
FakeDataTransferManager::DataRequestedHandlerEntry::DataRequestedHandlerEntry(
DataRequestedHandlerEntry const& other) = default;
FakeDataTransferManager::DataRequestedHandlerEntry::
~DataRequestedHandlerEntry() {
// Check that the event handler has not been over-freed.
//
// An explicit call to Reset() will cause an Access Violation exception if the
// reference count is already at 0. Though the underling ComPtr code does a
// similar check on destruction of the ComPtr, it does not throw an exception
// in that case, so we have to call Reset() to have the failure exposed to us.
//
// We cannot assume that this particular ComPtr is the last reference to the
// event handler, so do not check to see if the value returned by Reset() is
// 0.
event_handler.Reset();
}
} // namespace webshare
| ric2b/Vivaldi-browser | chromium/chrome/browser/webshare/win/fake_data_transfer_manager.cc | C++ | bsd-3-clause | 18,470 |
/* *
*
* (c) 2010-2018 Torstein Honsi
*
* License: www.highcharts.com/license
*
* */
/**
* Options to align the element relative to the chart or another box.
*
* @interface Highcharts.AlignObject
*//**
* Horizontal alignment. Can be one of `left`, `center` and `right`.
*
* @name Highcharts.AlignObject#align
* @type {string|undefined}
*
* @default left
*//**
* Vertical alignment. Can be one of `top`, `middle` and `bottom`.
*
* @name Highcharts.AlignObject#verticalAlign
* @type {string|undefined}
*
* @default top
*//**
* Horizontal pixel offset from alignment.
*
* @name Highcharts.AlignObject#x
* @type {number|undefined}
*
* @default 0
*//**
* Vertical pixel offset from alignment.
*
* @name Highcharts.AlignObject#y
* @type {number|undefined}
*
* @default 0
*//**
* Use the `transform` attribute with translateX and translateY custom
* attributes to align this elements rather than `x` and `y` attributes.
*
* @name Highcharts.AlignObject#alignByTranslate
* @type {boolean|undefined}
*
* @default false
*/
/**
* Bounding box of an element.
*
* @interface Highcharts.BBoxObject
*//**
* Height of the bounding box.
*
* @name Highcharts.BBoxObject#height
* @type {number}
*//**
* Width of the bounding box.
*
* @name Highcharts.BBoxObject#width
* @type {number}
*//**
* Horizontal position of the bounding box.
*
* @name Highcharts.BBoxObject#x
* @type {number}
*//**
* Vertical position of the bounding box.
*
* @name Highcharts.BBoxObject#y
* @type {number}
*/
/**
* A clipping rectangle that can be applied to one or more {@link SVGElement}
* instances. It is instanciated with the {@link SVGRenderer#clipRect} function
* and applied with the {@link SVGElement#clip} function.
*
* @example
* var circle = renderer.circle(100, 100, 100)
* .attr({ fill: 'red' })
* .add();
* var clipRect = renderer.clipRect(100, 100, 100, 100);
*
* // Leave only the lower right quarter visible
* circle.clip(clipRect);
*
* @typedef {Highcharts.SVGElement} Highcharts.ClipRectElement
*/
/**
* The font metrics.
*
* @interface Highcharts.FontMetricsObject
*//**
* The baseline relative to the top of the box.
*
* @name Highcharts.FontMetricsObject#b
* @type {number}
*//**
* The line height.
*
* @name Highcharts.FontMetricsObject#h
* @type {number}
*//**
* The font size.
*
* @name Highcharts.FontMetricsObject#f
* @type {number}
*/
/**
* Gradient options instead of a solid color.
*
* @example
* // Linear gradient used as a color option
* color: {
* linearGradient: { x1: 0, x2: 0, y1: 0, y2: 1 },
* stops: [
* [0, '#003399'], // start
* [0.5, '#ffffff'], // middle
* [1, '#3366AA'] // end
* ]
* }
* }
*
* @interface Highcharts.GradientColorObject
*//**
* Holds an object that defines the start position and the end position relative
* to the shape.
*
* @name Highcharts.GradientColorObject#linearGradient
* @type {Highcharts.LinearGradientColorObject|undefined}
*//**
* Holds an object that defines the center position and the radius.
*
* @name Highcharts.GradientColorObject#radialGradient
* @type {Highcharts.RadialGradientColorObject|undefined}
*//**
* The first item in each tuple is the position in the gradient, where 0 is the
* start of the gradient and 1 is the end of the gradient. Multiple stops can be
* applied. The second item is the color for each stop. This color can also be
* given in the rgba format.
*
* @name Highcharts.GradientColorObject#stops
* @type {Array<Array<number,Highcharts.ColorString>>|undefined}
*/
/**
* Defines the start position and the end position for a gradient relative
* to the shape. Start position (x1, y1) and end position (x2, y2) are relative
* to the shape, where 0 means top/left and 1 is bottom/right.
*
* @interface Highcharts.LinearGradientColorObject
*//**
* Start horizontal position of the gradient. Float ranges 0-1.
*
* @name Highcharts.LinearGradientColorObject#x1
* @type {number}
*//**
* End horizontal position of the gradient. Float ranges 0-1.
*
* @name Highcharts.LinearGradientColorObject#x2
* @type {number}
*//**
* Start vertical position of the gradient. Float ranges 0-1.
*
* @name Highcharts.LinearGradientColorObject#y1
* @type {number}
*//**
* End vertical position of the gradient. Float ranges 0-1.
*
* @name Highcharts.LinearGradientColorObject#y2
* @type {number}
*/
/**
* Defines the center position and the radius for a gradient.
*
* @interface Highcharts.RadialGradientColorObject
*//**
* Center horizontal position relative to the shape. Float ranges 0-1.
*
* @name Highcharts.RadialGradientColorObject#cx
* @type {number}
*//**
* Center vertical position relative to the shape. Float ranges 0-1.
*
* @name Highcharts.RadialGradientColorObject#cy
* @type {number}
*//**
* Radius relative to the shape. Float ranges 0-1.
*
* @name Highcharts.RadialGradientColorObject#r
* @type {number}
*/
/**
* A rectangle.
*
* @interface Highcharts.RectangleObject
*//**
* Height of the rectangle.
*
* @name Highcharts.RectangleObject#height
* @type {number}
*//**
* Width of the rectangle.
*
* @name Highcharts.RectangleObject#width
* @type {number}
*//**
* Horizontal position of the rectangle.
*
* @name Highcharts.RectangleObject#x
* @type {number}
*//**
* Vertical position of the rectangle.
*
* @name Highcharts.RectangleObject#y
* @type {number}
*/
/**
* The shadow options.
*
* @interface Highcharts.ShadowOptionsObject
*//**
* The shadow color.
*
* @name Highcharts.ShadowOptionsObject#color
* @type {string|undefined}
*
* @default #000000
*//**
* The horizontal offset from the element.
*
* @name Highcharts.ShadowOptionsObject#offsetX
* @type {number|undefined}
*
* @default 1
*//**
* The vertical offset from the element.
*
* @name Highcharts.ShadowOptionsObject#offsetY
* @type {number|undefined}
*
* @default 1
*//**
* The shadow opacity.
*
* @name Highcharts.ShadowOptionsObject#opacity
* @type {number|undefined}
*
* @default 0.15
*//**
* The shadow width or distance from the element.
*
* @name Highcharts.ShadowOptionsObject#width
* @type {number|undefined}
*
* @default 3
*/
/**
* Serialized form of an SVG definition, including children. Some key
* property names are reserved: tagName, textContent, and children.
*
* @interface Highcharts.SVGDefinitionObject
*//**
* @name Highcharts.SVGDefinitionObject#[key:string]
* @type {number|string|Array<Highcharts.SVGDefinitionObject>|undefined}
*//**
* @name Highcharts.SVGDefinitionObject#children
* @type {Array<Highcharts.SVGDefinitionObject>|undefined}
*//**
* @name Highcharts.SVGDefinitionObject#tagName
* @type {string|undefined}
*//**
* @name Highcharts.SVGDefinitionObject#textContent
* @type {string|undefined}
*/
/**
* An extendable collection of functions for defining symbol paths.
*
* @typedef Highcharts.SymbolDictionary
*
* @property {Function|undefined} [key:Highcharts.SymbolKey]
*/
/**
* Can be one of `arc`, `callout`, `circle`, `diamond`, `square`,
* `triangle`, `triangle-down`. Symbols are used internally for point
* markers, button and label borders and backgrounds, or custom shapes.
* Extendable by adding to {@link SVGRenderer#symbols}.
*
* @typedef {string} Highcharts.SymbolKey
* @validvalue ["arc", "callout", "circle", "diamond", "square", "triangle",
* "triangle-down"]
*/
/**
* Additional options, depending on the actual symbol drawn.
*
* @interface Highcharts.SymbolOptionsObject
*//**
* The anchor X position for the `callout` symbol. This is where the chevron
* points to.
*
* @name Highcharts.SymbolOptionsObject#anchorX
* @type {number}
*//**
* The anchor Y position for the `callout` symbol. This is where the chevron
* points to.
*
* @name Highcharts.SymbolOptionsObject#anchorY
* @type {number}
*//**
* The end angle of an `arc` symbol.
*
* @name Highcharts.SymbolOptionsObject#end
* @type {number}
*//**
* Whether to draw `arc` symbol open or closed.
*
* @name Highcharts.SymbolOptionsObject#open
* @type {boolean}
*//**
* The radius of an `arc` symbol, or the border radius for the `callout` symbol.
*
* @name Highcharts.SymbolOptionsObject#r
* @type {number}
*//**
* The start angle of an `arc` symbol.
*
* @name Highcharts.SymbolOptionsObject#start
* @type {number}
*/
'use strict';
import H from './Globals.js';
import './Utilities.js';
import './Color.js';
var SVGElement,
SVGRenderer,
addEvent = H.addEvent,
animate = H.animate,
attr = H.attr,
charts = H.charts,
color = H.color,
css = H.css,
createElement = H.createElement,
defined = H.defined,
deg2rad = H.deg2rad,
destroyObjectProperties = H.destroyObjectProperties,
doc = H.doc,
extend = H.extend,
erase = H.erase,
hasTouch = H.hasTouch,
isArray = H.isArray,
isFirefox = H.isFirefox,
isMS = H.isMS,
isObject = H.isObject,
isString = H.isString,
isWebKit = H.isWebKit,
merge = H.merge,
noop = H.noop,
objectEach = H.objectEach,
pick = H.pick,
pInt = H.pInt,
removeEvent = H.removeEvent,
splat = H.splat,
stop = H.stop,
svg = H.svg,
SVG_NS = H.SVG_NS,
symbolSizes = H.symbolSizes,
win = H.win;
/**
* The SVGElement prototype is a JavaScript wrapper for SVG elements used in the
* rendering layer of Highcharts. Combined with the {@link
* Highcharts.SVGRenderer} object, these prototypes allow freeform annotation
* in the charts or even in HTML pages without instanciating a chart. The
* SVGElement can also wrap HTML labels, when `text` or `label` elements are
* created with the `useHTML` parameter.
*
* The SVGElement instances are created through factory functions on the {@link
* Highcharts.SVGRenderer} object, like {@link Highcharts.SVGRenderer#rect|
* rect}, {@link Highcharts.SVGRenderer#path|path}, {@link
* Highcharts.SVGRenderer#text|text}, {@link Highcharts.SVGRenderer#label|
* label}, {@link Highcharts.SVGRenderer#g|g} and more.
*
* @class
* @name Highcharts.SVGElement
*/
SVGElement = H.SVGElement = function () {
return this;
};
extend(SVGElement.prototype, /** @lends Highcharts.SVGElement.prototype */ {
// Default base for animation
opacity: 1,
SVG_NS: SVG_NS,
/**
* For labels, these CSS properties are applied to the `text` node directly.
*
* @private
* @name Highcharts.SVGElement#textProps
* @type {Array<string>}
*/
textProps: ['direction', 'fontSize', 'fontWeight', 'fontFamily',
'fontStyle', 'color', 'lineHeight', 'width', 'textAlign',
'textDecoration', 'textOverflow', 'textOutline', 'cursor'],
/**
* Initialize the SVG element. This function only exists to make the
* initiation process overridable. It should not be called directly.
*
* @function Highcharts.SVGElement#init
*
* @param {Highcharts.SVGRenderer} renderer
* The SVGRenderer instance to initialize to.
*
* @param {string} nodeName
* The SVG node name.
*/
init: function (renderer, nodeName) {
/**
* The primary DOM node. Each `SVGElement` instance wraps a main DOM
* node, but may also represent more nodes.
*
* @name Highcharts.SVGElement#element
* @type {Highcharts.SVGDOMElement|Highcharts.HTMLDOMElement}
*/
this.element = nodeName === 'span' ?
createElement(nodeName) :
doc.createElementNS(this.SVG_NS, nodeName);
/**
* The renderer that the SVGElement belongs to.
*
* @name Highcharts.SVGElement#renderer
* @type {Highcharts.SVGRenderer}
*/
this.renderer = renderer;
},
/**
* Animate to given attributes or CSS properties.
*
* @sample highcharts/members/element-on/
* Setting some attributes by animation
*
* @function Highcharts.SVGElement#animate
*
* @param {Highcharts.SVGAttributes} params
* SVG attributes or CSS to animate.
*
* @param {Highcharts.AnimationOptionsObject} [options]
* Animation options.
*
* @param {Function} [complete]
* Function to perform at the end of animation.
*
* @return {Highcharts.SVGElement}
* Returns the SVGElement for chaining.
*/
animate: function (params, options, complete) {
var animOptions = H.animObject(
pick(options, this.renderer.globalAnimation, true)
);
if (animOptions.duration !== 0) {
// allows using a callback with the global animation without
// overwriting it
if (complete) {
animOptions.complete = complete;
}
animate(this, params, animOptions);
} else {
this.attr(params, null, complete);
if (animOptions.step) {
animOptions.step.call(this);
}
}
return this;
},
/**
* Build and apply an SVG gradient out of a common JavaScript configuration
* object. This function is called from the attribute setters. An event
* hook is added for supporting other complex color types.
*
* @private
* @function Highcharts.SVGElement#complexColor
*
* @param {Highcharts.GradientColorObject} color
* The gradient options structure.
*
* @param {string} prop
* The property to apply, can either be `fill` or `stroke`.
*
* @param {Highcharts.SVGDOMElement} elem
* SVG DOM element to apply the gradient on.
*/
complexColor: function (color, prop, elem) {
var renderer = this.renderer,
colorObject,
gradName,
gradAttr,
radAttr,
gradients,
gradientObject,
stops,
stopColor,
stopOpacity,
radialReference,
id,
key = [],
value;
H.fireEvent(this.renderer, 'complexColor', {
args: arguments
}, function () {
// Apply linear or radial gradients
if (color.radialGradient) {
gradName = 'radialGradient';
} else if (color.linearGradient) {
gradName = 'linearGradient';
}
if (gradName) {
gradAttr = color[gradName];
gradients = renderer.gradients;
stops = color.stops;
radialReference = elem.radialReference;
// Keep < 2.2 kompatibility
if (isArray(gradAttr)) {
color[gradName] = gradAttr = {
x1: gradAttr[0],
y1: gradAttr[1],
x2: gradAttr[2],
y2: gradAttr[3],
gradientUnits: 'userSpaceOnUse'
};
}
// Correct the radial gradient for the radial reference system
if (
gradName === 'radialGradient' &&
radialReference &&
!defined(gradAttr.gradientUnits)
) {
// Save the radial attributes for updating
radAttr = gradAttr;
gradAttr = merge(
gradAttr,
renderer.getRadialAttr(radialReference, radAttr),
{ gradientUnits: 'userSpaceOnUse' }
);
}
// Build the unique key to detect whether we need to create a
// new element (#1282)
objectEach(gradAttr, function (val, n) {
if (n !== 'id') {
key.push(n, val);
}
});
objectEach(stops, function (val) {
key.push(val);
});
key = key.join(',');
// Check if a gradient object with the same config object is
// created within this renderer
if (gradients[key]) {
id = gradients[key].attr('id');
} else {
// Set the id and create the element
gradAttr.id = id = H.uniqueKey();
gradients[key] = gradientObject =
renderer.createElement(gradName)
.attr(gradAttr)
.add(renderer.defs);
gradientObject.radAttr = radAttr;
// The gradient needs to keep a list of stops to be able to
// destroy them
gradientObject.stops = [];
stops.forEach(function (stop) {
var stopObject;
if (stop[1].indexOf('rgba') === 0) {
colorObject = H.color(stop[1]);
stopColor = colorObject.get('rgb');
stopOpacity = colorObject.get('a');
} else {
stopColor = stop[1];
stopOpacity = 1;
}
stopObject = renderer.createElement('stop').attr({
offset: stop[0],
'stop-color': stopColor,
'stop-opacity': stopOpacity
}).add(gradientObject);
// Add the stop element to the gradient
gradientObject.stops.push(stopObject);
});
}
// Set the reference to the gradient object
value = 'url(' + renderer.url + '#' + id + ')';
elem.setAttribute(prop, value);
elem.gradient = key;
// Allow the color to be concatenated into tooltips formatters
// etc. (#2995)
color.toString = function () {
return value;
};
}
});
},
/**
* Apply a text outline through a custom CSS property, by copying the text
* element and apply stroke to the copy. Used internally. Contrast checks at
* [example](https://jsfiddle.net/highcharts/43soe9m1/2/).
*
* @example
* // Specific color
* text.css({
* textOutline: '1px black'
* });
* // Automatic contrast
* text.css({
* color: '#000000', // black text
* textOutline: '1px contrast' // => white outline
* });
*
* @private
* @function Highcharts.SVGElement#applyTextOutline
*
* @param {string} textOutline
* A custom CSS `text-outline` setting, defined by `width color`.
*/
applyTextOutline: function (textOutline) {
var elem = this.element,
tspans,
tspan,
hasContrast = textOutline.indexOf('contrast') !== -1,
styles = {},
color,
strokeWidth,
firstRealChild,
i;
// When the text shadow is set to contrast, use dark stroke for light
// text and vice versa.
if (hasContrast) {
styles.textOutline = textOutline = textOutline.replace(
/contrast/g,
this.renderer.getContrast(elem.style.fill)
);
}
// Extract the stroke width and color
textOutline = textOutline.split(' ');
color = textOutline[textOutline.length - 1];
strokeWidth = textOutline[0];
if (strokeWidth && strokeWidth !== 'none' && H.svg) {
this.fakeTS = true; // Fake text shadow
tspans = [].slice.call(elem.getElementsByTagName('tspan'));
// In order to get the right y position of the clone,
// copy over the y setter
this.ySetter = this.xSetter;
// Since the stroke is applied on center of the actual outline, we
// need to double it to get the correct stroke-width outside the
// glyphs.
strokeWidth = strokeWidth.replace(
/(^[\d\.]+)(.*?)$/g,
function (match, digit, unit) {
return (2 * digit) + unit;
}
);
// Remove shadows from previous runs. Iterate from the end to
// support removing items inside the cycle (#6472).
i = tspans.length;
while (i--) {
tspan = tspans[i];
if (tspan.getAttribute('class') === 'highcharts-text-outline') {
// Remove then erase
erase(tspans, elem.removeChild(tspan));
}
}
// For each of the tspans, create a stroked copy behind it.
firstRealChild = elem.firstChild;
tspans.forEach(function (tspan, y) {
var clone;
// Let the first line start at the correct X position
if (y === 0) {
tspan.setAttribute('x', elem.getAttribute('x'));
y = elem.getAttribute('y');
tspan.setAttribute('y', y || 0);
if (y === null) {
elem.setAttribute('y', 0);
}
}
// Create the clone and apply outline properties
clone = tspan.cloneNode(1);
attr(clone, {
'class': 'highcharts-text-outline',
'fill': color,
'stroke': color,
'stroke-width': strokeWidth,
'stroke-linejoin': 'round'
});
elem.insertBefore(clone, firstRealChild);
});
}
},
// Custom attributes used for symbols, these should be filtered out when
// setting SVGElement attributes (#9375).
symbolCustomAttribs: [
'x',
'y',
'width',
'height',
'r',
'start',
'end',
'innerR',
'anchorX',
'anchorY',
'rounded'
],
/**
* Apply native and custom attributes to the SVG elements.
*
* In order to set the rotation center for rotation, set x and y to 0 and
* use `translateX` and `translateY` attributes to position the element
* instead.
*
* Attributes frequently used in Highcharts are `fill`, `stroke`,
* `stroke-width`.
*
* @sample highcharts/members/renderer-rect/
* Setting some attributes
*
* @example
* // Set multiple attributes
* element.attr({
* stroke: 'red',
* fill: 'blue',
* x: 10,
* y: 10
* });
*
* // Set a single attribute
* element.attr('stroke', 'red');
*
* // Get an attribute
* element.attr('stroke'); // => 'red'
*
* @function Highcharts.SVGElement#attr
*
* @param {string|Highcharts.SVGAttributes} [hash]
* The native and custom SVG attributes.
*
* @param {string} [val]
* If the type of the first argument is `string`, the second can be a
* value, which will serve as a single attribute setter. If the first
* argument is a string and the second is undefined, the function
* serves as a getter and the current value of the property is
* returned.
*
* @param {Function} [complete]
* A callback function to execute after setting the attributes. This
* makes the function compliant and interchangeable with the
* {@link SVGElement#animate} function.
*
* @param {boolean} [continueAnimation=true]
* Used internally when `.attr` is called as part of an animation
* step. Otherwise, calling `.attr` for an attribute will stop
* animation for that attribute.
*
* @return {number|string|Highcharts.SVGElement}
* If used as a setter, it returns the current
* {@link Highcharts.SVGElement} so the calls can be chained. If
* used as a getter, the current value of the attribute is returned.
*/
attr: function (hash, val, complete, continueAnimation) {
var key,
element = this.element,
hasSetSymbolSize,
ret = this,
skipAttr,
setter,
symbolCustomAttribs = this.symbolCustomAttribs;
// single key-value pair
if (typeof hash === 'string' && val !== undefined) {
key = hash;
hash = {};
hash[key] = val;
}
// used as a getter: first argument is a string, second is undefined
if (typeof hash === 'string') {
ret = (this[hash + 'Getter'] || this._defaultGetter).call(
this,
hash,
element
);
// setter
} else {
objectEach(hash, function eachAttribute(val, key) {
skipAttr = false;
// Unless .attr is from the animator update, stop current
// running animation of this property
if (!continueAnimation) {
stop(this, key);
}
// Special handling of symbol attributes
if (
this.symbolName &&
H.inArray(key, symbolCustomAttribs) !== -1
) {
if (!hasSetSymbolSize) {
this.symbolAttr(hash);
hasSetSymbolSize = true;
}
skipAttr = true;
}
if (this.rotation && (key === 'x' || key === 'y')) {
this.doTransform = true;
}
if (!skipAttr) {
setter = this[key + 'Setter'] || this._defaultSetter;
setter.call(this, val, key, element);
// Let the shadow follow the main element
if (
!this.styledMode &&
this.shadows &&
/^(width|height|visibility|x|y|d|transform|cx|cy|r)$/
.test(key)
) {
this.updateShadows(key, val, setter);
}
}
}, this);
this.afterSetters();
}
// In accordance with animate, run a complete callback
if (complete) {
complete.call(this);
}
return ret;
},
/**
* This method is executed in the end of `attr()`, after setting all
* attributes in the hash. In can be used to efficiently consolidate
* multiple attributes in one SVG property -- e.g., translate, rotate and
* scale are merged in one "transform" attribute in the SVG node.
*
* @private
* @function Highcharts.SVGElement#afterSetters
*/
afterSetters: function () {
// Update transform. Do this outside the loop to prevent redundant
// updating for batch setting of attributes.
if (this.doTransform) {
this.updateTransform();
this.doTransform = false;
}
},
/**
* Update the shadow elements with new attributes.
*
* @private
* @function Highcharts.SVGElement#updateShadows
*
* @param {string} key
* The attribute name.
*
* @param {string|number} value
* The value of the attribute.
*
* @param {Function} setter
* The setter function, inherited from the parent wrapper.
*/
updateShadows: function (key, value, setter) {
var shadows = this.shadows,
i = shadows.length;
while (i--) {
setter.call(
shadows[i],
key === 'height' ?
Math.max(value - (shadows[i].cutHeight || 0), 0) :
key === 'd' ? this.d : value,
key,
shadows[i]
);
}
},
/**
* Add a class name to an element.
*
* @function Highcharts.SVGElement#addClass
*
* @param {string} className
* The new class name to add.
*
* @param {boolean} [replace=false]
* When true, the existing class name(s) will be overwritten with
* the new one. When false, the new one is added.
*
* @return {Highcharts.SVGElement}
* Return the SVG element for chainability.
*/
addClass: function (className, replace) {
var currentClassName = this.attr('class') || '';
if (currentClassName.indexOf(className) === -1) {
if (!replace) {
className =
(currentClassName + (currentClassName ? ' ' : '') +
className).replace(' ', ' ');
}
this.attr('class', className);
}
return this;
},
/**
* Check if an element has the given class name.
*
* @function Highcharts.SVGElement#hasClass
*
* @param {string} className
* The class name to check for.
*
* @return {boolean}
* Whether the class name is found.
*/
hasClass: function (className) {
return (this.attr('class') || '').split(' ').indexOf(className) !== -1;
},
/**
* Remove a class name from the element.
*
* @function Highcharts.SVGElement#removeClass
*
* @param {string|RegExp} className
* The class name to remove.
*
* @return {Highcharts.SVGElement} Returns the SVG element for chainability.
*/
removeClass: function (className) {
return this.attr(
'class',
(this.attr('class') || '').replace(className, '')
);
},
/**
* If one of the symbol size affecting parameters are changed,
* check all the others only once for each call to an element's
* .attr() method
*
* @private
* @function Highcharts.SVGElement#symbolAttr
*
* @param {Highcharts.Dictionary<number|string>} hash
* The attributes to set.
*/
symbolAttr: function (hash) {
var wrapper = this;
[
'x',
'y',
'r',
'start',
'end',
'width',
'height',
'innerR',
'anchorX',
'anchorY'
].forEach(function (key) {
wrapper[key] = pick(hash[key], wrapper[key]);
});
wrapper.attr({
d: wrapper.renderer.symbols[wrapper.symbolName](
wrapper.x,
wrapper.y,
wrapper.width,
wrapper.height,
wrapper
)
});
},
/**
* Apply a clipping rectangle to this element.
*
* @function Highcharts.SVGElement#clip
*
* @param {Highcharts.ClipRectElement} [clipRect]
* The clipping rectangle. If skipped, the current clip is removed.
*
* @return {Highcharts.SVGElement}
* Returns the SVG element to allow chaining.
*/
clip: function (clipRect) {
return this.attr(
'clip-path',
clipRect ?
'url(' + this.renderer.url + '#' + clipRect.id + ')' :
'none'
);
},
/**
* Calculate the coordinates needed for drawing a rectangle crisply and
* return the calculated attributes.
*
* @function Highcharts.SVGElement#crisp
*
* @param {Highcharts.RectangleObject} rect
* Rectangle to crisp.
*
* @param {number} [strokeWidth]
* The stroke width to consider when computing crisp positioning. It
* can also be set directly on the rect parameter.
*
* @return {Highcharts.RectangleObject}
* The modified rectangle arguments.
*/
crisp: function (rect, strokeWidth) {
var wrapper = this,
normalizer;
strokeWidth = strokeWidth || rect.strokeWidth || 0;
// Math.round because strokeWidth can sometimes have roundoff errors
normalizer = Math.round(strokeWidth) % 2 / 2;
// normalize for crisp edges
rect.x = Math.floor(rect.x || wrapper.x || 0) + normalizer;
rect.y = Math.floor(rect.y || wrapper.y || 0) + normalizer;
rect.width = Math.floor(
(rect.width || wrapper.width || 0) - 2 * normalizer
);
rect.height = Math.floor(
(rect.height || wrapper.height || 0) - 2 * normalizer
);
if (defined(rect.strokeWidth)) {
rect.strokeWidth = strokeWidth;
}
return rect;
},
/**
* Set styles for the element. In addition to CSS styles supported by
* native SVG and HTML elements, there are also some custom made for
* Highcharts, like `width`, `ellipsis` and `textOverflow` for SVG text
* elements.
*
* @sample highcharts/members/renderer-text-on-chart/
* Styled text
*
* @function Highcharts.SVGElement#css
*
* @param {Highcharts.CSSObject} styles
* The new CSS styles.
*
* @return {Highcharts.SVGElement}
* Return the SVG element for chaining.
*/
css: function (styles) {
var oldStyles = this.styles,
newStyles = {},
elem = this.element,
textWidth,
serializedCss = '',
hyphenate,
hasNew = !oldStyles,
// These CSS properties are interpreted internally by the SVG
// renderer, but are not supported by SVG and should not be added to
// the DOM. In styled mode, no CSS should find its way to the DOM
// whatsoever (#6173, #6474).
svgPseudoProps = ['textOutline', 'textOverflow', 'width'];
// convert legacy
if (styles && styles.color) {
styles.fill = styles.color;
}
// Filter out existing styles to increase performance (#2640)
if (oldStyles) {
objectEach(styles, function (style, n) {
if (style !== oldStyles[n]) {
newStyles[n] = style;
hasNew = true;
}
});
}
if (hasNew) {
// Merge the new styles with the old ones
if (oldStyles) {
styles = extend(
oldStyles,
newStyles
);
}
// Get the text width from style
if (styles) {
// Previously set, unset it (#8234)
if (styles.width === null || styles.width === 'auto') {
delete this.textWidth;
// Apply new
} else if (
elem.nodeName.toLowerCase() === 'text' &&
styles.width
) {
textWidth = this.textWidth = pInt(styles.width);
}
}
// store object
this.styles = styles;
if (textWidth && (!svg && this.renderer.forExport)) {
delete styles.width;
}
// Serialize and set style attribute
if (elem.namespaceURI === this.SVG_NS) { // #7633
hyphenate = function (a, b) {
return '-' + b.toLowerCase();
};
objectEach(styles, function (style, n) {
if (svgPseudoProps.indexOf(n) === -1) {
serializedCss +=
n.replace(/([A-Z])/g, hyphenate) + ':' +
style + ';';
}
});
if (serializedCss) {
attr(elem, 'style', serializedCss); // #1881
}
} else {
css(elem, styles);
}
if (this.added) {
// Rebuild text after added. Cache mechanisms in the buildText
// will prevent building if there are no significant changes.
if (this.element.nodeName === 'text') {
this.renderer.buildText(this);
}
// Apply text outline after added
if (styles && styles.textOutline) {
this.applyTextOutline(styles.textOutline);
}
}
}
return this;
},
/**
* Get the computed style. Only in styled mode.
*
* @example
* chart.series[0].points[0].graphic.getStyle('stroke-width'); // => '1px'
*
* @function Highcharts.SVGElement#getStyle
*
* @param {string} prop
* The property name to check for.
*
* @return {string}
* The current computed value.
*/
getStyle: function (prop) {
return win.getComputedStyle(this.element || this, '')
.getPropertyValue(prop);
},
/**
* Get the computed stroke width in pixel values. This is used extensively
* when drawing shapes to ensure the shapes are rendered crisp and
* positioned correctly relative to each other. Using
* `shape-rendering: crispEdges` leaves us less control over positioning,
* for example when we want to stack columns next to each other, or position
* things pixel-perfectly within the plot box.
*
* The common pattern when placing a shape is:
* - Create the SVGElement and add it to the DOM. In styled mode, it will
* now receive a stroke width from the style sheet. In classic mode we
* will add the `stroke-width` attribute.
* - Read the computed `elem.strokeWidth()`.
* - Place it based on the stroke width.
*
* @function Highcharts.SVGElement#strokeWidth
*
* @return {number}
* The stroke width in pixels. Even if the given stroke widtch (in
* CSS or by attributes) is based on `em` or other units, the pixel
* size is returned.
*/
strokeWidth: function () {
// In non-styled mode, read the stroke width as set by .attr
if (!this.renderer.styledMode) {
return this['stroke-width'] || 0;
}
// In styled mode, read computed stroke width
var val = this.getStyle('stroke-width'),
ret,
dummy;
// Read pixel values directly
if (val.indexOf('px') === val.length - 2) {
ret = pInt(val);
// Other values like em, pt etc need to be measured
} else {
dummy = doc.createElementNS(SVG_NS, 'rect');
attr(dummy, {
'width': val,
'stroke-width': 0
});
this.element.parentNode.appendChild(dummy);
ret = dummy.getBBox().width;
dummy.parentNode.removeChild(dummy);
}
return ret;
},
/**
* Add an event listener. This is a simple setter that replaces all other
* events of the same type, opposed to the {@link Highcharts#addEvent}
* function.
*
* @sample highcharts/members/element-on/
* A clickable rectangle
*
* @function Highcharts.SVGElement#on
*
* @param {string} eventType
* The event type. If the type is `click`, Highcharts will internally
* translate it to a `touchstart` event on touch devices, to prevent
* the browser from waiting for a click event from firing.
*
* @param {Function} handler
* The handler callback.
*
* @return {Highcharts.SVGElement}
* The SVGElement for chaining.
*/
on: function (eventType, handler) {
var svgElement = this,
element = svgElement.element;
// touch
if (hasTouch && eventType === 'click') {
element.ontouchstart = function (e) {
svgElement.touchEventFired = Date.now(); // #2269
e.preventDefault();
handler.call(element, e);
};
element.onclick = function (e) {
if (win.navigator.userAgent.indexOf('Android') === -1 ||
Date.now() - (svgElement.touchEventFired || 0) > 1100) {
handler.call(element, e);
}
};
} else {
// simplest possible event model for internal use
element['on' + eventType] = handler;
}
return this;
},
/**
* Set the coordinates needed to draw a consistent radial gradient across
* a shape regardless of positioning inside the chart. Used on pie slices
* to make all the slices have the same radial reference point.
*
* @function Highcharts.SVGElement#setRadialReference
*
* @param {Array<number>} coordinates
* The center reference. The format is `[centerX, centerY, diameter]`
* in pixels.
*
* @return {Highcharts.SVGElement}
* Returns the SVGElement for chaining.
*/
setRadialReference: function (coordinates) {
var existingGradient = this.renderer.gradients[this.element.gradient];
this.element.radialReference = coordinates;
// On redrawing objects with an existing gradient, the gradient needs
// to be repositioned (#3801)
if (existingGradient && existingGradient.radAttr) {
existingGradient.animate(
this.renderer.getRadialAttr(
coordinates,
existingGradient.radAttr
)
);
}
return this;
},
/**
* Move an object and its children by x and y values.
*
* @function Highcharts.SVGElement#translate
*
* @param {number} x
* The x value.
*
* @param {number} y
* The y value.
*/
translate: function (x, y) {
return this.attr({
translateX: x,
translateY: y
});
},
/**
* Invert a group, rotate and flip. This is used internally on inverted
* charts, where the points and graphs are drawn as if not inverted, then
* the series group elements are inverted.
*
* @function Highcharts.SVGElement#invert
*
* @param {boolean} inverted
* Whether to invert or not. An inverted shape can be un-inverted by
* setting it to false.
*
* @return {Highcharts.SVGElement}
* Return the SVGElement for chaining.
*/
invert: function (inverted) {
var wrapper = this;
wrapper.inverted = inverted;
wrapper.updateTransform();
return wrapper;
},
/**
* Update the transform attribute based on internal properties. Deals with
* the custom `translateX`, `translateY`, `rotation`, `scaleX` and `scaleY`
* attributes and updates the SVG `transform` attribute.
*
* @private
* @function Highcharts.SVGElement#updateTransform
*/
updateTransform: function () {
var wrapper = this,
translateX = wrapper.translateX || 0,
translateY = wrapper.translateY || 0,
scaleX = wrapper.scaleX,
scaleY = wrapper.scaleY,
inverted = wrapper.inverted,
rotation = wrapper.rotation,
matrix = wrapper.matrix,
element = wrapper.element,
transform;
// Flipping affects translate as adjustment for flipping around the
// group's axis
if (inverted) {
translateX += wrapper.width;
translateY += wrapper.height;
}
// Apply translate. Nearly all transformed elements have translation,
// so instead of checking for translate = 0, do it always (#1767,
// #1846).
transform = ['translate(' + translateX + ',' + translateY + ')'];
// apply matrix
if (defined(matrix)) {
transform.push(
'matrix(' + matrix.join(',') + ')'
);
}
// apply rotation
if (inverted) {
transform.push('rotate(90) scale(-1,1)');
} else if (rotation) { // text rotation
transform.push(
'rotate(' + rotation + ' ' +
pick(this.rotationOriginX, element.getAttribute('x'), 0) +
' ' +
pick(this.rotationOriginY, element.getAttribute('y') || 0) + ')'
);
}
// apply scale
if (defined(scaleX) || defined(scaleY)) {
transform.push(
'scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'
);
}
if (transform.length) {
element.setAttribute('transform', transform.join(' '));
}
},
/**
* Bring the element to the front. Alternatively, a new zIndex can be set.
*
* @sample highcharts/members/element-tofront/
* Click an element to bring it to front
*
* @function Highcharts.SVGElement#toFront
*
* @return {Highcharts.SVGElement}
* Returns the SVGElement for chaining.
*/
toFront: function () {
var element = this.element;
element.parentNode.appendChild(element);
return this;
},
/**
* Align the element relative to the chart or another box.
*
* @function Highcharts.SVGElement#align
*
* @param {Highcharts.AlignObject} [alignOptions]
* The alignment options. The function can be called without this
* parameter in order to re-align an element after the box has been
* updated.
*
* @param {boolean} [alignByTranslate]
* Align element by translation.
*
* @param {string|Highcharts.BBoxObject} [box]
* The box to align to, needs a width and height. When the box is a
* string, it refers to an object in the Renderer. For example, when
* box is `spacingBox`, it refers to `Renderer.spacingBox` which
* holds `width`, `height`, `x` and `y` properties.
*
* @return {Highcharts.SVGElement} Returns the SVGElement for chaining.
*/
align: function (alignOptions, alignByTranslate, box) {
var align,
vAlign,
x,
y,
attribs = {},
alignTo,
renderer = this.renderer,
alignedObjects = renderer.alignedObjects,
alignFactor,
vAlignFactor;
// First call on instanciate
if (alignOptions) {
this.alignOptions = alignOptions;
this.alignByTranslate = alignByTranslate;
if (!box || isString(box)) {
this.alignTo = alignTo = box || 'renderer';
// prevent duplicates, like legendGroup after resize
erase(alignedObjects, this);
alignedObjects.push(this);
box = null; // reassign it below
}
// When called on resize, no arguments are supplied
} else {
alignOptions = this.alignOptions;
alignByTranslate = this.alignByTranslate;
alignTo = this.alignTo;
}
box = pick(box, renderer[alignTo], renderer);
// Assign variables
align = alignOptions.align;
vAlign = alignOptions.verticalAlign;
x = (box.x || 0) + (alignOptions.x || 0); // default: left align
y = (box.y || 0) + (alignOptions.y || 0); // default: top align
// Align
if (align === 'right') {
alignFactor = 1;
} else if (align === 'center') {
alignFactor = 2;
}
if (alignFactor) {
x += (box.width - (alignOptions.width || 0)) / alignFactor;
}
attribs[alignByTranslate ? 'translateX' : 'x'] = Math.round(x);
// Vertical align
if (vAlign === 'bottom') {
vAlignFactor = 1;
} else if (vAlign === 'middle') {
vAlignFactor = 2;
}
if (vAlignFactor) {
y += (box.height - (alignOptions.height || 0)) / vAlignFactor;
}
attribs[alignByTranslate ? 'translateY' : 'y'] = Math.round(y);
// Animate only if already placed
this[this.placed ? 'animate' : 'attr'](attribs);
this.placed = true;
this.alignAttr = attribs;
return this;
},
/**
* Get the bounding box (width, height, x and y) for the element. Generally
* used to get rendered text size. Since this is called a lot in charts,
* the results are cached based on text properties, in order to save DOM
* traffic. The returned bounding box includes the rotation, so for example
* a single text line of rotation 90 will report a greater height, and a
* width corresponding to the line-height.
*
* @sample highcharts/members/renderer-on-chart/
* Draw a rectangle based on a text's bounding box
*
* @function Highcharts.SVGElement#getBBox
*
* @param {boolean} [reload]
* Skip the cache and get the updated DOM bouding box.
*
* @param {number} [rot]
* Override the element's rotation. This is internally used on axis
* labels with a value of 0 to find out what the bounding box would
* be have been if it were not rotated.
*
* @return {Highcharts.BBoxObject}
* The bounding box with `x`, `y`, `width` and `height` properties.
*/
getBBox: function (reload, rot) {
var wrapper = this,
bBox, // = wrapper.bBox,
renderer = wrapper.renderer,
width,
height,
rotation,
rad,
element = wrapper.element,
styles = wrapper.styles,
fontSize,
textStr = wrapper.textStr,
toggleTextShadowShim,
cache = renderer.cache,
cacheKeys = renderer.cacheKeys,
isSVG = element.namespaceURI === wrapper.SVG_NS,
cacheKey;
rotation = pick(rot, wrapper.rotation);
rad = rotation * deg2rad;
fontSize = renderer.styledMode ? (
element &&
SVGElement.prototype.getStyle.call(element, 'font-size')
) : (
styles && styles.fontSize
);
// Avoid undefined and null (#7316)
if (defined(textStr)) {
cacheKey = textStr.toString();
// Since numbers are monospaced, and numerical labels appear a lot
// in a chart, we assume that a label of n characters has the same
// bounding box as others of the same length. Unless there is inner
// HTML in the label. In that case, leave the numbers as is (#5899).
if (cacheKey.indexOf('<') === -1) {
cacheKey = cacheKey.replace(/[0-9]/g, '0');
}
// Properties that affect bounding box
cacheKey += [
'',
rotation || 0,
fontSize,
wrapper.textWidth, // #7874, also useHTML
styles && styles.textOverflow // #5968
]
.join(',');
}
if (cacheKey && !reload) {
bBox = cache[cacheKey];
}
// No cache found
if (!bBox) {
// SVG elements
if (isSVG || renderer.forExport) {
try { // Fails in Firefox if the container has display: none.
// When the text shadow shim is used, we need to hide the
// fake shadows to get the correct bounding box (#3872)
toggleTextShadowShim = this.fakeTS && function (display) {
[].forEach.call(
element.querySelectorAll(
'.highcharts-text-outline'
),
function (tspan) {
tspan.style.display = display;
}
);
};
// Workaround for #3842, Firefox reporting wrong bounding
// box for shadows
if (toggleTextShadowShim) {
toggleTextShadowShim('none');
}
bBox = element.getBBox ?
// SVG: use extend because IE9 is not allowed to change
// width and height in case of rotation (below)
extend({}, element.getBBox()) : {
// Legacy IE in export mode
width: element.offsetWidth,
height: element.offsetHeight
};
// #3842
if (toggleTextShadowShim) {
toggleTextShadowShim('');
}
} catch (e) {}
// If the bBox is not set, the try-catch block above failed. The
// other condition is for Opera that returns a width of
// -Infinity on hidden elements.
if (!bBox || bBox.width < 0) {
bBox = { width: 0, height: 0 };
}
// VML Renderer or useHTML within SVG
} else {
bBox = wrapper.htmlGetBBox();
}
// True SVG elements as well as HTML elements in modern browsers
// using the .useHTML option need to compensated for rotation
if (renderer.isSVG) {
width = bBox.width;
height = bBox.height;
// Workaround for wrong bounding box in IE, Edge and Chrome on
// Windows. With Highcharts' default font, IE and Edge report
// a box height of 16.899 and Chrome rounds it to 17. If this
// stands uncorrected, it results in more padding added below
// the text than above when adding a label border or background.
// Also vertical positioning is affected.
// https://jsfiddle.net/highcharts/em37nvuj/
// (#1101, #1505, #1669, #2568, #6213).
if (isSVG) {
bBox.height = height = (
{
'11px,17': 14,
'13px,20': 16
}[
styles && styles.fontSize + ',' + Math.round(height)
] ||
height
);
}
// Adjust for rotated text
if (rotation) {
bBox.width = Math.abs(height * Math.sin(rad)) +
Math.abs(width * Math.cos(rad));
bBox.height = Math.abs(height * Math.cos(rad)) +
Math.abs(width * Math.sin(rad));
}
}
// Cache it. When loading a chart in a hidden iframe in Firefox and
// IE/Edge, the bounding box height is 0, so don't cache it (#5620).
if (cacheKey && bBox.height > 0) {
// Rotate (#4681)
while (cacheKeys.length > 250) {
delete cache[cacheKeys.shift()];
}
if (!cache[cacheKey]) {
cacheKeys.push(cacheKey);
}
cache[cacheKey] = bBox;
}
}
return bBox;
},
/**
* Show the element after it has been hidden.
*
* @function Highcharts.SVGElement#show
*
* @param {boolean} [inherit=false]
* Set the visibility attribute to `inherit` rather than `visible`.
* The difference is that an element with `visibility="visible"`
* will be visible even if the parent is hidden.
*
* @return {Highcharts.SVGElement}
* Returns the SVGElement for chaining.
*/
show: function (inherit) {
return this.attr({ visibility: inherit ? 'inherit' : 'visible' });
},
/**
* Hide the element, equivalent to setting the `visibility` attribute to
* `hidden`.
*
* @function Highcharts.SVGElement#hide
*
* @return {Highcharts.SVGElement}
* Returns the SVGElement for chaining.
*/
hide: function () {
return this.attr({ visibility: 'hidden' });
},
/**
* Fade out an element by animating its opacity down to 0, and hide it on
* complete. Used internally for the tooltip.
*
* @function Highcharts.SVGElement#fadeOut
*
* @param {number} [duration=150]
* The fade duration in milliseconds.
*/
fadeOut: function (duration) {
var elemWrapper = this;
elemWrapper.animate({
opacity: 0
}, {
duration: duration || 150,
complete: function () {
// #3088, assuming we're only using this for tooltips
elemWrapper.attr({ y: -9999 });
}
});
},
/**
* Add the element to the DOM. All elements must be added this way.
*
* @sample highcharts/members/renderer-g
* Elements added to a group
*
* @function Highcharts.SVGElement#add
*
* @param {Highcharts.SVGElement|Highcharts.SVGDOMElement} [parent]
* The parent item to add it to. If undefined, the element is added
* to the {@link Highcharts.SVGRenderer.box}.
*
* @return {Highcharts.SVGElement}
* Returns the SVGElement for chaining.
*/
add: function (parent) {
var renderer = this.renderer,
element = this.element,
inserted;
if (parent) {
this.parentGroup = parent;
}
// mark as inverted
this.parentInverted = parent && parent.inverted;
// build formatted text
if (this.textStr !== undefined) {
renderer.buildText(this);
}
// Mark as added
this.added = true;
// If we're adding to renderer root, or other elements in the group
// have a z index, we need to handle it
if (!parent || parent.handleZ || this.zIndex) {
inserted = this.zIndexSetter();
}
// If zIndex is not handled, append at the end
if (!inserted) {
(parent ? parent.element : renderer.box).appendChild(element);
}
// fire an event for internal hooks
if (this.onAdd) {
this.onAdd();
}
return this;
},
/**
* Removes an element from the DOM.
*
* @private
* @function Highcharts.SVGElement#safeRemoveChild
*
* @param {Highcharts.SVGDOMElement|Highcharts.HTMLDOMElement} element
* The DOM node to remove.
*/
safeRemoveChild: function (element) {
var parentNode = element.parentNode;
if (parentNode) {
parentNode.removeChild(element);
}
},
/**
* Destroy the element and element wrapper and clear up the DOM and event
* hooks.
*
* @function Highcharts.SVGElement#destroy
*/
destroy: function () {
var wrapper = this,
element = wrapper.element || {},
renderer = wrapper.renderer,
parentToClean =
renderer.isSVG &&
element.nodeName === 'SPAN' &&
wrapper.parentGroup,
grandParent,
ownerSVGElement = element.ownerSVGElement,
i,
clipPath = wrapper.clipPath;
// remove events
element.onclick = element.onmouseout = element.onmouseover =
element.onmousemove = element.point = null;
stop(wrapper); // stop running animations
if (clipPath && ownerSVGElement) {
// Look for existing references to this clipPath and remove them
// before destroying the element (#6196).
// The upper case version is for Edge
[].forEach.call(
ownerSVGElement.querySelectorAll('[clip-path],[CLIP-PATH]'),
function (el) {
var clipPathAttr = el.getAttribute('clip-path'),
clipPathId = clipPath.element.id;
// Include the closing paranthesis in the test to rule out
// id's from 10 and above (#6550). Edge puts quotes inside
// the url, others not.
if (
clipPathAttr.indexOf('(#' + clipPathId + ')') > -1 ||
clipPathAttr.indexOf('("#' + clipPathId + '")') > -1
) {
el.removeAttribute('clip-path');
}
}
);
wrapper.clipPath = clipPath.destroy();
}
// Destroy stops in case this is a gradient object
if (wrapper.stops) {
for (i = 0; i < wrapper.stops.length; i++) {
wrapper.stops[i] = wrapper.stops[i].destroy();
}
wrapper.stops = null;
}
// remove element
wrapper.safeRemoveChild(element);
if (!renderer.styledMode) {
wrapper.destroyShadows();
}
// In case of useHTML, clean up empty containers emulating SVG groups
// (#1960, #2393, #2697).
while (
parentToClean &&
parentToClean.div &&
parentToClean.div.childNodes.length === 0
) {
grandParent = parentToClean.parentGroup;
wrapper.safeRemoveChild(parentToClean.div);
delete parentToClean.div;
parentToClean = grandParent;
}
// remove from alignObjects
if (wrapper.alignTo) {
erase(renderer.alignedObjects, wrapper);
}
objectEach(wrapper, function (val, key) {
delete wrapper[key];
});
return null;
},
/**
* Add a shadow to the element. Must be called after the element is added to
* the DOM. In styled mode, this method is not used, instead use `defs` and
* filters.
*
* @example
* renderer.rect(10, 100, 100, 100)
* .attr({ fill: 'red' })
* .shadow(true);
*
* @function Highcharts.SVGElement#shadow
*
* @param {boolean|Highcharts.ShadowOptionsObject} shadowOptions
* The shadow options. If `true`, the default options are applied. If
* `false`, the current shadow will be removed.
*
* @param {Highcharts.SVGElement} [group]
* The SVG group element where the shadows will be applied. The
* default is to add it to the same parent as the current element.
* Internally, this is ised for pie slices, where all the shadows are
* added to an element behind all the slices.
*
* @param {boolean} [cutOff]
* Used internally for column shadows.
*
* @return {Highcharts.SVGElement}
* Returns the SVGElement for chaining.
*/
shadow: function (shadowOptions, group, cutOff) {
var shadows = [],
i,
shadow,
element = this.element,
strokeWidth,
shadowWidth,
shadowElementOpacity,
// compensate for inverted plot area
transform;
if (!shadowOptions) {
this.destroyShadows();
} else if (!this.shadows) {
shadowWidth = pick(shadowOptions.width, 3);
shadowElementOpacity = (shadowOptions.opacity || 0.15) /
shadowWidth;
transform = this.parentInverted ?
'(-1,-1)' :
'(' + pick(shadowOptions.offsetX, 1) + ', ' +
pick(shadowOptions.offsetY, 1) + ')';
for (i = 1; i <= shadowWidth; i++) {
shadow = element.cloneNode(0);
strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
attr(shadow, {
'stroke':
shadowOptions.color || '#000000',
'stroke-opacity': shadowElementOpacity * i,
'stroke-width': strokeWidth,
'transform': 'translate' + transform,
'fill': 'none'
});
shadow.setAttribute(
'class',
(shadow.getAttribute('class') || '') + ' highcharts-shadow'
);
if (cutOff) {
attr(
shadow,
'height',
Math.max(attr(shadow, 'height') - strokeWidth, 0)
);
shadow.cutHeight = strokeWidth;
}
if (group) {
group.element.appendChild(shadow);
} else if (element.parentNode) {
element.parentNode.insertBefore(shadow, element);
}
shadows.push(shadow);
}
this.shadows = shadows;
}
return this;
},
/**
* Destroy shadows on the element.
*
* @private
* @function Highcharts.SVGElement#destroyShadows
*/
destroyShadows: function () {
(this.shadows || []).forEach(function (shadow) {
this.safeRemoveChild(shadow);
}, this);
this.shadows = undefined;
},
/**
* @private
* @function Highcharts.SVGElement#xGetter
*
* @param {string} key
*
* @return {number|string|null}
*/
xGetter: function (key) {
if (this.element.nodeName === 'circle') {
if (key === 'x') {
key = 'cx';
} else if (key === 'y') {
key = 'cy';
}
}
return this._defaultGetter(key);
},
/**
* Get the current value of an attribute or pseudo attribute,
* used mainly for animation. Called internally from
* the {@link Highcharts.SVGRenderer#attr} function.
*
* @private
* @function Highcharts.SVGElement#_defaultGetter
*
* @param {string} key
* Property key.
*
* @return {number|string|null}
* Property value.
*/
_defaultGetter: function (key) {
var ret = pick(
this[key + 'Value'], // align getter
this[key],
this.element ? this.element.getAttribute(key) : null,
0
);
if (/^[\-0-9\.]+$/.test(ret)) { // is numerical
ret = parseFloat(ret);
}
return ret;
},
/**
* @private
* @function Highcharts.SVGElement#dSettter
*
* @param {number|string|Highcharts.SVGPathArray} value
*
* @param {string} key
*
* @param {Highcharts.SVGDOMElement} element
*/
dSetter: function (value, key, element) {
if (value && value.join) { // join path
value = value.join(' ');
}
if (/(NaN| {2}|^$)/.test(value)) {
value = 'M 0 0';
}
// Check for cache before resetting. Resetting causes disturbance in the
// DOM, causing flickering in some cases in Edge/IE (#6747). Also
// possible performance gain.
if (this[key] !== value) {
element.setAttribute(key, value);
this[key] = value;
}
},
/**
* @private
* @function Highcharts.SVGElement#dashstyleSetter
*
* @param {string} value
*/
dashstyleSetter: function (value) {
var i,
strokeWidth = this['stroke-width'];
// If "inherit", like maps in IE, assume 1 (#4981). With HC5 and the new
// strokeWidth function, we should be able to use that instead.
if (strokeWidth === 'inherit') {
strokeWidth = 1;
}
value = value && value.toLowerCase();
if (value) {
value = value
.replace('shortdashdotdot', '3,1,1,1,1,1,')
.replace('shortdashdot', '3,1,1,1')
.replace('shortdot', '1,1,')
.replace('shortdash', '3,1,')
.replace('longdash', '8,3,')
.replace(/dot/g, '1,3,')
.replace('dash', '4,3,')
.replace(/,$/, '')
.split(','); // ending comma
i = value.length;
while (i--) {
value[i] = pInt(value[i]) * strokeWidth;
}
value = value.join(',')
.replace(/NaN/g, 'none'); // #3226
this.element.setAttribute('stroke-dasharray', value);
}
},
/**
* @private
* @function Highcharts.SVGElement#alignSetter
*
* @param {"start"|"middle"|"end"} value
*/
alignSetter: function (value) {
var convert = { left: 'start', center: 'middle', right: 'end' };
this.alignValue = value;
this.element.setAttribute('text-anchor', convert[value]);
},
/**
* @private
* @function Highcharts.SVGElement#opacitySetter
*
* @param {string} value
*
* @param {string} key
*
* @param {Highcharts.SVGDOMElement} element
*/
opacitySetter: function (value, key, element) {
this[key] = value;
element.setAttribute(key, value);
},
/**
* @private
* @function Highcharts.SVGElement#titleSetter
*
* @param {string} value
*/
titleSetter: function (value) {
var titleNode = this.element.getElementsByTagName('title')[0];
if (!titleNode) {
titleNode = doc.createElementNS(this.SVG_NS, 'title');
this.element.appendChild(titleNode);
}
// Remove text content if it exists
if (titleNode.firstChild) {
titleNode.removeChild(titleNode.firstChild);
}
titleNode.appendChild(
doc.createTextNode(
// #3276, #3895
(String(pick(value), ''))
.replace(/<[^>]*>/g, '')
.replace(/</g, '<')
.replace(/>/g, '>')
)
);
},
/**
* @private
* @function Highcharts.SVGElement#textSetter
*
* @param {string} value
*/
textSetter: function (value) {
if (value !== this.textStr) {
// Delete bBox memo when the text changes
delete this.bBox;
this.textStr = value;
if (this.added) {
this.renderer.buildText(this);
}
}
},
/**
* @private
* @function Highcharts.SVGElement#fillSetter
*
* @param {Highcharts.Color|Highcharts.ColorString} value
*
* @param {string} key
*
* @param {Highcharts.SVGDOMElement} element
*/
fillSetter: function (value, key, element) {
if (typeof value === 'string') {
element.setAttribute(key, value);
} else if (value) {
this.complexColor(value, key, element);
}
},
/**
* @private
* @function Highcharts.SVGElement#visibilitySetter
*
* @param {string} value
*
* @param {string} key
*
* @param {Highcharts.SVGDOMElement} element
*/
visibilitySetter: function (value, key, element) {
// IE9-11 doesn't handle visibilty:inherit well, so we remove the
// attribute instead (#2881, #3909)
if (value === 'inherit') {
element.removeAttribute(key);
} else if (this[key] !== value) { // #6747
element.setAttribute(key, value);
}
this[key] = value;
},
/**
* @private
* @function Highcharts.SVGElement#zIndexSetter
*
* @param {string} value
*
* @param {string} key
*
* @return {boolean}
*/
zIndexSetter: function (value, key) {
var renderer = this.renderer,
parentGroup = this.parentGroup,
parentWrapper = parentGroup || renderer,
parentNode = parentWrapper.element || renderer.box,
childNodes,
otherElement,
otherZIndex,
element = this.element,
inserted,
undefinedOtherZIndex,
svgParent = parentNode === renderer.box,
run = this.added,
i;
if (defined(value)) {
// So we can read it for other elements in the group
element.setAttribute('data-z-index', value);
value = +value;
if (this[key] === value) { // Only update when needed (#3865)
run = false;
}
} else if (defined(this[key])) {
element.removeAttribute('data-z-index');
}
this[key] = value;
// Insert according to this and other elements' zIndex. Before .add() is
// called, nothing is done. Then on add, or by later calls to
// zIndexSetter, the node is placed on the right place in the DOM.
if (run) {
value = this.zIndex;
if (value && parentGroup) {
parentGroup.handleZ = true;
}
childNodes = parentNode.childNodes;
for (i = childNodes.length - 1; i >= 0 && !inserted; i--) {
otherElement = childNodes[i];
otherZIndex = otherElement.getAttribute('data-z-index');
undefinedOtherZIndex = !defined(otherZIndex);
if (otherElement !== element) {
if (
// Negative zIndex versus no zIndex:
// On all levels except the highest. If the parent is
// <svg>, then we don't want to put items before <desc>
// or <defs>
(value < 0 && undefinedOtherZIndex && !svgParent && !i)
) {
parentNode.insertBefore(element, childNodes[i]);
inserted = true;
} else if (
// Insert after the first element with a lower zIndex
pInt(otherZIndex) <= value ||
// If negative zIndex, add this before first undefined
// zIndex element
(
undefinedOtherZIndex &&
(!defined(value) || value >= 0)
)
) {
parentNode.insertBefore(
element,
childNodes[i + 1] || null // null for oldIE export
);
inserted = true;
}
}
}
if (!inserted) {
parentNode.insertBefore(
element,
childNodes[svgParent ? 3 : 0] || null // null for oldIE
);
inserted = true;
}
}
return inserted;
},
/**
* @private
* @function Highcharts.SVGElement#_defaultSetter
*
* @param {string} value
*
* @param {string} key
*
* @param {Highcharts.SVGDOMElement} element
*/
_defaultSetter: function (value, key, element) {
element.setAttribute(key, value);
}
});
// Some shared setters and getters
SVGElement.prototype.yGetter =
SVGElement.prototype.xGetter;
SVGElement.prototype.translateXSetter =
SVGElement.prototype.translateYSetter =
SVGElement.prototype.rotationSetter =
SVGElement.prototype.verticalAlignSetter =
SVGElement.prototype.rotationOriginXSetter =
SVGElement.prototype.rotationOriginYSetter =
SVGElement.prototype.scaleXSetter =
SVGElement.prototype.scaleYSetter =
SVGElement.prototype.matrixSetter = function (value, key) {
this[key] = value;
this.doTransform = true;
};
// WebKit and Batik have problems with a stroke-width of zero, so in this case
// we remove the stroke attribute altogether. #1270, #1369, #3065, #3072.
SVGElement.prototype['stroke-widthSetter'] =
/**
* @private
* @function Highcharts.SVGElement#strokeSetter
*
* @param {number|string} value
*
* @param {string} key
*
* @param {Highcharts.SVGDOMElement} element
*/
SVGElement.prototype.strokeSetter = function (value, key, element) {
this[key] = value;
// Only apply the stroke attribute if the stroke width is defined and larger
// than 0
if (this.stroke && this['stroke-width']) {
// Use prototype as instance may be overridden
SVGElement.prototype.fillSetter.call(
this,
this.stroke,
'stroke',
element
);
element.setAttribute('stroke-width', this['stroke-width']);
this.hasStroke = true;
} else if (key === 'stroke-width' && value === 0 && this.hasStroke) {
element.removeAttribute('stroke');
this.hasStroke = false;
}
};
/**
* Allows direct access to the Highcharts rendering layer in order to draw
* primitive shapes like circles, rectangles, paths or text directly on a chart,
* or independent from any chart. The SVGRenderer represents a wrapper object
* for SVG in modern browsers. Through the VMLRenderer, part of the `oldie.js`
* module, it also brings vector graphics to IE <= 8.
*
* An existing chart's renderer can be accessed through {@link Chart.renderer}.
* The renderer can also be used completely decoupled from a chart.
*
* @sample highcharts/members/renderer-on-chart
* Annotating a chart programmatically.
* @sample highcharts/members/renderer-basic
* Independent SVG drawing.
*
* @example
* // Use directly without a chart object.
* var renderer = new Highcharts.Renderer(parentNode, 600, 400);
*
* @class
* @name Highcharts.SVGRenderer
*
* @param {Highcharts.HTMLDOMElement} container
* Where to put the SVG in the web page.
*
* @param {number} width
* The width of the SVG.
*
* @param {number} height
* The height of the SVG.
*
* @param {boolean} [forExport=false]
* Whether the rendered content is intended for export.
*
* @param {boolean} [allowHTML=true]
* Whether the renderer is allowed to include HTML text, which will be
* projected on top of the SVG.
*/
SVGRenderer = H.SVGRenderer = function () {
this.init.apply(this, arguments);
};
extend(SVGRenderer.prototype, /** @lends Highcharts.SVGRenderer.prototype */ {
/**
* A pointer to the renderer's associated Element class. The VMLRenderer
* will have a pointer to VMLElement here.
*
* @name Highcharts.SVGRenderer#Element
* @type {Highcharts.SVGElement}
*/
Element: SVGElement,
SVG_NS: SVG_NS,
/**
* Initialize the SVGRenderer. Overridable initiator function that takes
* the same parameters as the constructor.
*
* @function Highcharts.SVGRenderer#init
*
* @param {Highcharts.HTMLDOMElement} container
* Where to put the SVG in the web page.
*
* @param {number} width
* The width of the SVG.
*
* @param {number} height
* The height of the SVG.
*
* @param {boolean} [forExport=false]
* Whether the rendered content is intended for export.
*
* @param {boolean} [allowHTML=true]
* Whether the renderer is allowed to include HTML text, which will
* be projected on top of the SVG.
*
* @param {boolean} [styledMode=false]
* Whether the renderer belongs to a chart that is in styled mode.
* If it does, it will avoid setting presentational attributes in
* some cases, but not when set explicitly through `.attr` and `.css`
* etc.
*
* @return {void}
*/
init: function (
container,
width,
height,
style,
forExport,
allowHTML,
styledMode
) {
var renderer = this,
boxWrapper,
element,
desc;
boxWrapper = renderer.createElement('svg')
.attr({
'version': '1.1',
'class': 'highcharts-root'
});
if (!styledMode) {
boxWrapper.css(this.getStyle(style));
}
element = boxWrapper.element;
container.appendChild(element);
// Always use ltr on the container, otherwise text-anchor will be
// flipped and text appear outside labels, buttons, tooltip etc (#3482)
attr(container, 'dir', 'ltr');
// For browsers other than IE, add the namespace attribute (#1978)
if (container.innerHTML.indexOf('xmlns') === -1) {
attr(element, 'xmlns', this.SVG_NS);
}
// object properties
renderer.isSVG = true;
/**
* The root `svg` node of the renderer.
*
* @name Highcharts.SVGRenderer#box
* @type {Highcharts.SVGDOMElement}
*/
this.box = element;
/**
* The wrapper for the root `svg` node of the renderer.
*
* @name Highcharts.SVGRenderer#boxWrapper
* @type {Highcharts.SVGElement}
*/
this.boxWrapper = boxWrapper;
renderer.alignedObjects = [];
/**
* Page url used for internal references.
*
* @private
* @name Highcharts.SVGRenderer#url
* @type {string}
*/
// #24, #672, #1070
this.url = (
(isFirefox || isWebKit) &&
doc.getElementsByTagName('base').length
) ?
win.location.href
.split('#')[0] // remove the hash
.replace(/<[^>]*>/g, '') // wing cut HTML
// escape parantheses and quotes
.replace(/([\('\)])/g, '\\$1')
// replace spaces (needed for Safari only)
.replace(/ /g, '%20') :
'';
// Add description
desc = this.createElement('desc').add();
desc.element.appendChild(
doc.createTextNode('Created with @product.name@ @product.version@')
);
/**
* A pointer to the `defs` node of the root SVG.
*
* @name Highcharts.SVGRenderer#defs
* @type {Highcharts.SVGElement}
*/
renderer.defs = this.createElement('defs').add();
renderer.allowHTML = allowHTML;
renderer.forExport = forExport;
renderer.styledMode = styledMode;
renderer.gradients = {}; // Object where gradient SvgElements are stored
renderer.cache = {}; // Cache for numerical bounding boxes
renderer.cacheKeys = [];
renderer.imgCount = 0;
renderer.setSize(width, height, false);
// Issue 110 workaround:
// In Firefox, if a div is positioned by percentage, its pixel position
// may land between pixels. The container itself doesn't display this,
// but an SVG element inside this container will be drawn at subpixel
// precision. In order to draw sharp lines, this must be compensated
// for. This doesn't seem to work inside iframes though (like in
// jsFiddle).
var subPixelFix, rect;
if (isFirefox && container.getBoundingClientRect) {
subPixelFix = function () {
css(container, { left: 0, top: 0 });
rect = container.getBoundingClientRect();
css(container, {
left: (Math.ceil(rect.left) - rect.left) + 'px',
top: (Math.ceil(rect.top) - rect.top) + 'px'
});
};
// run the fix now
subPixelFix();
// run it on resize
renderer.unSubPixelFix = addEvent(win, 'resize', subPixelFix);
}
},
/**
* General method for adding a definition to the SVG `defs` tag. Can be used
* for gradients, fills, filters etc. Styled mode only. A hook for adding
* general definitions to the SVG's defs tag. Definitions can be referenced
* from the CSS by its `id`. Read more in
* [gradients, shadows and patterns](https://www.highcharts.com/docs/chart-design-and-style/gradients-shadows-and-patterns).
* Styled mode only.
*
* @function Highcharts.SVGRenderer#definition
*
* @param {Highcharts.SVGDefinitionObject} def
* A serialized form of an SVG definition, including children.
*
* @return {Highcharts.SVGElement}
* The inserted node.
*/
definition: function (def) {
var ren = this;
function recurse(config, parent) {
var ret;
splat(config).forEach(function (item) {
var node = ren.createElement(item.tagName),
attr = {};
// Set attributes
objectEach(item, function (val, key) {
if (
key !== 'tagName' &&
key !== 'children' &&
key !== 'textContent'
) {
attr[key] = val;
}
});
node.attr(attr);
// Add to the tree
node.add(parent || ren.defs);
// Add text content
if (item.textContent) {
node.element.appendChild(
doc.createTextNode(item.textContent)
);
}
// Recurse
recurse(item.children || [], node);
ret = node;
});
// Return last node added (on top level it's the only one)
return ret;
}
return recurse(def);
},
/**
* Get the global style setting for the renderer.
*
* @private
* @function Highcharts.SVGRenderer#getStyle
*
* @param {Highcharts.CSSObject} style
* Style settings.
*
* @return {Highcharts.CSSObject}
* The style settings mixed with defaults.
*/
getStyle: function (style) {
this.style = extend({
fontFamily: '"Lucida Grande", "Lucida Sans Unicode", ' +
'Arial, Helvetica, sans-serif',
fontSize: '12px'
}, style);
return this.style;
},
/**
* Apply the global style on the renderer, mixed with the default styles.
*
* @function Highcharts.SVGRenderer#setStyle
*
* @param {Highcharts.CSSObject} style
* CSS to apply.
*/
setStyle: function (style) {
this.boxWrapper.css(this.getStyle(style));
},
/**
* Detect whether the renderer is hidden. This happens when one of the
* parent elements has `display: none`. Used internally to detect when we
* needto render preliminarily in another div to get the text bounding boxes
* right.
*
* @function Highcharts.SVGRenderer#isHidden
*
* @return {boolean}
* True if it is hidden.
*/
isHidden: function () { // #608
return !this.boxWrapper.getBBox().width;
},
/**
* Destroys the renderer and its allocated members.
*
* @function Highcharts.SVGRenderer#destroy
*/
destroy: function () {
var renderer = this,
rendererDefs = renderer.defs;
renderer.box = null;
renderer.boxWrapper = renderer.boxWrapper.destroy();
// Call destroy on all gradient elements
destroyObjectProperties(renderer.gradients || {});
renderer.gradients = null;
// Defs are null in VMLRenderer
// Otherwise, destroy them here.
if (rendererDefs) {
renderer.defs = rendererDefs.destroy();
}
// Remove sub pixel fix handler (#982)
if (renderer.unSubPixelFix) {
renderer.unSubPixelFix();
}
renderer.alignedObjects = null;
return null;
},
/**
* Create a wrapper for an SVG element. Serves as a factory for
* {@link SVGElement}, but this function is itself mostly called from
* primitive factories like {@link SVGRenderer#path}, {@link
* SVGRenderer#rect} or {@link SVGRenderer#text}.
*
* @function Highcharts.SVGRenderer#createElement
*
* @param {string} nodeName
* The node name, for example `rect`, `g` etc.
*
* @return {Highcharts.SVGElement}
* The generated SVGElement.
*/
createElement: function (nodeName) {
var wrapper = new this.Element();
wrapper.init(this, nodeName);
return wrapper;
},
/**
* Dummy function for plugins, called every time the renderer is updated.
* Prior to Highcharts 5, this was used for the canvg renderer.
*
* @deprecated
* @function Highcharts.SVGRenderer#draw
*/
draw: noop,
/**
* Get converted radial gradient attributes according to the radial
* reference. Used internally from the {@link SVGElement#colorGradient}
* function.
*
* @private
* @function Highcharts.SVGRenderer#getRadialAttr
*
* @param {Array<number>} radialReference
*
* @param {Highcharts.SVGAttributes} gradAttr
*
* @return {Highcharts.SVGAttributes}
*/
getRadialAttr: function (radialReference, gradAttr) {
return {
cx: (radialReference[0] - radialReference[2] / 2) +
gradAttr.cx * radialReference[2],
cy: (radialReference[1] - radialReference[2] / 2) +
gradAttr.cy * radialReference[2],
r: gradAttr.r * radialReference[2]
};
},
/**
* Truncate the text node contents to a given length. Used when the css
* width is set. If the `textOverflow` is `ellipsis`, the text is truncated
* character by character to the given length. If not, the text is
* word-wrapped line by line.
*
* @private
* @function Highcharts.SVGRenderer#truncate
*
* @param {Highcharts.SVGElement} wrapper
*
* @param {Highcharts.SVGDOMElement} tspan
*
* @param {string} text
*
* @param {Array.<string>} words
*
* @param {number} width
*
* @param {Function} getString
*
* @return {boolean}
* True if tspan is too long.
*/
truncate: function (
wrapper,
tspan,
text,
words,
startAt,
width,
getString
) {
var renderer = this,
rotation = wrapper.rotation,
str,
// Word wrap can not be truncated to shorter than one word, ellipsis
// text can be completely blank.
minIndex = words ? 1 : 0,
maxIndex = (text || words).length,
currentIndex = maxIndex,
// Cache the lengths to avoid checking the same twice
lengths = [],
updateTSpan = function (s) {
if (tspan.firstChild) {
tspan.removeChild(tspan.firstChild);
}
if (s) {
tspan.appendChild(doc.createTextNode(s));
}
},
getSubStringLength = function (charEnd, concatenatedEnd) {
// charEnd is useed when finding the character-by-character
// break for ellipsis, concatenatedEnd is used for word-by-word
// break for word wrapping.
var end = concatenatedEnd || charEnd;
if (lengths[end] === undefined) {
// Modern browsers
if (tspan.getSubStringLength) {
// Fails with DOM exception on unit-tests/legend/members
// of unknown reason. Desired width is 0, text content
// is "5" and end is 1.
try {
lengths[end] = startAt + tspan.getSubStringLength(
0,
words ? end + 1 : end
);
} catch (e) {}
// Legacy
} else if (renderer.getSpanWidth) { // #9058 jsdom
updateTSpan(getString(text || words, charEnd));
lengths[end] = startAt +
renderer.getSpanWidth(wrapper, tspan);
}
}
return lengths[end];
},
actualWidth,
truncated;
wrapper.rotation = 0; // discard rotation when computing box
actualWidth = getSubStringLength(tspan.textContent.length);
truncated = startAt + actualWidth > width;
if (truncated) {
// Do a binary search for the index where to truncate the text
while (minIndex <= maxIndex) {
currentIndex = Math.ceil((minIndex + maxIndex) / 2);
// When checking words for word-wrap, we need to build the
// string and measure the subStringLength at the concatenated
// word length.
if (words) {
str = getString(words, currentIndex);
}
actualWidth = getSubStringLength(
currentIndex,
str && str.length - 1
);
if (minIndex === maxIndex) {
// Complete
minIndex = maxIndex + 1;
} else if (actualWidth > width) {
// Too large. Set max index to current.
maxIndex = currentIndex - 1;
} else {
// Within width. Set min index to current.
minIndex = currentIndex;
}
}
// If max index was 0 it means the shortest possible text was also
// too large. For ellipsis that means only the ellipsis, while for
// word wrap it means the whole first word.
if (maxIndex === 0) {
// Remove ellipsis
updateTSpan('');
// If the new text length is one less than the original, we don't
// need the ellipsis
} else if (!(text && maxIndex === text.length - 1)) {
updateTSpan(str || getString(text || words, currentIndex));
}
}
// When doing line wrapping, prepare for the next line by removing the
// items from this line.
if (words) {
words.splice(0, currentIndex);
}
wrapper.actualWidth = actualWidth;
wrapper.rotation = rotation; // Apply rotation again.
return truncated;
},
/**
* A collection of characters mapped to HTML entities. When `useHTML` on an
* element is true, these entities will be rendered correctly by HTML. In
* the SVG pseudo-HTML, they need to be unescaped back to simple characters,
* so for example `<` will render as `<`.
*
* @example
* // Add support for unescaping quotes
* Highcharts.SVGRenderer.prototype.escapes['"'] = '"';
*
* @name Highcharts.SVGRenderer#escapes
* @type {Highcharts.Dictionary<string>}
*/
escapes: {
'&': '&',
'<': '<',
'>': '>',
"'": ''', // eslint-disable-line quotes
'"': '"'
},
/**
* Parse a simple HTML string into SVG tspans. Called internally when text
* is set on an SVGElement. The function supports a subset of HTML tags, CSS
* text features like `width`, `text-overflow`, `white-space`, and also
* attributes like `href` and `style`.
*
* @private
* @function Highcharts.SVGRenderer#buildText
*
* @param {Highcharts.SVGElement} wrapper
* The parent SVGElement.
*/
buildText: function (wrapper) {
var textNode = wrapper.element,
renderer = this,
forExport = renderer.forExport,
textStr = pick(wrapper.textStr, '').toString(),
hasMarkup = textStr.indexOf('<') !== -1,
lines,
childNodes = textNode.childNodes,
truncated,
parentX = attr(textNode, 'x'),
textStyles = wrapper.styles,
width = wrapper.textWidth,
textLineHeight = textStyles && textStyles.lineHeight,
textOutline = textStyles && textStyles.textOutline,
ellipsis = textStyles && textStyles.textOverflow === 'ellipsis',
noWrap = textStyles && textStyles.whiteSpace === 'nowrap',
fontSize = textStyles && textStyles.fontSize,
textCache,
isSubsequentLine,
i = childNodes.length,
tempParent = width && !wrapper.added && this.box,
getLineHeight = function (tspan) {
var fontSizeStyle;
if (!renderer.styledMode) {
fontSizeStyle =
/(px|em)$/.test(tspan && tspan.style.fontSize) ?
tspan.style.fontSize :
(fontSize || renderer.style.fontSize || 12);
}
return textLineHeight ?
pInt(textLineHeight) :
renderer.fontMetrics(
fontSizeStyle,
// Get the computed size from parent if not explicit
tspan.getAttribute('style') ? tspan : textNode
).h;
},
unescapeEntities = function (inputStr, except) {
objectEach(renderer.escapes, function (value, key) {
if (!except || except.indexOf(value) === -1) {
inputStr = inputStr.toString().replace(
new RegExp(value, 'g'), // eslint-disable-line security/detect-non-literal-regexp
key
);
}
});
return inputStr;
},
parseAttribute = function (s, attr) {
var start,
delimiter;
start = s.indexOf('<');
s = s.substring(start, s.indexOf('>') - start);
start = s.indexOf(attr + '=');
if (start !== -1) {
start = start + attr.length + 1;
delimiter = s.charAt(start);
if (delimiter === '"' || delimiter === "'") { // eslint-disable-line quotes
s = s.substring(start + 1);
return s.substring(0, s.indexOf(delimiter));
}
}
};
// The buildText code is quite heavy, so if we're not changing something
// that affects the text, skip it (#6113).
textCache = [
textStr,
ellipsis,
noWrap,
textLineHeight,
textOutline,
fontSize,
width
].join(',');
if (textCache === wrapper.textCache) {
return;
}
wrapper.textCache = textCache;
// Remove old text
while (i--) {
textNode.removeChild(childNodes[i]);
}
// Skip tspans, add text directly to text node. The forceTSpan is a hook
// used in text outline hack.
if (
!hasMarkup &&
!textOutline &&
!ellipsis &&
!width &&
textStr.indexOf(' ') === -1
) {
textNode.appendChild(doc.createTextNode(unescapeEntities(textStr)));
// Complex strings, add more logic
} else {
if (tempParent) {
// attach it to the DOM to read offset width
tempParent.appendChild(textNode);
}
if (hasMarkup) {
lines = renderer.styledMode ? (
textStr.replace(
/<(b|strong)>/g,
'<span class="highcharts-strong">'
)
.replace(
/<(i|em)>/g,
'<span class="highcharts-emphasized">'
)
) : (
textStr
.replace(
/<(b|strong)>/g,
'<span style="font-weight:bold">'
)
.replace(
/<(i|em)>/g,
'<span style="font-style:italic">'
)
);
lines = lines
.replace(/<a/g, '<span')
.replace(/<\/(b|strong|i|em|a)>/g, '</span>')
.split(/<br.*?>/g);
} else {
lines = [textStr];
}
// Trim empty lines (#5261)
lines = lines.filter(function (line) {
return line !== '';
});
// build the lines
lines.forEach(function buildTextLines(line, lineNo) {
var spans,
spanNo = 0,
lineLength = 0;
line = line
// Trim to prevent useless/costly process on the spaces
// (#5258)
.replace(/^\s+|\s+$/g, '')
.replace(/<span/g, '|||<span')
.replace(/<\/span>/g, '</span>|||');
spans = line.split('|||');
spans.forEach(function buildTextSpans(span) {
if (span !== '' || spans.length === 1) {
var attributes = {},
tspan = doc.createElementNS(
renderer.SVG_NS,
'tspan'
),
classAttribute,
styleAttribute, // #390
hrefAttribute;
classAttribute = parseAttribute(span, 'class');
if (classAttribute) {
attr(tspan, 'class', classAttribute);
}
styleAttribute = parseAttribute(span, 'style');
if (styleAttribute) {
styleAttribute = styleAttribute.replace(
/(;| |^)color([ :])/,
'$1fill$2'
);
attr(tspan, 'style', styleAttribute);
}
// Not for export - #1529
hrefAttribute = parseAttribute(span, 'href');
if (hrefAttribute && !forExport) {
attr(
tspan,
'onclick',
'location.href=\"' + hrefAttribute + '\"'
);
attr(tspan, 'class', 'highcharts-anchor');
if (!renderer.styledMode) {
css(tspan, { cursor: 'pointer' });
}
}
// Strip away unsupported HTML tags (#7126)
span = unescapeEntities(
span.replace(/<[a-zA-Z\/](.|\n)*?>/g, '') || ' '
);
// Nested tags aren't supported, and cause crash in
// Safari (#1596)
if (span !== ' ') {
// add the text node
tspan.appendChild(doc.createTextNode(span));
// First span in a line, align it to the left
if (!spanNo) {
if (lineNo && parentX !== null) {
attributes.x = parentX;
}
} else {
attributes.dx = 0; // #16
}
// add attributes
attr(tspan, attributes);
// Append it
textNode.appendChild(tspan);
// first span on subsequent line, add the line
// height
if (!spanNo && isSubsequentLine) {
// allow getting the right offset height in
// exporting in IE
if (!svg && forExport) {
css(tspan, { display: 'block' });
}
// Set the line height based on the font size of
// either the text element or the tspan element
attr(
tspan,
'dy',
getLineHeight(tspan)
);
}
// Check width and apply soft breaks or ellipsis
if (width) {
var words = span.replace(
/([^\^])-/g,
'$1- '
).split(' '), // #1273
hasWhiteSpace = !noWrap && (
spans.length > 1 ||
lineNo ||
words.length > 1
),
wrapLineNo = 0,
dy = getLineHeight(tspan);
if (ellipsis) {
truncated = renderer.truncate(
wrapper,
tspan,
span,
undefined,
0,
// Target width
Math.max(
0,
// Substract the font face to make
// room for the ellipsis itself
width - parseInt(fontSize || 12, 10)
),
// Build the text to test for
function (text, currentIndex) {
return text.substring(
0,
currentIndex
) + '\u2026';
}
);
} else if (hasWhiteSpace) {
while (words.length) {
// For subsequent lines, create tspans
// with the same style attributes as the
// parent text node.
if (
words.length &&
!noWrap &&
wrapLineNo > 0
) {
tspan = doc.createElementNS(
SVG_NS,
'tspan'
);
attr(tspan, {
dy: dy,
x: parentX
});
if (styleAttribute) { // #390
attr(
tspan,
'style',
styleAttribute
);
}
// Start by appending the full
// remaining text
tspan.appendChild(
doc.createTextNode(
words.join(' ')
.replace(/- /g, '-')
)
);
textNode.appendChild(tspan);
}
// For each line, truncate the remaining
// words into the line length.
renderer.truncate(
wrapper,
tspan,
null,
words,
wrapLineNo === 0 ? lineLength : 0,
width,
// Build the text to test for
function (text, currentIndex) {
return words
.slice(0, currentIndex)
.join(' ')
.replace(/- /g, '-');
}
);
lineLength = wrapper.actualWidth;
wrapLineNo++;
}
}
}
spanNo++;
}
}
});
// To avoid beginning lines that doesn't add to the textNode
// (#6144)
isSubsequentLine = (
isSubsequentLine ||
textNode.childNodes.length
);
});
if (ellipsis && truncated) {
wrapper.attr(
'title',
unescapeEntities(wrapper.textStr, ['<', '>']) // #7179
);
}
if (tempParent) {
tempParent.removeChild(textNode);
}
// Apply the text outline
if (textOutline && wrapper.applyTextOutline) {
wrapper.applyTextOutline(textOutline);
}
}
},
/**
* Returns white for dark colors and black for bright colors.
*
* @function Highcharts.SVGRenderer#getContrast
*
* @param {Highcharts.ColorString} rgba
* The color to get the contrast for.
*
* @return {string}
* The contrast color, either `#000000` or `#FFFFFF`.
*/
getContrast: function (rgba) {
rgba = color(rgba).rgba;
// The threshold may be discussed. Here's a proposal for adding
// different weight to the color channels (#6216)
rgba[0] *= 1; // red
rgba[1] *= 1.2; // green
rgba[2] *= 0.5; // blue
return rgba[0] + rgba[1] + rgba[2] > 1.8 * 255 ? '#000000' : '#FFFFFF';
},
/**
* Create a button with preset states.
*
* @function Highcharts.SVGRenderer#button
*
* @param {string} text
* The text or HTML to draw.
*
* @param {number} x
* The x position of the button's left side.
*
* @param {number} y
* The y position of the button's top side.
*
* @param {Function} callback
* The function to execute on button click or touch.
*
* @param {Highcharts.SVGAttributes} [normalState]
* SVG attributes for the normal state.
*
* @param {Highcharts.SVGAttributes} [hoverState]
* SVG attributes for the hover state.
*
* @param {Highcharts.SVGAttributes} [pressedState]
* SVG attributes for the pressed state.
*
* @param {Highcharts.SVGAttributes} [disabledState]
* SVG attributes for the disabled state.
*
* @param {Highcharts.SymbolKey} [shape=rect]
* The shape type.
*
* @return {Highcharts.SVGElement}
* The button element.
*/
button: function (
text,
x,
y,
callback,
normalState,
hoverState,
pressedState,
disabledState,
shape
) {
var label = this.label(
text,
x,
y,
shape,
null,
null,
null,
null,
'button'
),
curState = 0,
styledMode = this.styledMode;
// Default, non-stylable attributes
label.attr(merge({
'padding': 8,
'r': 2
}, normalState));
if (!styledMode) {
// Presentational
var normalStyle,
hoverStyle,
pressedStyle,
disabledStyle;
// Normal state - prepare the attributes
normalState = merge({
fill: '#f7f7f7',
stroke: '#cccccc',
'stroke-width': 1,
style: {
color: '#333333',
cursor: 'pointer',
fontWeight: 'normal'
}
}, normalState);
normalStyle = normalState.style;
delete normalState.style;
// Hover state
hoverState = merge(normalState, {
fill: '#e6e6e6'
}, hoverState);
hoverStyle = hoverState.style;
delete hoverState.style;
// Pressed state
pressedState = merge(normalState, {
fill: '#e6ebf5',
style: {
color: '#000000',
fontWeight: 'bold'
}
}, pressedState);
pressedStyle = pressedState.style;
delete pressedState.style;
// Disabled state
disabledState = merge(normalState, {
style: {
color: '#cccccc'
}
}, disabledState);
disabledStyle = disabledState.style;
delete disabledState.style;
}
// Add the events. IE9 and IE10 need mouseover and mouseout to funciton
// (#667).
addEvent(label.element, isMS ? 'mouseover' : 'mouseenter', function () {
if (curState !== 3) {
label.setState(1);
}
});
addEvent(label.element, isMS ? 'mouseout' : 'mouseleave', function () {
if (curState !== 3) {
label.setState(curState);
}
});
label.setState = function (state) {
// Hover state is temporary, don't record it
if (state !== 1) {
label.state = curState = state;
}
// Update visuals
label.removeClass(
/highcharts-button-(normal|hover|pressed|disabled)/
)
.addClass(
'highcharts-button-' +
['normal', 'hover', 'pressed', 'disabled'][state || 0]
);
if (!styledMode) {
label.attr([
normalState,
hoverState,
pressedState,
disabledState
][state || 0])
.css([
normalStyle,
hoverStyle,
pressedStyle,
disabledStyle
][state || 0]);
}
};
// Presentational attributes
if (!styledMode) {
label
.attr(normalState)
.css(extend({ cursor: 'default' }, normalStyle));
}
return label
.on('click', function (e) {
if (curState !== 3) {
callback.call(label, e);
}
});
},
/**
* Make a straight line crisper by not spilling out to neighbour pixels.
*
* @function Highcharts.SVGRenderer#crispLine
*
* @param {Highcharts.SVGPathArray} points
* The original points on the format `['M', 0, 0, 'L', 100, 0]`.
*
* @param {number} width
* The width of the line.
*
* @return {Highcharts.SVGPathArray}
* The original points array, but modified to render crisply.
*/
crispLine: function (points, width) {
// normalize to a crisp line
if (points[1] === points[4]) {
// Substract due to #1129. Now bottom and left axis gridlines behave
// the same.
points[1] = points[4] = Math.round(points[1]) - (width % 2 / 2);
}
if (points[2] === points[5]) {
points[2] = points[5] = Math.round(points[2]) + (width % 2 / 2);
}
return points;
},
/**
* Draw a path, wraps the SVG `path` element.
*
* @sample highcharts/members/renderer-path-on-chart/
* Draw a path in a chart
* @sample highcharts/members/renderer-path/
* Draw a path independent from a chart
*
* @example
* var path = renderer.path(['M', 10, 10, 'L', 30, 30, 'z'])
* .attr({ stroke: '#ff00ff' })
* .add();
*
* @function Highcharts.SVGRenderer#path
*
* @param {Highcharts.SVGPathArray} [path]
* An SVG path definition in array form.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*
*//**
* Draw a path, wraps the SVG `path` element.
*
* @function Highcharts.SVGRenderer#path
*
* @param {Highcharts.SVGAttributes} [attribs]
* The initial attributes.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*/
path: function (path) {
var attribs = this.styledMode ? {} : {
fill: 'none'
};
if (isArray(path)) {
attribs.d = path;
} else if (isObject(path)) { // attributes
extend(attribs, path);
}
return this.createElement('path').attr(attribs);
},
/**
* Draw a circle, wraps the SVG `circle` element.
*
* @sample highcharts/members/renderer-circle/
* Drawing a circle
*
* @function Highcharts.SVGRenderer#circle
*
* @param {number} [x]
* The center x position.
*
* @param {number} [y]
* The center y position.
*
* @param {number} [r]
* The radius.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*//**
* Draw a circle, wraps the SVG `circle` element.
*
* @function Highcharts.SVGRenderer#circle
*
* @param {Highcharts.SVGAttributes} [attribs]
* The initial attributes.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*/
circle: function (x, y, r) {
var attribs = (
isObject(x) ?
x :
x === undefined ? {} : { x: x, y: y, r: r }
),
wrapper = this.createElement('circle');
// Setting x or y translates to cx and cy
wrapper.xSetter = wrapper.ySetter = function (value, key, element) {
element.setAttribute('c' + key, value);
};
return wrapper.attr(attribs);
},
/**
* Draw and return an arc.
*
* @sample highcharts/members/renderer-arc/
* Drawing an arc
*
* @function Highcharts.SVGRenderer#arc
*
* @param {number} [x=0]
* Center X position.
*
* @param {number} [y=0]
* Center Y position.
*
* @param {number} [r=0]
* The outer radius of the arc.
*
* @param {number} [innerR=0]
* Inner radius like used in donut charts.
*
* @param {number} [start=0]
* The starting angle of the arc in radians, where 0 is to the right
* and `-Math.PI/2` is up.
*
* @param {number} [end=0]
* The ending angle of the arc in radians, where 0 is to the right
* and `-Math.PI/2` is up.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*//**
* Draw and return an arc. Overloaded function that takes arguments object.
*
* @function Highcharts.SVGRenderer#arc
*
* @param {Highcharts.SVGAttributes} attribs
* Initial SVG attributes.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*/
arc: function (x, y, r, innerR, start, end) {
var arc,
options;
if (isObject(x)) {
options = x;
y = options.y;
r = options.r;
innerR = options.innerR;
start = options.start;
end = options.end;
x = options.x;
} else {
options = {
innerR: innerR,
start: start,
end: end
};
}
// Arcs are defined as symbols for the ability to set
// attributes in attr and animate
arc = this.symbol('arc', x, y, r, r, options);
arc.r = r; // #959
return arc;
},
/**
* Draw and return a rectangle.
*
* @function Highcharts.SVGRenderer#rect
*
* @param {number} [x]
* Left position.
*
* @param {number} [y]
* Top position.
*
* @param {number} [width]
* Width of the rectangle.
*
* @param {number} [height]
* Height of the rectangle.
*
* @param {number} [r]
* Border corner radius.
*
* @param {number} [strokeWidth]
* A stroke width can be supplied to allow crisp drawing.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*//**
* Draw and return a rectangle.
*
* @sample highcharts/members/renderer-rect-on-chart/
* Draw a rectangle in a chart
* @sample highcharts/members/renderer-rect/
* Draw a rectangle independent from a chart
*
* @function Highcharts.SVGRenderer#rect
*
* @param {Highcharts.SVGAttributes} [attributes]
* General SVG attributes for the rectangle.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*/
rect: function (x, y, width, height, r, strokeWidth) {
r = isObject(x) ? x.r : r;
var wrapper = this.createElement('rect'),
attribs = isObject(x) ? x : x === undefined ? {} : {
x: x,
y: y,
width: Math.max(width, 0),
height: Math.max(height, 0)
};
if (!this.styledMode) {
if (strokeWidth !== undefined) {
attribs.strokeWidth = strokeWidth;
attribs = wrapper.crisp(attribs);
}
attribs.fill = 'none';
}
if (r) {
attribs.r = r;
}
wrapper.rSetter = function (value, key, element) {
attr(element, {
rx: value,
ry: value
});
};
return wrapper.attr(attribs);
},
/**
* Resize the {@link SVGRenderer#box} and re-align all aligned child
* elements.
*
* @sample highcharts/members/renderer-g/
* Show and hide grouped objects
*
* @function Highcharts.SVGRenderer#setSize
*
* @param {number} width
* The new pixel width.
*
* @param {number} height
* The new pixel height.
*
* @param {boolean|Highcharts.AnimationOptionsObject} [animate=true]
* Whether and how to animate.
*/
setSize: function (width, height, animate) {
var renderer = this,
alignedObjects = renderer.alignedObjects,
i = alignedObjects.length;
renderer.width = width;
renderer.height = height;
renderer.boxWrapper.animate({
width: width,
height: height
}, {
step: function () {
this.attr({
viewBox: '0 0 ' + this.attr('width') + ' ' +
this.attr('height')
});
},
duration: pick(animate, true) ? undefined : 0
});
while (i--) {
alignedObjects[i].align();
}
},
/**
* Create and return an svg group element. Child
* {@link Highcharts.SVGElement} objects are added to the group by using the
* group as the first parameter in {@link Highcharts.SVGElement#add|add()}.
*
* @function Highcharts.SVGRenderer#g
*
* @param {string} [name]
* The group will be given a class name of `highcharts-{name}`. This
* can be used for styling and scripting.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*/
g: function (name) {
var elem = this.createElement('g');
return name ? elem.attr({ 'class': 'highcharts-' + name }) : elem;
},
/**
* Display an image.
*
* @sample highcharts/members/renderer-image-on-chart/
* Add an image in a chart
* @sample highcharts/members/renderer-image/
* Add an image independent of a chart
*
* @function Highcharts.SVGRenderer#image
*
* @param {string} src
* The image source.
*
* @param {number} [x]
* The X position.
*
* @param {number} [y]
* The Y position.
*
* @param {number} [width]
* The image width. If omitted, it defaults to the image file width.
*
* @param {number} [height]
* The image height. If omitted it defaults to the image file
* height.
*
* @param {Function} [onload]
* Event handler for image load.
*
* @return {Highcharts.SVGElement}
* The generated wrapper element.
*/
image: function (src, x, y, width, height, onload) {
var attribs = {
preserveAspectRatio: 'none'
},
elemWrapper,
dummy,
setSVGImageSource = function (el, src) {
// Set the href in the xlink namespace
if (el.setAttributeNS) {
el.setAttributeNS(
'http://www.w3.org/1999/xlink', 'href', src
);
} else {
// could be exporting in IE
// using href throws "not supported" in ie7 and under,
// requries regex shim to fix later
el.setAttribute('hc-svg-href', src);
}
},
onDummyLoad = function (e) {
setSVGImageSource(elemWrapper.element, src);
onload.call(elemWrapper, e);
};
// optional properties
if (arguments.length > 1) {
extend(attribs, {
x: x,
y: y,
width: width,
height: height
});
}
elemWrapper = this.createElement('image').attr(attribs);
// Add load event if supplied
if (onload) {
// We have to use a dummy HTML image since IE support for SVG image
// load events is very buggy. First set a transparent src, wait for
// dummy to load, and then add the real src to the SVG image.
setSVGImageSource(
elemWrapper.element,
'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' /* eslint-disable-line */
);
dummy = new win.Image();
addEvent(dummy, 'load', onDummyLoad);
dummy.src = src;
if (dummy.complete) {
onDummyLoad({});
}
} else {
setSVGImageSource(elemWrapper.element, src);
}
return elemWrapper;
},
/**
* Draw a symbol out of pre-defined shape paths from
* {@link SVGRenderer#symbols}.
* It is used in Highcharts for point makers, which cake a `symbol` option,
* and label and button backgrounds like in the tooltip and stock flags.
*
* @function Highcharts.SVGRenderer#symbol
*
* @param {symbol} symbol
* The symbol name.
*
* @param {number} x
* The X coordinate for the top left position.
*
* @param {number} y
* The Y coordinate for the top left position.
*
* @param {number} width
* The pixel width.
*
* @param {number} height
* The pixel height.
*
* @param {Highcharts.SymbolOptionsObject} [options]
* Additional options, depending on the actual symbol drawn.
*
* @return {Highcharts.SVGElement}
*/
symbol: function (symbol, x, y, width, height, options) {
var ren = this,
obj,
imageRegex = /^url\((.*?)\)$/,
isImage = imageRegex.test(symbol),
sym = !isImage && (this.symbols[symbol] ? symbol : 'circle'),
// get the symbol definition function
symbolFn = sym && this.symbols[sym],
// check if there's a path defined for this symbol
path = defined(x) && symbolFn && symbolFn.call(
this.symbols,
Math.round(x),
Math.round(y),
width,
height,
options
),
imageSrc,
centerImage;
if (symbolFn) {
obj = this.path(path);
if (!ren.styledMode) {
obj.attr('fill', 'none');
}
// expando properties for use in animate and attr
extend(obj, {
symbolName: sym,
x: x,
y: y,
width: width,
height: height
});
if (options) {
extend(obj, options);
}
// Image symbols
} else if (isImage) {
imageSrc = symbol.match(imageRegex)[1];
// Create the image synchronously, add attribs async
obj = this.image(imageSrc);
// The image width is not always the same as the symbol width. The
// image may be centered within the symbol, as is the case when
// image shapes are used as label backgrounds, for example in flags.
obj.imgwidth = pick(
symbolSizes[imageSrc] && symbolSizes[imageSrc].width,
options && options.width
);
obj.imgheight = pick(
symbolSizes[imageSrc] && symbolSizes[imageSrc].height,
options && options.height
);
/**
* Set the size and position
*/
centerImage = function () {
obj.attr({
width: obj.width,
height: obj.height
});
};
/**
* Width and height setters that take both the image's physical size
* and the label size into consideration, and translates the image
* to center within the label.
*/
['width', 'height'].forEach(function (key) {
obj[key + 'Setter'] = function (value, key) {
var attribs = {},
imgSize = this['img' + key],
trans = key === 'width' ? 'translateX' : 'translateY';
this[key] = value;
if (defined(imgSize)) {
if (this.element) {
this.element.setAttribute(key, imgSize);
}
if (!this.alignByTranslate) {
attribs[trans] = ((this[key] || 0) - imgSize) / 2;
this.attr(attribs);
}
}
};
});
if (defined(x)) {
obj.attr({
x: x,
y: y
});
}
obj.isImg = true;
if (defined(obj.imgwidth) && defined(obj.imgheight)) {
centerImage();
} else {
// Initialize image to be 0 size so export will still function
// if there's no cached sizes.
obj.attr({ width: 0, height: 0 });
// Create a dummy JavaScript image to get the width and height.
createElement('img', {
onload: function () {
var chart = charts[ren.chartIndex];
// Special case for SVGs on IE11, the width is not
// accessible until the image is part of the DOM
// (#2854).
if (this.width === 0) {
css(this, {
position: 'absolute',
top: '-999em'
});
doc.body.appendChild(this);
}
// Center the image
symbolSizes[imageSrc] = { // Cache for next
width: this.width,
height: this.height
};
obj.imgwidth = this.width;
obj.imgheight = this.height;
if (obj.element) {
centerImage();
}
// Clean up after #2854 workaround.
if (this.parentNode) {
this.parentNode.removeChild(this);
}
// Fire the load event when all external images are
// loaded
ren.imgCount--;
if (!ren.imgCount && chart && chart.onload) {
chart.onload();
}
},
src: imageSrc
});
this.imgCount++;
}
}
return obj;
},
/**
* An extendable collection of functions for defining symbol paths.
*
* @name Highcharts.SVGRenderer#symbols
* @type {Highcharts.SymbolDictionary}
*/
symbols: {
'circle': function (x, y, w, h) {
// Return a full arc
return this.arc(x + w / 2, y + h / 2, w / 2, h / 2, {
start: 0,
end: Math.PI * 2,
open: false
});
},
'square': function (x, y, w, h) {
return [
'M', x, y,
'L', x + w, y,
x + w, y + h,
x, y + h,
'Z'
];
},
'triangle': function (x, y, w, h) {
return [
'M', x + w / 2, y,
'L', x + w, y + h,
x, y + h,
'Z'
];
},
'triangle-down': function (x, y, w, h) {
return [
'M', x, y,
'L', x + w, y,
x + w / 2, y + h,
'Z'
];
},
'diamond': function (x, y, w, h) {
return [
'M', x + w / 2, y,
'L', x + w, y + h / 2,
x + w / 2, y + h,
x, y + h / 2,
'Z'
];
},
'arc': function (x, y, w, h, options) {
var start = options.start,
rx = options.r || w,
ry = options.r || h || w,
proximity = 0.001,
fullCircle =
Math.abs(options.end - options.start - 2 * Math.PI) <
proximity,
// Substract a small number to prevent cos and sin of start and
// end from becoming equal on 360 arcs (related: #1561)
end = options.end - proximity,
innerRadius = options.innerR,
open = pick(options.open, fullCircle),
cosStart = Math.cos(start),
sinStart = Math.sin(start),
cosEnd = Math.cos(end),
sinEnd = Math.sin(end),
// Proximity takes care of rounding errors around PI (#6971)
longArc = options.end - start - Math.PI < proximity ? 0 : 1,
arc;
arc = [
'M',
x + rx * cosStart,
y + ry * sinStart,
'A', // arcTo
rx, // x radius
ry, // y radius
0, // slanting
longArc, // long or short arc
1, // clockwise
x + rx * cosEnd,
y + ry * sinEnd
];
if (defined(innerRadius)) {
arc.push(
open ? 'M' : 'L',
x + innerRadius * cosEnd,
y + innerRadius * sinEnd,
'A', // arcTo
innerRadius, // x radius
innerRadius, // y radius
0, // slanting
longArc, // long or short arc
0, // clockwise
x + innerRadius * cosStart,
y + innerRadius * sinStart
);
}
arc.push(open ? '' : 'Z'); // close
return arc;
},
/**
* Callout shape used for default tooltips, also used for rounded
* rectangles in VML
*/
'callout': function (x, y, w, h, options) {
var arrowLength = 6,
halfDistance = 6,
r = Math.min((options && options.r) || 0, w, h),
safeDistance = r + halfDistance,
anchorX = options && options.anchorX,
anchorY = options && options.anchorY,
path;
path = [
'M', x + r, y,
'L', x + w - r, y, // top side
'C', x + w, y, x + w, y, x + w, y + r, // top-right corner
'L', x + w, y + h - r, // right side
'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-rgt
'L', x + r, y + h, // bottom side
'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner
'L', x, y + r, // left side
'C', x, y, x, y, x + r, y // top-left corner
];
// Anchor on right side
if (anchorX && anchorX > w) {
// Chevron
if (
anchorY > y + safeDistance &&
anchorY < y + h - safeDistance
) {
path.splice(13, 3,
'L', x + w, anchorY - halfDistance,
x + w + arrowLength, anchorY,
x + w, anchorY + halfDistance,
x + w, y + h - r
);
// Simple connector
} else {
path.splice(13, 3,
'L', x + w, h / 2,
anchorX, anchorY,
x + w, h / 2,
x + w, y + h - r
);
}
// Anchor on left side
} else if (anchorX && anchorX < 0) {
// Chevron
if (
anchorY > y + safeDistance &&
anchorY < y + h - safeDistance
) {
path.splice(33, 3,
'L', x, anchorY + halfDistance,
x - arrowLength, anchorY,
x, anchorY - halfDistance,
x, y + r
);
// Simple connector
} else {
path.splice(33, 3,
'L', x, h / 2,
anchorX, anchorY,
x, h / 2,
x, y + r
);
}
} else if ( // replace bottom
anchorY &&
anchorY > h &&
anchorX > x + safeDistance &&
anchorX < x + w - safeDistance
) {
path.splice(23, 3,
'L', anchorX + halfDistance, y + h,
anchorX, y + h + arrowLength,
anchorX - halfDistance, y + h,
x + r, y + h
);
} else if ( // replace top
anchorY &&
anchorY < 0 &&
anchorX > x + safeDistance &&
anchorX < x + w - safeDistance
) {
path.splice(3, 3,
'L', anchorX - halfDistance, y,
anchorX, y - arrowLength,
anchorX + halfDistance, y,
w - r, y
);
}
return path;
}
},
/**
* Define a clipping rectangle. The clipping rectangle is later applied
* to {@link SVGElement} objects through the {@link SVGElement#clip}
* function.
*
* @example
* var circle = renderer.circle(100, 100, 100)
* .attr({ fill: 'red' })
* .add();
* var clipRect = renderer.clipRect(100, 100, 100, 100);
*
* // Leave only the lower right quarter visible
* circle.clip(clipRect);
*
* @function Highcharts.SVGRenderer#clipRect
*
* @param {string} id
*
* @param {number} x
*
* @param {number} y
*
* @param {number} width
*
* @param {number} height
*
* @return {Highcharts.ClipRectElement}
* A clipping rectangle.
*/
clipRect: function (x, y, width, height) {
var wrapper,
id = H.uniqueKey(),
clipPath = this.createElement('clipPath').attr({
id: id
}).add(this.defs);
wrapper = this.rect(x, y, width, height, 0).add(clipPath);
wrapper.id = id;
wrapper.clipPath = clipPath;
wrapper.count = 0;
return wrapper;
},
/**
* Draw text. The text can contain a subset of HTML, like spans and anchors
* and some basic text styling of these. For more advanced features like
* border and background, use {@link Highcharts.SVGRenderer#label} instead.
* To update the text after render, run `text.attr({ text: 'New text' })`.
*
* @sample highcharts/members/renderer-text-on-chart/
* Annotate the chart freely
* @sample highcharts/members/renderer-on-chart/
* Annotate with a border and in response to the data
* @sample highcharts/members/renderer-text/
* Formatted text
*
* @function Highcharts.SVGRenderer#text
*
* @param {string} str
* The text of (subset) HTML to draw.
*
* @param {number} x
* The x position of the text's lower left corner.
*
* @param {number} y
* The y position of the text's lower left corner.
*
* @param {boolean} [useHTML=false]
* Use HTML to render the text.
*
* @return {Highcharts.SVGElement}
* The text object.
*/
text: function (str, x, y, useHTML) {
// declare variables
var renderer = this,
wrapper,
attribs = {};
if (useHTML && (renderer.allowHTML || !renderer.forExport)) {
return renderer.html(str, x, y);
}
attribs.x = Math.round(x || 0); // X always needed for line-wrap logic
if (y) {
attribs.y = Math.round(y);
}
if (defined(str)) {
attribs.text = str;
}
wrapper = renderer.createElement('text')
.attr(attribs);
if (!useHTML) {
wrapper.xSetter = function (value, key, element) {
var tspans = element.getElementsByTagName('tspan'),
tspan,
parentVal = element.getAttribute(key),
i;
for (i = 0; i < tspans.length; i++) {
tspan = tspans[i];
// If the x values are equal, the tspan represents a
// linebreak
if (tspan.getAttribute(key) === parentVal) {
tspan.setAttribute(key, value);
}
}
element.setAttribute(key, value);
};
}
return wrapper;
},
/**
* Utility to return the baseline offset and total line height from the font
* size.
*
* @function Highcharts.SVGRenderer#fontMetrics
*
* @param {string} [fontSize]
* The current font size to inspect. If not given, the font size
* will be found from the DOM element.
*
* @param {Highcharts.SVGElement|Highcharts.SVGDOMElement} [elem]
* The element to inspect for a current font size.
*
* @return {Highcharts.FontMetricsObject}
* The font metrics.
*/
fontMetrics: function (fontSize, elem) {
var lineHeight,
baseline;
if (this.styledMode) {
fontSize = elem && SVGElement.prototype.getStyle.call(
elem,
'font-size'
);
} else {
fontSize = fontSize ||
// When the elem is a DOM element (#5932)
(elem && elem.style && elem.style.fontSize) ||
// Fall back on the renderer style default
(this.style && this.style.fontSize);
}
// Handle different units
if (/px/.test(fontSize)) {
fontSize = pInt(fontSize);
} else if (/em/.test(fontSize)) {
// The em unit depends on parent items
fontSize = parseFloat(fontSize) *
(elem ? this.fontMetrics(null, elem.parentNode).f : 16);
} else {
fontSize = 12;
}
// Empirical values found by comparing font size and bounding box
// height. Applies to the default font family.
// https://jsfiddle.net/highcharts/7xvn7/
lineHeight = fontSize < 24 ? fontSize + 3 : Math.round(fontSize * 1.2);
baseline = Math.round(lineHeight * 0.8);
return {
h: lineHeight,
b: baseline,
f: fontSize
};
},
/**
* Correct X and Y positioning of a label for rotation (#1764).
*
* @private
* @function Highcharts.SVGRenderer#rotCorr
*
* @param {number} baseline
*
* @param {number} rotation
*
* @param {boolean} alterY
*/
rotCorr: function (baseline, rotation, alterY) {
var y = baseline;
if (rotation && alterY) {
y = Math.max(y * Math.cos(rotation * deg2rad), 4);
}
return {
x: (-baseline / 3) * Math.sin(rotation * deg2rad),
y: y
};
},
/**
* Draw a label, which is an extended text element with support for border
* and background. Highcharts creates a `g` element with a text and a `path`
* or `rect` inside, to make it behave somewhat like a HTML div. Border and
* background are set through `stroke`, `stroke-width` and `fill` attributes
* using the {@link Highcharts.SVGElement#attr|attr} method. To update the
* text after render, run `label.attr({ text: 'New text' })`.
*
* @sample highcharts/members/renderer-label-on-chart/
* A label on the chart
*
* @function Highcharts.SVGRenderer#label
*
* @param {string} str
* The initial text string or (subset) HTML to render.
*
* @param {number} x
* The x position of the label's left side.
*
* @param {number} y
* The y position of the label's top side or baseline, depending on
* the `baseline` parameter.
*
* @param {string} [shape='rect']
* The shape of the label's border/background, if any. Defaults to
* `rect`. Other possible values are `callout` or other shapes
* defined in {@link Highcharts.SVGRenderer#symbols}.
*
* @param {string} [shape='rect']
* The shape of the label's border/background, if any. Defaults to
* `rect`. Other possible values are `callout` or other shapes
* defined in {@link Highcharts.SVGRenderer#symbols}.
*
* @param {number} [anchorX]
* In case the `shape` has a pointer, like a flag, this is the
* coordinates it should be pinned to.
*
* @param {number} [anchorY]
* In case the `shape` has a pointer, like a flag, this is the
* coordinates it should be pinned to.
*
* @param {boolean} [useHTML=false]
* Wether to use HTML to render the label.
*
* @param {boolean} [baseline=false]
* Whether to position the label relative to the text baseline,
* like {@link Highcharts.SVGRenderer#text|renderer.text}, or to the
* upper border of the rectangle.
*
* @param {string} [className]
* Class name for the group.
*
* @return {Highcharts.SVGElement}
* The generated label.
*/
label: function (
str,
x,
y,
shape,
anchorX,
anchorY,
useHTML,
baseline,
className
) {
var renderer = this,
styledMode = renderer.styledMode,
wrapper = renderer.g(className !== 'button' && 'label'),
text = wrapper.text = renderer.text('', 0, 0, useHTML)
.attr({
zIndex: 1
}),
box,
bBox,
alignFactor = 0,
padding = 3,
paddingLeft = 0,
width,
height,
wrapperX,
wrapperY,
textAlign,
deferredAttr = {},
strokeWidth,
baselineOffset,
hasBGImage = /^url\((.*?)\)$/.test(shape),
needsBox = styledMode || hasBGImage,
getCrispAdjust = function () {
return styledMode ?
box.strokeWidth() % 2 / 2 :
(strokeWidth ? parseInt(strokeWidth, 10) : 0) % 2 / 2;
},
updateBoxSize,
updateTextPadding,
boxAttr;
if (className) {
wrapper.addClass('highcharts-' + className);
}
/* This function runs after the label is added to the DOM (when the
bounding box is available), and after the text of the label is
updated to detect the new bounding box and reflect it in the border
box. */
updateBoxSize = function () {
var style = text.element.style,
crispAdjust,
attribs = {};
bBox = (
(width === undefined || height === undefined || textAlign) &&
defined(text.textStr) &&
text.getBBox()
); // #3295 && 3514 box failure when string equals 0
wrapper.width = (
(width || bBox.width || 0) +
2 * padding +
paddingLeft
);
wrapper.height = (height || bBox.height || 0) + 2 * padding;
// Update the label-scoped y offset
baselineOffset = padding + Math.min(
renderer.fontMetrics(style && style.fontSize, text).b,
// Math.min because of inline style (#9400)
bBox ? bBox.height : Infinity
);
if (needsBox) {
// Create the border box if it is not already present
if (!box) {
// Symbol definition exists (#5324)
wrapper.box = box = renderer.symbols[shape] || hasBGImage ?
renderer.symbol(shape) :
renderer.rect();
box.addClass( // Don't use label className for buttons
(className === 'button' ? '' : 'highcharts-label-box') +
(className ? ' highcharts-' + className + '-box' : '')
);
box.add(wrapper);
crispAdjust = getCrispAdjust();
attribs.x = crispAdjust;
attribs.y = (baseline ? -baselineOffset : 0) + crispAdjust;
}
// Apply the box attributes
attribs.width = Math.round(wrapper.width);
attribs.height = Math.round(wrapper.height);
box.attr(extend(attribs, deferredAttr));
deferredAttr = {};
}
};
/*
* This function runs after setting text or padding, but only if padding
* is changed.
*/
updateTextPadding = function () {
var textX = paddingLeft + padding,
textY;
// determin y based on the baseline
textY = baseline ? 0 : baselineOffset;
// compensate for alignment
if (
defined(width) &&
bBox &&
(textAlign === 'center' || textAlign === 'right')
) {
textX += { center: 0.5, right: 1 }[textAlign] *
(width - bBox.width);
}
// update if anything changed
if (textX !== text.x || textY !== text.y) {
text.attr('x', textX);
// #8159 - prevent misplaced data labels in treemap
// (useHTML: true)
if (text.hasBoxWidthChanged) {
bBox = text.getBBox(true);
updateBoxSize();
}
if (textY !== undefined) {
text.attr('y', textY);
}
}
// record current values
text.x = textX;
text.y = textY;
};
/*
* Set a box attribute, or defer it if the box is not yet created
*/
boxAttr = function (key, value) {
if (box) {
box.attr(key, value);
} else {
deferredAttr[key] = value;
}
};
/*
* After the text element is added, get the desired size of the border
* box and add it before the text in the DOM.
*/
wrapper.onAdd = function () {
text.add(wrapper);
wrapper.attr({
// Alignment is available now (#3295, 0 not rendered if given
// as a value)
text: (str || str === 0) ? str : '',
x: x,
y: y
});
if (box && defined(anchorX)) {
wrapper.attr({
anchorX: anchorX,
anchorY: anchorY
});
}
};
/*
* Add specific attribute setters.
*/
// only change local variables
wrapper.widthSetter = function (value) {
width = H.isNumber(value) ? value : null; // width:auto => null
};
wrapper.heightSetter = function (value) {
height = value;
};
wrapper['text-alignSetter'] = function (value) {
textAlign = value;
};
wrapper.paddingSetter = function (value) {
if (defined(value) && value !== padding) {
padding = wrapper.padding = value;
updateTextPadding();
}
};
wrapper.paddingLeftSetter = function (value) {
if (defined(value) && value !== paddingLeft) {
paddingLeft = value;
updateTextPadding();
}
};
// change local variable and prevent setting attribute on the group
wrapper.alignSetter = function (value) {
value = { left: 0, center: 0.5, right: 1 }[value];
if (value !== alignFactor) {
alignFactor = value;
// Bounding box exists, means we're dynamically changing
if (bBox) {
wrapper.attr({ x: wrapperX }); // #5134
}
}
};
// apply these to the box and the text alike
wrapper.textSetter = function (value) {
if (value !== undefined) {
text.textSetter(value);
}
updateBoxSize();
updateTextPadding();
};
// apply these to the box but not to the text
wrapper['stroke-widthSetter'] = function (value, key) {
if (value) {
needsBox = true;
}
strokeWidth = this['stroke-width'] = value;
boxAttr(key, value);
};
if (styledMode) {
wrapper.rSetter = function (value, key) {
boxAttr(key, value);
};
} else {
wrapper.strokeSetter =
wrapper.fillSetter =
wrapper.rSetter = function (value, key) {
if (key !== 'r') {
if (key === 'fill' && value) {
needsBox = true;
}
// for animation getter (#6776)
wrapper[key] = value;
}
boxAttr(key, value);
};
}
wrapper.anchorXSetter = function (value, key) {
anchorX = wrapper.anchorX = value;
boxAttr(key, Math.round(value) - getCrispAdjust() - wrapperX);
};
wrapper.anchorYSetter = function (value, key) {
anchorY = wrapper.anchorY = value;
boxAttr(key, value - wrapperY);
};
// rename attributes
wrapper.xSetter = function (value) {
wrapper.x = value; // for animation getter
if (alignFactor) {
value -= alignFactor * ((width || bBox.width) + 2 * padding);
// Force animation even when setting to the same value (#7898)
wrapper['forceAnimate:x'] = true;
}
wrapperX = Math.round(value);
wrapper.attr('translateX', wrapperX);
};
wrapper.ySetter = function (value) {
wrapperY = wrapper.y = Math.round(value);
wrapper.attr('translateY', wrapperY);
};
// Redirect certain methods to either the box or the text
var baseCss = wrapper.css;
var wrapperExtension = {
/**
* Pick up some properties and apply them to the text instead of the
* wrapper.
*/
css: function (styles) {
if (styles) {
var textStyles = {};
// Create a copy to avoid altering the original object
// (#537)
styles = merge(styles);
wrapper.textProps.forEach(function (prop) {
if (styles[prop] !== undefined) {
textStyles[prop] = styles[prop];
delete styles[prop];
}
});
text.css(textStyles);
// Update existing text and box
if ('width' in textStyles) {
updateBoxSize();
}
// Keep updated (#9400)
if ('fontSize' in textStyles) {
updateBoxSize();
updateTextPadding();
}
}
return baseCss.call(wrapper, styles);
},
/*
* Return the bounding box of the box, not the group.
*/
getBBox: function () {
return {
width: bBox.width + 2 * padding,
height: bBox.height + 2 * padding,
x: bBox.x - padding,
y: bBox.y - padding
};
},
/**
* Destroy and release memory.
*/
destroy: function () {
// Added by button implementation
removeEvent(wrapper.element, 'mouseenter');
removeEvent(wrapper.element, 'mouseleave');
if (text) {
text = text.destroy();
}
if (box) {
box = box.destroy();
}
// Call base implementation to destroy the rest
SVGElement.prototype.destroy.call(wrapper);
// Release local pointers (#1298)
wrapper =
renderer =
updateBoxSize =
updateTextPadding =
boxAttr = null;
}
};
if (!styledMode) {
/**
* Apply the shadow to the box.
*
* @ignore
* @function Highcharts.SVGElement#shadow
*
* @return {Highcharts.SVGElement}
*/
wrapperExtension.shadow = function (b) {
if (b) {
updateBoxSize();
if (box) {
box.shadow(b);
}
}
return wrapper;
};
}
return extend(wrapper, wrapperExtension);
}
}); // end SVGRenderer
// general renderer
H.Renderer = SVGRenderer;
| extend1994/cdnjs | ajax/libs/highcharts/7.0.1/es-modules/parts/SvgRenderer.js | JavaScript | mit | 165,077 |
// wrapped by build app
define("FileSaver/demo/demo", ["dojo","dijit","dojox"], function(dojo,dijit,dojox){
/* FileSaver.js demo script
* 2012-01-23
*
* By Eli Grey, http://eligrey.com
* License: X11/MIT
* See LICENSE.md
*/
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/demo/demo.js */
(function(view) {
"use strict";
// The canvas drawing portion of the demo is based off the demo at
// http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/
var
document = view.document
, $ = function(id) {
return document.getElementById(id);
}
, session = view.sessionStorage
// only get URL when necessary in case Blob.js hasn't defined it yet
, get_blob = function() {
return view.Blob;
}
, canvas = $("canvas")
, canvas_options_form = $("canvas-options")
, canvas_filename = $("canvas-filename")
, canvas_clear_button = $("canvas-clear")
, text = $("text")
, text_options_form = $("text-options")
, text_filename = $("text-filename")
, html = $("html")
, html_options_form = $("html-options")
, html_filename = $("html-filename")
, ctx = canvas.getContext("2d")
, drawing = false
, x_points = session.x_points || []
, y_points = session.y_points || []
, drag_points = session.drag_points || []
, add_point = function(x, y, dragging) {
x_points.push(x);
y_points.push(y);
drag_points.push(dragging);
}
, draw = function(){
canvas.width = canvas.width;
ctx.lineWidth = 6;
ctx.lineJoin = "round";
ctx.strokeStyle = "#000000";
var
i = 0
, len = x_points.length
;
for(; i < len; i++) {
ctx.beginPath();
if (i && drag_points[i]) {
ctx.moveTo(x_points[i-1], y_points[i-1]);
} else {
ctx.moveTo(x_points[i]-1, y_points[i]);
}
ctx.lineTo(x_points[i], y_points[i]);
ctx.closePath();
ctx.stroke();
}
}
, stop_drawing = function() {
drawing = false;
}
// Title guesser and document creator available at https://gist.github.com/1059648
, guess_title = function(doc) {
var
h = "h6 h5 h4 h3 h2 h1".split(" ")
, i = h.length
, headers
, header_text
;
while (i--) {
headers = doc.getElementsByTagName(h[i]);
for (var j = 0, len = headers.length; j < len; j++) {
header_text = headers[j].textContent.trim();
if (header_text) {
return header_text;
}
}
}
}
, doc_impl = document.implementation
, create_html_doc = function(html) {
var
dt = doc_impl.createDocumentType('html', null, null)
, doc = doc_impl.createDocument("http://www.w3.org/1999/xhtml", "html", dt)
, doc_el = doc.documentElement
, head = doc_el.appendChild(doc.createElement("head"))
, charset_meta = head.appendChild(doc.createElement("meta"))
, title = head.appendChild(doc.createElement("title"))
, body = doc_el.appendChild(doc.createElement("body"))
, i = 0
, len = html.childNodes.length
;
charset_meta.setAttribute("charset", html.ownerDocument.characterSet);
for (; i < len; i++) {
body.appendChild(doc.importNode(html.childNodes.item(i), true));
}
var title_text = guess_title(doc);
if (title_text) {
title.appendChild(doc.createTextNode(title_text));
}
return doc;
}
;
canvas.width = 500;
canvas.height = 300;
if (typeof x_points === "string") {
x_points = JSON.parse(x_points);
} if (typeof y_points === "string") {
y_points = JSON.parse(y_points);
} if (typeof drag_points === "string") {
drag_points = JSON.parse(drag_points);
} if (session.canvas_filename) {
canvas_filename.value = session.canvas_filename;
} if (session.text) {
text.value = session.text;
} if (session.text_filename) {
text_filename.value = session.text_filename;
} if (session.html) {
html.innerHTML = session.html;
} if (session.html_filename) {
html_filename.value = session.html_filename;
}
drawing = true;
draw();
drawing = false;
canvas_clear_button.addEventListener("click", function() {
canvas.width = canvas.width;
x_points.length =
y_points.length =
drag_points.length =
0;
}, false);
canvas.addEventListener("mousedown", function(event) {
event.preventDefault();
drawing = true;
add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, false);
draw();
}, false);
canvas.addEventListener("mousemove", function(event) {
if (drawing) {
add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, true);
draw();
}
}, false);
canvas.addEventListener("mouseup", stop_drawing, false);
canvas.addEventListener("mouseout", stop_drawing, false);
canvas_options_form.addEventListener("submit", function(event) {
event.preventDefault();
canvas.toBlob(function(blob) {
saveAs(
blob
, (canvas_filename.value || canvas_filename.placeholder) + ".png"
);
}, "image/png");
}, false);
text_options_form.addEventListener("submit", function(event) {
event.preventDefault();
var BB = get_blob();
saveAs(
new BB(
[text.value || text.placeholder]
, {type: "text/plain;charset=" + document.characterSet}
)
, (text_filename.value || text_filename.placeholder) + ".txt"
);
}, false);
html_options_form.addEventListener("submit", function(event) {
event.preventDefault();
var
BB = get_blob()
, xml_serializer = new XMLSerializer
, doc = create_html_doc(html)
;
saveAs(
new BB(
[xml_serializer.serializeToString(doc)]
, {type: "application/xhtml+xml;charset=" + document.characterSet}
)
, (html_filename.value || html_filename.placeholder) + ".xhtml"
);
}, false);
view.addEventListener("unload", function() {
session.x_points = JSON.stringify(x_points);
session.y_points = JSON.stringify(y_points);
session.drag_points = JSON.stringify(drag_points);
session.canvas_filename = canvas_filename.value;
session.text = text.value;
session.text_filename = text_filename.value;
session.html = html.innerHTML;
session.html_filename = html_filename.value;
}, false);
}(self));
});
| dawenx/p3_web | public/js/release/FileSaver/demo/demo.js | JavaScript | mit | 5,888 |
/* ****************************************************************************
* Start Flags series code *
*****************************************************************************/
var symbols = SVGRenderer.prototype.symbols;
// 1 - set default options
defaultPlotOptions.flags = merge(defaultPlotOptions.column, {
dataGrouping: null,
fillColor: 'white',
lineWidth: 1,
pointRange: 0, // #673
//radius: 2,
shape: 'flag',
stackDistance: 12,
states: {
hover: {
lineColor: 'black',
fillColor: '#FCFFC5'
}
},
style: {
fontSize: '11px',
fontWeight: 'bold',
textAlign: 'center'
},
tooltip: {
pointFormat: '{point.text}<br/>'
},
threshold: null,
y: -30
});
// 2 - Create the CandlestickSeries object
seriesTypes.flags = extendClass(seriesTypes.column, {
type: 'flags',
sorted: false,
noSharedTooltip: true,
takeOrdinalPosition: false, // #1074
trackerGroups: ['markerGroup'],
forceCrop: true,
/**
* Inherit the initialization from base Series
*/
init: Series.prototype.init,
/**
* One-to-one mapping from options to SVG attributes
*/
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
fill: 'fillColor',
stroke: 'color',
'stroke-width': 'lineWidth',
r: 'radius'
},
/**
* Extend the translate method by placing the point on the related series
*/
translate: function () {
seriesTypes.column.prototype.translate.apply(this);
var series = this,
options = series.options,
chart = series.chart,
points = series.points,
cursor = points.length - 1,
point,
lastPoint,
optionsOnSeries = options.onSeries,
onSeries = optionsOnSeries && chart.get(optionsOnSeries),
step = onSeries && onSeries.options.step,
onData = onSeries && onSeries.points,
i = onData && onData.length,
xAxis = series.xAxis,
xAxisExt = xAxis.getExtremes(),
leftPoint,
lastX,
rightPoint,
currentDataGrouping;
// relate to a master series
if (onSeries && onSeries.visible && i) {
currentDataGrouping = onSeries.currentDataGrouping;
lastX = onData[i - 1].x + (currentDataGrouping ? currentDataGrouping.totalRange : 0); // #2374
// sort the data points
points.sort(function (a, b) {
return (a.x - b.x);
});
while (i-- && points[cursor]) {
point = points[cursor];
leftPoint = onData[i];
if (leftPoint.x <= point.x && leftPoint.plotY !== UNDEFINED) {
if (point.x <= lastX) { // #803
point.plotY = leftPoint.plotY;
// interpolate between points, #666
if (leftPoint.x < point.x && !step) {
rightPoint = onData[i + 1];
if (rightPoint && rightPoint.plotY !== UNDEFINED) {
point.plotY +=
((point.x - leftPoint.x) / (rightPoint.x - leftPoint.x)) * // the distance ratio, between 0 and 1
(rightPoint.plotY - leftPoint.plotY); // the y distance
}
}
}
cursor--;
i++; // check again for points in the same x position
if (cursor < 0) {
break;
}
}
}
}
// Add plotY position and handle stacking
each(points, function (point, i) {
// Undefined plotY means the point is either on axis, outside series range or hidden series.
// If the series is outside the range of the x axis it should fall through with
// an undefined plotY, but then we must remove the shapeArgs (#847).
if (point.plotY === UNDEFINED) {
if (point.x >= xAxisExt.min && point.x <= xAxisExt.max) { // we're inside xAxis range
point.plotY = chart.chartHeight - xAxis.bottom - (xAxis.opposite ? xAxis.height : 0) + xAxis.offset - chart.plotTop;
} else {
point.shapeArgs = {}; // 847
}
}
// if multiple flags appear at the same x, order them into a stack
lastPoint = points[i - 1];
if (lastPoint && lastPoint.plotX === point.plotX) {
if (lastPoint.stackIndex === UNDEFINED) {
lastPoint.stackIndex = 0;
}
point.stackIndex = lastPoint.stackIndex + 1;
}
});
},
/**
* Draw the markers
*/
drawPoints: function () {
var series = this,
pointAttr,
points = series.points,
chart = series.chart,
renderer = chart.renderer,
plotX,
plotY,
options = series.options,
optionsY = options.y,
shape,
i,
point,
graphic,
stackIndex,
crisp = (options.lineWidth % 2 / 2),
anchorX,
anchorY,
outsideRight;
i = points.length;
while (i--) {
point = points[i];
outsideRight = point.plotX > series.xAxis.len;
plotX = point.plotX + (outsideRight ? crisp : -crisp);
stackIndex = point.stackIndex;
shape = point.options.shape || options.shape;
plotY = point.plotY;
if (plotY !== UNDEFINED) {
plotY = point.plotY + optionsY + crisp - (stackIndex !== UNDEFINED && stackIndex * options.stackDistance);
}
anchorX = stackIndex ? UNDEFINED : point.plotX + crisp; // skip connectors for higher level stacked points
anchorY = stackIndex ? UNDEFINED : point.plotY;
graphic = point.graphic;
// only draw the point if y is defined and the flag is within the visible area
if (plotY !== UNDEFINED && plotX >= 0 && !outsideRight) {
// shortcuts
pointAttr = point.pointAttr[point.selected ? 'select' : ''];
if (graphic) { // update
graphic.attr({
x: plotX,
y: plotY,
r: pointAttr.r,
anchorX: anchorX,
anchorY: anchorY
});
} else {
graphic = point.graphic = renderer.label(
point.options.title || options.title || 'A',
plotX,
plotY,
shape,
anchorX,
anchorY,
options.useHTML
)
.css(merge(options.style, point.style))
.attr(pointAttr)
.attr({
align: shape === 'flag' ? 'left' : 'center',
width: options.width,
height: options.height
})
.add(series.markerGroup)
.shadow(options.shadow);
}
// Set the tooltip anchor position
point.tooltipPos = [plotX, plotY];
} else if (graphic) {
point.graphic = graphic.destroy();
}
}
},
/**
* Extend the column trackers with listeners to expand and contract stacks
*/
drawTracker: function () {
var series = this,
points = series.points;
TrackerMixin.drawTrackerPoint.apply(this);
// Bring each stacked flag up on mouse over, this allows readability of vertically
// stacked elements as well as tight points on the x axis. #1924.
each(points, function (point) {
var graphic = point.graphic;
if (graphic) {
addEvent(graphic.element, 'mouseover', function () {
// Raise this point
if (point.stackIndex > 0 && !point.raised) {
point._y = graphic.y;
graphic.attr({
y: point._y - 8
});
point.raised = true;
}
// Revert other raised points
each(points, function (otherPoint) {
if (otherPoint !== point && otherPoint.raised && otherPoint.graphic) {
otherPoint.graphic.attr({
y: otherPoint._y
});
otherPoint.raised = false;
}
});
});
}
});
},
/**
* Disable animation
*/
animate: noop
});
// create the flag icon with anchor
symbols.flag = function (x, y, w, h, options) {
var anchorX = (options && options.anchorX) || x,
anchorY = (options && options.anchorY) || y;
return [
'M', anchorX, anchorY,
'L', x, y + h,
x, y,
x + w, y,
x + w, y + h,
x, y + h,
'M', anchorX, anchorY,
'Z'
];
};
// create the circlepin and squarepin icons with anchor
each(['circle', 'square'], function (shape) {
symbols[shape + 'pin'] = function (x, y, w, h, options) {
var anchorX = options && options.anchorX,
anchorY = options && options.anchorY,
path = symbols[shape](x, y, w, h),
labelTopOrBottomY;
if (anchorX && anchorY) {
// if the label is below the anchor, draw the connecting line from the top edge of the label
// otherwise start drawing from the bottom edge
labelTopOrBottomY = (y > anchorY) ? y : y + h;
path.push('M', anchorX, labelTopOrBottomY, 'L', anchorX, anchorY);
}
return path;
};
});
// The symbol callbacks are generated on the SVGRenderer object in all browsers. Even
// VML browsers need this in order to generate shapes in export. Now share
// them with the VMLRenderer.
if (Renderer === Highcharts.VMLRenderer) {
each(['flag', 'circlepin', 'squarepin'], function (shape) {
VMLRenderer.prototype.symbols[shape] = symbols[shape];
});
}
/* ****************************************************************************
* End Flags series code *
*****************************************************************************/
| Ecodev/gims | htdocs/lib/highcharts.com/js/parts/FlagsSeries.js | JavaScript | mit | 8,576 |
<?php
/**
* WooCommerce REST Exception Class
*
* Extends Exception to provide additional data.
*
* @author WooThemes
* @category API
* @package WooCommerce/API
* @since 2.6.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* WC_REST_Exception class.
*/
class WC_REST_Exception extends Exception {
/**
* Sanitized error code.
*
* @var string
*/
protected $error_code;
/**
* Error extra data.
*
* @var array
*/
protected $error_data;
/**
* Setup exception.
*
* @param string $code Machine-readable error code, e.g `woocommerce_invalid_product_id`.
* @param string $message User-friendly translated error message, e.g. 'Product ID is invalid'.
* @param int $http_status_code Proper HTTP status code to respond with, e.g. 400.
* @param array $data Extra error data.
*/
public function __construct( $code, $message, $http_status_code = 400, $data = array() ) {
$this->error_code = $code;
$this->error_data = array_merge( array( 'status' => $http_status_code ), $data );
parent::__construct( $message, $http_status_code );
}
/**
* Returns the error code.
*
* @return string
*/
public function getErrorCode() {
return $this->error_code;
}
/**
* Returns error data.
*
* @return array
*/
public function getErrorData() {
return $this->error_data;
}
}
| Kilbourne/biosphaera | web/app/plugins/woocommerce/includes/api/class-wc-rest-exception.php | PHP | mit | 1,373 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using Nuwa;
using WebStack.QA.Test.OData.Common;
using Xunit;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Web.Http.OData;
using System.Net.Http.Headers;
namespace WebStack.QA.Test.OData.QueryComposition
{
public class JsonSingleResultExpandTests : ODataTestBase
{
[NuwaConfiguration]
public static void UpdateConfiguration(HttpConfiguration configuration)
{
configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
configuration.Routes.Clear();
configuration.Routes.MapHttpRoute("api", "api/{controller}/{id}", new { id = RouteParameter.Optional });
}
[Fact]
public void QueryJustThePropertiesOfTheEntriesOnASingleResult()
{
string queryUrl = string.Format("{0}/api/JsonSingleResultCustomer/1?$select=*", BaseAddress);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, queryUrl);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
HttpClient client = new HttpClient();
HttpResponseMessage response;
JObject result;
string content;
response = client.SendAsync(request).Result;
Assert.NotNull(response);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
content = response.Content.ReadAsStringAsync().Result;
result = JObject.Parse(content);
Assert.NotNull(result);
Assert.Equal(2, result.Properties().Count());
}
[Fact]
public void QueryASubsetOfThePropertiesOfAnEntryOnASingleResult()
{
string queryUrl = string.Format("{0}/api/JsonSingleResultCustomer/1/?$select=Name", BaseAddress);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, queryUrl);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
HttpClient client = new HttpClient();
HttpResponseMessage response;
JObject result;
string content;
response = client.SendAsync(request).Result;
Assert.NotNull(response);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
content = response.Content.ReadAsStringAsync().Result;
result = JObject.Parse(content);
Assert.NotNull(result);
Assert.True(result.Properties().Count() == 1 && result.Properties().All(p => p.Name == "Name"));
}
[Fact]
public void QueryASubsetOfThePropertiesOfAnEntryAndASubsetOfThePropertiesOfARelatedEntryOnASingleResult()
{
string queryUrl = string.Format("{0}/api/JsonSingleResultCustomer/1/?$select=Id,Name,JsonSingleResultOrders/Id&$expand=JsonSingleResultOrders", BaseAddress);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, queryUrl);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
HttpClient client = new HttpClient();
HttpResponseMessage response;
JObject result;
string content;
response = client.SendAsync(request).Result;
Assert.NotNull(response);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
content = response.Content.ReadAsStringAsync().Result;
result = JObject.Parse(content);
Assert.NotNull(result);
Assert.Equal(3, result.Properties().Count());
Assert.Equal((int)result["Id"], ((JArray)result["JsonSingleResultOrders"]).Count);
}
[Fact]
public void QueryASubSetOfThePropertiesPresentOnlyInADerivedEntryOnASingleResult()
{
string queryUrl = string.Format("{0}/api/JsonSingleResultCustomer/10/?$select=Id,WebStack.QA.Test.OData.QueryComposition.JsonSingleResultPremiumCustomer/Category", BaseAddress);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, queryUrl);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
HttpClient client = new HttpClient();
HttpResponseMessage response;
JObject result;
string content;
response = client.SendAsync(request).Result;
Assert.NotNull(response);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
content = response.Content.ReadAsStringAsync().Result;
result = JObject.Parse(content);
Assert.NotNull(result);
Assert.Equal(2, result.Properties().Count());
}
[Fact]//(Skip = "Issue #1048 - $select and $expand not working properly for complex types in json formatter")]
public void QueryAnEntryAndIncludeTheRelatedEntriesForAGivenNavigationPropertyInlineOnASingleResult()
{
string queryUrl = string.Format("{0}/api/JsonSingleResultCustomer/1?$select=Id,JsonSingleResultOrders&$expand=JsonSingleResultOrders", BaseAddress);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, queryUrl);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
HttpClient client = new HttpClient();
HttpResponseMessage response;
JObject result;
string content;
response = client.SendAsync(request).Result;
Assert.NotNull(response);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
content = response.Content.ReadAsStringAsync().Result;
result = JObject.Parse(content);
Assert.NotNull(result);
Assert.Equal(2, result.Properties().Count());
JArray orders = result["JsonSingleResultOrders"] as JArray;
Assert.Equal((int)result["Id"], orders.Count);
foreach (JObject order in orders)
{
Assert.Equal(2, order.Properties().Count());
}
}
[Fact]//(Skip = "Issue #1048 - $select and $expand not working properly for complex types in json formatter")]
public void QueryForAnEntryAnIncludeTheRelatedEntriesForASetOfNavigationPropertiesOnASingleResult()
{
string queryUrl = string.Format("{0}/api/JsonSingleResultCustomer/10?$select=Id,JsonSingleResultOrders,WebStack.QA.Test.OData.QueryComposition.JsonSingleResultPremiumCustomer/Bonuses&$expand=JsonSingleResultOrders,WebStack.QA.Test.OData.QueryComposition.JsonSingleResultPremiumCustomer/Bonuses", BaseAddress);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, queryUrl);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
HttpClient client = new HttpClient();
HttpResponseMessage response;
JObject result;
string content;
response = client.SendAsync(request).Result;
Assert.NotNull(response);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
content = response.Content.ReadAsStringAsync().Result;
result = JObject.Parse(content);
Assert.NotNull(result);
Assert.True(result.Properties().Count() == 3);
JArray orders = result["JsonSingleResultOrders"] as JArray;
Assert.Equal((int)result["Id"], orders.Count);
foreach (JObject order in orders)
{
Assert.Equal(2, order.Properties().Count());
}
JArray bonuses = result["Bonuses"] as JArray;
Assert.Equal((int)result["Id"], bonuses.Count);
foreach (JObject bonus in bonuses)
{
Assert.Equal(2, bonus.Properties().Count());
}
}
[Fact]//(Skip = "Issue #1048 - $select and $expand not working properly for complex types in json formatter")]
public void QueryForAnEntryAndIncludeTheRelatedEntriesForAGivenNavigationPropertyPathOnASingleResult()
{
string queryUrl = string.Format("{0}/api/JsonSingleResultCustomer/10?$select=Id,JsonSingleResultOrders,JsonSingleResultOrders/OrderDetails&$expand=JsonSingleResultOrders/OrderDetails", BaseAddress);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, queryUrl);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
HttpClient client = new HttpClient();
HttpResponseMessage response;
JObject result;
string content;
response = client.SendAsync(request).Result;
Assert.NotNull(response);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
content = response.Content.ReadAsStringAsync().Result;
result = JObject.Parse(content);
Assert.NotNull(result);
Assert.True(result.Properties().Count() == 2);
JArray orders = result["JsonSingleResultOrders"] as JArray;
Assert.Equal((int)result["Id"], orders.Count);
foreach (JObject order in orders)
{
Assert.Equal(3, order.Properties().Count());
JArray orderDetails = order["OrderDetails"] as JArray;
Assert.Equal((int)order["Id"], orderDetails.Count);
foreach (JObject orderDetail in orderDetails)
{
Assert.Equal(4, orderDetail.Properties().Count());
}
}
}
[Fact]
public void QueryForAnEntryAnIncludeTheRelatedEntriesForANavigationPropertyPresentOnlyInDerivedEntriesOnASingleResult()
{
string queryUrl = string.Format("{0}/api/JsonSingleResultCustomer/10?$select=Id,WebStack.QA.Test.OData.QueryComposition.JsonSingleResultPremiumCustomer/Bonuses&$expand=WebStack.QA.Test.OData.QueryComposition.JsonSingleResultPremiumCustomer/Bonuses", BaseAddress);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, queryUrl);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
HttpClient client = new HttpClient();
HttpResponseMessage response;
JObject result;
string content;
response = client.SendAsync(request).Result;
Assert.NotNull(response);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
content = response.Content.ReadAsStringAsync().Result;
result = JObject.Parse(content);
Assert.NotNull(result);
Assert.Equal(2, result.Properties().Count());
JArray bonuses = result["Bonuses"] as JArray;
Assert.Equal((int)result["Id"], bonuses.Count);
foreach (JObject bonus in bonuses)
{
Assert.Equal(2, bonus.Properties().Count());
}
}
}
public class JsonSingleResultCustomerController : ApiController
{
[EnableQuery(MaxExpansionDepth = 10)]
public SingleResult<JsonSingleResultCustomer> Get(int id)
{
return SingleResult.Create(Enumerable.Range(0, 10).Select(i => new JsonSingleResultCustomer
{
Id = i,
Name = string.Format("Customer{0}", i),
JsonSingleResultOrders = Enumerable.Range(0, i).Select(j => new JsonSingleResultOrder
{
Id = j,
Date = DateTime.Now.Subtract(TimeSpan.FromDays(j)),
BillingAddress = new JsonSingleResultAddress
{
FirstLine = string.Format("First line {0}", j),
SecondLine = string.Format("Second line {0}", j),
ZipCode = j * 100,
City = string.Format("City {0}", j),
State = string.Format("State {0}", j),
Country = string.Format("Country {0}", j),
},
OrderDetails = Enumerable.Range(0, j).Select(k => new JsonSingleResultOrderDetail
{
Id = k,
Ammount = k,
Name = string.Format("Name {0}", k),
Price = k * 1000
}).ToList()
}).ToList()
}).Concat(
Enumerable.Range(10, 10).Select(i => new JsonSingleResultPremiumCustomer
{
Id = i,
Name = string.Format("Customer{0}", i),
Category = string.Format("Category{0}", i),
Bonuses = Enumerable.Range(0, i).Select(j => new JsonSingleResultBonus
{
Id = j,
Ammount = j * 1000
}).ToList(),
JsonSingleResultOrders = Enumerable.Range(0, i).Select(j => new JsonSingleResultOrder
{
Id = j,
Date = DateTime.Now.Subtract(TimeSpan.FromDays(j)),
BillingAddress = new JsonSingleResultAddress
{
FirstLine = string.Format("First line {0}", j),
SecondLine = string.Format("Second line {0}", j),
ZipCode = j * 100,
City = string.Format("City {0}", j),
State = string.Format("State {0}", j),
Country = string.Format("Country {0}", j),
},
OrderDetails = Enumerable.Range(0, j).Select(k => new JsonSingleResultOrderDetail
{
Id = k,
Ammount = k,
Name = string.Format("Name {0}", k),
Price = k * 1000
}).ToList()
}).ToList()
})).AsQueryable().Where(x => x.Id == id));
}
}
public class JsonSingleResultCustomer
{
public int Id { get; set; }
public string Name { get; set; }
public virtual IList<JsonSingleResultOrder> JsonSingleResultOrders { get; set; }
}
public class JsonSingleResultPremiumCustomer : JsonSingleResultCustomer
{
public string Category { get; set; }
public IList<JsonSingleResultBonus> Bonuses { get; set; }
}
public class JsonSingleResultBonus
{
public int Id { get; set; }
public double Ammount { get; set; }
}
public class JsonSingleResultOrder
{
public int Id { get; set; }
public DateTime Date { get; set; }
public JsonSingleResultAddress BillingAddress { get; set; }
public virtual IList<JsonSingleResultOrderDetail> OrderDetails { get; set; }
}
public class JsonSingleResultAddress
{
public string FirstLine { get; set; }
public string SecondLine { get; set; }
public int ZipCode { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
public class JsonSingleResultOrderDetail
{
public int Id { get; set; }
public string Name { get; set; }
public int Ammount { get; set; }
public double Price { get; set; }
}
}
| lungisam/WebApi | OData/test/E2ETestV3/WebStack.QA.Test.OData/QueryComposition/JsonSingleResultSelectExpandTests.cs | C# | mit | 16,115 |
version https://git-lfs.github.com/spec/v1
oid sha256:f09386339b7a083e92b706c491817eb6f328805c49481a614f996a194d761fdc
size 1848
| yogeshsaroya/new-cdnjs | ajax/libs/dojo/1.9.7/cldr/nls/zh/ethiopic.js.uncompressed.js | JavaScript | mit | 129 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MarbleMazeGame")]
[assembly: AssemblyProduct("MarbleMazeGame")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type. Only Windows
// assemblies support COM.
[assembly: ComVisible(false)]
// On Windows, the following GUID is for the ID of the typelib if this
// project is exposed to COM. On other platforms, it unique identifies the
// title storage container when deploying this assembly to the device.
[assembly: Guid("d4a724f3-3812-4aab-9c68-f222f61bc078")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
| DDReaper/XNAGameStudio | Samples/MarbleMaze_4_0/Source/EX2_Polishing/End/MarbleMazeGame/MarbleMazeGame/Properties/AssemblyInfo.cs | C# | mit | 1,352 |
if (typeof (QP) == "undefined" || !QP) {
var QP = {}
};
(function() {
/* Draws the lines linking nodes in query plan diagram.
root - The document element in which the diagram is contained. */
QP.drawLines = function(root) {
if (root === null || root === undefined) {
// Try and find it ourselves
root = $(".qp-root").parent();
} else {
// Make sure the object passed is jQuery wrapped
root = $(root);
}
internalDrawLines(root);
};
/* Internal implementaiton of drawLines. */
function internalDrawLines(root) {
var canvas = getCanvas(root);
var canvasElm = canvas[0];
// Check for browser compatability
if (canvasElm.getContext !== null && canvasElm.getContext !== undefined) {
// Chrome is usually too quick with document.ready
window.setTimeout(function() {
var context = canvasElm.getContext("2d");
// The first root node may be smaller than the full query plan if using overflow
var firstNode = $(".qp-tr", root);
canvasElm.width = firstNode.outerWidth(true);
canvasElm.height = firstNode.outerHeight(true);
var offset = canvas.offset();
$(".qp-tr", root).each(function() {
var from = $("> * > .qp-node", $(this));
$("> * > .qp-tr > * > .qp-node", $(this)).each(function() {
drawLine(context, offset, from, $(this));
});
});
context.stroke();
}, 1);
}
}
/* Locates or creates the canvas element to use to draw lines for a given root element. */
function getCanvas(root) {
var returnValue = $("canvas", root);
if (returnValue.length == 0) {
root.prepend($("<canvas></canvas>")
.css("position", "absolute")
.css("top", 0).css("left", 0)
);
returnValue = $("canvas", root);
}
return returnValue;
}
/* Draws a line between two nodes.
context - The canvas context with which to draw.
offset - Canvas offset in the document.
from - The document jQuery object from which to draw the line.
to - The document jQuery object to which to draw the line. */
function drawLine(context, offset, from, to) {
var fromOffset = from.offset();
fromOffset.top += from.outerHeight() / 2;
fromOffset.left += from.outerWidth();
var toOffset = to.offset();
toOffset.top += to.outerHeight() / 2;
var midOffsetLeft = fromOffset.left / 2 + toOffset.left / 2;
context.moveTo(fromOffset.left - offset.left, fromOffset.top - offset.top);
context.lineTo(midOffsetLeft - offset.left, fromOffset.top - offset.top);
context.lineTo(midOffsetLeft - offset.left, toOffset.top - offset.top);
context.lineTo(toOffset.left - offset.left, toOffset.top - offset.top);
}
})(); | jemmy655/sqlfiddle | src/main/webapp/javascripts/libs/xplans/mssql.js | JavaScript | mit | 3,162 |
module PDF
class Inspector
module Graphics
class Line < Inspector
attr_accessor :points, :widths
def initialize
@points = []
@widths = []
end
def append_line(*params)
@points << params
end
def begin_new_subpath(*params)
@points << params
end
def set_line_width(params)
@widths << params
end
end
class Rectangle < Inspector
attr_reader :rectangles
def initialize
@rectangles = []
end
def append_rectangle(*params)
@rectangles << { :point => params[0..1],
:width => params[2],
:height => params[3] }
end
end
class Curve < Inspector
attr_reader :coords
def initialize
@coords = []
end
def begin_new_subpath(*params)
@coords += params
end
def append_curved_segment(*params)
@coords += params
end
end
class Color < Inspector
attr_reader :stroke_color, :fill_color, :stroke_color_count,
:fill_color_count
def initialize
@stroke_color_count = 0
@fill_color_count = 0
end
def set_rgb_color_for_stroking(*params)
@stroke_color_count += 1
@stroke_color = params
end
def set_rgb_color_for_nonstroking(*params)
@fill_color_count += 1
@fill_color = params
end
end
class Dash < Inspector
attr_reader :stroke_dash, :stroke_dash_count
def initialize
@stroke_dash_count = 0
end
def set_line_dash(*params)
@stroke_dash_count += 1
@stroke_dash = params
end
end
class CapStyle < Inspector
attr_reader :cap_style, :cap_style_count
def initialize
@cap_style_count = 0
end
def set_line_cap_style(*params)
@cap_style_count += 1
@cap_style = params[0]
end
end
class JoinStyle < Inspector
attr_reader :join_style, :join_style_count
def initialize
@join_style_count = 0
end
def set_line_join_style(*params)
@join_style_count += 1
@join_style = params[0]
end
end
end
end
end
| felipeferreira/websales | vendor/gems/prawn-layout-0.3.2/vendor/prawn-core/vendor/pdf-inspector/lib/pdf/inspector/graphics.rb | Ruby | mit | 2,617 |
# frozen_string_literal: true
class Pirate < ActiveRecord::Base
belongs_to :parrot, validate: true
belongs_to :non_validated_parrot, class_name: "Parrot"
has_and_belongs_to_many :parrots, -> { order("parrots.id ASC") }, validate: true
has_and_belongs_to_many :non_validated_parrots, class_name: "Parrot"
has_and_belongs_to_many :parrots_with_method_callbacks, class_name: "Parrot",
before_add: :log_before_add,
after_add: :log_after_add,
before_remove: :log_before_remove,
after_remove: :log_after_remove
has_and_belongs_to_many :parrots_with_proc_callbacks, class_name: "Parrot",
before_add: proc { |p, pa| p.ship_log << "before_adding_proc_parrot_#{pa.id || '<new>'}" },
after_add: proc { |p, pa| p.ship_log << "after_adding_proc_parrot_#{pa.id || '<new>'}" },
before_remove: proc { |p, pa| p.ship_log << "before_removing_proc_parrot_#{pa.id}" },
after_remove: proc { |p, pa| p.ship_log << "after_removing_proc_parrot_#{pa.id}" }
has_and_belongs_to_many :autosaved_parrots, class_name: "Parrot", autosave: true
module PostTreasuresExtension
def build(attributes = {})
super({ name: "from extension" }.merge(attributes))
end
end
has_many :treasures, as: :looter, extend: PostTreasuresExtension
has_many :treasure_estimates, through: :treasures, source: :price_estimates
has_one :ship
has_one :update_only_ship, class_name: "Ship"
has_one :non_validated_ship, class_name: "Ship"
has_many :birds, -> { order("birds.id ASC") }
has_many :birds_with_method_callbacks, class_name: "Bird",
before_add: :log_before_add,
after_add: :log_after_add,
before_remove: :log_before_remove,
after_remove: :log_after_remove
has_many :birds_with_proc_callbacks, class_name: "Bird",
before_add: proc { |p, b| p.ship_log << "before_adding_proc_bird_#{b.id || '<new>'}" },
after_add: proc { |p, b| p.ship_log << "after_adding_proc_bird_#{b.id || '<new>'}" },
before_remove: proc { |p, b| p.ship_log << "before_removing_proc_bird_#{b.id}" },
after_remove: proc { |p, b| p.ship_log << "after_removing_proc_bird_#{b.id}" }
has_many :birds_with_reject_all_blank, class_name: "Bird"
has_one :foo_bulb, -> { where name: "foo" }, foreign_key: :car_id, class_name: "Bulb"
accepts_nested_attributes_for :parrots, :birds, allow_destroy: true, reject_if: proc(&:empty?)
accepts_nested_attributes_for :ship, allow_destroy: true, reject_if: proc(&:empty?)
accepts_nested_attributes_for :update_only_ship, update_only: true
accepts_nested_attributes_for :parrots_with_method_callbacks, :parrots_with_proc_callbacks,
:birds_with_method_callbacks, :birds_with_proc_callbacks, allow_destroy: true
accepts_nested_attributes_for :birds_with_reject_all_blank, reject_if: :all_blank
validates_presence_of :catchphrase
def ship_log
@ship_log ||= []
end
def reject_empty_ships_on_create(attributes)
attributes.delete("_reject_me_if_new").present? && !persisted?
end
attr_accessor :cancel_save_from_callback, :parrots_limit
before_save :cancel_save_callback_method, if: :cancel_save_from_callback
def cancel_save_callback_method
throw(:abort)
end
private
def log_before_add(record)
log(record, "before_adding_method")
end
def log_after_add(record)
log(record, "after_adding_method")
end
def log_before_remove(record)
log(record, "before_removing_method")
end
def log_after_remove(record)
log(record, "after_removing_method")
end
def log(record, callback)
ship_log << "#{callback}_#{record.class.name.downcase}_#{record.id || '<new>'}"
end
end
class DestructivePirate < Pirate
has_one :dependent_ship, class_name: "Ship", foreign_key: :pirate_id, dependent: :destroy
end
class FamousPirate < ActiveRecord::Base
self.table_name = "pirates"
has_many :famous_ships
validates_presence_of :catchphrase, on: :conference
end
| baerjam/rails | activerecord/test/models/pirate.rb | Ruby | mit | 3,929 |
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.0-rc4-master-c81f9f1
*/
goog.provide('ng.material.components.swipe');
goog.require('ng.material.core');
/**
* @ngdoc module
* @name material.components.swipe
* @description Swipe module!
*/
/**
* @ngdoc directive
* @module material.components.swipe
* @name mdSwipeLeft
*
* @restrict A
*
* @description
* The md-swipe-left directive allows you to specify custom behavior when an element is swiped
* left.
*
* @usage
* <hljs lang="html">
* <div md-swipe-left="onSwipeLeft()">Swipe me left!</div>
* </hljs>
*/
/**
* @ngdoc directive
* @module material.components.swipe
* @name mdSwipeRight
*
* @restrict A
*
* @description
* The md-swipe-right directive allows you to specify custom behavior when an element is swiped
* right.
*
* @usage
* <hljs lang="html">
* <div md-swipe-right="onSwipeRight()">Swipe me right!</div>
* </hljs>
*/
/**
* @ngdoc directive
* @module material.components.swipe
* @name mdSwipeUp
*
* @restrict A
*
* @description
* The md-swipe-up directive allows you to specify custom behavior when an element is swiped
* up.
*
* @usage
* <hljs lang="html">
* <div md-swipe-up="onSwipeUp()">Swipe me up!</div>
* </hljs>
*/
/**
* @ngdoc directive
* @module material.components.swipe
* @name mdSwipeDown
*
* @restrict A
*
* @description
* The md-swipe-down directive allows you to specify custom behavior when an element is swiped
* down.
*
* @usage
* <hljs lang="html">
* <div md-swipe-down="onSwipDown()">Swipe me down!</div>
* </hljs>
*/
angular.module('material.components.swipe', ['material.core'])
.directive('mdSwipeLeft', getDirective('SwipeLeft'))
.directive('mdSwipeRight', getDirective('SwipeRight'))
.directive('mdSwipeUp', getDirective('SwipeUp'))
.directive('mdSwipeDown', getDirective('SwipeDown'));
function getDirective(name) {
var directiveName = 'md' + name;
var eventName = '$md.' + name.toLowerCase();
DirectiveFactory.$inject = ["$parse"];
return DirectiveFactory;
/* ngInject */
function DirectiveFactory($parse) {
return { restrict: 'A', link: postLink };
function postLink(scope, element, attr) {
var fn = $parse(attr[directiveName]);
element.on(eventName, function(ev) {
scope.$apply(function() { fn(scope, { $event: ev }); });
});
}
}
}
ng.material.components.swipe = angular.module("material.components.swipe"); | JoPaRoRo/Fleet | web/assets/global/plugins/angular-material/modules/closure/swipe/swipe_1.js | JavaScript | mit | 2,501 |
import {
describe,
ddescribe,
it,
iit,
xit,
xdescribe,
expect,
beforeEach,
el
} from 'angular2/testing_internal';
import {EventManager, EventManagerPlugin} from 'angular2/platform/common_dom';
import {DomEventsPlugin} from 'angular2/src/platform/dom/events/dom_events';
import {NgZone} from 'angular2/src/core/zone/ng_zone';
import {ListWrapper, Map, MapWrapper} from 'angular2/src/facade/collection';
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
export function main() {
var domEventPlugin;
describe('EventManager', () => {
beforeEach(() => { domEventPlugin = new DomEventsPlugin(); });
it('should delegate event bindings to plugins that are passed in from the most generic one to the most specific one',
() => {
var element = el('<div></div>');
var handler = (e) => e;
var plugin = new FakeEventManagerPlugin(['click']);
var manager = new EventManager([domEventPlugin, plugin], new FakeNgZone());
manager.addEventListener(element, 'click', handler);
expect(plugin._eventHandler.get('click')).toBe(handler);
});
it('should delegate event bindings to the first plugin supporting the event', () => {
var element = el('<div></div>');
var clickHandler = (e) => e;
var dblClickHandler = (e) => e;
var plugin1 = new FakeEventManagerPlugin(['dblclick']);
var plugin2 = new FakeEventManagerPlugin(['click', 'dblclick']);
var manager = new EventManager([plugin2, plugin1], new FakeNgZone());
manager.addEventListener(element, 'click', clickHandler);
manager.addEventListener(element, 'dblclick', dblClickHandler);
expect(plugin1._eventHandler.has('click')).toBe(false);
expect(plugin2._eventHandler.get('click')).toBe(clickHandler);
expect(plugin2._eventHandler.has('dblclick')).toBe(false);
expect(plugin1._eventHandler.get('dblclick')).toBe(dblClickHandler);
});
it('should throw when no plugin can handle the event', () => {
var element = el('<div></div>');
var plugin = new FakeEventManagerPlugin(['dblclick']);
var manager = new EventManager([plugin], new FakeNgZone());
expect(() => manager.addEventListener(element, 'click', null))
.toThrowError('No event manager plugin found for event click');
});
it('events are caught when fired from a child', () => {
var element = el('<div><div></div></div>');
// Workaround for https://bugs.webkit.org/show_bug.cgi?id=122755
DOM.appendChild(DOM.defaultDoc().body, element);
var child = DOM.firstChild(element);
var dispatchedEvent = DOM.createMouseEvent('click');
var receivedEvent = null;
var handler = (e) => { receivedEvent = e; };
var manager = new EventManager([domEventPlugin], new FakeNgZone());
manager.addEventListener(element, 'click', handler);
DOM.dispatchEvent(child, dispatchedEvent);
expect(receivedEvent).toBe(dispatchedEvent);
});
it('should add and remove global event listeners', () => {
var element = el('<div><div></div></div>');
DOM.appendChild(DOM.defaultDoc().body, element);
var dispatchedEvent = DOM.createMouseEvent('click');
var receivedEvent = null;
var handler = (e) => { receivedEvent = e; };
var manager = new EventManager([domEventPlugin], new FakeNgZone());
var remover = manager.addGlobalEventListener("document", 'click', handler);
DOM.dispatchEvent(element, dispatchedEvent);
expect(receivedEvent).toBe(dispatchedEvent);
receivedEvent = null;
remover();
DOM.dispatchEvent(element, dispatchedEvent);
expect(receivedEvent).toBe(null);
});
});
}
class FakeEventManagerPlugin extends EventManagerPlugin {
_eventHandler = new Map<string, Function>();
constructor(public _supports: string[]) { super(); }
supports(eventName: string): boolean { return ListWrapper.contains(this._supports, eventName); }
addEventListener(element, eventName: string, handler: Function) {
this._eventHandler.set(eventName, handler);
return () => { this._eventHandler.delete(eventName); };
}
}
class FakeNgZone extends NgZone {
constructor() { super({enableLongStackTrace: false}); }
run(fn) { fn(); }
runOutsideAngular(fn) { return fn(); }
}
| robertmesserle/angular | modules/angular2/test/platform/dom/events/event_manager_spec.ts | TypeScript | mit | 4,328 |
<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
* @author Ivan Tcholakov <ivantcholakov@gmail.com>, 2015
* @license The MIT License, http://opensource.org/licenses/MIT
*/
class Bootstrap_modals_controller extends Base_Controller {
public function __construct() {
parent::__construct();
$this->template
->title('Bootstrap Modal Dialogs')
;
$this->registry->set('nav', 'playground');
}
public function index() {
$this->template
->inject_partial('css', css('lib/bootstrap3-dialog/bootstrap-dialog.min.css'))
->set_partial('scripts', 'bootstrap_modals_scripts')
->build('bootstrap_modals');
}
public function remote_html() {
$this->load->view('bootstrap_modals_remote_html');
}
}
| demenvil/starter-public-edition-4 | platform/applications/site_example/modules/playground/controllers/Bootstrap_modals_controller.php | PHP | mit | 837 |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v18.0.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LinkedList = (function () {
function LinkedList() {
this.first = null;
this.last = null;
}
LinkedList.prototype.add = function (item) {
var entry = {
item: item,
next: null
};
if (this.last) {
this.last.next = entry;
}
else {
this.first = entry;
}
this.last = entry;
};
LinkedList.prototype.remove = function () {
var result = this.first;
if (result) {
this.first = result.next;
if (!this.first) {
this.last = null;
}
}
return result.item;
};
LinkedList.prototype.isEmpty = function () {
return !this.first;
};
return LinkedList;
}());
exports.LinkedList = LinkedList;
var LinkedListItem = (function () {
function LinkedListItem() {
}
return LinkedListItem;
}());
| sashberd/cdnjs | ajax/libs/ag-grid/18.0.0/lib/misc/linkedList.js | JavaScript | mit | 1,186 |
/**
* This pagination style shows Previous/Next buttons, and page numbers only
* for "known" pages that are visited at least once time using [Next>] button.
* Initially only Prev/Next buttons are shown (Prev is initially disabled).
*
* [<Previous] [Next>]
*
* When user navigates through the pages using [Next>] button, navigation shows
* the numbers for the previous pages. As an example, when user reaches page 2,
* page numbers 1 and 2 are shown:
*
* [<Previous] 1 2 [Next>]
*
* When user reaches page 4, page numbers 1, 2, 3, and 4 are shown:
*
* [<Previous] 1 2 3 4 [Next>]
*
* When user navigates back, pagination will remember the last page number
* he reached and the numbesr up to the last known page are shown. As an example,
* when user returns to the page 2, page numbers 1, 2, 3, and 4 are still shown:
*
* [<Previous] 1 2 3 4 [Next>]
*
* This pagination style is designed for users who will not directly jump to
* the random page that they have not opened before. Assumption is that users
* will discover new pages using [Next>] button. This pagination enables users
* to easily go back and forth to any page that they discovered.
*
* Key benefit: This pagination supports usual pagination pattern and does not
* require server to return total count of items just to calculate last page and
* all numbers. This migh be huge performance benefit because server does not
* need to execute two queries in server-side processing mode:
* - One to get the records that will be shown on the current page,
* - Second to get the total count just to calculate full pagination.
*
* Without second query, page load time might be 2x faster, especially in cases
* when server can quickly get top 100 records, but it would need to scan entire
* database table just to calculate the total count and position of the last
* page. This pagination style is reasonable trade-off between simple and fullnumbers
* pagination.
*
* @name Simple Incremental navigation (Bootstrap)
* @summary Shows forward/back buttons and all known page numbers.
* @author [Jovan Popovic](http://github.com/JocaPC)
*
* @example
* $(document).ready(function() {
* $('#example').dataTable( {
* "pagingType": "simple_incremental_bootstrap"
* } );
* } );
*/
$.fn.dataTableExt.oPagination.simple_incremental_bootstrap = {
"fnInit": function (oSettings, nPaging, fnCallbackDraw) {
$(nPaging).prepend($("<ul class=\"pagination\"></ul>"));
var ul = $("ul", $(nPaging));
nFirst = document.createElement('li');
nPrevious = document.createElement('li');
nNext = document.createElement('li');
$(nPrevious).append($('<span>' + (oSettings.oLanguage.oPaginate.sPrevious) + '</span>'));
$(nFirst).append($('<span>1</span>'));
$(nNext).append($('<span>' + (oSettings.oLanguage.oPaginate.sNext) + '</span>'));
nFirst.className = "paginate_button first active";
nPrevious.className = "paginate_button previous";
nNext.className = "paginate_button next";
ul.append(nPrevious);
ul.append(nFirst);
ul.append(nNext);
$(nFirst).click(function () {
oSettings.oApi._fnPageChange(oSettings, "first");
fnCallbackDraw(oSettings);
});
$(nPrevious).click(function () {
if (!(oSettings._iDisplayStart === 0)) {
oSettings.oApi._fnPageChange(oSettings, "previous");
fnCallbackDraw(oSettings);
}
});
$(nNext).click(function () {
if(oSettings.aiDisplay.length < oSettings._iDisplayLength){
oSettings._iRecordsTotal = oSettings._iDisplayStart + oSettings.aiDisplay.length;
}else{
oSettings._iRecordsTotal = oSettings._iDisplayStart + oSettings._iDisplayLength + 1;
}
if (!(oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay()
||
oSettings.aiDisplay.length < oSettings._iDisplayLength)) {
oSettings.oApi._fnPageChange(oSettings, "next");
fnCallbackDraw(oSettings);
}
});
/* Disallow text selection */
$(nFirst).bind('selectstart', function () { return false; });
$(nPrevious).bind('selectstart', function () { return false; });
$(nNext).bind('selectstart', function () { return false; });
// Reset dynamically generated pages on length/filter change.
$(oSettings.nTable).DataTable().on('length.dt', function (e, settings, len) {
$("li.dynamic_page_item", nPaging).remove();
});
$(oSettings.nTable).DataTable().on('search.dt', function (e, settings, len) {
$("li.dynamic_page_item", nPaging).remove();
});
},
/*
* Function: oPagination.simple_incremental_bootstrap.fnUpdate
* Purpose: Update the list of page buttons shows
* Inputs: object:oSettings - dataTables settings object
* function:fnCallbackDraw - draw function which must be called on update
*/
"fnUpdate": function (oSettings, fnCallbackDraw) {
if (!oSettings.aanFeatures.p) {
return;
}
/* Loop over each instance of the pager */
var an = oSettings.aanFeatures.p;
for (var i = 0, iLen = an.length ; i < iLen ; i++) {
var buttons = an[i].getElementsByTagName('li');
$(buttons).removeClass("active");
if (oSettings._iDisplayStart === 0) {
buttons[0].className = "paginate_buttons disabled previous";
buttons[buttons.length - 1].className = "paginate_button enabled next";
} else {
buttons[0].className = "paginate_buttons enabled previous";
}
var page = Math.round(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1;
if (page == buttons.length-1 && oSettings.aiDisplay.length > 0) {
$new = $('<li class="dynamic_page_item active"><span>' + page + "</span></li>");
$(buttons[buttons.length - 1]).before($new);
$new.click(function () {
$(oSettings.nTable).DataTable().page(page-1);
fnCallbackDraw(oSettings);
});
} else
$(buttons[page]).addClass("active");
if (oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay()
||
oSettings.aiDisplay.length < oSettings._iDisplayLength) {
buttons[buttons.length - 1].className = "paginate_button disabled next";
}
}
}
};
| cdnjs/cdnjs | ajax/libs/datatables-plugins/1.11.5/pagination/simple_incremental_bootstrap.js | JavaScript | mit | 6,799 |
class PassengerStatus < Scout::Plugin
def build_report
cmd = option(:passenger_status_command) || "passenger-status"
data = `#{cmd} 2>&1`
if $?.success?
stats = parse_data(data)
report(stats)
else
error "Could not get data from command", "Error: #{data}"
end
end
private
def parse_data(data)
stats = {}
data.each_line do |line|
#line = line.gsub(/\e\[\d+m/,'')
if line =~ /^max\s+=\s(\d+)/
stats["max"] = $1
elsif line =~ /^count\s+=\s(\d+)/
stats["current"] = $1
elsif line =~ /^active\s+=\s(\d+)/
stats["active"] = $1
elsif line =~ /^inactive\s+=\s(\d+)/
stats["inactive"] = $1
elsif line =~ /^Waiting on global queue: (\d+)/
stats["gq_wait"] = $1
end
end
stats
end
end
| pingdomserver/scout-plugins | passenger_status/passenger_status.rb | Ruby | mit | 830 |
/**
* Copyright (c) 2014,2019 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.smarthome.binding.mqtt.discovery;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.eclipse.smarthome.io.transport.mqtt.MqttBrokerConnection;
/**
* Implement this interface to get notified of received values and vanished topics.
*
* @author David Graeff - Initial contribution
*/
@NonNullByDefault
public interface MQTTTopicDiscoveryParticipant {
/**
* Called whenever a message on the subscribed topic got published or a retained message was received.
*
* @param thingUID The MQTT thing UID of the Thing that established/created the given broker connection.
* @param connection The broker connection
* @param topic The topic
* @param payload The topic payload
*/
void receivedMessage(ThingUID thingUID, MqttBrokerConnection connection, String topic, byte[] payload);
/**
* A MQTT topic vanished.
*
* @param thingUID The MQTT thing UID of the Thing that established/created the given broker connection.
* @param connection The broker connection
* @param topic The topic
*/
void topicVanished(ThingUID thingUID, MqttBrokerConnection connection, String topic);
}
| Snickermicker/smarthome | extensions/binding/org.eclipse.smarthome.binding.mqtt/src/main/java/org/eclipse/smarthome/binding/mqtt/discovery/MQTTTopicDiscoveryParticipant.java | Java | epl-1.0 | 1,646 |
// license:BSD-3-Clause
// copyright-holders:Jim Stolis
/*
Arachnid - English Mark Darts
Driver by Jim Stolis.
--- Technical Notes ---
Name: English Mark Darts
Company: Arachnid, Inc.
Year: 1987/88/89/90
--- Hardware ---
A 6809 CPU (U3) is clocked by a 556 (U2) circuit with 3 Pin addressing decoding via a 74LS138 (U14)
Program ROM is a 27256 (U15)
Two 6821 PIAs (U4/U17) are used for I/O
Video is processed via a TMS9118 (U11) with two TMS4416 (U12/U13) as RAM
Main RAM is a 2K 6116 (U23) chip
Sound is generated via a PTM 6840 (U16) directly to an amplified speaker
--- Target Interface Board ---
The target interface board is used to combine 33 conductors from the switch matrix
into 16 conductors. The middle 13 pin connector is common to all switches.
3 connectors and their labels
EFBHDACGH NMPLMNJOMIKOP EBACFDCEAHB
Switch Matrix Table
Score Single Double Triple
1 DN EN FN
2 AL BL CL
3 AN BN CN
4 DL EL FL
5 AP BP CP
6 GL HL GP
7 DO EO FO
8 GI HI GM
9 AO BO CO
10 AI BI CI
11 AK BK CK
12 DP EP FP
13 AM BM CM
14 GK HK GO
15 GJ HJ GN
16 AJ BJ CJ
17 DM EM FM
18 DI EI FI
19 DJ EJ FJ
20 DK EK FK
Bull -- HM --
TODO:
- Dip Switches (Controls credits per coin), Currently 2 coins per credit
- Test Mode Won't Activate
- Layout with Lamps
- Default monitor is yellow/amber, no colour (board does have an extra
composite-out connector though, allowing a standard tv)
*/
#include "emu.h"
#include "cpu/m6809/m6809.h"
#include "machine/6821pia.h"
#include "machine/ram.h"
#include "machine/6840ptm.h"
#include "video/tms9928a.h"
#include "sound/speaker.h"
#define SCREEN_TAG "screen"
#define M6809_TAG "u3"
#define TMS9118_TAG "u11"
#define PIA6821_U4_TAG "u4"
#define PIA6821_U17_TAG "u17"
#define PTM6840_TAG "u16"
#define SPEAKER_TAG "speaker"
class arachnid_state : public driver_device
{
public:
arachnid_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag),
m_maincpu(*this, M6809_TAG),
m_pia_u4(*this, PIA6821_U4_TAG),
m_pia_u17(*this, PIA6821_U17_TAG),
m_speaker(*this, SPEAKER_TAG)
{ }
required_device<cpu_device> m_maincpu;
required_device<pia6821_device> m_pia_u4;
required_device<pia6821_device> m_pia_u17;
required_device<speaker_sound_device> m_speaker;
virtual void machine_start() override;
DECLARE_READ8_MEMBER( pia_u4_pa_r );
DECLARE_READ8_MEMBER( pia_u4_pb_r );
DECLARE_READ_LINE_MEMBER( pia_u4_pca_r );
DECLARE_READ_LINE_MEMBER( pia_u4_pcb_r );
DECLARE_WRITE8_MEMBER( pia_u4_pa_w );
DECLARE_WRITE8_MEMBER( pia_u4_pb_w );
DECLARE_WRITE_LINE_MEMBER( pia_u4_pca_w );
DECLARE_WRITE_LINE_MEMBER( pia_u4_pcb_w );
DECLARE_READ8_MEMBER( pia_u17_pa_r );
DECLARE_READ_LINE_MEMBER( pia_u17_pca_r );
DECLARE_WRITE8_MEMBER( pia_u17_pb_w );
DECLARE_WRITE_LINE_MEMBER( pia_u17_pcb_w );
DECLARE_WRITE8_MEMBER(ptm_o1_callback);
UINT8 read_keyboard(int pa);
};
/***************************************************************************
MEMORY MAPS
***************************************************************************/
/*-------------------------------------------------
ADDRESS_MAP( arachnid_map )
-------------------------------------------------*/
static ADDRESS_MAP_START( arachnid_map, AS_PROGRAM, 8, arachnid_state )
AM_RANGE(0x0000, 0x1fff) AM_RAM
AM_RANGE(0x2000, 0x2007) AM_DEVREADWRITE(PTM6840_TAG, ptm6840_device, read, write)
AM_RANGE(0x4004, 0x4007) AM_DEVREADWRITE(PIA6821_U4_TAG, pia6821_device, read, write)
AM_RANGE(0x4008, 0x400b) AM_DEVREADWRITE(PIA6821_U17_TAG, pia6821_device, read, write)
AM_RANGE(0x6000, 0x6000) AM_DEVWRITE(TMS9118_TAG, tms9928a_device, vram_write)
AM_RANGE(0x6002, 0x6002) AM_DEVWRITE(TMS9118_TAG, tms9928a_device, register_write)
AM_RANGE(0x8000, 0xffff) AM_ROM AM_REGION(M6809_TAG, 0)
ADDRESS_MAP_END
/***************************************************************************
INPUT PORTS
***************************************************************************/
/*-------------------------------------------------
INPUT_PORTS( arachnid )
-------------------------------------------------*/
static INPUT_PORTS_START( arachnid )
PORT_START("PA0-0")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Q) PORT_CHAR('Q') // SELECT
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA0-1")
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_W) PORT_CHAR('W') // PLAYER
PORT_BIT( 0xfd, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA0-2")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN1 ) // COIN
PORT_BIT( 0xfb, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA0-3")
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_T) PORT_CHAR('T') // TEST
PORT_BIT( 0xf7, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA0-4")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA0-5")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA0-6")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA0-7")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("SW1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Z) PORT_CHAR('Z') PORT_TOGGLE
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("SW2")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_X) PORT_CHAR('X') PORT_TOGGLE
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNUSED )
// Matrix Switch Part I
PORT_START("PA1-0")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_G) PORT_CHAR('G')
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA1-1")
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_H) PORT_CHAR('H')
PORT_BIT( 0xfd, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA1-2")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_E) PORT_CHAR('E')
PORT_BIT( 0xfb, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA1-3")
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F) PORT_CHAR('F')
PORT_BIT( 0xf7, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA1-4")
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_C) PORT_CHAR('C')
PORT_BIT( 0xef, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA1-5")
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_D) PORT_CHAR('D')
PORT_BIT( 0xdf, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA1-6")
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_A) PORT_CHAR('A')
PORT_BIT( 0xbf, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA1-7")
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_B) PORT_CHAR('B')
PORT_BIT( 0x7f, IP_ACTIVE_LOW, IPT_UNUSED )
// Matrix Switch Part II
PORT_START("PB1-0")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_J) PORT_CHAR('J')
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PB1-1")
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_I) PORT_CHAR('I')
PORT_BIT( 0xfd, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PB1-2")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_L) PORT_CHAR('L')
PORT_BIT( 0xfb, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PB1-3")
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_K) PORT_CHAR('K')
PORT_BIT( 0xf7, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PB1-4")
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_N) PORT_CHAR('N')
PORT_BIT( 0xef, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PB1-5")
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_M) PORT_CHAR('M')
PORT_BIT( 0xdf, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PB1-6")
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_P) PORT_CHAR('P')
PORT_BIT( 0xbf, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PB1-7")
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_O) PORT_CHAR('O')
PORT_BIT( 0x7f, IP_ACTIVE_LOW, IPT_UNUSED )
INPUT_PORTS_END
/***************************************************************************
DEVICE CONFIGURATION
***************************************************************************/
/*-------------------------------------------------
ptm6840_interface ptm_intf
-------------------------------------------------*/
WRITE8_MEMBER(arachnid_state::ptm_o1_callback)
{
m_speaker->level_w(data);
}
UINT8 arachnid_state::read_keyboard(int pa)
{
int i;
UINT8 value;
static const char *const keynames[3][8] =
{
{ "PA0-0", "PA0-1", "PA0-2", "PA0-3", "PA0-4", "PA0-5", "PA0-6", "PA0-7" },
{ "PA1-0", "PA1-1", "PA1-2", "PA1-3", "PA1-4", "PA1-5", "PA1-6", "PA1-7" },
{ "PB1-0", "PB1-1", "PB1-2", "PB1-3", "PB1-4", "PB1-5", "PB1-6", "PB1-7" }
};
for (i = 0; i < 8; i++)
{
value = ioport(keynames[pa][i])->read();
if (value != 0xff)
{
if (value == 0xff - (1 << i))
return value;
else
return value - (1 << i);
}
}
return 0xff;
}
READ8_MEMBER( arachnid_state::pia_u4_pa_r )
{
// Pulses from Switch Matrix Part I
// PA0 - G
// PA1 - H
// PA2 - E
// PA3 - F
// PA4 - C
// PA5 - D
// PA6 - A
// PA7 - B
UINT8 data = 0xff;
data &= read_keyboard(1);
return data;
}
READ8_MEMBER( arachnid_state::pia_u4_pb_r )
{
// Pulses from Switch Matrix Part II
// PB0 - J
// PB1 - I
// PB2 - L
// PB3 - K
// PB4 - N
// PB5 - M
// PB6 - P
// PB7 - O
UINT8 data = 0xff;
data &= read_keyboard(2);
return data;
}
READ_LINE_MEMBER( arachnid_state::pia_u4_pca_r )
{
// CA1 - SW1 Coin In (Coin Door)
UINT8 data = 1;
data &= ioport("SW1")->read();
return data;
}
READ_LINE_MEMBER( arachnid_state::pia_u4_pcb_r )
{
// CB1 - SW2 Test Mode (Coin Door)
UINT8 data = 1;
data &= ioport("SW2")->read();
return data;
}
READ8_MEMBER( arachnid_state::pia_u17_pa_r )
{
// PA0 - Select
// PA1 - Player Change
// PA2 - Coin
// PA3 - Test
// PA4 thru PA7 - DIP SW1
UINT8 data = 0xff;
data &= read_keyboard(0);
return data;
}
READ_LINE_MEMBER( arachnid_state::pia_u17_pca_r )
{
// CA1 - 1000 HZ Input
UINT8 data = 1;
return data;
}
WRITE8_MEMBER( arachnid_state::pia_u4_pa_w )
{
// PA0 thru PA7 Pulses to Switch Matrix Part I
}
WRITE8_MEMBER( arachnid_state::pia_u4_pb_w )
{
// PA0 thru PA7 Pulses to Switch Matrix Part II
}
WRITE_LINE_MEMBER( arachnid_state::pia_u4_pca_w )
{
// CA1 - Remove Darts Lamp
}
WRITE_LINE_MEMBER( arachnid_state::pia_u4_pcb_w )
{
// CB2 - Throw Darts Lamp
}
WRITE8_MEMBER( arachnid_state::pia_u17_pb_w )
{
// PB0 - Select Lamp
// PB1 - Player Change Lamp
// PB2 - Not Used
// PB3 - Not Used
// PB4 - Not Used
// PB5 - Not Used
// PB6 - Not Used
// PB7 - N/C
}
WRITE_LINE_MEMBER( arachnid_state::pia_u17_pcb_w )
{
// CB2 - Target Lamp
}
/***************************************************************************
MACHINE INITIALIZATION
***************************************************************************/
/*-------------------------------------------------
MACHINE_START( arachnid )
-------------------------------------------------*/
void arachnid_state::machine_start()
{
}
/***************************************************************************
MACHINE DRIVERS
***************************************************************************/
/*-------------------------------------------------
MACHINE_CONFIG_START( arachnid, arachnid_state )
-------------------------------------------------*/
static MACHINE_CONFIG_START( arachnid, arachnid_state )
// basic machine hardware
MCFG_CPU_ADD(M6809_TAG, M6809, XTAL_1MHz)
MCFG_CPU_PROGRAM_MAP(arachnid_map)
// devices
MCFG_DEVICE_ADD(PIA6821_U4_TAG, PIA6821, 0)
MCFG_PIA_READPA_HANDLER(READ8(arachnid_state, pia_u4_pa_r))
MCFG_PIA_READPB_HANDLER(READ8(arachnid_state, pia_u4_pb_r))
MCFG_PIA_READCA1_HANDLER(READLINE(arachnid_state, pia_u4_pca_r))
MCFG_PIA_READCB1_HANDLER(READLINE(arachnid_state, pia_u4_pcb_r))
MCFG_PIA_WRITEPA_HANDLER(WRITE8(arachnid_state, pia_u4_pa_w))
MCFG_PIA_WRITEPB_HANDLER(WRITE8(arachnid_state, pia_u4_pb_w))
MCFG_PIA_CA2_HANDLER(WRITELINE(arachnid_state, pia_u4_pca_w))
MCFG_PIA_CB2_HANDLER(WRITELINE(arachnid_state, pia_u4_pcb_w))
MCFG_DEVICE_ADD(PIA6821_U17_TAG, PIA6821, 0)
MCFG_PIA_READPA_HANDLER(READ8(arachnid_state, pia_u17_pa_r))
MCFG_PIA_READCA1_HANDLER(READLINE(arachnid_state, pia_u17_pca_r))
MCFG_PIA_WRITEPB_HANDLER(WRITE8(arachnid_state, pia_u17_pb_w))
MCFG_PIA_CB2_HANDLER(WRITELINE(arachnid_state, pia_u17_pcb_w))
// video hardware
MCFG_DEVICE_ADD( TMS9118_TAG, TMS9118, XTAL_10_738635MHz / 2 )
MCFG_TMS9928A_VRAM_SIZE(0x4000)
MCFG_TMS9928A_OUT_INT_LINE_CB(INPUTLINE(M6809_TAG, INPUT_LINE_IRQ0))
MCFG_TMS9928A_SCREEN_ADD_NTSC( SCREEN_TAG )
MCFG_SCREEN_UPDATE_DEVICE( TMS9118_TAG, tms9118_device, screen_update )
// sound hardware
MCFG_SPEAKER_STANDARD_MONO("mono")
MCFG_SOUND_ADD("speaker", SPEAKER_SOUND, 0)
MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0)
MCFG_DEVICE_ADD(PTM6840_TAG, PTM6840, 0)
MCFG_PTM6840_INTERNAL_CLOCK(XTAL_8MHz / 4)
MCFG_PTM6840_EXTERNAL_CLOCKS(0, 0, 0)
MCFG_PTM6840_OUT0_CB(WRITE8(arachnid_state, ptm_o1_callback))
MACHINE_CONFIG_END
/***************************************************************************
ROMS
***************************************************************************/
ROM_START( arac6000 )
ROM_REGION( 0x8000, M6809_TAG, 0 )
ROM_LOAD( "01-0140-6300-v2.7-19910208.u15", 0x0000, 0x8000, CRC(f1c4412d) SHA1(6ff9a8f25f315c2df5c0785043521d036ec0964e) )
ROM_END
/***************************************************************************
SYSTEM DRIVERS
***************************************************************************/
/* YEAR NAME PARENT COMPAT MACHINE INPUT INIT COMPANY FULLNAME */
GAME( 1990, arac6000, 0, arachnid, arachnid, driver_device, 0, ROT0, "Arachnid", "Super Six Plus II English Mark Darts", MACHINE_MECHANICAL | MACHINE_NOT_WORKING )
| h0tw1r3/mame | src/mame/drivers/arachnid.cpp | C++ | gpl-2.0 | 14,284 |
<?php
/**
* @version $Id: ucwords.php 10381 2008-06-01 03:35:53Z pasamio $
* @package utf8
* @subpackage strings
*/
//---------------------------------------------------------------
/**
* UTF-8 aware alternative to ucwords
* Uppercase the first character of each word in a string
* Note: requires utf8_substr_replace and utf8_strtoupper
* @param string
* @return string with first char of each word uppercase
* @see http://www.php.net/ucwords
* @package utf8
* @subpackage strings
*/
function utf8_ucwords($str) {
// Note: [\x0c\x09\x0b\x0a\x0d\x20] matches;
// form feeds, horizontal tabs, vertical tabs, linefeeds and carriage returns
// This corresponds to the definition of a "word" defined at http://www.php.net/ucwords
$pattern = '/(^|([\x0c\x09\x0b\x0a\x0d\x20]+))([^\x0c\x09\x0b\x0a\x0d\x20]{1})[^\x0c\x09\x0b\x0a\x0d\x20]*/u';
return preg_replace_callback($pattern, 'utf8_ucwords_callback',$str);
}
//---------------------------------------------------------------
/**
* Callback function for preg_replace_callback call in utf8_ucwords
* You don't need to call this yourself
* @param array of matches corresponding to a single word
* @return string with first char of the word in uppercase
* @see utf8_ucwords
* @see utf8_strtoupper
* @package utf8
* @subpackage strings
*/
function utf8_ucwords_callback($matches) {
$leadingws = $matches[2];
$ucfirst = utf8_strtoupper($matches[3]);
$ucword = utf8_substr_replace(ltrim($matches[0]),$ucfirst,0,1);
return $leadingws . $ucword;
}
| viollarr/alab | site2011/libraries/phputf8/ucwords.php | PHP | gpl-2.0 | 1,571 |
package org.checkerframework.checker.regex.qual;
import org.checkerframework.qualframework.poly.SimpleQualifierParameterAnnotationConverter;
import org.checkerframework.qualframework.poly.qual.Wildcard;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Var is a qualifier parameter use.
*
* @see org.checkerframework.checker.tainting.qual.Var
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
@Repeatable(MultiVar.class)
public @interface Var {
/**
* Which parameter this @Var is a use of.
*/
String arg() default SimpleQualifierParameterAnnotationConverter.PRIMARY_TARGET;
/**
* The name of the parameter to set.
*/
String param() default SimpleQualifierParameterAnnotationConverter.PRIMARY_TARGET;
/**
* Specify that this use is a wildcard with a bound.
*/
Wildcard wildcard() default Wildcard.NONE;
}
| renatoathaydes/checker-framework | checker/src/org/checkerframework/checker/regex/qual/Var.java | Java | gpl-2.0 | 1,075 |
<?php if (!defined('W3TC')) die(); ?>
<?php include W3TC_INC_DIR . '/options/common/header.php'; ?>
<div id="about">
<p><?php _e('User experience is an important aspect of every web site and all web sites can benefit from effective caching and file size reduction. We have applied web site optimization methods typically used with high traffic sites and simplified their implementation. Coupling these methods either <a href="http://www.danga.com/memcached/" target="_blank">memcached</a> and/or opcode caching and the <acronym title="Content Delivery Network">CDN</acronym> of your choosing to provide the following features and benefits:') ?></p>
<ul>
<li><?php _e('Improved Google search engine ranking', 'w3-total-cache'); ?></li>
<li><?php _e('Increased visitor time on site', 'w3-total-cache'); ?></li>
<li><?php _e('Optimized progressive render (pages start rendering immediately)', 'w3-total-cache'); ?></li>
<li><?php _e('Reduced <acronym title="Hypertext Transfer Protocol">HTTP</acronym> Transactions, <acronym title="Domain Name System">DNS</acronym> lookups and reduced document load time', 'w3-total-cache'); ?></li>
<li><?php _e('Bandwidth savings via Minify and <acronym title="Hypertext Transfer Protocol">HTTP</acronym> compression of <acronym title="Hypertext Markup Language">HTML</acronym>, <acronym title="Cascading Style Sheet">CSS</acronym>, JavaScript and feeds', 'w3-total-cache'); ?></li>
<li><?php _e('Increased web server concurrency and increased scale (easily sustain high traffic spikes)', 'w3-total-cache'); ?></li>
<li><?php _e('Transparent content delivery network (<acronym title="Content Delivery Network">CDN</acronym>) integration with Media Library, theme files and WordPress core', 'w3-total-cache'); ?></li>
<li><?php _e('Caching of pages / posts in memory or on disk or on CDN (mirror only)', 'w3-total-cache'); ?></li>
<li><?php _e('Caching of (minified) <acronym title="Cascading Style Sheet">CSS</acronym> and JavaScript in memory, on disk or on <acronym title="Content Delivery Network">CDN</acronym>', 'w3-total-cache'); ?></li>
<li><?php _e('Caching of database objects in memory or on disk', 'w3-total-cache'); ?></li>
<li><?php _e('Caching of objects in memory or on disk', 'w3-total-cache'); ?></li>
<li><?php _e('Caching of feeds (site, categories, tags, comments, search results) in memory or on disk', 'w3-total-cache'); ?></li>
<li><?php _e('Caching of search results pages (i.e. <acronym title="Uniform Resource Identifier">URI</acronym>s with query string variables) in memory or on disk', 'w3-total-cache'); ?></li>
<li><?php _e('Minification of posts / pages and feeds', 'w3-total-cache'); ?></li>
<li><?php _e('Minification (concatenation and white space removal) of inline, external or 3rd party JavaScript / <acronym title="Cascading Style Sheet">CSS</acronym> with automated updates', 'w3-total-cache'); ?></li>
<li><?php _e('Complete header management including <a href="http://en.wikipedia.org/wiki/HTTP_ETag">Etags</a>', 'w3-total-cache'); ?></li>
<li><?php _e('JavaScript embedding group and location management', 'w3-total-cache'); ?></li>
<li><?php _e('Import post attachments directly into the Media Library (and <acronym title="Content Delivery Network">CDN</acronym>)', 'w3-total-cache'); ?></li>
</ul>
<p><?php _e('Your users have less data to download, you can now serve more visitors at once without upgrading your hardware and you don\'t have to change how you do anything; just set it and forget it.', 'w3-total-cache'); ?></p>
<h4><?php _e('Who do I thank for all of this?', 'w3-total-cache'); ?></h4>
<p><?php _e('It\'s quite difficult to recall all of the innovators that have shared their thoughts, code and experiences in the blogosphere over the years, but here are some names to get you started:', 'w3-total-cache'); ?></p>
<ul>
<li><a href="http://stevesouders.com/" target="_blank">Steve Souders</a></li>
<li><a href="http://mrclay.org/" target="_blank">Steve Clay</a></li>
<li><a href="http://wonko.com/" target="_blank">Ryan Grove</a></li>
<li><a href="http://www.nczonline.net/blog/2009/06/23/loading-javascript-without-blocking/" target="_blank">Nicholas Zakas</a> </li>
<li><a href="http://rtdean.livejournal.com/" target="_blank">Ryan Dean</a></li>
<li><a href="http://gravitonic.com/" target="_blank">Andrei Zmievski</a></li>
<li>George Schlossnagle</li>
<li>Daniel Cowgill</li>
<li><a href="http://toys.lerdorf.com/" target="_blank">Rasmus Lerdorf</a></li>
<li><a href="http://t3.dotgnu.info/" target="_blank">Gopal Vijayaraghavan</a></li>
<li><a href="http://eaccelerator.net/" target="_blank">Bart Vanbraban</a></li>
<li><a href="http://xcache.lighttpd.net/" target="_blank">mOo</a></li>
</ul>
<p><?php _e('Please reach out to all of these people and support their projects if you\'re so inclined.', 'w3-total-cache'); ?></p>
</div>
<?php include W3TC_INC_DIR . '/options/common/footer.php'; ?> | victorsenam/vempraruaorg | wp-content/plugins/w3-total-cache/inc/options/about.php | PHP | gpl-2.0 | 5,067 |
<?php
/*
* @package Joomla.Framework
* @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*
* @component Phoca Component
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License version 2 or later;
*/
defined('_JEXEC') or die();
jimport( 'joomla.application.component.view');
class PhocaGalleryViewMap extends JViewLegacy
{
public $tmpl;
protected $params;
function display($tpl = null) {
$app = JFactory::getApplication();
$document = JFactory::getDocument();
$this->params = $app->getParams();
// PLUGIN WINDOW - we get information from plugin
$get = '';
$get['map'] = $app->input->get( 'map', '', 'string' );
$this->itemId = $app->input->get('Itemid', 0, 'int');
// Multibox
$get['mapwidth'] = $app->input->get( 'mapwidth', '', 'string' );
$get['mapheight'] = $app->input->get( 'mapheight', '', 'string' );
$this->tmpl['enable_multibox'] = $this->params->get( 'enable_multibox', 0);
$this->tmpl['enable_multibox_iframe'] = 0;
if ($get['mapwidth'] != '') {
// Seems we are in iframe
$this->tmpl['enable_multibox_iframe'] = 1;
}
$this->tmpl['enablecustomcss'] = $this->params->get( 'enable_custom_css', 0);
$this->tmpl['customcss'] = $this->params->get( 'custom_css', '');
// CSS
PhocaGalleryRenderFront::renderAllCSS();
// PARAMS - Open window parameters - modal popup box or standard popup window
$this->tmpl['detailwindow'] = $this->params->get( 'detail_window', 0 );
// Plugin information
if (isset($get['map']) && $get['map'] != '') {
$this->tmpl['detailwindow'] = $get['map'];
}
// Close and Reload links (for different window types)
$close = PhocaGalleryRenderFront::renderCloseReloadDetail($this->tmpl['detailwindow']);
$detail_window_close = $close['detailwindowclose'];
$detail_window_reload = $close['detailwindowreload'];
// PARAMS - Display Description in Detail window - set the font color
$this->tmpl['detailwindow'] = $this->params->get( 'detail_window', 0 );
$this->tmpl['detailwindowbackgroundcolor']= $this->params->get( 'detail_window_background_color', '#ffffff' );
$description_lightbox_font_color = $this->params->get( 'description_lightbox_font_color', '#ffffff' );
$description_lightbox_bg_color = $this->params->get( 'description_lightbox_bg_color', '#000000' );
$description_lightbox_font_size = $this->params->get( 'description_lightbox_font_size', 12 );
$this->tmpl['gallerymetakey'] = $this->params->get( 'gallery_metakey', '' );
$this->tmpl['gallerymetadesc'] = $this->params->get( 'gallery_metadesc', '' );
if ($this->tmpl['gallerymetakey'] != '') {
$document->setMetaData('keywords', $this->tmpl['gallerymetakey']);
}
if ($this->tmpl['gallerymetadesc'] != '') {
$document->setMetaData('description', $this->tmpl['gallerymetadesc']);
}
// NO SCROLLBAR IN DETAIL WINDOW
if ($this->tmpl['detailwindow'] == 7) {
} else {
$document->addCustomTag( "<style type=\"text/css\"> \n"
." html,body, .contentpane{overflow:hidden;background:".$this->tmpl['detailwindowbackgroundcolor'].";} \n"
." center, table {background:".$this->tmpl['detailwindowbackgroundcolor'].";} \n"
." #sbox-window {background-color:#fff;padding:5px} \n"
." </style> \n");
}
// PARAMS - Get image height and width
$this->tmpl['largemapwidth'] = (int)$this->params->get( 'front_modal_box_width', 680 ) - 40;
$this->tmpl['largemapheight'] = (int)$this->params->get( 'front_modal_box_height', 560 ) - 20;
// Multibox
if (isset($get['mapwidth']) && $get['mapwidth'] != '') {
$this->tmpl['largemapwidth'] = $get['mapwidth'];
}
if (isset($get['mapheight']) && $get['mapheight'] != '') {
$this->tmpl['largemapheight'] = $get['mapheight'];
}
// $this->tmpl['googlemapsapikey'] = $this->params->get( 'google_maps_api_key', '' );
// MODEL
$model = $this->getModel();
$map = $model->getData();
phocagalleryimport('phocagallery.image.imagefront');
if (!empty($map)) {
if (isset($map->filename) && $map->filename != '') {
$file_thumbnail = PhocaGalleryImageFront::displayCategoryImageOrNoImage($map->filename, 'small');
$map->thumbnail = $file_thumbnail;
} else {
$map->thumbnail = '';
}
if (isset($map->latitude) && $map->latitude != '' && $map->latitude != 0
&& isset($map->longitude) && $map->longitude != '' && $map->longitude != 0 ) {
} else {
$map->longitude = '';
$map->latitude = '';
$map->zoom = 2;
$map->geotitle = '';
}
}
// Second try to get category data
if ((empty($map)) || ($map->longitude == '' && $map->latitude == '' && $map->geotitle == '')) {
$map = $model->getDataCategory();
if (!empty($map)) {
if (isset($map->latitude) && $map->latitude != '' && $map->latitude != 0
&& isset($map->longitude) && $map->longitude != '' && $map->longitude != 0 ) {
$map->thumbnail = '';
if ($map->geotitle == '') {
$map->geotitle = $map->title;
}
} else {
$map->longitude = '';
$map->latitude = '';
$map->zoom = 2;
$map->geotitle = '';
}
} else {
$map->longitude = '';
$map->latitude = '';
$map->zoom = 2;
$map->geotitle = '';
$map->catslug = '';
}
}
// Back button
$this->tmpl['backbutton'] = '';
if ($this->tmpl['detailwindow'] == 7) {
phocagalleryimport('phocagallery.image.image');
$this->tmpl['backbutton'] = '<div><a href="'.JRoute::_('index.php?option=com_phocagallery&view=category&id='. $map->catslug.'&Itemid='. $app->input->get('Itemid', 0, 'int')).'"'
.' title="'.JText::_( 'COM_PHOCAGALLERY_BACK_TO_CATEGORY' ).'">'
. JHtml::_('image', 'media/com_phocagallery/images/icon-up-images.png', JText::_( 'COM_PHOCAGALLERY_BACK_TO_CATEGORY' )).'</a></div>';
}
// ASIGN
$this->assignRef( 'tmpl', $this->tmpl );
$this->assignRef( 'map', $map );
$this->_prepareDocument($map);
parent::display($tpl);
}
protected function _prepareDocument($item) {
$app = JFactory::getApplication();
$menus = $app->getMenu();
$pathway = $app->getPathway();
$this->params = $app->getParams();
$title = null;
$this->tmpl['gallerymetakey'] = $this->params->get( 'gallery_metakey', '' );
$this->tmpl['gallerymetadesc'] = $this->params->get( 'gallery_metadesc', '' );
$menu = $menus->getActive();
if ($menu) {
$this->params->def('page_heading', $this->params->get('page_title', $menu->title));
} else {
$this->params->def('page_heading', JText::_('JGLOBAL_ARTICLES'));
}
$title = $this->params->get('page_title', '');
if (empty($title)) {
$title = htmlspecialchars_decode($app->getCfg('sitename'));
} else if ($app->getCfg('sitename_pagetitles', 0) == 1) {
$title = JText::sprintf('JPAGETITLE', htmlspecialchars_decode($app->getCfg('sitename')), $title);
if (isset($item->title) && $item->title != '') {
$title = $title .' - ' . $item->title;
}
} else if ($app->getCfg('sitename_pagetitles', 0) == 2) {
if (isset($item->title) && $item->title != '') {
$title = $title .' - ' . $item->title;
}
$title = JText::sprintf('JPAGETITLE', $title, htmlspecialchars_decode($app->getCfg('sitename')));
}
$this->document->setTitle($title);
/*
if ($item->metadesc != '') {
$this->document->setDescription($item->metadesc);
} else */ if ($this->tmpl['gallerymetadesc'] != '') {
$this->document->setDescription($this->tmpl['gallerymetadesc']);
} else if ($this->params->get('menu-meta_description', '')) {
$this->document->setDescription($this->params->get('menu-meta_description', ''));
}
/*
if ($item->metakey != '') {
$this->document->setMetadata('keywords', $item->metakey);
} else*/ if ($this->tmpl['gallerymetakey'] != '') {
$this->document->setMetadata('keywords', $this->tmpl['gallerymetakey']);
} else if ($this->params->get('menu-meta_keywords', '')) {
$this->document->setMetadata('keywords', $this->params->get('menu-meta_keywords', ''));
}
if ($app->getCfg('MetaTitle') == '1' && $this->params->get('menupage_title', '')) {
$this->document->setMetaData('title', $this->params->get('page_title', ''));
}
/*if ($app->getCfg('MetaAuthor') == '1') {
$this->document->setMetaData('author', $this->item->author);
}
/*$mdata = $this->item->metadata->toArray();
foreach ($mdata as $k => $v) {
if ($v) {
$this->document->setMetadata($k, $v);
}
}*/
// Breadcrumbs TODO (Add the whole tree)
/*if (isset($this->category[0]->parentid)) {
if ($this->category[0]->parentid == 1) {
} else if ($this->category[0]->parentid > 0) {
$pathway->addItem($this->category[0]->parenttitle, JRoute::_(PhocaDocumentationHelperRoute::getCategoryRoute($this->category[0]->parentid, $this->category[0]->parentalias)));
}
}
if (!empty($this->category[0]->title)) {
$pathway->addItem($this->category[0]->title);
}*/
}
}
?> | xbegault/clrh-idf | tmp/install_56542e012168b/site/views/map/view.html.php | PHP | gpl-2.0 | 9,126 |
/*
This file is part of Cyclos (www.cyclos.org).
A project of the Social Trade Organisation (www.socialtrade.org).
Cyclos 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.
Cyclos 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 Cyclos; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package nl.strohalm.cyclos.controls.access.transactionpassword;
import javax.servlet.http.HttpServletRequest;
import nl.strohalm.cyclos.controls.ActionContext;
import nl.strohalm.cyclos.controls.BaseFormAction;
import nl.strohalm.cyclos.entities.access.OperatorUser;
import nl.strohalm.cyclos.entities.access.TransactionPassword;
import nl.strohalm.cyclos.entities.access.User;
import nl.strohalm.cyclos.entities.members.Element;
import nl.strohalm.cyclos.entities.members.Operator;
import nl.strohalm.cyclos.services.elements.ResetTransactionPasswordDTO;
import nl.strohalm.cyclos.utils.ActionHelper;
import nl.strohalm.cyclos.utils.RelationshipHelper;
import nl.strohalm.cyclos.utils.RequestHelper;
import nl.strohalm.cyclos.utils.validation.ValidationException;
import org.apache.struts.action.ActionForward;
/**
* Action used to reset a member's transaction password
* @author luis
*/
public class ManageTransactionPasswordAction extends BaseFormAction {
@Override
protected ActionForward handleDisplay(final ActionContext context) throws Exception {
final HttpServletRequest request = context.getRequest();
final ManageTransactionPasswordForm form = context.getForm();
final User user = retrieveUser(context);
boolean canReset = false;
boolean canBlock = false;
switch (user.getTransactionPasswordStatus()) {
case ACTIVE:
canReset = true;
canBlock = true;
break;
case BLOCKED:
canReset = true;
break;
case PENDING:
canBlock = true;
break;
case NEVER_CREATED:
if (user.getElement().getGroup().getBasicSettings().getTransactionPassword() == TransactionPassword.MANUAL) {
canReset = true;
}
break;
}
request.setAttribute("groupStatus", user.getElement().getGroup().getBasicSettings().getTransactionPassword());
request.setAttribute("user", user);
request.setAttribute("canReset", canReset);
request.setAttribute("canBlock", canBlock);
RequestHelper.storeEnum(request, TransactionPassword.class, "globalTransactionPasswordStatus");
RequestHelper.storeEnum(request, User.TransactionPasswordStatus.class, "userTransactionPasswordStatus");
if (form.isEmbed()) {
return new ActionForward("/pages/access/transactionPassword/manageTransactionPassword.jsp");
} else {
return context.getInputForward();
}
}
@Override
protected ActionForward handleSubmit(final ActionContext context) throws Exception {
final ManageTransactionPasswordForm form = context.getForm();
User user = retrieveUser(context);
final boolean block = form.isBlock();
final ResetTransactionPasswordDTO dto = new ResetTransactionPasswordDTO();
dto.setUser(user);
dto.setAllowGeneration(!block);
user = accessService.resetTransactionPassword(dto);
context.sendMessage(block ? "transactionPassword.blocked" : "transactionPassword.reset");
return ActionHelper.redirectWithParam(context.getRequest(), context.getSuccessForward(), "userId", user.getId());
}
private User retrieveUser(final ActionContext context) {
final HttpServletRequest request = context.getRequest();
if (request.getAttribute("element") != null) {
// The element may be already retrieved on the manage passwords action
return ((Element) request.getAttribute("element")).getUser();
}
final ManageTransactionPasswordForm form = context.getForm();
User user;
final long userId = form.getUserId();
try {
user = elementService.loadUser(userId, RelationshipHelper.nested(User.Relationships.ELEMENT, Element.Relationships.GROUP));
if (user instanceof OperatorUser) {
Element element = user.getElement();
element = elementService.load(element.getId(), RelationshipHelper.nested(Operator.Relationships.MEMBER, Element.Relationships.GROUP));
}
} catch (final Exception e) {
throw new ValidationException();
}
return user;
}
}
| robertoandrade/cyclos | src/nl/strohalm/cyclos/controls/access/transactionpassword/ManageTransactionPasswordAction.java | Java | gpl-2.0 | 5,153 |
/* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Soft-core version: Agilio Padua (Univ Blaise Pascal & CNRS)
------------------------------------------------------------------------- */
#include "math.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "pair_coul_cut_soft.h"
#include "atom.h"
#include "comm.h"
#include "force.h"
#include "neighbor.h"
#include "neigh_list.h"
#include "memory.h"
#include "error.h"
using namespace LAMMPS_NS;
/* ---------------------------------------------------------------------- */
PairCoulCutSoft::PairCoulCutSoft(LAMMPS *lmp) : Pair(lmp) {}
/* ---------------------------------------------------------------------- */
PairCoulCutSoft::~PairCoulCutSoft()
{
if (allocated) {
memory->destroy(setflag);
memory->destroy(cutsq);
memory->destroy(cut);
memory->destroy(lambda);
memory->destroy(lam1);
memory->destroy(lam2);
}
}
/* ---------------------------------------------------------------------- */
void PairCoulCutSoft::compute(int eflag, int vflag)
{
int i,j,ii,jj,inum,jnum,itype,jtype;
double qtmp,xtmp,ytmp,ztmp,delx,dely,delz,ecoul,fpair;
double rsq,forcecoul,factor_coul;
double denc;
int *ilist,*jlist,*numneigh,**firstneigh;
ecoul = 0.0;
if (eflag || vflag) ev_setup(eflag,vflag);
else evflag = vflag_fdotr = 0;
double **x = atom->x;
double **f = atom->f;
double *q = atom->q;
int *type = atom->type;
int nlocal = atom->nlocal;
double *special_coul = force->special_coul;
int newton_pair = force->newton_pair;
double qqrd2e = force->qqrd2e;
inum = list->inum;
ilist = list->ilist;
numneigh = list->numneigh;
firstneigh = list->firstneigh;
// loop over neighbors of my atoms
for (ii = 0; ii < inum; ii++) {
i = ilist[ii];
qtmp = q[i];
xtmp = x[i][0];
ytmp = x[i][1];
ztmp = x[i][2];
itype = type[i];
jlist = firstneigh[i];
jnum = numneigh[i];
for (jj = 0; jj < jnum; jj++) {
j = jlist[jj];
factor_coul = special_coul[sbmask(j)];
j &= NEIGHMASK;
delx = xtmp - x[j][0];
dely = ytmp - x[j][1];
delz = ztmp - x[j][2];
rsq = delx*delx + dely*dely + delz*delz;
jtype = type[j];
if (rsq < cutsq[itype][jtype]) {
denc = sqrt(lam2[itype][jtype] + rsq);
forcecoul = qqrd2e * lam1[itype][jtype] * qtmp*q[j] / (denc*denc*denc);
fpair = factor_coul*forcecoul;
f[i][0] += delx*fpair;
f[i][1] += dely*fpair;
f[i][2] += delz*fpair;
if (newton_pair || j < nlocal) {
f[j][0] -= delx*fpair;
f[j][1] -= dely*fpair;
f[j][2] -= delz*fpair;
}
if (eflag)
ecoul = factor_coul * qqrd2e * lam1[itype][jtype] * qtmp*q[j] / denc;
if (evflag) ev_tally(i,j,nlocal,newton_pair,
0.0,ecoul,fpair,delx,dely,delz);
}
}
}
if (vflag_fdotr) virial_fdotr_compute();
}
/* ----------------------------------------------------------------------
allocate all arrays
------------------------------------------------------------------------- */
void PairCoulCutSoft::allocate()
{
allocated = 1;
int n = atom->ntypes;
memory->create(setflag,n+1,n+1,"pair:setflag");
for (int i = 1; i <= n; i++)
for (int j = i; j <= n; j++)
setflag[i][j] = 0;
memory->create(cutsq,n+1,n+1,"pair:cutsq");
memory->create(cut,n+1,n+1,"pair:cut");
memory->create(lambda,n+1,n+1,"pair:lambda");
memory->create(lam1,n+1,n+1,"pair:lam1");
memory->create(lam2,n+1,n+1,"pair:lam2");
}
/* ----------------------------------------------------------------------
global settings
------------------------------------------------------------------------- */
void PairCoulCutSoft::settings(int narg, char **arg)
{
if (narg != 3) error->all(FLERR,"Illegal pair_style command");
nlambda = force->numeric(FLERR,arg[0]);
alphac = force->numeric(FLERR,arg[1]);
cut_global = force->numeric(FLERR,arg[2]);
// reset cutoffs that have been explicitly set
if (allocated) {
int i,j;
for (i = 1; i <= atom->ntypes; i++)
for (j = i+1; j <= atom->ntypes; j++)
if (setflag[i][j]) cut[i][j] = cut_global;
}
}
/* ----------------------------------------------------------------------
set coeffs for one or more type pairs
------------------------------------------------------------------------- */
void PairCoulCutSoft::coeff(int narg, char **arg)
{
if (narg < 3 || narg > 4)
error->all(FLERR,"Incorrect args for pair coefficients");
if (!allocated) allocate();
int ilo,ihi,jlo,jhi;
force->bounds(arg[0],atom->ntypes,ilo,ihi);
force->bounds(arg[1],atom->ntypes,jlo,jhi);
double lambda_one = force->numeric(FLERR,arg[2]);
double cut_one = cut_global;
if (narg == 4) cut_one = force->numeric(FLERR,arg[3]);
int count = 0;
for (int i = ilo; i <= ihi; i++) {
for (int j = MAX(jlo,i); j <= jhi; j++) {
lambda[i][j] = lambda_one;
cut[i][j] = cut_one;
setflag[i][j] = 1;
count++;
}
}
if (count == 0) error->all(FLERR,"Incorrect args for pair coefficients");
}
/* ----------------------------------------------------------------------
init specific to this pair style
------------------------------------------------------------------------- */
void PairCoulCutSoft::init_style()
{
if (!atom->q_flag)
error->all(FLERR,"Pair style coul/cut/soft requires atom attribute q");
neighbor->request(this);
}
/* ----------------------------------------------------------------------
init for one type pair i,j and corresponding j,i
------------------------------------------------------------------------- */
double PairCoulCutSoft::init_one(int i, int j)
{
if (setflag[i][j] == 0) {
if (lambda[i][i] != lambda[j][j])
error->all(FLERR,"Pair coul/cut/soft different lambda values in mix");
lambda[i][j] = lambda[i][i];
cut[i][j] = mix_distance(cut[i][i],cut[j][j]);
}
lam1[i][j] = pow(lambda[i][j], nlambda);
lam2[i][j] = alphac * (1.0 - lambda[i][j])*(1.0 - lambda[i][j]);
cut[j][i] = cut[i][j];
lambda[j][i] = lambda[i][j];
lam1[j][i] = lam1[i][j];
lam2[j][i] = lam2[i][j];
return cut[i][j];
}
/* ----------------------------------------------------------------------
proc 0 writes to restart file
------------------------------------------------------------------------- */
void PairCoulCutSoft::write_restart(FILE *fp)
{
write_restart_settings(fp);
int i,j;
for (i = 1; i <= atom->ntypes; i++)
for (j = i; j <= atom->ntypes; j++) {
fwrite(&setflag[i][j],sizeof(int),1,fp);
if (setflag[i][j]) {
fwrite(&lambda[i][j],sizeof(double),1,fp);
fwrite(&cut[i][j],sizeof(double),1,fp);
}
}
}
/* ----------------------------------------------------------------------
proc 0 reads from restart file, bcasts
------------------------------------------------------------------------- */
void PairCoulCutSoft::read_restart(FILE *fp)
{
read_restart_settings(fp);
allocate();
int i,j;
int me = comm->me;
for (i = 1; i <= atom->ntypes; i++)
for (j = i; j <= atom->ntypes; j++) {
if (me == 0) fread(&setflag[i][j],sizeof(int),1,fp);
MPI_Bcast(&setflag[i][j],1,MPI_INT,0,world);
if (setflag[i][j]) {
if (me == 0) {
fread(&lambda[i][j],sizeof(double),1,fp);
fread(&cut[i][j],sizeof(double),1,fp);
}
MPI_Bcast(&lambda[i][j],1,MPI_DOUBLE,0,world);
MPI_Bcast(&cut[i][j],1,MPI_DOUBLE,0,world);
}
}
}
/* ----------------------------------------------------------------------
proc 0 writes to restart file
------------------------------------------------------------------------- */
void PairCoulCutSoft::write_restart_settings(FILE *fp)
{
fwrite(&nlambda,sizeof(double),1,fp);
fwrite(&alphac,sizeof(double),1,fp);
fwrite(&cut_global,sizeof(double),1,fp);
fwrite(&offset_flag,sizeof(int),1,fp);
fwrite(&mix_flag,sizeof(int),1,fp);
}
/* ----------------------------------------------------------------------
proc 0 reads from restart file, bcasts
------------------------------------------------------------------------- */
void PairCoulCutSoft::read_restart_settings(FILE *fp)
{
if (comm->me == 0) {
fread(&nlambda,sizeof(double),1,fp);
fread(&alphac,sizeof(double),1,fp);
fread(&cut_global,sizeof(double),1,fp);
fread(&offset_flag,sizeof(int),1,fp);
fread(&mix_flag,sizeof(int),1,fp);
}
MPI_Bcast(&nlambda,1,MPI_DOUBLE,0,world);
MPI_Bcast(&alphac,1,MPI_DOUBLE,0,world);
MPI_Bcast(&cut_global,1,MPI_DOUBLE,0,world);
MPI_Bcast(&offset_flag,1,MPI_INT,0,world);
MPI_Bcast(&mix_flag,1,MPI_INT,0,world);
}
/* ----------------------------------------------------------------------
proc 0 writes to data file
------------------------------------------------------------------------- */
void PairCoulCutSoft::write_data(FILE *fp)
{
for (int i = 1; i <= atom->ntypes; i++)
fprintf(fp,"%d %g\n",i,lambda[i][i]);
}
/* ----------------------------------------------------------------------
proc 0 writes all pairs to data file
------------------------------------------------------------------------- */
void PairCoulCutSoft::write_data_all(FILE *fp)
{
for (int i = 1; i <= atom->ntypes; i++)
for (int j = i; j <= atom->ntypes; j++)
fprintf(fp,"%d %d %g\n",i,j,lambda[i][j]);
}
/* ---------------------------------------------------------------------- */
double PairCoulCutSoft::single(int i, int j, int itype, int jtype,
double rsq, double factor_coul, double factor_lj,
double &fforce)
{
double forcecoul,phicoul;
double denc;
if (rsq < cutsq[itype][jtype]) {
denc = sqrt(lam2[itype][jtype] + rsq);
forcecoul = force->qqrd2e * lam1[itype][jtype] * atom->q[i]*atom->q[j] /
(denc*denc*denc);
} else forcecoul = 0.0;
fforce = factor_coul*forcecoul;
if (rsq < cutsq[itype][jtype])
phicoul = force->qqrd2e * lam1[itype][jtype] * atom->q[i]*atom->q[j] / denc;
else phicoul = 0.0;
return factor_coul*phicoul;
}
/* ---------------------------------------------------------------------- */
void *PairCoulCutSoft::extract(const char *str, int &dim)
{
dim = 2;
if (strcmp(str,"lambda") == 0) return (void *) lambda;
return NULL;
}
| slitvinov/lammps-swimmer | src/USER-FEP/pair_coul_cut_soft.cpp | C++ | gpl-2.0 | 10,990 |
<?php
/**
* @file
* Contains \Drupal\Console\Command\RouterRebuildCommand.
*/
namespace Drupal\Console\Command\Router;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Drupal\Console\Command\ContainerAwareCommand;
class RebuildCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('router:rebuild')
->setDescription($this->trans('commands.router.rebuild.description'));
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('');
$output->writeln('[+] <comment>'.$this->trans('commands.router.rebuild.messages.rebuilding').'</comment>');
$container = $this->getContainer();
$router_builder = $container->get('router.builder');
$router_builder->rebuild();
$output->writeln('[+] <info>'.$this->trans('commands.router.rebuild.messages.completed').'</info>');
}
}
| nrackleff/capstone | vendor/drupal/console/src/Command/Router/RebuildCommand.php | PHP | gpl-2.0 | 1,009 |
/* YUI 3.9.0 (build 5827) Copyright 2013 Yahoo! Inc. http://yuilibrary.com/license/ */
YUI.add('yui-later', function (Y, NAME) {
/**
* Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module,
* <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>.
*
* @module yui
* @submodule yui-later
*/
var NO_ARGS = [];
/**
* Executes the supplied function in the context of the supplied
* object 'when' milliseconds later. Executes the function a
* single time unless periodic is set to true.
* @for YUI
* @method later
* @param when {int} the number of milliseconds to wait until the fn
* is executed.
* @param o the context object.
* @param fn {Function|String} the function to execute or the name of
* the method in the 'o' object to execute.
* @param data [Array] data that is provided to the function. This
* accepts either a single item or an array. If an array is provided,
* the function is executed with one parameter for each array item.
* If you need to pass a single array parameter, it needs to be wrapped
* in an array [myarray].
*
* Note: native methods in IE may not have the call and apply methods.
* In this case, it will work, but you are limited to four arguments.
*
* @param periodic {boolean} if true, executes continuously at supplied
* interval until canceled.
* @return {object} a timer object. Call the cancel() method on this
* object to stop the timer.
*/
Y.later = function(when, o, fn, data, periodic) {
when = when || 0;
data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS;
o = o || Y.config.win || Y;
var cancelled = false,
method = (o && Y.Lang.isString(fn)) ? o[fn] : fn,
wrapper = function() {
// IE 8- may execute a setInterval callback one last time
// after clearInterval was called, so in order to preserve
// the cancel() === no more runny-run, we have to jump through
// an extra hoop.
if (!cancelled) {
if (!method.apply) {
method(data[0], data[1], data[2], data[3]);
} else {
method.apply(o, data || NO_ARGS);
}
}
},
id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when);
return {
id: id,
interval: periodic,
cancel: function() {
cancelled = true;
if (this.interval) {
clearInterval(id);
} else {
clearTimeout(id);
}
}
};
};
Y.Lang.later = Y.later;
}, '3.9.0', {"requires": ["yui-base"]});
| alafon/ezpublish-community-built | ezpublish_legacy/extension/ezjscore/design/standard/lib/yui/3.9.0/build/yui-later/yui-later.js | JavaScript | gpl-2.0 | 2,686 |
/*
*
* (C) 2015 - ntop.org
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#include "ntop_includes.h"
/* ************************************************** */
VirtualHost::VirtualHost(HostHash *_h, char *_name) : GenericHashEntry(NULL) {
h = _h, name = strdup(_name), last_num_requests = 0, last_diff = 0, trend = trend_stable;
h->incNumHTTPEntries();
}
/* ************************************************** */
VirtualHost::~VirtualHost() {
h->decNumHTTPEntries();
if(name) free(name);
}
/* ************************************************** */
void VirtualHost::update_stats() {
u_int32_t diff = (u_int32_t)(num_requests.getNumBytes() - last_num_requests);
trend = (diff > last_diff) ? trend_up : ((diff < last_diff) ? trend_down : trend_stable);
/*
ntop->getTrace()->traceEvent(TRACE_WARNING, "%s\t%u [%u][%u]",
name, diff, num_requests.getNumBytes(), last_num_requests);
*/
last_num_requests = num_requests.getNumBytes(), last_diff = diff;
};
| kuffz/ntopng-bk | src/VirtualHost.cpp | C++ | gpl-3.0 | 1,662 |
/*
* Copyright 2010-2016 OpenXcom Developers.
*
* This file is part of OpenXcom.
*
* OpenXcom 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.
*
* OpenXcom 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 OpenXcom. If not, see <http://www.gnu.org/licenses/>.
*/
#include "DogfightErrorState.h"
#include "../Engine/Game.h"
#include "../Mod/Mod.h"
#include "../Engine/LocalizedText.h"
#include "../Interface/TextButton.h"
#include "../Interface/Window.h"
#include "../Interface/Text.h"
#include "../Engine/Options.h"
#include "../Savegame/Craft.h"
namespace OpenXcom
{
/**
* Initializes all the elements in a Dogfight Error window.
* @param game Pointer to the core game.
* @param state Pointer to the Geoscape state.
* @param msg Error message.
*/
DogfightErrorState::DogfightErrorState(Craft *craft, const std::wstring &msg) : _craft(craft)
{
_screen = false;
// Create objects
_window = new Window(this, 208, 120, 24, 48, POPUP_BOTH);
_btnIntercept = new TextButton(180, 12, 38, 128);
_btnBase = new TextButton(180, 12, 38, 144);
_txtCraft = new Text(198, 16, 29, 63);
_txtMessage = new Text(198, 20, 29, 94);
// Set palette
setInterface("dogfightInfo");
add(_window, "window", "dogfightInfo");
add(_btnIntercept, "button", "dogfightInfo");
add(_btnBase, "button", "dogfightInfo");
add(_txtCraft, "text", "dogfightInfo");
add(_txtMessage, "text", "dogfightInfo");
centerAllSurfaces();
// Set up objects
_window->setBackground(_game->getMod()->getSurface("BACK15.SCR"));
_btnIntercept->setText(tr("STR_CONTINUE_INTERCEPTION_PURSUIT"));
_btnIntercept->onMouseClick((ActionHandler)&DogfightErrorState::btnInterceptClick);
_btnIntercept->onKeyboardPress((ActionHandler)&DogfightErrorState::btnInterceptClick, Options::keyCancel);
_btnBase->setText(tr("STR_RETURN_TO_BASE"));
_btnBase->onMouseClick((ActionHandler)&DogfightErrorState::btnBaseClick);
_btnBase->onKeyboardPress((ActionHandler)&DogfightErrorState::btnBaseClick, Options::keyOk);
_txtCraft->setAlign(ALIGN_CENTER);
_txtCraft->setBig();
_txtCraft->setText(_craft->getName(_game->getLanguage()));
_txtMessage->setAlign(ALIGN_CENTER);
_txtMessage->setWordWrap(true);
_txtMessage->setText(msg);
}
/**
*
*/
DogfightErrorState::~DogfightErrorState()
{
}
/**
* Closes the window.
* @param action Pointer to an action.
*/
void DogfightErrorState::btnInterceptClick(Action *)
{
_game->popState();
}
/**
* Returns the craft to base.
* @param action Pointer to an action.
*/
void DogfightErrorState::btnBaseClick(Action *)
{
_craft->returnToBase();
_game->popState();
}
}
| Darineth/OpenXcom | src/Geoscape/DogfightErrorState.cpp | C++ | gpl-3.0 | 3,044 |
/*
* StaticChartXAxisInverse.java of project jchart2d, a demonstration
* of the minimal code to set up a chart with static data and an
* inverse x axis.
* Copyright (C) 2007 - 2011 Achim Westermann, created on 10.12.2004, 13:48:55
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* If you modify or optimize the code in a useful way please let me know.
* Achim.Westermann@gmx.de
*
*/
package info.monitorenter.gui.chart.demos;
import info.monitorenter.gui.chart.Chart2D;
import info.monitorenter.gui.chart.IAxisScalePolicy;
import info.monitorenter.gui.chart.ITrace2D;
import info.monitorenter.gui.chart.axis.AAxis;
import info.monitorenter.gui.chart.axis.AxisInverse;
import info.monitorenter.gui.chart.traces.Trace2DSimple;
import info.monitorenter.gui.chart.views.ChartPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* Title: StaticChartXAxisInverse.
* <p>
*
* Description: A demonstration of the minimal code to set up a chart with
* static data and an inverse x axis (<code>{@link AxisInverse}</code>).
*
* @author Achim Westermann
*
* @version $Revision: 1.7 $
*/
public final class StaticChartXAxisInverse extends JPanel {
/**
* Generated for <code>serialVersionUID</code>.
*/
private static final long serialVersionUID = -7965444904622492209L;
/**
* Main entry.
* <p>
*
* @param args
* ignored.
*/
public static void main(final String[] args) {
for (int i = 0; i < 1; i++) {
JFrame frame = new JFrame("Static Chart x inverted");
frame.getContentPane().add(new StaticChartXAxisInverse());
frame.addWindowListener(new WindowAdapter() {
/**
* @see java.awt.event.WindowAdapter#windowClosing(java.awt.event.WindowEvent)
*/
@Override
public void windowClosing(final WindowEvent e) {
System.exit(0);
}
});
frame.setSize(600, 600);
frame.setLocation(i % 3 * 200, i / 3 * 100);
frame.setVisible(true);
}
}
/**
* Defcon.
*/
private StaticChartXAxisInverse() {
this.setLayout(new BorderLayout());
Chart2D chart = new Chart2D();
AAxis<?> axisXinverted = new AxisInverse<IAxisScalePolicy>();
chart.setAxisXBottom(axisXinverted, 0);
// Create an ITrace:
// Note that dynamic charts need limited amount of values!!!
// ITrace2D trace = new Trace2DLtd(200);
ITrace2D trace = new Trace2DSimple();
// Add the trace to the chart:
chart.addTrace(trace);
trace.setColor(Color.RED);
// Add all points, as it is static:
double xValue = 0;
for (int i = 0; i < 120; i++) {
trace.addPoint(xValue + i, i);
}
// Make it visible:
this.add(new ChartPanel(chart), BorderLayout.CENTER);
}
}
| cheshirekow/codebase | third_party/lcm/lcm-java/jchart2d-code/src/info/monitorenter/gui/chart/demos/StaticChartXAxisInverse.java | Java | gpl-3.0 | 3,599 |
<?php
$L = array();
$L["DATA_TYPE"] = array(
"NAME" => "Straat en huisnummer",
"DESC" => "Generates random street addresses."
);
$L["ap_num"] = "Ap #";
$L["po_box"] = "PO Box";
$L["street_types"] = "St., St., straat, weg, Rd., Rd., Ave, Av., Avenue";
| nickmoorman/generatedata | plugins/dataTypes/StreetAddress/lang/nl.php | PHP | gpl-3.0 | 261 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Version details
*
* @package report
* @subpackage progress
* @copyright 2008 Sam Marshall
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
$plugin->version = 2018120300; // The current plugin version (Date: YYYYMMDDXX)
$plugin->requires = 2018112800; // Requires this Moodle version
$plugin->component = 'report_progress'; // Full name of the plugin (used for diagnostics)
| msoni11/moodle | report/progress/version.php | PHP | gpl-3.0 | 1,159 |
/*
* 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.zeroturnaround.zip.extra;
import static org.zeroturnaround.zip.extra.ZipConstants.BYTE_MASK;
/**
* This is a class that has been made significantly smaller (deleted a bunch of methods) and originally
* is from the Apache Ant Project (http://ant.apache.org), org.apache.tools.zip package.
* All license and other documentation is intact.
*
* Utility class that represents a two byte integer with conversion
* rules for the big endian byte order of ZIP files.
*
*/
public final class ZipShort implements Cloneable {
private static final int BYTE_1_MASK = 0xFF00;
private static final int BYTE_1_SHIFT = 8;
private final int value;
/**
* Create instance from a number.
*
* @param value the int to store as a ZipShort
* @since 1.1
*/
public ZipShort(int value) {
this.value = value;
}
/**
* Create instance from bytes.
*
* @param bytes the bytes to store as a ZipShort
* @since 1.1
*/
public ZipShort(byte[] bytes) {
this(bytes, 0);
}
/**
* Create instance from the two bytes starting at offset.
*
* @param bytes the bytes to store as a ZipShort
* @param offset the offset to start
* @since 1.1
*/
public ZipShort(byte[] bytes, int offset) {
value = ZipShort.getValue(bytes, offset);
}
/**
* Get value as two bytes in big endian byte order.
*
* @return the value as a a two byte array in big endian byte order
* @since 1.1
*/
public byte[] getBytes() {
byte[] result = new byte[2];
result[0] = (byte) (value & BYTE_MASK);
result[1] = (byte) ((value & BYTE_1_MASK) >> BYTE_1_SHIFT);
return result;
}
/**
* Get value as Java int.
*
* @return value as a Java int
* @since 1.1
*/
public int getValue() {
return value;
}
/**
* Get value as two bytes in big endian byte order.
*
* @param value the Java int to convert to bytes
* @return the converted int as a byte array in big endian byte order
*/
public static byte[] getBytes(int value) {
byte[] result = new byte[2];
result[0] = (byte) (value & BYTE_MASK);
result[1] = (byte) ((value & BYTE_1_MASK) >> BYTE_1_SHIFT);
return result;
}
/**
* Helper method to get the value as a java int from two bytes starting at given array offset
*
* @param bytes the array of bytes
* @param offset the offset to start
* @return the corresponding java int value
*/
public static int getValue(byte[] bytes, int offset) {
int value = (bytes[offset + 1] << BYTE_1_SHIFT) & BYTE_1_MASK;
value += (bytes[offset] & BYTE_MASK);
return value;
}
/**
* Helper method to get the value as a java int from a two-byte array
*
* @param bytes the array of bytes
* @return the corresponding java int value
*/
public static int getValue(byte[] bytes) {
return getValue(bytes, 0);
}
/**
* Override to make two instances with same value equal.
*
* @param o an object to compare
* @return true if the objects are equal
* @since 1.1
*/
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof ZipShort)) {
return false;
}
return value == ((ZipShort) o).getValue();
}
/**
* Override to make two instances with same value equal.
*
* @return the value stored in the ZipShort
* @since 1.1
*/
@Override
public int hashCode() {
return value;
}
@Override
public Object clone() {
try {
return super.clone();
}
catch (CloneNotSupportedException cnfe) {
// impossible
throw new RuntimeException(cnfe);
}
}
@Override
public String toString() {
return "ZipShort value: " + value;
}
}
| OhmGeek/ThanCue | src/org/zeroturnaround/zip/extra/ZipShort.java | Java | gpl-3.0 | 4,527 |
#!/usr/bin/python
#
# Copyright (c) 2017 Ansible Project
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
---
module: elasticache
short_description: Manage cache clusters in Amazon Elasticache.
description:
- Manage cache clusters in Amazon Elasticache.
- Returns information about the specified cache cluster.
version_added: "1.4"
requirements: [ boto3 ]
author: "Jim Dalton (@jsdalton)"
options:
state:
description:
- C(absent) or C(present) are idempotent actions that will create or destroy a cache cluster as needed. C(rebooted) will reboot the cluster,
resulting in a momentary outage.
choices: ['present', 'absent', 'rebooted']
required: true
name:
description:
- The cache cluster identifier
required: true
engine:
description:
- Name of the cache engine to be used.
required: false
default: memcached
choices: ['redis', 'memcached']
cache_engine_version:
description:
- The version number of the cache engine
required: false
default: None
node_type:
description:
- The compute and memory capacity of the nodes in the cache cluster
required: false
default: cache.m1.small
num_nodes:
description:
- The initial number of cache nodes that the cache cluster will have. Required when state=present.
required: false
cache_port:
description:
- The port number on which each of the cache nodes will accept connections
required: false
default: None
cache_parameter_group:
description:
- The name of the cache parameter group to associate with this cache cluster. If this argument is omitted, the default cache parameter group
for the specified engine will be used.
required: false
default: None
version_added: "2.0"
aliases: [ 'parameter_group' ]
cache_subnet_group:
description:
- The subnet group name to associate with. Only use if inside a vpc. Required if inside a vpc
required: false
default: None
version_added: "2.0"
security_group_ids:
description:
- A list of vpc security group names to associate with this cache cluster. Only use if inside a vpc
required: false
default: None
version_added: "1.6"
cache_security_groups:
description:
- A list of cache security group names to associate with this cache cluster. Must be an empty list if inside a vpc
required: false
default: None
zone:
description:
- The EC2 Availability Zone in which the cache cluster will be created
required: false
default: None
wait:
description:
- Wait for cache cluster result before returning
required: false
default: yes
choices: [ "yes", "no" ]
hard_modify:
description:
- Whether to destroy and recreate an existing cache cluster if necessary in order to modify its state
required: false
default: no
choices: [ "yes", "no" ]
extends_documentation_fragment:
- aws
- ec2
"""
EXAMPLES = """
# Note: None of these examples set aws_access_key, aws_secret_key, or region.
# It is assumed that their matching environment variables are set.
# Basic example
- elasticache:
name: "test-please-delete"
state: present
engine: memcached
cache_engine_version: 1.4.14
node_type: cache.m1.small
num_nodes: 1
cache_port: 11211
cache_security_groups:
- default
zone: us-east-1d
# Ensure cache cluster is gone
- elasticache:
name: "test-please-delete"
state: absent
# Reboot cache cluster
- elasticache:
name: "test-please-delete"
state: rebooted
"""
from time import sleep
from traceback import format_exc
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import ec2_argument_spec, get_aws_connection_info, boto3_conn, HAS_BOTO3, camel_dict_to_snake_dict
try:
import boto3
import botocore
except ImportError:
pass # will be detected by imported HAS_BOTO3
class ElastiCacheManager(object):
"""Handles elasticache creation and destruction"""
EXIST_STATUSES = ['available', 'creating', 'rebooting', 'modifying']
def __init__(self, module, name, engine, cache_engine_version, node_type,
num_nodes, cache_port, cache_parameter_group, cache_subnet_group,
cache_security_groups, security_group_ids, zone, wait,
hard_modify, region, **aws_connect_kwargs):
self.module = module
self.name = name
self.engine = engine.lower()
self.cache_engine_version = cache_engine_version
self.node_type = node_type
self.num_nodes = num_nodes
self.cache_port = cache_port
self.cache_parameter_group = cache_parameter_group
self.cache_subnet_group = cache_subnet_group
self.cache_security_groups = cache_security_groups
self.security_group_ids = security_group_ids
self.zone = zone
self.wait = wait
self.hard_modify = hard_modify
self.region = region
self.aws_connect_kwargs = aws_connect_kwargs
self.changed = False
self.data = None
self.status = 'gone'
self.conn = self._get_elasticache_connection()
self._refresh_data()
def ensure_present(self):
"""Ensure cache cluster exists or create it if not"""
if self.exists():
self.sync()
else:
self.create()
def ensure_absent(self):
"""Ensure cache cluster is gone or delete it if not"""
self.delete()
def ensure_rebooted(self):
"""Ensure cache cluster is gone or delete it if not"""
self.reboot()
def exists(self):
"""Check if cache cluster exists"""
return self.status in self.EXIST_STATUSES
def create(self):
"""Create an ElastiCache cluster"""
if self.status == 'available':
return
if self.status in ['creating', 'rebooting', 'modifying']:
if self.wait:
self._wait_for_status('available')
return
if self.status == 'deleting':
if self.wait:
self._wait_for_status('gone')
else:
msg = "'%s' is currently deleting. Cannot create."
self.module.fail_json(msg=msg % self.name)
kwargs = dict(CacheClusterId=self.name,
NumCacheNodes=self.num_nodes,
CacheNodeType=self.node_type,
Engine=self.engine,
EngineVersion=self.cache_engine_version,
CacheSecurityGroupNames=self.cache_security_groups,
SecurityGroupIds=self.security_group_ids,
CacheParameterGroupName=self.cache_parameter_group,
CacheSubnetGroupName=self.cache_subnet_group)
if self.cache_port is not None:
kwargs['Port'] = self.cache_port
if self.zone is not None:
kwargs['PreferredAvailabilityZone'] = self.zone
try:
self.conn.create_cache_cluster(**kwargs)
except botocore.exceptions.ClientError as e:
self.module.fail_json(msg=e.message, exception=format_exc(),
**camel_dict_to_snake_dict(e.response))
self._refresh_data()
self.changed = True
if self.wait:
self._wait_for_status('available')
return True
def delete(self):
"""Destroy an ElastiCache cluster"""
if self.status == 'gone':
return
if self.status == 'deleting':
if self.wait:
self._wait_for_status('gone')
return
if self.status in ['creating', 'rebooting', 'modifying']:
if self.wait:
self._wait_for_status('available')
else:
msg = "'%s' is currently %s. Cannot delete."
self.module.fail_json(msg=msg % (self.name, self.status))
try:
response = self.conn.delete_cache_cluster(CacheClusterId=self.name)
except botocore.exceptions.ClientError as e:
self.module.fail_json(msg=e.message, exception=format_exc(),
**camel_dict_to_snake_dict(e.response))
cache_cluster_data = response['CacheCluster']
self._refresh_data(cache_cluster_data)
self.changed = True
if self.wait:
self._wait_for_status('gone')
def sync(self):
"""Sync settings to cluster if required"""
if not self.exists():
msg = "'%s' is %s. Cannot sync."
self.module.fail_json(msg=msg % (self.name, self.status))
if self.status in ['creating', 'rebooting', 'modifying']:
if self.wait:
self._wait_for_status('available')
else:
# Cluster can only be synced if available. If we can't wait
# for this, then just be done.
return
if self._requires_destroy_and_create():
if not self.hard_modify:
msg = "'%s' requires destructive modification. 'hard_modify' must be set to true to proceed."
self.module.fail_json(msg=msg % self.name)
if not self.wait:
msg = "'%s' requires destructive modification. 'wait' must be set to true."
self.module.fail_json(msg=msg % self.name)
self.delete()
self.create()
return
if self._requires_modification():
self.modify()
def modify(self):
"""Modify the cache cluster. Note it's only possible to modify a few select options."""
nodes_to_remove = self._get_nodes_to_remove()
try:
self.conn.modify_cache_cluster(CacheClusterId=self.name,
NumCacheNodes=self.num_nodes,
CacheNodeIdsToRemove=nodes_to_remove,
CacheSecurityGroupNames=self.cache_security_groups,
CacheParameterGroupName=self.cache_parameter_group,
SecurityGroupIds=self.security_group_ids,
ApplyImmediately=True,
EngineVersion=self.cache_engine_version)
except botocore.exceptions.ClientError as e:
self.module.fail_json(msg=e.message, exception=format_exc(),
**camel_dict_to_snake_dict(e.response))
self._refresh_data()
self.changed = True
if self.wait:
self._wait_for_status('available')
def reboot(self):
"""Reboot the cache cluster"""
if not self.exists():
msg = "'%s' is %s. Cannot reboot."
self.module.fail_json(msg=msg % (self.name, self.status))
if self.status == 'rebooting':
return
if self.status in ['creating', 'modifying']:
if self.wait:
self._wait_for_status('available')
else:
msg = "'%s' is currently %s. Cannot reboot."
self.module.fail_json(msg=msg % (self.name, self.status))
# Collect ALL nodes for reboot
cache_node_ids = [cn['CacheNodeId'] for cn in self.data['CacheNodes']]
try:
self.conn.reboot_cache_cluster(CacheClusterId=self.name,
CacheNodeIdsToReboot=cache_node_ids)
except botocore.exceptions.ClientError as e:
self.module.fail_json(msg=e.message, exception=format_exc(),
**camel_dict_to_snake_dict(e.response))
self._refresh_data()
self.changed = True
if self.wait:
self._wait_for_status('available')
def get_info(self):
"""Return basic info about the cache cluster"""
info = {
'name': self.name,
'status': self.status
}
if self.data:
info['data'] = self.data
return info
def _wait_for_status(self, awaited_status):
"""Wait for status to change from present status to awaited_status"""
status_map = {
'creating': 'available',
'rebooting': 'available',
'modifying': 'available',
'deleting': 'gone'
}
if self.status == awaited_status:
# No need to wait, we're already done
return
if status_map[self.status] != awaited_status:
msg = "Invalid awaited status. '%s' cannot transition to '%s'"
self.module.fail_json(msg=msg % (self.status, awaited_status))
if awaited_status not in set(status_map.values()):
msg = "'%s' is not a valid awaited status."
self.module.fail_json(msg=msg % awaited_status)
while True:
sleep(1)
self._refresh_data()
if self.status == awaited_status:
break
def _requires_modification(self):
"""Check if cluster requires (nondestructive) modification"""
# Check modifiable data attributes
modifiable_data = {
'NumCacheNodes': self.num_nodes,
'EngineVersion': self.cache_engine_version
}
for key, value in modifiable_data.items():
if value is not None and self.data[key] != value:
return True
# Check cache security groups
cache_security_groups = []
for sg in self.data['CacheSecurityGroups']:
cache_security_groups.append(sg['CacheSecurityGroupName'])
if set(cache_security_groups) != set(self.cache_security_groups):
return True
# check vpc security groups
if self.security_group_ids:
vpc_security_groups = []
security_groups = self.data['SecurityGroups'] or []
for sg in security_groups:
vpc_security_groups.append(sg['SecurityGroupId'])
if set(vpc_security_groups) != set(self.security_group_ids):
return True
return False
def _requires_destroy_and_create(self):
"""
Check whether a destroy and create is required to synchronize cluster.
"""
unmodifiable_data = {
'node_type': self.data['CacheNodeType'],
'engine': self.data['Engine'],
'cache_port': self._get_port()
}
# Only check for modifications if zone is specified
if self.zone is not None:
unmodifiable_data['zone'] = self.data['PreferredAvailabilityZone']
for key, value in unmodifiable_data.items():
if getattr(self, key) is not None and getattr(self, key) != value:
return True
return False
def _get_elasticache_connection(self):
"""Get an elasticache connection"""
region, ec2_url, aws_connect_params = get_aws_connection_info(self.module, boto3=True)
if region:
return boto3_conn(self.module, conn_type='client', resource='elasticache',
region=region, endpoint=ec2_url, **aws_connect_params)
else:
self.module.fail_json(msg="region must be specified")
def _get_port(self):
"""Get the port. Where this information is retrieved from is engine dependent."""
if self.data['Engine'] == 'memcached':
return self.data['ConfigurationEndpoint']['Port']
elif self.data['Engine'] == 'redis':
# Redis only supports a single node (presently) so just use
# the first and only
return self.data['CacheNodes'][0]['Endpoint']['Port']
def _refresh_data(self, cache_cluster_data=None):
"""Refresh data about this cache cluster"""
if cache_cluster_data is None:
try:
response = self.conn.describe_cache_clusters(CacheClusterId=self.name, ShowCacheNodeInfo=True)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'CacheClusterNotFound':
self.data = None
self.status = 'gone'
return
else:
self.module.fail_json(msg=e.message, exception=format_exc(),
**camel_dict_to_snake_dict(e.response))
cache_cluster_data = response['CacheClusters'][0]
self.data = cache_cluster_data
self.status = self.data['CacheClusterStatus']
# The documentation for elasticache lies -- status on rebooting is set
# to 'rebooting cache cluster nodes' instead of 'rebooting'. Fix it
# here to make status checks etc. more sane.
if self.status == 'rebooting cache cluster nodes':
self.status = 'rebooting'
def _get_nodes_to_remove(self):
"""If there are nodes to remove, it figures out which need to be removed"""
num_nodes_to_remove = self.data['NumCacheNodes'] - self.num_nodes
if num_nodes_to_remove <= 0:
return []
if not self.hard_modify:
msg = "'%s' requires removal of cache nodes. 'hard_modify' must be set to true to proceed."
self.module.fail_json(msg=msg % self.name)
cache_node_ids = [cn['CacheNodeId'] for cn in self.data['CacheNodes']]
return cache_node_ids[-num_nodes_to_remove:]
def main():
""" elasticache ansible module """
argument_spec = ec2_argument_spec()
argument_spec.update(dict(
state=dict(required=True, choices=['present', 'absent', 'rebooted']),
name=dict(required=True),
engine=dict(default='memcached'),
cache_engine_version=dict(default=""),
node_type=dict(default='cache.t2.small'),
num_nodes=dict(default=1, type='int'),
# alias for compat with the original PR 1950
cache_parameter_group=dict(default="", aliases=['parameter_group']),
cache_port=dict(type='int'),
cache_subnet_group=dict(default=""),
cache_security_groups=dict(default=[], type='list'),
security_group_ids=dict(default=[], type='list'),
zone=dict(),
wait=dict(default=True, type='bool'),
hard_modify=dict(type='bool')
))
module = AnsibleModule(
argument_spec=argument_spec,
)
if not HAS_BOTO3:
module.fail_json(msg='boto3 required for this module')
region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module)
name = module.params['name']
state = module.params['state']
engine = module.params['engine']
cache_engine_version = module.params['cache_engine_version']
node_type = module.params['node_type']
num_nodes = module.params['num_nodes']
cache_port = module.params['cache_port']
cache_subnet_group = module.params['cache_subnet_group']
cache_security_groups = module.params['cache_security_groups']
security_group_ids = module.params['security_group_ids']
zone = module.params['zone']
wait = module.params['wait']
hard_modify = module.params['hard_modify']
cache_parameter_group = module.params['cache_parameter_group']
if cache_subnet_group and cache_security_groups:
module.fail_json(msg="Can't specify both cache_subnet_group and cache_security_groups")
if state == 'present' and not num_nodes:
module.fail_json(msg="'num_nodes' is a required parameter. Please specify num_nodes > 0")
elasticache_manager = ElastiCacheManager(module, name, engine,
cache_engine_version, node_type,
num_nodes, cache_port,
cache_parameter_group,
cache_subnet_group,
cache_security_groups,
security_group_ids, zone, wait,
hard_modify, region, **aws_connect_kwargs)
if state == 'present':
elasticache_manager.ensure_present()
elif state == 'absent':
elasticache_manager.ensure_absent()
elif state == 'rebooted':
elasticache_manager.ensure_rebooted()
facts_result = dict(changed=elasticache_manager.changed,
elasticache=elasticache_manager.get_info())
module.exit_json(**facts_result)
if __name__ == '__main__':
main()
| wrouesnel/ansible | lib/ansible/modules/cloud/amazon/elasticache.py | Python | gpl-3.0 | 20,816 |
<?php
// PDU - Phase
$oids = snmp_walk($device, 'rPDUStatusPhaseIndex', '-OsqnU', 'PowerNet-MIB');
if (empty($oids)) {
$oids = snmp_walk($device, 'rPDULoadPhaseConfigIndex', '-OsqnU', 'PowerNet-MIB');
}
if ($oids) {
d_echo($oids."\n");
$oids = trim($oids);
if ($oids) {
echo 'APC PowerNet-MIB Phase ';
}
$type = 'apc';
$precision = '10';
foreach (explode("\n", $oids) as $data) {
$data = trim($data);
if ($data) {
list($oid,$kind) = explode(' ', $data);
$split_oid = explode('.', $oid);
$index = $split_oid[(count($split_oid) - 1)];
$current_oid = '.1.3.6.1.4.1.318.1.1.12.2.3.1.1.2.'.$index;
// rPDULoadStatusLoad
$phase_oid = '.1.3.6.1.4.1.318.1.1.12.2.3.1.1.4.'.$index;
// rPDULoadStatusPhaseNumber
$limit_oid = '.1.3.6.1.4.1.318.1.1.12.2.2.1.1.4.'.$index;
// rPDULoadPhaseConfigOverloadThreshold
$lowlimit_oid = '.1.3.6.1.4.1.318.1.1.12.2.2.1.1.2.'.$index;
// rPDULoadPhaseConfigLowLoadThreshold
$warnlimit_oid = '.1.3.6.1.4.1.318.1.1.12.2.2.1.1.3.'.$index;
// rPDULoadPhaseConfigNearOverloadThreshold
$phase = snmp_get($device, $phase_oid, '-Oqv', '');
$current = (snmp_get($device, $current_oid, '-Oqv', '') / $precision);
$limit = snmp_get($device, $limit_oid, '-Oqv', '');
// No / $precision here! Nice, APC!
$lowlimit = snmp_get($device, $lowlimit_oid, '-Oqv', '');
// No / $precision here! Nice, APC!
$warnlimit = snmp_get($device, $warnlimit_oid, '-Oqv', '');
// No / $precision here! Nice, APC!
if (count(explode("\n", $oids)) != 1) {
$descr = "Phase $phase";
} else {
$descr = 'Output';
}
discover_sensor($valid['sensor'], 'current', $device, $current_oid, $index, $type, $descr, '10', '1', $lowlimit, null, $warnlimit, $limit, $current);
}
}
}
unset($oids);
// v2 firmware- first bank is total, v3 firmware, 3rd bank is total
$bank_count = snmp_get($device, 'rPDULoadDevNumBanks.0', '-Oqv', 'PowerNet-MIB');
if ($bank_count > 0) {
$oids = snmp_walk($device, 'rPDULoadStatusIndex', '-OsqnU', 'PowerNet-MIB');
}
// should work with firmware v2 and v3
if ($oids) {
echo 'APC PowerNet-MIB Banks ';
d_echo($oids."\n");
$oids = trim($oids);
$type = 'apc';
$precision = '10';
// version 2 does some stuff differently- total power is first oid in index instead of the last.
// will look something like "AOS v2.6.4 / App v2.6.5"
$baseversion = '3';
if (stristr($device['version'], 'AOS v2') == true) {
$baseversion = '2';
}
foreach (explode("\n", $oids) as $data) {
$data = trim($data);
if ($data) {
list($oid,$kind) = explode(' ', $data);
$split_oid = explode('.', $oid);
$index = $split_oid[(count($split_oid) - 1)];
$banknum = ($index - 1);
$descr = 'Bank '.$banknum;
if ($baseversion == '3') {
if ($index == '1') {
$descr = 'Bank Total';
}
}
if ($baseversion == '2') {
if ($index == '1') {
$descr = 'Bank Total';
}
}
$current_oid = '.1.3.6.1.4.1.318.1.1.12.2.3.1.1.2.'.$index;
// rPDULoadStatusLoad
$bank_oid = '.1.3.6.1.4.1.318.1.1.12.2.3.1.1.5.'.$index;
// rPDULoadStatusBankNumber
$limit_oid = '.1.3.6.1.4.1.318.1.1.12.2.4.1.1.4.'.$index;
// rPDULoadBankConfigOverloadThreshold
$lowlimit_oid = '.1.3.6.1.4.1.318.1.1.12.2.4.1.1.2.'.$index;
// rPDULoadBankConfigLowLoadThreshold
$warnlimit_oid = '.1.3.6.1.4.1.318.1.1.12.2.4.1.1.3.'.$index;
// rPDULoadBankConfigNearOverloadThreshold
$bank = snmp_get($device, $bank_oid, '-Oqv', '');
$current = (snmp_get($device, $current_oid, '-Oqv', '') / $precision);
$limit = snmp_get($device, $limit_oid, '-Oqv', '');
$lowlimit = snmp_get($device, $lowlimit_oid, '-Oqv', '');
$warnlimit = snmp_get($device, $warnlimit_oid, '-Oqv', '');
if ($limit != -1 && $lowlimit != -1 && $warnlimit != -1) {
discover_sensor($valid['sensor'], 'current', $device, $current_oid, $index, $type, $descr, '10', '1', $lowlimit, null, $warnlimit, $limit, $current);
}
}
}
unset($baseversion);
}
unset($oids);
// Per Outlet Power Bar
$oids = snmp_walk($device, '.1.3.6.1.4.1.318.1.1.26.9.4.3.1.1', '-t 30 -OsqnU', 'PowerNet-MIB');
if ($oids) {
echo 'APC PowerNet-MIB Outlets ';
d_echo($oids."\n");
$oids = trim($oids);
$type = 'apc';
$precision = '10';
foreach (explode("\n", $oids) as $data) {
$data = trim($data);
if ($data) {
list($oid,$kind) = explode(' ', $data);
$split_oid = explode('.', $oid);
$index = $split_oid[(count($split_oid) - 1)];
$voltage_oid = '.1.3.6.1.4.1.318.1.1.26.6.3.1.6';
// rPDU2PhaseStatusVoltage
$current_oid = '.1.3.6.1.4.1.318.1.1.26.9.4.3.1.6.'.$index;
// rPDU2OutletMeteredStatusCurrent
$limit_oid = '.1.3.6.1.4.1.318.1.1.26.9.4.1.1.7.'.$index;
// rPDU2OutletMeteredConfigOverloadCurrentThreshold
$lowlimit_oid = '.1.3.6.1.4.1.318.1.1.26.9.4.1.1.7.'.$index;
// rPDU2OutletMeteredConfigLowLoadCurrentThreshold
$warnlimit_oid = '.1.3.6.1.4.1.318.1.1.26.9.4.1.1.6.'.$index;
// rPDU2OutletMeteredConfigNearOverloadCurrentThreshold
$name_oid = '.1.3.6.1.4.1.318.1.1.26.9.4.3.1.3.'.$index;
// rPDU2OutletMeteredStatusName
$voltage = snmp_get($device, $voltage_oid, '-Oqv', '');
$current = (snmp_get($device, $current_oid, '-Oqv', '') / $precision);
$limit = (snmp_get($device, $limit_oid, '-Oqv', '') / $voltage);
$lowlimit = (snmp_get($device, $lowlimit_oid, '-Oqv', '') / $voltage);
$warnlimit = (snmp_get($device, $warnlimit_oid, '-Oqv', '') / $voltage);
$descr = 'Outlet '.$index.' - '.snmp_get($device, $name_oid, '-Oqv', '');
discover_sensor($valid['sensor'], 'current', $device, $current_oid, $index, $type, $descr, '10', '1', $lowlimit, null, $warnlimit, $limit, $current);
}
}
}
unset($oids);
// ATS
$oids = snmp_walk($device, 'atsConfigPhaseTableIndex', '-OsqnU', 'PowerNet-MIB');
if ($oids) {
$type = 'apc';
d_echo($oids."\n");
$oids = trim($oids);
if ($oids) {
echo 'APC PowerNet-MIB ATS ';
}
$current_oid = '.1.3.6.1.4.1.318.1.1.8.5.4.3.1.4.1.1.1';
// atsOutputCurrent
$limit_oid = '.1.3.6.1.4.1.318.1.1.8.4.16.1.5.1';
// atsConfigPhaseOverLoadThreshold
$lowlimit_oid = '.1.3.6.1.4.1.318.1.1.8.4.16.1.3.1';
// atsConfigPhaseLowLoadThreshold
$warnlimit_oid = '.1.3.6.1.4.1.318.1.1.8.4.16.1.4.1';
// atsConfigPhaseNearOverLoadThreshold
$index = 1;
$current = (snmp_get($device, $current_oid, '-Oqv', '') / $precision);
$limit = snmp_get($device, $limit_oid, '-Oqv', '');
// No / $precision here! Nice, APC!
$lowlimit = snmp_get($device, $lowlimit_oid, '-Oqv', '');
// No / $precision here! Nice, APC!
$warnlimit = snmp_get($device, $warnlimit_oid, '-Oqv', '');
// No / $precision here! Nice, APC!
$descr = 'Output Feed';
discover_sensor($valid['sensor'], 'current', $device, $current_oid, $index, $type, $descr, '10', '1', $lowlimit, null, $warnlimit, $limit, $current);
}
unset($oids);
// UPS
$oid_array = array(
array(
'HighPrecOid' => 'upsHighPrecOutputCurrent',
'AdvOid' => 'upsAdvOutputCurrent',
'type' => 'apc',
'index' => 0,
'descr' => 'Current Drawn',
'divisor' => 10,
'mib' => '+PowerNet-MIB',
),
);
foreach ($oid_array as $item) {
$oids = snmp_get($device, $item['HighPrecOid'].'.'.$item['index'], '-OsqnU', $item['mib']);
if (empty($oids)) {
$oids = snmp_get($device, $item['AdvOid'].'.'.$item['index'], '-OsqnU', $item['mib']);
$current_oid = '.1.3.6.1.4.1.318.1.1.1.4.2.4';
$current = $oids;
$item['divisor'] = 1;
} else {
$current_oid = '.1.3.6.1.4.1.318.1.1.1.4.3.4';
$value = explode(" ", $oids);
$current = $value[1]/$item['divisor'];
}
if (!empty($oids)) {
d_echo($oids."\n");
$oids = trim($oids);
if ($oids) {
echo $item['type'].' '.$item['mib'].' UPS';
}
discover_sensor($valid['sensor'], 'current', $device, $current_oid.'.'.$item['index'], $current_oid.'.'.$item['index'], $item['type'], $item['descr'], $item['divisor'], 1, null, null, null, null, $current);
}
}
| wrgeorge1983/librenms | includes/discovery/sensors/current/apc.inc.php | PHP | gpl-3.0 | 9,157 |
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*
* Version: 5.3.1 (2020-05-27)
*/
(function () {
'use strict';
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');
var getNonEditableClass = function (editor) {
return editor.getParam('noneditable_noneditable_class', 'mceNonEditable');
};
var getEditableClass = function (editor) {
return editor.getParam('noneditable_editable_class', 'mceEditable');
};
var getNonEditableRegExps = function (editor) {
var nonEditableRegExps = editor.getParam('noneditable_regexp', []);
if (nonEditableRegExps && nonEditableRegExps.constructor === RegExp) {
return [nonEditableRegExps];
} else {
return nonEditableRegExps;
}
};
var hasClass = function (checkClassName) {
return function (node) {
return (' ' + node.attr('class') + ' ').indexOf(checkClassName) !== -1;
};
};
var replaceMatchWithSpan = function (editor, content, cls) {
return function (match) {
var args = arguments, index = args[args.length - 2];
var prevChar = index > 0 ? content.charAt(index - 1) : '';
if (prevChar === '"') {
return match;
}
if (prevChar === '>') {
var findStartTagIndex = content.lastIndexOf('<', index);
if (findStartTagIndex !== -1) {
var tagHtml = content.substring(findStartTagIndex, index);
if (tagHtml.indexOf('contenteditable="false"') !== -1) {
return match;
}
}
}
return '<span class="' + cls + '" data-mce-content="' + editor.dom.encode(args[0]) + '">' + editor.dom.encode(typeof args[1] === 'string' ? args[1] : args[0]) + '</span>';
};
};
var convertRegExpsToNonEditable = function (editor, nonEditableRegExps, e) {
var i = nonEditableRegExps.length, content = e.content;
if (e.format === 'raw') {
return;
}
while (i--) {
content = content.replace(nonEditableRegExps[i], replaceMatchWithSpan(editor, content, getNonEditableClass(editor)));
}
e.content = content;
};
var setup = function (editor) {
var editClass, nonEditClass;
var contentEditableAttrName = 'contenteditable';
editClass = ' ' + global$1.trim(getEditableClass(editor)) + ' ';
nonEditClass = ' ' + global$1.trim(getNonEditableClass(editor)) + ' ';
var hasEditClass = hasClass(editClass);
var hasNonEditClass = hasClass(nonEditClass);
var nonEditableRegExps = getNonEditableRegExps(editor);
editor.on('PreInit', function () {
if (nonEditableRegExps.length > 0) {
editor.on('BeforeSetContent', function (e) {
convertRegExpsToNonEditable(editor, nonEditableRegExps, e);
});
}
editor.parser.addAttributeFilter('class', function (nodes) {
var i = nodes.length, node;
while (i--) {
node = nodes[i];
if (hasEditClass(node)) {
node.attr(contentEditableAttrName, 'true');
} else if (hasNonEditClass(node)) {
node.attr(contentEditableAttrName, 'false');
}
}
});
editor.serializer.addAttributeFilter(contentEditableAttrName, function (nodes) {
var i = nodes.length, node;
while (i--) {
node = nodes[i];
if (!hasEditClass(node) && !hasNonEditClass(node)) {
continue;
}
if (nonEditableRegExps.length > 0 && node.attr('data-mce-content')) {
node.name = '#text';
node.type = 3;
node.raw = true;
node.value = node.attr('data-mce-content');
} else {
node.attr(contentEditableAttrName, null);
}
}
});
});
};
function Plugin () {
global.add('noneditable', function (editor) {
setup(editor);
});
}
Plugin();
}());
| francbartoli/geonode | geonode/static/lib/js/plugins/noneditable/plugin.js | JavaScript | gpl-3.0 | 4,286 |
<?php
namespace Sabre\HTTP;
/**
* HTTP Digest Authentication handler
*
* Use this class for easy http digest authentication.
* Instructions:
*
* 1. Create the object
* 2. Call the setRealm() method with the realm you plan to use
* 3. Call the init method function.
* 4. Call the getUserName() function. This function may return false if no
* authentication information was supplied. Based on the username you
* should check your internal database for either the associated password,
* or the so-called A1 hash of the digest.
* 5. Call either validatePassword() or validateA1(). This will return true
* or false.
* 6. To make sure an authentication prompt is displayed, call the
* requireLogin() method.
*
*
* @copyright Copyright (C) 2007-2013 fruux GmbH (https://fruux.com/).
* @author Evert Pot (http://evertpot.com/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class DigestAuth extends AbstractAuth {
/**
* These constants are used in setQOP();
*/
const QOP_AUTH = 1;
const QOP_AUTHINT = 2;
protected $nonce;
protected $opaque;
protected $digestParts;
protected $A1;
protected $qop = self::QOP_AUTH;
/**
* Initializes the object
*/
public function __construct() {
$this->nonce = uniqid();
$this->opaque = md5($this->realm);
parent::__construct();
}
/**
* Gathers all information from the headers
*
* This method needs to be called prior to anything else.
*
* @return void
*/
public function init() {
$digest = $this->getDigest();
$this->digestParts = $this->parseDigest($digest);
}
/**
* Sets the quality of protection value.
*
* Possible values are:
* Sabre\HTTP\DigestAuth::QOP_AUTH
* Sabre\HTTP\DigestAuth::QOP_AUTHINT
*
* Multiple values can be specified using logical OR.
*
* QOP_AUTHINT ensures integrity of the request body, but this is not
* supported by most HTTP clients. QOP_AUTHINT also requires the entire
* request body to be md5'ed, which can put strains on CPU and memory.
*
* @param int $qop
* @return void
*/
public function setQOP($qop) {
$this->qop = $qop;
}
/**
* Validates the user.
*
* The A1 parameter should be md5($username . ':' . $realm . ':' . $password);
*
* @param string $A1
* @return bool
*/
public function validateA1($A1) {
$this->A1 = $A1;
return $this->validate();
}
/**
* Validates authentication through a password. The actual password must be provided here.
* It is strongly recommended not store the password in plain-text and use validateA1 instead.
*
* @param string $password
* @return bool
*/
public function validatePassword($password) {
$this->A1 = md5($this->digestParts['username'] . ':' . $this->realm . ':' . $password);
return $this->validate();
}
/**
* Returns the username for the request
*
* @return string
*/
public function getUsername() {
return $this->digestParts['username'];
}
/**
* Validates the digest challenge
*
* @return bool
*/
protected function validate() {
$A2 = $this->httpRequest->getMethod() . ':' . $this->digestParts['uri'];
if ($this->digestParts['qop']=='auth-int') {
// Making sure we support this qop value
if (!($this->qop & self::QOP_AUTHINT)) return false;
// We need to add an md5 of the entire request body to the A2 part of the hash
$body = $this->httpRequest->getBody(true);
$this->httpRequest->setBody($body,true);
$A2 .= ':' . md5($body);
} else {
// We need to make sure we support this qop value
if (!($this->qop & self::QOP_AUTH)) return false;
}
$A2 = md5($A2);
$validResponse = md5("{$this->A1}:{$this->digestParts['nonce']}:{$this->digestParts['nc']}:{$this->digestParts['cnonce']}:{$this->digestParts['qop']}:{$A2}");
return $this->digestParts['response']==$validResponse;
}
/**
* Returns an HTTP 401 header, forcing login
*
* This should be called when username and password are incorrect, or not supplied at all
*
* @return void
*/
public function requireLogin() {
$qop = '';
switch($this->qop) {
case self::QOP_AUTH : $qop = 'auth'; break;
case self::QOP_AUTHINT : $qop = 'auth-int'; break;
case self::QOP_AUTH | self::QOP_AUTHINT : $qop = 'auth,auth-int'; break;
}
$this->httpResponse->setHeader('WWW-Authenticate','Digest realm="' . $this->realm . '",qop="'.$qop.'",nonce="' . $this->nonce . '",opaque="' . $this->opaque . '"');
$this->httpResponse->sendStatus(401);
}
/**
* This method returns the full digest string.
*
* It should be compatibile with mod_php format and other webservers.
*
* If the header could not be found, null will be returned
*
* @return mixed
*/
public function getDigest() {
// mod_php
$digest = $this->httpRequest->getRawServerValue('PHP_AUTH_DIGEST');
if ($digest) return $digest;
// most other servers
$digest = $this->httpRequest->getHeader('Authorization');
// Apache could prefix environment variables with REDIRECT_ when urls
// are passed through mod_rewrite
if (!$digest) {
$digest = $this->httpRequest->getRawServerValue('REDIRECT_HTTP_AUTHORIZATION');
}
if ($digest && strpos(strtolower($digest),'digest')===0) {
return substr($digest,7);
} else {
return null;
}
}
/**
* Parses the different pieces of the digest string into an array.
*
* This method returns false if an incomplete digest was supplied
*
* @param string $digest
* @return mixed
*/
protected function parseDigest($digest) {
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
preg_match_all('@(\w+)=(?:(?:")([^"]+)"|([^\s,$]+))@', $digest, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$data[$m[1]] = $m[2] ? $m[2] : $m[3];
unset($needed_parts[$m[1]]);
}
return $needed_parts ? false : $data;
}
}
| stefjakobs/cgp2zarafa | zarafa-sabre/lib/SabreDAV/lib/Sabre/HTTP/DigestAuth.php | PHP | gpl-3.0 | 6,672 |
import {helper} from 'ember-helper';
import {htmlSafe} from 'ember-string';
import ghostPaths from 'ghost-admin/utils/ghost-paths';
// Handlebars Helper {{gh-path}}
// Usage: Assume 'http://www.myghostblog.org/myblog/'
// {{gh-path}} or {{gh-path 'blog'}} for Ghost's root (/myblog/)
// {{gh-path 'admin'}} for Ghost's admin root (/myblog/ghost/)
// {{gh-path 'api'}} for Ghost's api root (/myblog/ghost/api/v0.1/)
// {{gh-path 'admin' '/assets/hi.png'}} for resolved url (/myblog/ghost/assets/hi.png)
export default helper(function (params) {
let paths = ghostPaths();
let [path, url] = params;
let base;
if (!path) {
path = 'blog';
}
if (!/^(blog|admin|api)$/.test(path)) {
url = path;
path = 'blog';
}
switch (path.toString()) {
case 'blog':
base = paths.blogRoot;
break;
case 'admin':
base = paths.adminRoot;
break;
case 'api':
base = paths.apiRoot;
break;
default:
base = paths.blogRoot;
break;
}
// handle leading and trailing slashes
base = base[base.length - 1] !== '/' ? `${base}/` : base;
if (url && url.length > 0) {
if (url[0] === '/') {
url = url.substr(1);
}
base = base + url;
}
return htmlSafe(base);
});
| Elektro1776/latestEarthables | core/client/app/helpers/gh-path.js | JavaScript | gpl-3.0 | 1,375 |
// This file has been generated by Py++.
#ifndef PropertyLinkDefinitionVector2f_hpp__pyplusplus_wrapper
#define PropertyLinkDefinitionVector2f_hpp__pyplusplus_wrapper
void register_PropertyLinkDefinitionVector2f_class();
#endif//PropertyLinkDefinitionVector2f_hpp__pyplusplus_wrapper
| geminy/aidear | oss/cegui/cegui-0.8.7/cegui/src/ScriptModules/Python/bindings/output/CEGUI/PropertyLinkDefinitionVector2f.pypp.hpp | C++ | gpl-3.0 | 287 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2015 Evan Debenham
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.ui;
import com.watabou.noosa.Game;
import com.watabou.noosa.NinePatch;
import com.watabou.noosa.ui.Button;
import com.shatteredpixel.shatteredpixeldungeon.Chrome;
public class Tag extends Button {
private float r;
private float g;
private float b;
protected NinePatch bg;
protected float lightness = 0;
public Tag( int color ) {
super();
this.r = (color >> 16) / 255f;
this.g = ((color >> 8) & 0xFF) / 255f;
this.b = (color & 0xFF) / 255f;
}
@Override
protected void createChildren() {
super.createChildren();
bg = Chrome.get( Chrome.Type.TAG );
add( bg );
}
@Override
protected void layout() {
super.layout();
bg.x = x;
bg.y = y;
bg.size( width, height );
}
public void flash() {
lightness = 1f;
}
@Override
public void update() {
super.update();
if (visible && lightness > 0.5) {
if ((lightness -= Game.elapsed) > 0.5) {
bg.ra = bg.ga = bg.ba = 2 * lightness - 1;
bg.rm = 2 * r * (1 - lightness);
bg.gm = 2 * g * (1 - lightness);
bg.bm = 2 * b * (1 - lightness);
} else {
bg.hardlight( r, g, b );
}
}
}
}
| 5AMW3155/shattered-pixel-dungeon | src/com/shatteredpixel/shatteredpixeldungeon/ui/Tag.java | Java | gpl-3.0 | 1,948 |
<?php
$this->load->view('cheader');
$this->load->view('admin_header');
?>
<style>
.datatables{
width:75% !important;}
</style>
<body>
<!-- Beginning header -->
<!-- End of header-->
<div style='height:5px;'></div>
<!-- block -->
<div>
<?php echo $output; ?>
</div>
</div>
</body> | CollinsIchigo/LEO | application/views/view_payment.php | PHP | gpl-3.0 | 447 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2014 Oleg Dolya
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.ui;
import com.shatteredpixel.shatteredpixeldungeon.scenes.PixelScene;
public class CheckBox extends RedButton {
private boolean checked = false;
public CheckBox( String label ) {
super( label );
icon( Icons.get( Icons.UNCHECKED ) );
}
@Override
protected void layout() {
super.layout();
float margin = (height - text.baseLine()) / 2;
text.x = PixelScene.align( PixelScene.uiCamera, x + margin );
text.y = PixelScene.align( PixelScene.uiCamera, y + margin );
margin = (height - icon.height) / 2;
icon.x = PixelScene.align( PixelScene.uiCamera, x + width - margin - icon.width );
icon.y = PixelScene.align( PixelScene.uiCamera, y + margin );
}
public boolean checked() {
return checked;
}
public void checked( boolean value ) {
if (checked != value) {
checked = value;
icon.copy( Icons.get( checked ? Icons.CHECKED : Icons.UNCHECKED ) );
}
}
@Override
protected void onClick() {
super.onClick();
checked( !checked );
}
}
| Lobz/reforged-pixel-dungeon | src/com/shatteredpixel/shatteredpixeldungeon/ui/CheckBox.java | Java | gpl-3.0 | 1,771 |
<?php namespace Maatwebsite\Excel\Classes;
use Closure;
use PHPExcel_Cell;
use PHPExcel_Exception;
use PHPExcel_Worksheet;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Writers\CellWriter;
use Maatwebsite\Excel\Exceptions\LaravelExcelException;
use PHPExcel_Worksheet_PageSetup;
/**
*
* Laravel wrapper for PHPExcel_Worksheet
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @copyright Original Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
* @author Maatwebsite <info@maatwebsite.nl>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class LaravelExcelWorksheet extends PHPExcel_Worksheet {
/**
* Parent
* @var PHPExcel
*/
public $_parent;
/**
* Parser
* @var ViewParser
*/
protected $parser;
/**
* View
* @var string
*/
public $view;
/**
* Data
* @var array
*/
public $data = [];
/**
* Merge data
* @var array
*/
public $mergeData = [];
/**
* Allowed page setup
* @var array
*/
public $allowedPageSetup = [
'orientation',
'paperSize',
'scale',
'fitToPage',
'fitToHeight',
'fitToWidth',
'columnsToRepeatAtLeft',
'rowsToRepeatAtTop',
'horizontalCentered',
'verticalCentered',
'printArea',
'firstPageNumber'
];
/**
* Allowed page setup
* @var array
*/
public $allowedStyles = [
'fontFamily',
'fontSize',
'fontBold'
];
/**
* Check if the file was autosized
* @var boolean
*/
public $hasFixedSizeColumns = false;
/**
* Auto generate table heading
* @var [type]
*/
protected $autoGenerateHeading = true;
/**
* @var bool
*/
protected $hasRowsAdded = false;
/**
* Create a new worksheet
*
* @param PHPExcel $pParent
* @param string $pTitle
*/
public function __construct(PHPExcel $pParent = null, $pTitle = 'Worksheet')
{
parent::__construct($pParent, $pTitle);
$this->setParent($pParent);
// check if we should generate headings
// defaults to true if not overridden by settings
$this->autoGenerateHeading = config('excel.export.generate_heading_by_indices', true);
}
/**
* Set default page setup
* @return void
*/
public function setDefaultPageSetup()
{
// Get the page setup
$pageSetup = $this->getPageSetup();
foreach ($this->allowedPageSetup as $setup)
{
// set the setter
list($setter, $set) = $this->_setSetter($setup);
// get the value
$value = config('excel.sheets.pageSetup.' . $setup, null);
// Set the page setup value
if (!is_null($value))
call_user_func_array(array($pageSetup, $setter), array($value));
}
// Set default page margins
$this->setPageMargin(config('excel.export.sheets.page_margin', false));
}
/**
* Set the page margin
* @param array|boolean|integer|float $margin
*/
public function setPageMargin($margin = false)
{
if (!is_array($margin))
{
$marginArray = [$margin, $margin, $margin, $margin];
}
else
{
$marginArray = $margin;
}
// Get margin
$pageMargin = $this->getPageMargins();
if (isset($marginArray[0]))
$pageMargin->setTop($marginArray[0]);
if (isset($marginArray[1]))
$pageMargin->setRight($marginArray[1]);
if (isset($marginArray[2]))
$pageMargin->setBottom($marginArray[2]);
if (isset($marginArray[3]))
$pageMargin->setLeft($marginArray[3]);
}
/**
* Manipulate a single row
* @param integer|callback|array $rowNumber
* @param array|callback $callback
* @param boolean $explicit
* @return LaravelExcelWorksheet
*/
public function row($rowNumber, $callback = null, $explicit = false)
{
// If a callback is given, handle it with the cell writer
if ($callback instanceof Closure)
{
$range = $this->rowToRange($rowNumber);
return $this->cells($range, $callback);
}
// Else if the 2nd param was set, we will use it as a cell value
if (is_array($callback))
{
// Interpret the callback as cell values
$values = $callback;
// Set start column
$column = 'A';
foreach ($values as $rowValue)
{
// Set cell coordinate
$cell = $column . $rowNumber;
// Set the cell value
if ($explicit) {
$this->setCellValueExplicit($cell, $rowValue);
} else {
$this->setCellValue($cell, $rowValue);
}
$column++;
}
}
// Remember that we have added rows
$this->hasRowsAdded = true;
return $this;
}
/**
* Add multiple rows
* @param array $rows
* @param boolean $explicit
* @return LaravelExcelWorksheet
*/
public function rows($rows = [], $explicit = false)
{
// Get the start row
$startRow = $this->getStartRow();
// Add rows
foreach ($rows as $row)
{
$this->row($startRow, $row, $explicit);
$startRow++;
}
return $this;
}
/**
* Prepend a row
* @param integer $rowNumber
* @param array|callback $callback
* @param boolean $explicit
* @return LaravelExcelWorksheet
*/
public function prependRow($rowNumber = 1, $callback = null, $explicit = false)
{
// If only one param was given, prepend it before the first row
if (is_null($callback))
{
$callback = $rowNumber;
$rowNumber = 1;
}
// Create new row
$this->insertNewRowBefore($rowNumber);
// Add data to row
return $this->row($rowNumber, $callback, $explicit);
}
/**
* Prepend a row explicitly
* @param integer $rowNumber
* @param array|callback $callback
* @return LaravelExcelWorksheet
*/
public function prependRowExplicit($rowNumber = 1, $callback = null)
{
return $this->prependRow($rowNumber, $callback, true);
}
/**
* Append a row
* @param integer|callback $rowNumber
* @param array|callback $callback
* @param boolean $explicit
* @return LaravelExcelWorksheet
*/
public function appendRow($rowNumber = 1, $callback = null, $explicit = false)
{
// If only one param was given, add it as very last
if (is_null($callback))
{
$callback = $rowNumber;
$rowNumber = $this->getStartRow();
}
// Add the row
return $this->row($rowNumber, $callback, $explicit);
}
/**
* Append a row explicitly
* @param integer|callback $rowNumber
* @param array|callback $callback
* @return LaravelExcelWorksheet
*/
public function appendRowExplicit($rowNumber = 1, $callback = null)
{
return $this->appendRow($rowNumber, $callback, true);
}
/**
* Manipulate a single cell
* @param array|string $cell
* @param bool|callable $callback $callback
* @param boolean $explicit
* @return LaravelExcelWorksheet
*/
public function cell($cell, $callback = false, $explicit = false)
{
// If a callback is given, handle it with the cell writer
if ($callback instanceof Closure)
return $this->cells($cell, $callback);
// Else if the 2nd param was set, we will use it as a cell value
if ($callback) {
if ($explicit) {
$this->setCellValueExplicit($cell, $callback);
} else {
$this->setCellValue($cell, $callback);
}
}
return $this;
}
/**
* Manipulate a cell or a range of cells
* @param array $cells
* @param bool|callable $callback $callback
* @return LaravelExcelWorksheet
*/
public function cells($cells, $callback = false)
{
// Init the cell writer
$cells = new CellWriter($cells, $this);
// Do the callback
if ($callback instanceof Closure)
call_user_func($callback, $cells);
return $this;
}
/**
* Load a View and convert to HTML
* @return LaravelExcelWorksheet
*/
public function setView()
{
return call_user_func_array([$this, 'loadView'], func_get_args());
}
/**
* Load a View and convert to HTML
* @param string $view
* @param array $data
* @param array $mergeData
* @return LaravelExcelWorksheet
*/
public function loadView($view, $data = [], $mergeData = [])
{
// Init the parser
if (!$this->parser)
$this->setParser();
$this->parser->setView($view);
$this->parser->setData($data);
$this->parser->setMergeData($mergeData);
return $this;
}
/**
* Unset the view
* @return LaravelExcelWorksheet
*/
public function unsetView()
{
$this->parser = null;
return $this;
}
/**
* Set the parser
* @param boolean $parser
* @return ViewParser
*/
public function setParser($parser = false)
{
return $this->parser = $parser ? $parser : app('excel.parsers.view');
}
/**
* Get the view
* @return ViewParser
*/
public function getView()
{
return $this->parser;
}
/**
* Return parsed sheet
* @return LaravelExcelWorksheet
*/
public function parsed()
{
// If parser is set, use it
if ($this->parser)
return $this->parser->parse($this);
// Else return the entire sheet
return $this;
}
/**
* Set data for the current sheet
* @param $key
* @param bool|string $value
* @param boolean $headingGeneration
* @return LaravelExcelWorksheet
*/
public function with($key, $value = false, $headingGeneration = true)
{
// Set the heading generation setting
$this->setAutoHeadingGeneration($headingGeneration);
// Add the vars
$this->_addVars($key, $value);
return $this;
}
/**
* From array
* @param Collection|array $source
* @param null $nullValue
* @param bool|string $startCell
* @param bool $strictNullComparison
* @param boolean $headingGeneration
* @return LaravelExcelWorksheet
*/
public function fromModel($source = null, $nullValue = null, $startCell = 'A1', $strictNullComparison = false, $headingGeneration = true)
{
return $this->fromArray($source, $nullValue, $startCell, $strictNullComparison, $headingGeneration);
}
/**
* Fill worksheet from values in array
*
* @param array $source Source array
* @param mixed $nullValue Value in source array that stands for blank cell
* @param bool|string $startCell Insert array starting from this cell address as the top left coordinate
* @param boolean $strictNullComparison Apply strict comparison when testing for null values in the array
* @param bool $headingGeneration
* @throws PHPExcel_Exception
* @return LaravelExcelWorksheet
*/
public function fromArray($source = null, $nullValue = null, $startCell = 'A1', $strictNullComparison = false, $headingGeneration = true)
{
// Set defaults
$nullValue = !is_null($nullValue) ? $nullValue : $this->getDefaultNullValue();
$startCell = $startCell ? $startCell : $this->getDefaultStartCell();
$strictNullComparison = $strictNullComparison ? $strictNullComparison : $this->getDefaultStrictNullComparison();
// Set the heading generation setting
$this->setAutoHeadingGeneration($headingGeneration);
// Add the vars
$this->_addVars($source, false, $nullValue, $startCell, $strictNullComparison);
return $this;
}
/**
* Create sheet from array
* @param null $source
* @param null $nullValue
* @param bool|string $startCell
* @param bool $strictNullComparison
* @throws PHPExcel_Exception
* @return $this
*/
public function createSheetFromArray($source = null, $nullValue = null, $startCell = 'A1', $strictNullComparison = false)
{
if (is_array($source))
{
// Convert a 1-D array to 2-D (for ease of looping)
if (!is_array(end($source)))
{
$source = array($source);
}
// start coordinate
list ($startColumn, $startRow) = PHPExcel_Cell::coordinateFromString($startCell);
// Loop through $source
foreach ($source as $rowData)
{
$currentColumn = $startColumn;
foreach ($rowData as $cellValue)
{
if ($strictNullComparison)
{
if ($cellValue !== $nullValue)
{
// Set cell value
$this->setValueOfCell($cellValue, $currentColumn, $startRow);
}
}
else
{
if ($cellValue != $nullValue)
{
// Set cell value
$this->setValueOfCell($cellValue, $currentColumn, $startRow);
}
}
++$currentColumn;
}
++$startRow;
}
}
else
{
throw new PHPExcel_Exception("Parameter \$source should be an array.");
}
return $this;
}
/**
* Add vars to the data array
* @param string $key
* @param bool|string $value
* @param null $nullValue
* @param bool|string $startCell
* @param bool $strictNullComparison
* @throws PHPExcel_Exception
* @return void|$this
*/
protected function _addVars($key, $value = false, $nullValue = null, $startCell = 'A1', $strictNullComparison = false)
{
// Add array of data
if (is_array($key) || $key instanceof Collection)
{
// Set the data
$this->data = $this->addData($key);
// Create excel from array without a view
if (!$this->parser)
{
return $this->createSheetFromArray($this->data, $nullValue, $startCell, $strictNullComparison);
}
}
// Add seperate values
else
{
$this->data[$key] = $value;
}
// Set data to parser
if ($this->parser)
$this->parser->setData($this->data);
}
/**
* Add data
* @param array $array
* @return array
*/
protected function addData($array)
{
// If a parser was set
if ($this->parser)
{
// Don't change anything
$data = $array;
}
else
{
// Transform model/collection to array
if ($array instanceof Collection)
$array = $array->toArray();
// Get the firstRow
$firstRow = reset($array);
// Check if the array has array values
if (count($firstRow) != count($firstRow, 1))
{
// Loop through the data to remove arrays
$data = [];
$r = 0;
foreach ($array as $row)
{
$data[$r] = array();
foreach ($row as $key => $cell)
{
if (!is_array($cell))
{
$data[$r][$key] = $cell;
}
}
$r++;
}
}
else
{
$data = $array;
}
// Check if we should auto add the first row based on the indices
if ($this->generateHeadingByIndices())
{
// Get the first row
$firstRow = reset($data);
if (is_array($firstRow))
{
// Get the array keys
$tableHeading = array_keys($firstRow);
// Add table headings as first row
array_unshift($data, $tableHeading);
}
}
}
// Add results
if (!empty($data))
$this->data = !empty($this->data) ? array_merge($this->data, $data) : $data;
// return data
return $this->data;
}
/**
* Set the auto heading generation setting
* @param boolean $boolean
* @return LaravelExcelWorksheet
*/
public function setAutoHeadingGeneration($boolean)
{
$this->autoGenerateHeading = $boolean;
return $this;
}
/**
* Disable the heading generation
* @param boolean $boolean
* @return LaravelExcelWorksheet
*/
public function disableHeadingGeneration($boolean = false)
{
$this->setAutoHeadingGeneration($boolean);
return $this;
}
/**
* Check if we should auto generate the table heading
* @return boolean
*/
protected function generateHeadingByIndices()
{
return $this->autoGenerateHeading;
}
/**
* Set attributes
* @param $setter
* @param array|string $params
* @throws LaravelExcelException
* @return void|PHPExcel_Worksheet_PageSetup
*/
public function _setAttributes($setter, $params)
{
// Set the setter and the key
list($setter, $key) = $this->_setSetter($setter);
// If is page setup
if (in_array($key, $this->allowedPageSetup))
{
// Set params
$params = is_array($params) ? $params : [$params];
// Call the setter
return call_user_func_array([$this->getPageSetup(), $setter], $params);
}
// If is a style
elseif (in_array($key, $this->allowedStyles))
{
return $this->setDefaultStyles($setter, $key, $params);
}
else
{
throw new LaravelExcelException('[ERROR] Laravel Worksheet method [' . $setter . '] does not exist.');
}
}
/**
* Set default styles
* @param string $setter
* @param string $key
* @param array|string $params
* @return PHPExcel_Style
*/
protected function setDefaultStyles($setter, $key, $params)
{
$caller = $this->getDefaultStyle();
$params = is_array($params) ? $params : [$params];
if (str_contains($key, 'font'))
return $this->setFontStyle($caller, $setter, $key, $params);
return call_user_func_array([$caller, $setter], $params);
}
/**
* Set default styles by array
* @param array $styles
* @return LaravelExcelWorksheet
*/
public function setStyle($styles)
{
$this->getDefaultStyle()->applyFromArray($styles);
return $this;
}
/**
* Set the font
* @param array $fonts
* @return LaravelExcelWorksheet
*/
public function setFont($fonts)
{
foreach ($fonts as $key => $value)
{
$this->setFontStyle($this->getDefaultStyle(), $key, $key, $value);
}
return $this;
}
/**
* Set default font styles
* @param string $caller
* @param string $key
* @param array|string $params
* @return PHPExcel_Style
*/
protected function setFontStyle($caller, $setter, $key, $params)
{
// Set caller to font
$caller = $caller->getFont();
$params = is_array($params) ? $params : [$params];
// Clean the setter name
$setter = lcfirst(str_replace('Font', '', $setter));
// Replace special cases
$setter = str_replace('Family', 'Name', $setter);
return call_user_func_array([$caller, $setter], $params);
}
/**
* Set the setter
* @param string $setter
* @return array
*/
protected function _setSetter($setter)
{
if (starts_with($setter, 'set'))
{
$key = lcfirst(str_replace('set', '', $setter));
}
else
{
$key = $setter;
$setter = 'set' . ucfirst($key);
}
// Return the setter method and the key
return array($setter, $key);
}
/**
* Set the parent (excel object)
* @param PHPExcel $parent
*/
public function setParent($parent)
{
$this->_parent = $parent;
}
/**
* Get the parent excel obj
* @return PHPExcel
*/
public function getParent()
{
return $this->_parent;
}
/**
* Set the column width
* @param string|array $column
* @param boolean $value
* @return LaravelExcelWorksheet
*/
public function setWidth($column, $value = false)
{
// if is array of columns
if (is_array($column))
{
// Set width for each column
foreach ($column as $subColumn => $subValue)
{
$this->setWidth($subColumn, $subValue);
}
}
else
{
// Disable the autosize and set column width
$this->getColumnDimension($column)
->setAutoSize(false)
->setWidth($value);
// Set autosized to true
$this->hasFixedSizeColumns = true;
}
return $this;
}
/**
* Set the row height
* @param integer|array $row
* @param boolean $value
* @return LaravelExcelWorksheet
*/
public function setHeight($row, $value = false)
{
// if is array of columns
if (is_array($row))
{
// Set width for each column
foreach ($row as $subRow => $subValue)
{
$this->setHeight($subRow, $subValue);
}
}
else
{
// Set column width
$this->getRowDimension($row)->setRowHeight($value);
}
return $this;
}
/**
* Set cell size
* @param array|string $cell
* @param bool $width
* @param bool|int $height
* @return LaravelExcelWorksheet
*/
public function setSize($cell, $width = false, $height = false)
{
// if is array of columns
if (is_array($cell))
{
// Set width for each column
foreach ($cell as $subCell => $sizes)
{
$this->setSize($subCell, reset($sizes), end($sizes));
}
}
else
{
// Split the cell to column and row
list($column, $row) = preg_split('/(?<=[a-z])(?=[0-9]+)/i', $cell);
if ($column)
$this->setWidth($column, $width);
if ($row)
$this->setHeight($row, $height);
}
return $this;
}
/**
* Autosize column for document
* @param array|boolean $columns
* @return void
*/
public function setAutoSize($columns = false)
{
// Remember that the sheet was autosized
$this->hasFixedSizeColumns = $columns || !empty($columns) ? false : true;
// Set autosize to true
$this->autoSize = $columns ? $columns : false;
// If is not an array
if (!is_array($columns) && $columns)
{
// Get the highest column
$toCol = $this->getHighestColumn();
// Lop through the columns and set the auto size
$toCol++;
for ($i = 'A'; $i !== $toCol; $i++)
{
$this->getColumnDimension($i)->setAutoSize(true);
}
}
// Set autosize for the given columns
elseif (is_array($columns))
{
foreach ($columns as $column)
{
$this->getColumnDimension($column)->setAutoSize(true);
}
}
// Calculate the column widths
$this->calculateColumnWidths();
return $this;
}
/**
* Get Auto size
* @return bool
*/
public function getAutosize()
{
if (isset($this->autoSize))
return $this->autoSize;
return config('excel.export.autosize', true);
}
/**
* Check if the sheet was auto sized dynamically
* @return boolean
*/
public function hasFixedSizeColumns()
{
return $this->hasFixedSizeColumns ? true : false;
}
/**
* Set the auto filter
* @param boolean $value
* @return LaravelExcelWorksheet
*/
public function setAutoFilter($value = false)
{
$value = $value ? $value : $this->calculateWorksheetDimension();
parent::setAutoFilter($value);
return $this;
}
/**
* Freeze or lock rows and columns
* @param string $pane rows and columns
* @return LaravelExcelWorksheet
*/
public function setFreeze($pane = 'A2')
{
$this->freezePane($pane);
return $this;
}
/**
* Freeze the first row
* @return LaravelExcelWorksheet
*/
public function freezeFirstRow()
{
$this->setFreeze('A2');
return $this;
}
/**
* Freeze the first column
* @return LaravelExcelWorksheet
*/
public function freezeFirstColumn()
{
$this->setFreeze('B1');
return $this;
}
/**
* Freeze the first row and column
* @return LaravelExcelWorksheet
*/
public function freezeFirstRowAndColumn()
{
$this->setFreeze('B2');
return $this;
}
/**
* Set a range of cell borders
* @param string $pane Start and end of the cell (A1:F10)
* @param string $weight Border style
* @return LaravelExcelWorksheet
*/
public function setBorder($pane = 'A1', $weight = 'thin')
{
// Set all borders
$this->getStyle($pane)
->getBorders()
->getAllBorders()
->setBorderStyle($weight);
return $this;
}
/**
* Set all cell borders
* @param string $weight Border style (Reference setBorder style list)
* @return LaravelExcelWorksheet
*/
public function setAllBorders($weight = 'thin')
{
$styleArray = [
'borders' => [
'allborders' => [
'style' => $weight
]
]
];
// Apply the style
$this->getDefaultStyle()
->applyFromArray($styleArray);
return $this;
}
/**
* Set the cell format of the column
* @param array $formats An array of cells you want to format columns
* @return LaravelExcelWorksheet
*/
public function setColumnFormat(Array $formats)
{
// Loop through the columns
foreach ($formats as $column => $format)
{
// Change the format for a specific cell or range
$this->getStyle($column)
->getNumberFormat()
->setFormatCode($format);
}
return $this;
}
/**
* Merge cells
* @param string $pRange
* @param bool $alignment
* @throws PHPExcel_Exception
* @return LaravelExcelWorksheet
*/
public function mergeCells($pRange = 'A1:A1', $alignment = false)
{
// Merge the cells
parent::mergeCells($pRange);
// Set center alignment on merge cells
$this->cells($pRange, function ($cell) use ($alignment)
{
$aligment = is_string($alignment) ? $alignment : config('excel.export.merged_cell_alignment', 'left');
$cell->setAlignment($aligment);
});
return $this;
}
/**
* Set the columns you want to merge
* @return LaravelExcelWorksheet
* @param array $mergeColumn An array of columns you want to merge
* @param bool $alignment
*/
public function setMergeColumn(Array $mergeColumn, $alignment = false)
{
foreach ($mergeColumn['columns'] as $column)
{
foreach ($mergeColumn['rows'] as $row)
{
$this->mergeCells($column . $row[0] . ":" . $column . $row[1], $alignment);
}
}
return $this;
}
/**
* Password protect a sheet
* @param $password
* @param callable $callback
*/
public function protect($password, Closure $callback = null)
{
$protection = $this->getProtection();
$protection->setPassword($password);
$protection->setSheet(true);
$protection->setSort(true);
$protection->setInsertRows(true);
$protection->setFormatCells(true);
if(is_callable($callback)) {
call_user_func($callback, $protection);
}
}
/**
* Return the start row
* @return integer
*/
protected function getStartRow()
{
if ($this->getHighestRow() == 1 && !$this->hasRowsAdded)
return 1;
return $this->getHighestRow() + 1;
}
/**
* Return range from row
* @param integer $rowNumber
* @return string $range
*/
protected function rowToRange($rowNumber)
{
return 'A' . $rowNumber . ':' . $this->getHighestColumn() . $rowNumber;
}
/**
* Return default null value
* @return string|integer|null
*/
protected function getDefaultNullValue()
{
return config('excel.export.sheets.nullValue', null);
}
/**
* Return default null value
* @return string|integer|null
*/
protected function getDefaultStartCell()
{
return config('excel.export.sheets.startCell', 'A1');
}
/**
* Return default strict null comparison
* @return boolean
*/
protected function getDefaultStrictNullComparison()
{
return config('excel.export.sheets.strictNullComparison', false);
}
/**
* load info from parent obj
* @param \PHPExcel_Worksheet $sheet
* @return $this
*/
function cloneParent(PHPExcel_Worksheet $sheet)
{
// Init new reflection object
$class = new \ReflectionClass(get_class($sheet));
// Loop through all properties
foreach($class->getProperties() as $property)
{
// Make the property public
$property->setAccessible(true);
// Get value from original sheet
$value = $property->getValue($sheet);
// Set the found value to this sheet
$property->setValue(
$this,
$value
);
}
// Rebind the PhpExcel object to the style objects
$this->getStyle()->bindParent($this->getParent());
return $this;
}
/**
* Dynamically call methods
* @param string $method
* @param array $params
* @throws LaravelExcelException
* @return LaravelExcelWorksheet
*/
public function __call($method, $params)
{
// If the dynamic call starts with "with", add the var to the data array
if (starts_with($method, 'with'))
{
$key = lcfirst(str_replace('with', '', $method));
$this->_addVars($key, reset($params));
return $this;
}
// If it's a setter
elseif (starts_with($method, 'set'))
{
// set the attribute
$this->_setAttributes($method, $params);
return $this;
}
throw new LaravelExcelException('[ERROR] Laravel Worksheet method [' . $method . '] does not exist.');
}
/**
* @param string $cellValue
* @param mixed|null $currentColumn
* @param bool $startRow
* @return \PHPExcel_Cell|\PHPExcel_Worksheet|void
* @throws PHPExcel_Exception
*/
public function setValueOfCell($cellValue, $currentColumn, $startRow)
{
is_string($cellValue) && is_numeric($cellValue) && !is_integer($cellValue)
? $this->getCell($currentColumn . $startRow)->setValueExplicit($cellValue)
: $this->getCell($currentColumn . $startRow)->setValue($cellValue);
}
}
| alejandri/crud-laravel-databel | vendor/maatwebsite/excel/src/Maatwebsite/Excel/Classes/LaravelExcelWorksheet.php | PHP | gpl-3.0 | 33,483 |
var ccoding_stds_naming =
[
[ "Naming Overview", "ccoding_stds_naming.html#cstdsNaming", [
[ "Be Descriptive", "ccoding_stds_naming.html#descript", null ],
[ "Prefixes", "ccoding_stds_naming.html#prefix", null ],
[ "Component Interfaces", "ccoding_stds_naming.html#cstdsInterComponentInterfaces", null ],
[ "Module Interfaces", "ccoding_stds_naming.html#cstdsInterModuleInterfaces", null ]
] ],
[ "Files", "ccoding_stds_naming.html#cstdsFiles", null ],
[ "Macros", "ccoding_stds_naming.html#cstdsMacros", null ],
[ "Types", "ccoding_stds_name_types.html", [
[ "Suffix", "ccoding_stds_name_types.html#cstdsNameSuffix", null ],
[ "Prefix", "ccoding_stds_name_types.html#cstdsNameTypesPrefix", null ],
[ "Name", "ccoding_stds_name_types.html#cstdsNameType", null ],
[ "Cardinal Types", "ccoding_stds_name_types.html#cstdsCardinalTypes", null ],
[ "Enumeration Members", "ccoding_stds_name_types.html#cstdsEnumerationMembers", null ],
[ "Struct and Union Namespaces", "ccoding_stds_name_types.html#cstdsStructandUnionNamespaces", null ],
[ "Struct and Union Members", "ccoding_stds_name_types.html#cstdsStructandUnionMembers", null ]
] ],
[ "Functions", "ccoding_stds_name_funcs.html", [
[ "Prefix", "ccoding_stds_name_funcs.html#cstdsFuncsPrefix", null ],
[ "Camel Case", "ccoding_stds_name_funcs.html#cstdsCamelCaseName", null ],
[ "Verbage", "ccoding_stds_name_funcs.html#cstdsVerbage", null ]
] ],
[ "Variables & Function Parameters", "ccoding_stds_param.html", [
[ "Camel Case", "ccoding_stds_param.html#cstdsparamCamelCase", null ],
[ "Prefix", "ccoding_stds_param.html#cstdsparamPrefix", null ],
[ "Pointers", "ccoding_stds_param.html#cstdsparamPointers", null ],
[ "Static Variables", "ccoding_stds_param.html#cstdsparamStaticVariables", null ],
[ "Abbreviations", "ccoding_stds_param.html#cstdsparamAbbreviations", null ]
] ]
]; | legatoproject/legato-docs | 15_10/ccoding_stds_naming.js | JavaScript | mpl-2.0 | 1,987 |
var global = newGlobal();
var arrayIter = (new global.Array())[global.Symbol.iterator]();
var ArrayIteratorPrototype = Object.getPrototypeOf(arrayIter);
var arrayIterProtoBase = Object.getPrototypeOf(ArrayIteratorPrototype);
var IteratorPrototype = arrayIterProtoBase;
delete IteratorPrototype.next;
var obj = global.eval('({a: 1})')
for (var x in obj) {}
assertEq(x, "a");
| cstipkovic/spidermonkey-research | js/src/jit-test/tests/basic/cross-global-for-in.js | JavaScript | mpl-2.0 | 376 |