repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
computergeek1507/openhab | bundles/binding/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/network/typicals/SoulissGenericTypical.java | 4886 | /**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* 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.openhab.binding.souliss.internal.network.typicals;
import java.net.DatagramSocket;
import org.openhab.binding.souliss.internal.network.udp.SoulissCommGate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class implements the base Souliss Typical All other Typicals derive from
* this class
*
* ...from wiki of Dario De Maio
* In Souliss the logics that drive your lights, curtains, LED, and
* others are pre-configured into so called Typicals. A Typical is a
* logic with a predefined set of inputs and outputs and a know
* behavior, are used to standardize the user interface and have a
* configuration-less behavior.
*
* @author Tonino Fazio
* @since 1.7.0
*/
public abstract class SoulissGenericTypical {
private int iSlot;
private int iSoulissNodeID;
private short sType;
private float fState;
private String sName;
private boolean isUpdated = false;
private String sNote;
private static Logger logger = LoggerFactory.getLogger(SoulissGenericTypical.class);
/**
* @return the iSlot
*/
public int getSlot() {
return iSlot;
}
/**
* @param iSlot
* the Slot number to set
*/
public void setSlot(int iSlot) {
this.iSlot = iSlot;
}
/**
* @param SoulissNode
* the SoulissNodeID to get
*/
public int getSoulissNodeID() {
return iSoulissNodeID;
}
/**
* @param SoulissNode
* the SoulissNodeID to set
*/
public void setSoulissNodeID(int setSoulissNodeID) {
this.iSoulissNodeID = setSoulissNodeID;
}
/**
* @return the sType
*/
public short getType() {
return sType;
}
/**
* @param soulissT
* the typical to set
*/
protected void setType(short soulissT) {
this.sType = soulissT;
}
/**
* @return the iState
*/
public float getState() {
return fState;
}
/**
* @param iState
* the state of typical
*/
public void setState(float iState) {
logger.debug("Update State. Name: {}, Typ: 0x{}, Node: {}, Slot: {}. New State: {}", getName(),
Integer.toHexString(getType()), getSoulissNodeID(), getSlot(), iState);
this.fState = iState;
setUpdatedTrue();
}
/**
* @return the nodeName
*/
public String getName() {
return sName;
}
/**
* @param nodeName
* the nodeName to set
*/
public void setName(String nodeName) {
this.sName = nodeName;
}
/**
* @return isUpdated
*/
public boolean isUpdated() {
return isUpdated;
}
/**
* Set to FALSE if new values have been read
*/
public void resetUpdate() {
isUpdated = false;
}
/**
* Set to TRUE if there are a new values inside.
*
* @return the isUpdated
*/
public void setUpdatedTrue() {
this.isUpdated = true;
}
public String getNote() {
return sNote;
}
/**
* Used to store the Openhab type inside typical
*/
public void setNote(String sNote) {
this.sNote = sNote;
}
/**
* Send command in multicast
*
* @param datagramSocket
* @param command
*/
void commandMulticast(DatagramSocket datagramSocket, short command) {
logger.debug("Typ: {}, Name: {} - CommandMulticast: {}", getType(), getName(), command);
SoulissCommGate.sendMULTICASTFORCEFrame(datagramSocket, SoulissNetworkParameter.IPAddressOnLAN, getType(),
command);
}
/**
* Request the database structure, aka DBStruct
*
* @param datagramSocket
*/
public void sendDBStructFrame(DatagramSocket datagramSocket) {
logger.debug("Typ: {}, Name: {} - sendDBStructFrame", getType(), getName());
SoulissCommGate.sendDBStructFrame(datagramSocket, SoulissNetworkParameter.IPAddressOnLAN);
}
/**
* Ping the gateway
*
* @param datagramSocket
* @param putIn_1
* @param punIn_2
*/
public void ping(DatagramSocket datagramSocket, short putIn_1, short punIn_2) {
logger.debug("Typ: {}, Name: {} - ping", getType(), getName());
SoulissCommGate.sendPing(datagramSocket, SoulissNetworkParameter.IPAddressOnLAN, putIn_1, punIn_2);
}
public abstract org.openhab.core.types.State getOHState();
}
| epl-1.0 |
idserda/openhab | bundles/binding/org.openhab.binding.primare/src/main/java/org/openhab/binding/primare/internal/protocol/spa20/PrimareSPA20MessageFactory.java | 2083 | /**
* Copyright (c) 2010-2019 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.primare.internal.protocol.spa20;
import org.openhab.binding.primare.internal.protocol.PrimareMessageFactory;
import org.openhab.core.types.Command;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class for Primare SP31.7/SP31/SPA20/SPA21 messages
* This class is used for converting OpenHAB commands
* to a byte array representation to be sent to the Primare.
*
* @author Veli-Pekka Juslin
* @since 1.7.0
*/
public class PrimareSPA20MessageFactory extends PrimareMessageFactory {
private static final Logger logger = LoggerFactory.getLogger(PrimareSPA20MessageFactory.class);
public PrimareSPA20Message getMessage(Command command, PrimareSPA20Command deviceCmd) {
return new PrimareSPA20Message(command, deviceCmd);
}
@Override
public PrimareSPA20Message getMessage(Command command, String deviceCmdString) {
return getMessage(command, PrimareSPA20Command.valueOf(deviceCmdString));
}
// Request full status at connection initialization
@Override
public PrimareSPA20Message[] getInitMessages() {
return new PrimareSPA20Message[] { getMessage(null, PrimareSPA20Command.VERBOSE_ON), // send response after
// update
getMessage(null, PrimareSPA20Command.ALL_QUERY) };
}
@Override
public PrimareSPA20Message[] getPingMessages() {
return new PrimareSPA20Message[] { getMessage(null, PrimareSPA20Command.VERBOSE_ON), // send response after
// update
getMessage(null, PrimareSPA20Command.POWER_QUERY) };
}
}
| epl-1.0 |
hexbinary/landing | src/main/java/oscar/oscarWaitingList/bean/WLWaitingListNameBean.java | 1959 | /**
* Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved.
* This software is published under the GPL GNU General Public License.
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* This software was written for the
* Department of Family Medicine
* McMaster University
* Hamilton
* Ontario, Canada
*/
package oscar.oscarWaitingList.bean;
public class WLWaitingListNameBean{
String waitingListName;
String ID;
String groupNo;
String providerNo;
String createdDate;
public WLWaitingListNameBean(String nameId, String waitingListName, String groupNo,
String providerNo, String createdDate ){
this.waitingListName = waitingListName;
this.ID = nameId;
this.groupNo = groupNo;
this.providerNo = providerNo;
this.createdDate = createdDate;
}
public String getWaitingListName(){
return waitingListName;
}
public String getId(){
return ID;
}
public String getGroupNo() {
return groupNo;
}
public String getProviderNo() {
return providerNo;
}
public String getCreatedDate() {
return createdDate;
}
}
| gpl-2.0 |
hexbinary/landing | src/main/java/org/oscarehr/casemgmt/web/ProviderAccessRight.java | 1454 | /**
*
* Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved.
* This software is published under the GPL GNU General Public License.
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* This software was written for
* Centre for Research on Inner City Health, St. Michael's Hospital,
* Toronto, Ontario, Canada
*/
package org.oscarehr.casemgmt.web;
public class ProviderAccessRight
{
private String accessName;
private boolean isAccess;
public String getAccessName()
{
return accessName;
}
public void setAccessName(String accessName)
{
this.accessName = accessName;
}
public boolean isAccess()
{
return isAccess;
}
public void setAccess(boolean isAccess)
{
this.isAccess = isAccess;
}
}
| gpl-2.0 |
mdaniel/svn-caucho-com-resin | modules/resin/src/com/caucho/rewrite/NotFound.java | 1908 | /*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.rewrite;
import javax.servlet.DispatcherType;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletResponse;
import com.caucho.config.Configurable;
import com.caucho.server.dispatch.ErrorFilterChain;
/**
* Sends a HTTP 404 Not Found response
*
* <pre>
* <web-app xmlns:resin="urn:java:com.caucho.resin">
*
* <resin:NotFound regexp="^/hidden" target="/bar"/>
*
* </web-app>
* </pre>
*/
@Configurable
public class NotFound extends AbstractTargetDispatchRule
{
@Override
public FilterChain createDispatch(DispatcherType type,
String uri,
String queryString,
String target,
FilterChain next)
{
return new ErrorFilterChain(HttpServletResponse.SC_NOT_FOUND);
}
}
| gpl-2.0 |
axDev-JDK/jaxp | src/com/sun/org/apache/xalan/internal/xsltc/runtime/ErrorMessages_fr.java | 12383 | /*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: ErrorMessages_fr.java,v 1.2.4.1 2005/09/14 05:15:37 pvedula Exp $
*/
package com.sun.org.apache.xalan.internal.xsltc.runtime;
import java.util.ListResourceBundle;
/**
* @author Morten Jorgensen
*/
public class ErrorMessages_fr extends ListResourceBundle {
/*
* XSLTC run-time error messages.
*
* General notes to translators and definitions:
*
* 1) XSLTC is the name of the product. It is an acronym for XML Stylesheet:
* Transformations Compiler
*
* 2) A stylesheet is a description of how to transform an input XML document
* into a resultant output XML document (or HTML document or text)
*
* 3) An axis is a particular "dimension" in a tree representation of an XML
* document; the nodes in the tree are divided along different axes.
* Traversing the "child" axis, for instance, means that the program
* would visit each child of a particular node; traversing the "descendant"
* axis means that the program would visit the child nodes of a particular
* node, their children, and so on until the leaf nodes of the tree are
* reached.
*
* 4) An iterator is an object that traverses nodes in a tree along a
* particular axis, one at a time.
*
* 5) An element is a mark-up tag in an XML document; an attribute is a
* modifier on the tag. For example, in <elem attr='val' attr2='val2'>
* "elem" is an element name, "attr" and "attr2" are attribute names with
* the values "val" and "val2", respectively.
*
* 6) A namespace declaration is a special attribute that is used to associate
* a prefix with a URI (the namespace). The meanings of element names and
* attribute names that use that prefix are defined with respect to that
* namespace.
*
* 7) DOM is an acronym for Document Object Model. It is a tree
* representation of an XML document.
*
* SAX is an acronym for the Simple API for XML processing. It is an API
* used inform an XML processor (in this case XSLTC) of the structure and
* content of an XML document.
*
* Input to the stylesheet processor can come from an XML parser in the
* form of a DOM tree or through the SAX API.
*
* 8) DTD is a document type declaration. It is a way of specifying the
* grammar for an XML file, the names and types of elements, attributes,
* etc.
*
* 9) Translet is an invented term that refers to the class file that contains
* the compiled form of a stylesheet.
*/
// These message should be read from a locale-specific resource bundle
private static final Object[][] _contents = new Object[][] {
/*
* Note to translators: the substitution text in the following message
* is a class name. Used for internal errors in the processor.
*/
{BasisLibrary.RUN_TIME_INTERNAL_ERR,
"Erreur interne d''ex\u00E9cution dans ''{0}''"},
/*
* Note to translators: <xsl:copy> is a keyword that should not be
* translated.
*/
{BasisLibrary.RUN_TIME_COPY_ERR,
"Erreur d'ex\u00E9cution de <xsl:copy>."},
/*
* Note to translators: The substitution text refers to data types.
* The message is displayed if a value in a particular context needs to
* be converted to type {1}, but that's not possible for a value of type
* {0}.
*/
{BasisLibrary.DATA_CONVERSION_ERR,
"Conversion de ''{0}'' \u00E0 ''{1}'' non valide."},
/*
* Note to translators: This message is displayed if the function named
* by the substitution text is not a function that is supported. XSLTC
* is the acronym naming the product.
*/
{BasisLibrary.EXTERNAL_FUNC_ERR,
"Fonction externe ''{0}'' non prise en charge par XSLTC."},
/*
* Note to translators: This message is displayed if two values are
* compared for equality, but the data type of one of the values is
* unknown.
*/
{BasisLibrary.EQUALITY_EXPR_ERR,
"Type d'argument inconnu dans l'expression d'\u00E9galit\u00E9."},
/*
* Note to translators: The substitution text for {0} will be a data
* type; the substitution text for {1} will be the name of a function.
* This is displayed if an argument of the particular data type is not
* permitted for a call to this function.
*/
{BasisLibrary.INVALID_ARGUMENT_ERR,
"Type d''argument ''{0}'' non valide dans l''appel de ''{1}''"},
/*
* Note to translators: There is way of specifying a format for a
* number using a pattern; the processor was unable to format the
* particular value using the specified pattern.
*/
{BasisLibrary.FORMAT_NUMBER_ERR,
"Tentative de formatage du nombre ''{0}'' \u00E0 l''aide du mod\u00E8le ''{1}''."},
/*
* Note to translators: The following represents an internal error
* situation in XSLTC. The processor was unable to create a copy of an
* iterator. (See definition of iterator above.)
*/
{BasisLibrary.ITERATOR_CLONE_ERR,
"Impossible de cloner l''it\u00E9rateur ''{0}''."},
/*
* Note to translators: The following represents an internal error
* situation in XSLTC. The processor attempted to create an iterator
* for a particular axis (see definition above) that it does not
* support.
*/
{BasisLibrary.AXIS_SUPPORT_ERR,
"It\u00E9rateur de l''axe ''{0}'' non pris en charge."},
/*
* Note to translators: The following represents an internal error
* situation in XSLTC. The processor attempted to create an iterator
* for a particular axis (see definition above) that it does not
* support.
*/
{BasisLibrary.TYPED_AXIS_SUPPORT_ERR,
"It\u00E9rateur de l''axe saisi ''{0}'' non pris en charge."},
/*
* Note to translators: This message is reported if the stylesheet
* being processed attempted to construct an XML document with an
* attribute in a place other than on an element. The substitution text
* specifies the name of the attribute.
*/
{BasisLibrary.STRAY_ATTRIBUTE_ERR,
"Attribut ''{0}'' en dehors de l''\u00E9l\u00E9ment."},
/*
* Note to translators: As with the preceding message, a namespace
* declaration has the form of an attribute and is only permitted to
* appear on an element. The substitution text {0} is the namespace
* prefix and {1} is the URI that was being used in the erroneous
* namespace declaration.
*/
{BasisLibrary.STRAY_NAMESPACE_ERR,
"La d\u00E9claration d''espace de noms ''{0}''=''{1}'' est \u00E0 l''ext\u00E9rieur de l''\u00E9l\u00E9ment."},
/*
* Note to translators: The stylesheet contained a reference to a
* namespace prefix that was undefined. The value of the substitution
* text is the name of the prefix.
*/
{BasisLibrary.NAMESPACE_PREFIX_ERR,
"L''espace de noms du pr\u00E9fixe ''{0}'' n''a pas \u00E9t\u00E9 d\u00E9clar\u00E9."},
/*
* Note to translators: The following represents an internal error.
* DOMAdapter is a Java class in XSLTC.
*/
{BasisLibrary.DOM_ADAPTER_INIT_ERR,
"DOMAdapter cr\u00E9\u00E9 avec le mauvais type de DOM source."},
/*
* Note to translators: The following message indicates that the XML
* parser that is providing input to XSLTC cannot be used because it
* does not describe to XSLTC the structure of the input XML document's
* DTD.
*/
{BasisLibrary.PARSER_DTD_SUPPORT_ERR,
"L'analyseur SAX que vous utilisez ne g\u00E8re pas les \u00E9v\u00E9nements de d\u00E9claration DTD."},
/*
* Note to translators: The following message indicates that the XML
* parser that is providing input to XSLTC cannot be used because it
* does not distinguish between ordinary XML attributes and namespace
* declarations.
*/
{BasisLibrary.NAMESPACES_SUPPORT_ERR,
"L'analyseur SAX que vous utilisez ne prend pas en charge les espaces de noms XML."},
/*
* Note to translators: The substitution text is the URI that was in
* error.
*/
{BasisLibrary.CANT_RESOLVE_RELATIVE_URI_ERR,
"Impossible de r\u00E9soudre la r\u00E9f\u00E9rence d''URI ''{0}''."},
/*
* Note to translators: The stylesheet contained an element that was
* not recognized as part of the XSL syntax. The substitution text
* gives the element name.
*/
{BasisLibrary.UNSUPPORTED_XSL_ERR,
"El\u00E9ment XSL ''{0}'' non pris en charge"},
/*
* Note to translators: The stylesheet referred to an extension to the
* XSL syntax and indicated that it was defined by XSLTC, but XSLTC does
* not recognize the particular extension named. The substitution text
* gives the extension name.
*/
{BasisLibrary.UNSUPPORTED_EXT_ERR,
"Extension XSLTC ''{0}'' non reconnue"},
/*
* Note to translators: This error message is produced if the translet
* class was compiled using a newer version of XSLTC and deployed for
* execution with an older version of XSLTC. The substitution text is
* the name of the translet class.
*/
{BasisLibrary.UNKNOWN_TRANSLET_VERSION_ERR,
"Le translet sp\u00E9cifi\u00E9, ''{0}'', a \u00E9t\u00E9 cr\u00E9\u00E9 \u00E0 l''aide d''une version de XSLTC plus r\u00E9cente que la version de l''ex\u00E9cution XSLTC utilis\u00E9e. Vous devez recompiler la feuille de style ou utiliser une version plus r\u00E9cente de XSLTC pour ex\u00E9cuter ce translet."},
/*
* Note to translators: An attribute whose effective value is required
* to be a "QName" had a value that was incorrect.
* 'QName' is an XML syntactic term that must not be translated. The
* substitution text contains the actual value of the attribute.
*/
{BasisLibrary.INVALID_QNAME_ERR,
"Un attribut dont la valeur doit \u00EAtre un QName avait la valeur ''{0}''"},
/*
* Note to translators: An attribute whose effective value is required
* to be a "NCName" had a value that was incorrect.
* 'NCName' is an XML syntactic term that must not be translated. The
* substitution text contains the actual value of the attribute.
*/
{BasisLibrary.INVALID_NCNAME_ERR,
"Un attribut dont la valeur doit \u00EAtre un NCName avait la valeur ''{0}''"},
{BasisLibrary.UNALLOWED_EXTENSION_FUNCTION_ERR,
"L''utilisation de la fonction d''extension ''{0}'' n''est pas autoris\u00E9e lorsque la fonctionnalit\u00E9 de traitement s\u00E9curis\u00E9 est d\u00E9finie sur True."},
{BasisLibrary.UNALLOWED_EXTENSION_ELEMENT_ERR,
"L''utilisation de l''\u00E9l\u00E9ment d''extension ''{0}'' n''est pas autoris\u00E9e lorsque la fonctionnalit\u00E9 de traitement s\u00E9curis\u00E9 est d\u00E9finie sur True."},
};
/** Get the lookup table for error messages.
*
* @return The message lookup table.
*/
public Object[][] getContents()
{
return _contents;
}
}
| gpl-2.0 |
lostdj/Jaklin-OpenJDK-JDK | src/java.desktop/share/classes/javax/imageio/metadata/IIOMetadataNode.java | 33401 | /*
* Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.metadata;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.DOMException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.TypeInfo;
import org.w3c.dom.UserDataHandler;
class IIODOMException extends DOMException {
private static final long serialVersionUID = -4369510142067447468L;
public IIODOMException(short code, String message) {
super(code, message);
}
}
class IIONamedNodeMap implements NamedNodeMap {
List<? extends Node> nodes;
public IIONamedNodeMap(List<? extends Node> nodes) {
this.nodes = nodes;
}
public int getLength() {
return nodes.size();
}
public Node getNamedItem(String name) {
Iterator<? extends Node> iter = nodes.iterator();
while (iter.hasNext()) {
Node node = iter.next();
if (name.equals(node.getNodeName())) {
return node;
}
}
return null;
}
public Node item(int index) {
Node node = nodes.get(index);
return node;
}
public Node removeNamedItem(java.lang.String name) {
throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
"This NamedNodeMap is read-only!");
}
public Node setNamedItem(Node arg) {
throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
"This NamedNodeMap is read-only!");
}
/**
* Equivalent to <code>getNamedItem(localName)</code>.
*/
public Node getNamedItemNS(String namespaceURI, String localName) {
return getNamedItem(localName);
}
/**
* Equivalent to <code>setNamedItem(arg)</code>.
*/
public Node setNamedItemNS(Node arg) {
return setNamedItem(arg);
}
/**
* Equivalent to <code>removeNamedItem(localName)</code>.
*/
public Node removeNamedItemNS(String namespaceURI, String localName) {
return removeNamedItem(localName);
}
}
class IIONodeList implements NodeList {
List<? extends Node> nodes;
public IIONodeList(List<? extends Node> nodes) {
this.nodes = nodes;
}
public int getLength() {
return nodes.size();
}
public Node item(int index) {
if (index < 0 || index > nodes.size()) {
return null;
}
return nodes.get(index);
}
}
class IIOAttr extends IIOMetadataNode implements Attr {
Element owner;
String name;
String value;
public IIOAttr(Element owner, String name, String value) {
this.owner = owner;
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public String getNodeName() {
return name;
}
public short getNodeType() {
return ATTRIBUTE_NODE;
}
public boolean getSpecified() {
return true;
}
public String getValue() {
return value;
}
public String getNodeValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public void setNodeValue(String value) {
this.value = value;
}
public Element getOwnerElement() {
return owner;
}
public void setOwnerElement(Element owner) {
this.owner = owner;
}
/** This method is new in the DOM L3 for Attr interface.
* Could throw DOMException here, but its probably OK
* to always return false. One reason for this, is we have no good
* way to document this exception, since this class, IIOAttr,
* is not a public class. The rest of the methods that throw
* DOMException are publically documented as such on IIOMetadataNode.
* @return false
*/
public boolean isId() {
return false;
}
}
/**
* A class representing a node in a meta-data tree, which implements
* the <a
* href="../../../../api/org/w3c/dom/Element.html">
* <code>org.w3c.dom.Element</code></a> interface and additionally allows
* for the storage of non-textual objects via the
* <code>getUserObject</code> and <code>setUserObject</code> methods.
*
* <p> This class is not intended to be used for general XML
* processing. In particular, <code>Element</code> nodes created
* within the Image I/O API are not compatible with those created by
* Sun's standard implementation of the <code>org.w3.dom</code> API.
* In particular, the implementation is tuned for simple uses and may
* not perform well for intensive processing.
*
* <p> Namespaces are ignored in this implementation. The terms "tag
* name" and "node name" are always considered to be synonymous.
*
* <em>Note:</em>
* The DOM Level 3 specification added a number of new methods to the
* {@code Node}, {@code Element} and {@code Attr} interfaces that are not
* of value to the {@code IIOMetadataNode} implementation or specification.
*
* Calling such methods on an {@code IIOMetadataNode}, or an {@code Attr}
* instance returned from an {@code IIOMetadataNode} will result in a
* {@code DOMException} being thrown.
*
* @see IIOMetadata#getAsTree
* @see IIOMetadata#setFromTree
* @see IIOMetadata#mergeTree
*
*/
public class IIOMetadataNode implements Element, NodeList {
/**
* The name of the node as a <code>String</code>.
*/
private String nodeName = null;
/**
* The value of the node as a <code>String</code>. The Image I/O
* API typically does not make use of the node value.
*/
private String nodeValue = null;
/**
* The <code>Object</code> value associated with this node.
*/
private Object userObject = null;
/**
* The parent node of this node, or <code>null</code> if this node
* forms the root of its own tree.
*/
private IIOMetadataNode parent = null;
/**
* The number of child nodes.
*/
private int numChildren = 0;
/**
* The first (leftmost) child node of this node, or
* <code>null</code> if this node is a leaf node.
*/
private IIOMetadataNode firstChild = null;
/**
* The last (rightmost) child node of this node, or
* <code>null</code> if this node is a leaf node.
*/
private IIOMetadataNode lastChild = null;
/**
* The next (right) sibling node of this node, or
* <code>null</code> if this node is its parent's last child node.
*/
private IIOMetadataNode nextSibling = null;
/**
* The previous (left) sibling node of this node, or
* <code>null</code> if this node is its parent's first child node.
*/
private IIOMetadataNode previousSibling = null;
/**
* A <code>List</code> of <code>IIOAttr</code> nodes representing
* attributes.
*/
private List<IIOAttr> attributes = new ArrayList<>();
/**
* Constructs an empty <code>IIOMetadataNode</code>.
*/
public IIOMetadataNode() {}
/**
* Constructs an <code>IIOMetadataNode</code> with a given node
* name.
*
* @param nodeName the name of the node, as a <code>String</code>.
*/
public IIOMetadataNode(String nodeName) {
this.nodeName = nodeName;
}
/**
* Check that the node is either <code>null</code> or an
* <code>IIOMetadataNode</code>.
*
* @throws DOMException if {@code node} is not {@code null} and not an
* instance of {@code IIOMetadataNode}
*/
private void checkNode(Node node) throws DOMException {
if (node == null) {
return;
}
if (!(node instanceof IIOMetadataNode)) {
throw new IIODOMException(DOMException.WRONG_DOCUMENT_ERR,
"Node not an IIOMetadataNode!");
}
}
// Methods from Node
/**
* Returns the node name associated with this node.
*
* @return the node name, as a <code>String</code>.
*/
public String getNodeName() {
return nodeName;
}
/**
* Returns the value associated with this node.
*
* @return the node value, as a <code>String</code>.
*/
public String getNodeValue(){
return nodeValue;
}
/**
* Sets the <code>String</code> value associated with this node.
*/
public void setNodeValue(String nodeValue) {
this.nodeValue = nodeValue;
}
/**
* Returns the node type, which is always
* <code>ELEMENT_NODE</code>.
*
* @return the <code>short</code> value <code>ELEMENT_NODE</code>.
*/
public short getNodeType() {
return ELEMENT_NODE;
}
/**
* Returns the parent of this node. A <code>null</code> value
* indicates that the node is the root of its own tree. To add a
* node to an existing tree, use one of the
* <code>insertBefore</code>, <code>replaceChild</code>, or
* <code>appendChild</code> methods.
*
* @return the parent, as a <code>Node</code>.
*
* @see #insertBefore
* @see #replaceChild
* @see #appendChild
*/
public Node getParentNode() {
return parent;
}
/**
* Returns a <code>NodeList</code> that contains all children of this node.
* If there are no children, this is a <code>NodeList</code> containing
* no nodes.
*
* @return the children as a <code>NodeList</code>
*/
public NodeList getChildNodes() {
return this;
}
/**
* Returns the first child of this node, or <code>null</code> if
* the node has no children.
*
* @return the first child, as a <code>Node</code>, or
* <code>null</code>
*/
public Node getFirstChild() {
return firstChild;
}
/**
* Returns the last child of this node, or <code>null</code> if
* the node has no children.
*
* @return the last child, as a <code>Node</code>, or
* <code>null</code>.
*/
public Node getLastChild() {
return lastChild;
}
/**
* Returns the previous sibling of this node, or <code>null</code>
* if this node has no previous sibling.
*
* @return the previous sibling, as a <code>Node</code>, or
* <code>null</code>.
*/
public Node getPreviousSibling() {
return previousSibling;
}
/**
* Returns the next sibling of this node, or <code>null</code> if
* the node has no next sibling.
*
* @return the next sibling, as a <code>Node</code>, or
* <code>null</code>.
*/
public Node getNextSibling() {
return nextSibling;
}
/**
* Returns a <code>NamedNodeMap</code> containing the attributes of
* this node.
*
* @return a <code>NamedNodeMap</code> containing the attributes of
* this node.
*/
public NamedNodeMap getAttributes() {
return new IIONamedNodeMap(attributes);
}
/**
* Returns <code>null</code>, since <code>IIOMetadataNode</code>s
* do not belong to any <code>Document</code>.
*
* @return <code>null</code>.
*/
public Document getOwnerDocument() {
return null;
}
/**
* Inserts the node <code>newChild</code> before the existing
* child node <code>refChild</code>. If <code>refChild</code> is
* <code>null</code>, insert <code>newChild</code> at the end of
* the list of children.
*
* @param newChild the <code>Node</code> to insert.
* @param refChild the reference <code>Node</code>.
*
* @return the node being inserted.
*
* @exception IllegalArgumentException if <code>newChild</code> is
* <code>null</code>.
*/
public Node insertBefore(Node newChild,
Node refChild) {
if (newChild == null) {
throw new IllegalArgumentException("newChild == null!");
}
checkNode(newChild);
checkNode(refChild);
IIOMetadataNode newChildNode = (IIOMetadataNode)newChild;
IIOMetadataNode refChildNode = (IIOMetadataNode)refChild;
// Siblings, can be null.
IIOMetadataNode previous = null;
IIOMetadataNode next = null;
if (refChild == null) {
previous = this.lastChild;
next = null;
this.lastChild = newChildNode;
} else {
previous = refChildNode.previousSibling;
next = refChildNode;
}
if (previous != null) {
previous.nextSibling = newChildNode;
}
if (next != null) {
next.previousSibling = newChildNode;
}
newChildNode.parent = this;
newChildNode.previousSibling = previous;
newChildNode.nextSibling = next;
// N.B.: O.K. if refChild == null
if (this.firstChild == refChildNode) {
this.firstChild = newChildNode;
}
++numChildren;
return newChildNode;
}
/**
* Replaces the child node <code>oldChild</code> with
* <code>newChild</code> in the list of children, and returns the
* <code>oldChild</code> node.
*
* @param newChild the <code>Node</code> to insert.
* @param oldChild the <code>Node</code> to be replaced.
*
* @return the node replaced.
*
* @exception IllegalArgumentException if <code>newChild</code> is
* <code>null</code>.
*/
public Node replaceChild(Node newChild,
Node oldChild) {
if (newChild == null) {
throw new IllegalArgumentException("newChild == null!");
}
checkNode(newChild);
checkNode(oldChild);
IIOMetadataNode newChildNode = (IIOMetadataNode)newChild;
IIOMetadataNode oldChildNode = (IIOMetadataNode)oldChild;
IIOMetadataNode previous = oldChildNode.previousSibling;
IIOMetadataNode next = oldChildNode.nextSibling;
if (previous != null) {
previous.nextSibling = newChildNode;
}
if (next != null) {
next.previousSibling = newChildNode;
}
newChildNode.parent = this;
newChildNode.previousSibling = previous;
newChildNode.nextSibling = next;
if (firstChild == oldChildNode) {
firstChild = newChildNode;
}
if (lastChild == oldChildNode) {
lastChild = newChildNode;
}
oldChildNode.parent = null;
oldChildNode.previousSibling = null;
oldChildNode.nextSibling = null;
return oldChildNode;
}
/**
* Removes the child node indicated by <code>oldChild</code> from
* the list of children, and returns it.
*
* @param oldChild the <code>Node</code> to be removed.
*
* @return the node removed.
*
* @exception IllegalArgumentException if <code>oldChild</code> is
* <code>null</code>.
*/
public Node removeChild(Node oldChild) {
if (oldChild == null) {
throw new IllegalArgumentException("oldChild == null!");
}
checkNode(oldChild);
IIOMetadataNode oldChildNode = (IIOMetadataNode)oldChild;
IIOMetadataNode previous = oldChildNode.previousSibling;
IIOMetadataNode next = oldChildNode.nextSibling;
if (previous != null) {
previous.nextSibling = next;
}
if (next != null) {
next.previousSibling = previous;
}
if (this.firstChild == oldChildNode) {
this.firstChild = next;
}
if (this.lastChild == oldChildNode) {
this.lastChild = previous;
}
oldChildNode.parent = null;
oldChildNode.previousSibling = null;
oldChildNode.nextSibling = null;
--numChildren;
return oldChildNode;
}
/**
* Adds the node <code>newChild</code> to the end of the list of
* children of this node.
*
* @param newChild the <code>Node</code> to insert.
*
* @return the node added.
*
* @exception IllegalArgumentException if <code>newChild</code> is
* <code>null</code>.
*/
public Node appendChild(Node newChild) {
if (newChild == null) {
throw new IllegalArgumentException("newChild == null!");
}
checkNode(newChild);
// insertBefore will increment numChildren
return insertBefore(newChild, null);
}
/**
* Returns <code>true</code> if this node has child nodes.
*
* @return <code>true</code> if this node has children.
*/
public boolean hasChildNodes() {
return numChildren > 0;
}
/**
* Returns a duplicate of this node. The duplicate node has no
* parent (<code>getParentNode</code> returns <code>null</code>).
* If a shallow clone is being performed (<code>deep</code> is
* <code>false</code>), the new node will not have any children or
* siblings. If a deep clone is being performed, the new node
* will form the root of a complete cloned subtree.
*
* @param deep if <code>true</code>, recursively clone the subtree
* under the specified node; if <code>false</code>, clone only the
* node itself.
*
* @return the duplicate node.
*/
public Node cloneNode(boolean deep) {
IIOMetadataNode newNode = new IIOMetadataNode(this.nodeName);
newNode.setUserObject(getUserObject());
// Attributes
if (deep) {
for (IIOMetadataNode child = firstChild;
child != null;
child = child.nextSibling) {
newNode.appendChild(child.cloneNode(true));
}
}
return newNode;
}
/**
* Does nothing, since <code>IIOMetadataNode</code>s do not
* contain <code>Text</code> children.
*/
public void normalize() {
}
/**
* Returns <code>false</code> since DOM features are not
* supported.
*
* @return <code>false</code>.
*
* @param feature a <code>String</code>, which is ignored.
* @param version a <code>String</code>, which is ignored.
*/
public boolean isSupported(String feature, String version) {
return false;
}
/**
* Returns <code>null</code>, since namespaces are not supported.
*/
public String getNamespaceURI() throws DOMException {
return null;
}
/**
* Returns <code>null</code>, since namespaces are not supported.
*
* @return <code>null</code>.
*
* @see #setPrefix
*/
public String getPrefix() {
return null;
}
/**
* Does nothing, since namespaces are not supported.
*
* @param prefix a <code>String</code>, which is ignored.
*
* @see #getPrefix
*/
public void setPrefix(String prefix) {
}
/**
* Equivalent to <code>getNodeName</code>.
*
* @return the node name, as a <code>String</code>.
*/
public String getLocalName() {
return nodeName;
}
// Methods from Element
/**
* Equivalent to <code>getNodeName</code>.
*
* @return the node name, as a <code>String</code>
*/
public String getTagName() {
return nodeName;
}
/**
* Retrieves an attribute value by name.
* @param name The name of the attribute to retrieve.
* @return The <code>Attr</code> value as a string, or the empty string
* if that attribute does not have a specified or default value.
*/
public String getAttribute(String name) {
Attr attr = getAttributeNode(name);
if (attr == null) {
return "";
}
return attr.getValue();
}
/**
* Equivalent to <code>getAttribute(localName)</code>.
*
* @see #setAttributeNS
*/
public String getAttributeNS(String namespaceURI, String localName) {
return getAttribute(localName);
}
public void setAttribute(String name, String value) {
// Name must be valid unicode chars
boolean valid = true;
char[] chs = name.toCharArray();
for (int i=0;i<chs.length;i++) {
if (chs[i] >= 0xfffe) {
valid = false;
break;
}
}
if (!valid) {
throw new IIODOMException(DOMException.INVALID_CHARACTER_ERR,
"Attribute name is illegal!");
}
removeAttribute(name, false);
attributes.add(new IIOAttr(this, name, value));
}
/**
* Equivalent to <code>setAttribute(qualifiedName, value)</code>.
*
* @see #getAttributeNS
*/
public void setAttributeNS(String namespaceURI,
String qualifiedName, String value) {
setAttribute(qualifiedName, value);
}
public void removeAttribute(String name) {
removeAttribute(name, true);
}
private void removeAttribute(String name, boolean checkPresent) {
int numAttributes = attributes.size();
for (int i = 0; i < numAttributes; i++) {
IIOAttr attr = attributes.get(i);
if (name.equals(attr.getName())) {
attr.setOwnerElement(null);
attributes.remove(i);
return;
}
}
// If we get here, the attribute doesn't exist
if (checkPresent) {
throw new IIODOMException(DOMException.NOT_FOUND_ERR,
"No such attribute!");
}
}
/**
* Equivalent to <code>removeAttribute(localName)</code>.
*/
public void removeAttributeNS(String namespaceURI,
String localName) {
removeAttribute(localName);
}
public Attr getAttributeNode(String name) {
Node node = getAttributes().getNamedItem(name);
return (Attr)node;
}
/**
* Equivalent to <code>getAttributeNode(localName)</code>.
*
* @see #setAttributeNodeNS
*/
public Attr getAttributeNodeNS(String namespaceURI,
String localName) {
return getAttributeNode(localName);
}
public Attr setAttributeNode(Attr newAttr) throws DOMException {
Element owner = newAttr.getOwnerElement();
if (owner != null) {
if (owner == this) {
return null;
} else {
throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR,
"Attribute is already in use");
}
}
IIOAttr attr;
if (newAttr instanceof IIOAttr) {
attr = (IIOAttr)newAttr;
attr.setOwnerElement(this);
} else {
attr = new IIOAttr(this,
newAttr.getName(),
newAttr.getValue());
}
Attr oldAttr = getAttributeNode(attr.getName());
if (oldAttr != null) {
removeAttributeNode(oldAttr);
}
attributes.add(attr);
return oldAttr;
}
/**
* Equivalent to <code>setAttributeNode(newAttr)</code>.
*
* @see #getAttributeNodeNS
*/
public Attr setAttributeNodeNS(Attr newAttr) {
return setAttributeNode(newAttr);
}
public Attr removeAttributeNode(Attr oldAttr) {
removeAttribute(oldAttr.getName());
return oldAttr;
}
public NodeList getElementsByTagName(String name) {
List<Node> l = new ArrayList<>();
getElementsByTagName(name, l);
return new IIONodeList(l);
}
private void getElementsByTagName(String name, List<Node> l) {
if (nodeName.equals(name)) {
l.add(this);
}
Node child = getFirstChild();
while (child != null) {
((IIOMetadataNode)child).getElementsByTagName(name, l);
child = child.getNextSibling();
}
}
/**
* Equivalent to <code>getElementsByTagName(localName)</code>.
*/
public NodeList getElementsByTagNameNS(String namespaceURI,
String localName) {
return getElementsByTagName(localName);
}
public boolean hasAttributes() {
return attributes.size() > 0;
}
public boolean hasAttribute(String name) {
return getAttributeNode(name) != null;
}
/**
* Equivalent to <code>hasAttribute(localName)</code>.
*/
public boolean hasAttributeNS(String namespaceURI,
String localName) {
return hasAttribute(localName);
}
// Methods from NodeList
public int getLength() {
return numChildren;
}
public Node item(int index) {
if (index < 0) {
return null;
}
Node child = getFirstChild();
while (child != null && index-- > 0) {
child = child.getNextSibling();
}
return child;
}
/**
* Returns the <code>Object</code> value associated with this node.
*
* @return the user <code>Object</code>.
*
* @see #setUserObject
*/
public Object getUserObject() {
return userObject;
}
/**
* Sets the value associated with this node.
*
* @param userObject the user <code>Object</code>.
*
* @see #getUserObject
*/
public void setUserObject(Object userObject) {
this.userObject = userObject;
}
// Start of dummy methods for DOM L3.
/**
* This DOM Level 3 method is not supported for {@code IIOMetadataNode}
* and will throw a {@code DOMException}.
* @throws DOMException - always.
*/
public void setIdAttribute(String name,
boolean isId)
throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Method not supported");
}
/**
* This DOM Level 3 method is not supported for {@code IIOMetadataNode}
* and will throw a {@code DOMException}.
* @throws DOMException - always.
*/
public void setIdAttributeNS(String namespaceURI,
String localName,
boolean isId)
throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Method not supported");
}
/**
* This DOM Level 3 method is not supported for {@code IIOMetadataNode}
* and will throw a {@code DOMException}.
* @throws DOMException - always.
*/
public void setIdAttributeNode(Attr idAttr,
boolean isId)
throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Method not supported");
}
/**
* This DOM Level 3 method is not supported for {@code IIOMetadataNode}
* and will throw a {@code DOMException}.
* @throws DOMException - always.
*/
public TypeInfo getSchemaTypeInfo() throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Method not supported");
}
/**
* This DOM Level 3 method is not supported for {@code IIOMetadataNode}
* and will throw a {@code DOMException}.
* @throws DOMException - always.
*/
public Object setUserData(String key,
Object data,
UserDataHandler handler) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Method not supported");
}
/**
* This DOM Level 3 method is not supported for {@code IIOMetadataNode}
* and will throw a {@code DOMException}.
* @throws DOMException - always.
*/
public Object getUserData(String key) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Method not supported");
}
/**
* This DOM Level 3 method is not supported for {@code IIOMetadataNode}
* and will throw a {@code DOMException}.
* @throws DOMException - always.
*/
public Object getFeature(String feature, String version)
throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Method not supported");
}
/**
* This DOM Level 3 method is not supported for {@code IIOMetadataNode}
* and will throw a {@code DOMException}.
* @throws DOMException - always.
*/
public boolean isSameNode(Node node) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Method not supported");
}
/**
* This DOM Level 3 method is not supported for {@code IIOMetadataNode}
* and will throw a {@code DOMException}.
* @throws DOMException - always.
*/
public boolean isEqualNode(Node node) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Method not supported");
}
/**
* This DOM Level 3 method is not supported for {@code IIOMetadataNode}
* and will throw a {@code DOMException}.
* @throws DOMException - always.
*/
public String lookupNamespaceURI(String prefix) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Method not supported");
}
/**
* This DOM Level 3 method is not supported for {@code IIOMetadataNode}
* and will throw a {@code DOMException}.
* @throws DOMException - always.
*/
public boolean isDefaultNamespace(String namespaceURI)
throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Method not supported");
}
/**
* This DOM Level 3 method is not supported for {@code IIOMetadataNode}
* and will throw a {@code DOMException}.
* @throws DOMException - always.
*/
public String lookupPrefix(String namespaceURI) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Method not supported");
}
/**
* This DOM Level 3 method is not supported for {@code IIOMetadataNode}
* and will throw a {@code DOMException}.
* @throws DOMException - always.
*/
public String getTextContent() throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Method not supported");
}
/**
* This DOM Level 3 method is not supported for {@code IIOMetadataNode}
* and will throw a {@code DOMException}.
* @throws DOMException - always.
*/
public void setTextContent(String textContent) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Method not supported");
}
/**
* This DOM Level 3 method is not supported for {@code IIOMetadataNode}
* and will throw a {@code DOMException}.
* @throws DOMException - always.
*/
public short compareDocumentPosition(Node other)
throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Method not supported");
}
/**
* This DOM Level 3 method is not supported for {@code IIOMetadataNode}
* and will throw a {@code DOMException}.
* @throws DOMException - always.
*/
public String getBaseURI() throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Method not supported");
}
//End of dummy methods for DOM L3.
}
| gpl-2.0 |
WelcomeHUME/svn-caucho-com-resin | modules/servlet16/src/javax/servlet/jsp/tagext/ValidationMessage.java | 1602 | /*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
* Free SoftwareFoundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package javax.servlet.jsp.tagext;
/**
* Abstract class for a JSP page validator. The validator works on the
* XML version of the page.
*/
public class ValidationMessage {
private String _id;
private String _message;
/**
* Constructor for the message.
*/
public ValidationMessage(String id, String message)
{
_id = id;
_message = message;
}
/**
* Returns the jsp:id value.
*/
public String getId()
{
return _id;
}
/**
* Returns the validation message
*/
public String getMessage()
{
return _message;
}
}
| gpl-2.0 |
Kaputnik120/AllProjects | TuxGuitar/tuxguitar-fork-code-91-trunk/TuxGuitar-musicxml/src/org/herac/tuxguitar/io/musicxml/MusicXMLPluginExporter.java | 587 | package org.herac.tuxguitar.io.musicxml;
import org.herac.tuxguitar.gui.system.plugins.base.TGExporterPlugin;
import org.herac.tuxguitar.io.base.TGRawExporter;
public class MusicXMLPluginExporter extends TGExporterPlugin{
protected TGRawExporter getExporter() {
return new MusicXMLSongExporter();
}
public String getAuthor() {
return "Julian Casadesus <julian@casadesus.com.ar>";
}
public String getDescription() {
return "MusicXML exporter plugin";
}
public String getName() {
return "MusicXML exporter";
}
public String getVersion() {
return "1.0";
}
}
| gpl-2.0 |
ar-/art-of-illusion | ArtOfIllusion/src/artofillusion/SceneChangedEvent.java | 1178 | /* Copyright (C) 2006-2009 by Peter Eastman
This program is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details. */
package artofillusion;
import artofillusion.ui.*;
/**
* A SceneChangedEvent is dispatched by an EditingWindow to indicate that some element of the
* scene has changed. This includes all aspects of the scene, including the list of objects,
* properties of individual objects, textures, the list of currently selected objects, etc.
*/
public class SceneChangedEvent
{
private EditingWindow window;
public SceneChangedEvent(EditingWindow window)
{
this.window = window;
}
/**
* Get the LayoutWindow containing the scene which was changed.
*/
public EditingWindow getWindow()
{
return window;
}
}
| gpl-2.0 |
matadorhong/CoreNLP | itest/src/edu/stanford/nlp/pipeline/TokensRegexNERAnnotatorITest.java | 10775 | package edu.stanford.nlp.pipeline;
import edu.stanford.nlp.io.IOUtils;
import edu.stanford.nlp.ling.CoreAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.util.StringUtils;
import junit.framework.TestCase;
import java.io.File;
import java.io.PrintWriter;
import java.util.List;
import java.util.Properties;
/**
* Test cases for TokensRegexNERAnnotator (taken from RegexNERAnnotator)
* @author Angel Chang
*/
public class TokensRegexNERAnnotatorITest extends TestCase {
private static final String REGEX_ANNOTATOR_NAME = "tokensregexner";
private static final String MAPPING = "/u/nlp/data/TAC-KBP2010/sentence_extraction/itest_map";
private static StanfordCoreNLP pipeline;
private static Annotator caseless;
private static Annotator cased;
private static Annotator annotator;
@Override
public void setUp() throws Exception {
synchronized(TokensRegexNERAnnotatorITest.class) {
if (pipeline == null) { // Hack so we don't load the pipeline fresh for every test
Properties props = new Properties();
props.setProperty("annotators", "tokenize, ssplit, pos, lemma, ner");
pipeline = new StanfordCoreNLP(props);
// Basic caseless and cased tokens regex annotators
caseless = new TokensRegexNERAnnotator(MAPPING, true);
cased = new TokensRegexNERAnnotator(MAPPING);
annotator = cased;
}
}
}
// Helper methods
protected static TokensRegexNERAnnotator getTokensRegexNerAnnotator(Properties props)
{
return new TokensRegexNERAnnotator(REGEX_ANNOTATOR_NAME, props);
}
protected static TokensRegexNERAnnotator getTokensRegexNerAnnotator(String[][] patterns, boolean ignoreCase) throws Exception
{
return getTokensRegexNerAnnotator(new Properties(), patterns, ignoreCase);
}
protected static TokensRegexNERAnnotator getTokensRegexNerAnnotator(Properties props, String[][] patterns, boolean ignoreCase) throws Exception
{
File tempFile = File.createTempFile("tokensregexnertest.patterns", "txt");
tempFile.deleteOnExit();
PrintWriter pw = IOUtils.getPrintWriter(tempFile.getAbsolutePath());
for (String[] p: patterns) {
pw.println(StringUtils.join(p, "\t"));
}
pw.close();
props.setProperty(REGEX_ANNOTATOR_NAME + ".mapping", tempFile.getAbsolutePath());
props.setProperty(REGEX_ANNOTATOR_NAME + ".ignorecase", String.valueOf(ignoreCase));
return new TokensRegexNERAnnotator(REGEX_ANNOTATOR_NAME, props);
}
protected static Annotation createDocument(String text) {
Annotation annotation = new Annotation(text);
pipeline.annotate(annotation);
return annotation;
}
/**
* Helper method, checks that each token is tagged with the expected NER type.
*/
private static void checkNerTags(List<CoreLabel> tokens, String... tags) {
assertEquals(tags.length, tokens.size());
for (int i = 0; i < tags.length; ++i) {
assertEquals("Mismatch for token tag NER " + i + " " + tokens.get(i),
tags[i], tokens.get(i).get(CoreAnnotations.NamedEntityTagAnnotation.class));
}
}
private static void checkTags(List<CoreLabel> tokens, Class key, String... tags) {
assertEquals(tags.length, tokens.size());
for (int i = 0; i < tags.length; ++i) {
assertEquals("Mismatch for token tag " + key + " " + i + " " + tokens.get(i),
tags[i], tokens.get(i).get(key));
}
}
/**
* Helper method, re-annotate each token with specified tag
*/
private static void reannotate(List<CoreLabel> tokens, Class key, String ... tags) {
assertEquals(tags.length, tokens.size());
for (int i = 0; i < tags.length; ++i) {
tokens.get(i).set(key, tags[i]);
}
}
// Tests for TokensRegex syntax
public void testTokensRegexSyntax() throws Exception {
String[][] regexes =
new String[][]{
new String[]{"( /University/ /of/ [ {ner:LOCATION} ] )", "SCHOOL"}
// TODO: TokensRegex literal string patterns ignores ignoreCase settings
//new String[]{"( University of [ {ner:LOCATION} ] )", "SCHOOL"}
};
Annotator annotatorCased = getTokensRegexNerAnnotator(regexes, false);
String str = "University of Alaska is located in Alaska.";
Annotation document = createDocument(str);
annotatorCased.annotate(document);
List<CoreLabel> tokens = document.get(CoreAnnotations.TokensAnnotation.class);
checkNerTags(tokens,
"ORGANIZATION", "ORGANIZATION", "ORGANIZATION", "O", "O", "O", "LOCATION", "O");
reannotate(tokens, CoreAnnotations.NamedEntityTagAnnotation.class,
"O", "O", "LOCATION", "O", "O", "O", "LOCATION", "O");
annotatorCased.annotate(document);
checkNerTags(tokens,
"SCHOOL", "SCHOOL", "SCHOOL", "O", "O", "O", "LOCATION", "O");
// Try lowercase
Annotator annotatorCaseless = getTokensRegexNerAnnotator(regexes, true);
str = "university of alaska is located in alaska.";
document = createDocument(str);
tokens = document.get(CoreAnnotations.TokensAnnotation.class);
checkNerTags(tokens,
"O", "O", "LOCATION", "O", "O", "O", "LOCATION", "O");
annotatorCased.annotate(document);
checkNerTags(tokens,
"O", "O", "LOCATION", "O", "O", "O", "LOCATION", "O");
annotatorCaseless.annotate(document);
checkNerTags(tokens,
"SCHOOL", "SCHOOL", "SCHOOL", "O", "O", "O", "LOCATION", "O");
}
// Tests for TokensRegex syntax with match group
public void testTokensRegexMatchGroup() throws Exception {
String[][] regexes =
new String[][]{
new String[]{"( /the/? /movie/ (/[A-Z].*/+) )", "MOVIE", "", "0", "1"}
};
Annotator annotatorCased = getTokensRegexNerAnnotator(regexes, false);
String str = "the movie Mud was very muddy";
Annotation document = createDocument(str);
annotatorCased.annotate(document);
List<CoreLabel> tokens = document.get(CoreAnnotations.TokensAnnotation.class);
checkNerTags(tokens,
"O", "O", "MOVIE", "O", "O", "O");
}
// Tests for TokensRegexNer annotator annotating other fields
public void testTokensRegexNormalizedAnnotate() throws Exception {
Properties props = new Properties();
props.setProperty(REGEX_ANNOTATOR_NAME + ".mapping.header", "pattern,ner,normalized,overwrite,priority,group");
String[][] regexes =
new String[][]{
new String[]{"blue", "COLOR", "B", "", "0"},
new String[]{"red", "COLOR", "R", "", "0"},
new String[]{"green", "COLOR", "G", "", "0"}
};
Annotator annotatorCased = getTokensRegexNerAnnotator(props, regexes, false);
String str = "These are all colors: blue, red, and green.";
Annotation document = createDocument(str);
annotatorCased.annotate(document);
List<CoreLabel> tokens = document.get(CoreAnnotations.TokensAnnotation.class);
checkTags(tokens, CoreAnnotations.TextAnnotation.class, "These", "are", "all", "colors", ":", "blue", ",", "red", ",", "and", "green", ".");
checkTags(tokens, CoreAnnotations.NamedEntityTagAnnotation.class, "O", "O", "O", "O", "O", "COLOR", "O", "COLOR", "O", "O", "COLOR", "O");
checkTags(tokens, CoreAnnotations.NormalizedNamedEntityTagAnnotation.class, null, null, null, null, null, "B", null, "R", null, null, "G", null);
}
public static class TestAnnotation implements CoreAnnotation<String> {
public Class<String> getType() {
return String.class;
}
}
// Tests for TokensRegexNer annotator annotating other fields with custom key mapping
public void testTokensRegexCustomAnnotate() throws Exception {
Properties props = new Properties();
props.setProperty(REGEX_ANNOTATOR_NAME + ".mapping.header", "pattern,test,overwrite,priority,group");
props.setProperty(REGEX_ANNOTATOR_NAME + ".mapping.field.test", "edu.stanford.nlp.pipeline.TokensRegexNERAnnotatorITest$TestAnnotation");
String[][] regexes =
new String[][]{
new String[]{"test", "TEST", "", "0"}
};
Annotator annotatorCased = getTokensRegexNerAnnotator(props, regexes, true);
String str = "Marking all test as test";
Annotation document = createDocument(str);
annotatorCased.annotate(document);
List<CoreLabel> tokens = document.get(CoreAnnotations.TokensAnnotation.class);
checkTags(tokens, CoreAnnotations.TextAnnotation.class, "Marking", "all", "test", "as", "test");
checkTags(tokens, TestAnnotation.class, null, null, "TEST", null, "TEST");
}
// Basic tests from RegexNERAnnotatorITest
public void testBasicMatching() throws Exception {
String str = "President Barack Obama lives in Chicago , Illinois , " +
"and is a practicing Christian .";
Annotation document = createDocument(str);
annotator.annotate(document);
List<CoreLabel> tokens = document.get(CoreAnnotations.TokensAnnotation.class);
checkNerTags(tokens,
"TITLE", "PERSON", "PERSON", "O", "O", "LOCATION", "O", "STATE_OR_PROVINCE",
"O", "O", "O", "O", "O", "IDEOLOGY", "O");
}
/**
* The LOCATION on Ontario Lake should not be overwritten since Ontario (STATE_OR_PROVINCE)
* does not span Ontario Lake. Native American Church will overwrite ORGANIZATION with
* RELIGION.
*/
public void testOverwrite() throws Exception {
String str = "I like Ontario Lake , and I like the Native American Church , too .";
Annotation document = createDocument(str);
annotator.annotate(document);
List<CoreLabel> tokens = document.get(CoreAnnotations.TokensAnnotation.class);
checkNerTags(tokens, "O", "O", "LOCATION", "LOCATION", "O", "O", "O", "O", "O", "RELIGION",
"RELIGION", "RELIGION", "O", "O", "O");
}
/**
* In the mapping file, Christianity is assigned a higher priority than Early Christianity,
* and so Early should not be marked as RELIGION.
*/
public void testPriority() throws Exception {
String str = "Christianity is of higher regex priority than Early Christianity . ";
Annotation document = createDocument(str);
annotator.annotate(document);
List<CoreLabel> tokens = document.get(CoreAnnotations.TokensAnnotation.class);
checkNerTags(tokens, "RELIGION", "O", "O", "O", "O", "O", "O", "O", "RELIGION", "O");
}
/**
* Test that if there are no annotations at all, the annotator
* throws an exception. We are happy if we can catch an exception
* and continue, and if we don't get any exceptions, we throw an
* exception of our own.
*/
public void testEmptyAnnotation() throws Exception {
try {
annotator.annotate(new Annotation(""));
} catch(RuntimeException e) {
return;
}
fail("Never expected to get this far... the annotator should have thrown an exception by now");
}
}
| gpl-2.0 |
hexbinary/landing | src/main/java/org/oscarehr/billing/CA/model/GstControl.java | 2391 | /**
*
* Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved.
* This software is published under the GPL GNU General Public License.
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* This software was written for
* Centre for Research on Inner City Health, St. Michael's Hospital,
* Toronto, Ontario, Canada
*/
package org.oscarehr.billing.CA.model;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.oscarehr.common.model.AbstractModel;
/**
*
* @author rjonasz
*/
@Entity
@Table(name="gstControl")
public class GstControl extends AbstractModel<Integer> implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private Boolean gstFlag;
private BigDecimal gstPercent;
/**
* @return the gstFlag
*/
public Boolean getGstFlag() {
return gstFlag;
}
/**
* @param gstFlag the gstFlag to set
*/
public void setGstFlag(Boolean gstFlag) {
this.gstFlag = gstFlag;
}
/**
* @return the gstPercent
*/
public BigDecimal getGstPercent() {
return gstPercent;
}
/**
* @param gstPercent the gstPercent to set
*/
public void setGstPercent(BigDecimal gstPercent) {
this.gstPercent = gstPercent;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
@Override
public Integer getId() {
return id;
}
}
| gpl-2.0 |
krharrison/cilib | library/src/test/java/net/sourceforge/cilib/nn/domain/LambdaGammaSolutionInterpretationStrategyTest.java | 2624 | /** __ __
* _____ _/ /_/ /_ Computational Intelligence Library (CIlib)
* / ___/ / / / __ \ (c) CIRG @ UP
* / /__/ / / / /_/ / http://cilib.net
* \___/_/_/_/_.___/
*/
package net.sourceforge.cilib.nn.domain;
import net.sourceforge.cilib.functions.activation.Sigmoid;
import net.sourceforge.cilib.math.Maths;
import net.sourceforge.cilib.nn.NeuralNetwork;
import net.sourceforge.cilib.nn.NeuralNetworksTestHelper;
import net.sourceforge.cilib.nn.architecture.Layer;
import net.sourceforge.cilib.nn.architecture.visitors.ArchitectureVisitor;
import net.sourceforge.cilib.nn.components.BiasNeuron;
import net.sourceforge.cilib.nn.components.Neuron;
import net.sourceforge.cilib.type.types.container.Vector;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class LambdaGammaSolutionInterpretationStrategyTest {
private NeuralNetwork neuralNetwork;
@Before
public void setup() {
neuralNetwork = NeuralNetworksTestHelper.createFFNN(3, 2, 1);
}
@Test
public void shouldCreateVisitor() {
Vector solution = Vector.of(1.1, 1.2, 1.3, 1.4, 0.1, 0.4, 1.5, 1.6, 1.7, 1.8, 0.2, 0.5, 1.9, 2.0, 2.1, 0.3, 0.6);
LambdaGammaSolutionConversionStrategy lambdaGammaSolutionInterpretationStrategy = new LambdaGammaSolutionConversionStrategy();
ArchitectureVisitor lambdaGammaVisitor = lambdaGammaSolutionInterpretationStrategy.interpretSolution(solution);
Vector weights = Vector.of(1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1);
Vector lambdas = Vector.of(0.1, 0.2, 0.3);
Vector gammas = Vector.of(0.4, 0.5, 0.6);
lambdaGammaVisitor.visit(neuralNetwork.getArchitecture());
int lambdaIdx = 0;
int gammaIdx = 0;
int weightIdx = 0;
for (Layer layer : neuralNetwork.getArchitecture().getActivationLayers()) {
for (Neuron neuron : layer) {
if (!(neuron instanceof BiasNeuron)) {
assertEquals(lambdas.get(lambdaIdx++).doubleValue(), ((Sigmoid) neuron.getActivationFunction()).getLambda().getParameter(), Maths.EPSILON);
assertEquals(gammas.get(gammaIdx++).doubleValue(), ((Sigmoid) neuron.getActivationFunction()).getGamma().getParameter(), Maths.EPSILON);
}
Vector neuronWeights = neuron.getWeights();
int size = neuronWeights.size();
for (int j = 0; j < size; j++) {
assertEquals(weights.get(weightIdx++), neuronWeights.get(j));
}
}
}
}
}
| gpl-3.0 |
ricksbrown/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WMenuRenderer.java | 2118 | package com.github.bordertech.wcomponents.render.webxml;
import com.github.bordertech.wcomponents.WComponent;
import com.github.bordertech.wcomponents.WMenu;
import com.github.bordertech.wcomponents.XmlStringBuilder;
import com.github.bordertech.wcomponents.servlet.WebXmlRenderContext;
/**
* The Renderer for the {@link WMenu} component.
*
* @author Yiannis Paschalidis
* @since 1.0.0
*/
final class WMenuRenderer extends AbstractWebXmlRenderer {
/**
* Paints the given WMenu.
*
* @param component the WMenu to paint.
* @param renderContext the RenderContext to paint to.
*/
@Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WMenu menu = (WMenu) component;
XmlStringBuilder xml = renderContext.getWriter();
int rows = menu.getRows();
xml.appendTagOpen("ui:menu");
xml.appendAttribute("id", component.getId());
xml.appendOptionalAttribute("class", component.getHtmlClass());
xml.appendOptionalAttribute("track", component.isTracking(), "true");
switch (menu.getType()) {
case BAR:
xml.appendAttribute("type", "bar");
break;
case FLYOUT:
xml.appendAttribute("type", "flyout");
break;
case TREE:
xml.appendAttribute("type", "tree");
break;
case COLUMN:
xml.appendAttribute("type", "column");
break;
default:
throw new IllegalStateException("Invalid menu type: " + menu.getType());
}
xml.appendOptionalAttribute("disabled", menu.isDisabled(), "true");
xml.appendOptionalAttribute("hidden", menu.isHidden(), "true");
xml.appendOptionalAttribute("rows", rows > 0, rows);
switch (menu.getSelectionMode()) {
case NONE:
break;
case SINGLE:
xml.appendAttribute("selectMode", "single");
break;
case MULTIPLE:
xml.appendAttribute("selectMode", "multiple");
break;
default:
throw new IllegalStateException("Invalid select mode: " + menu.getSelectMode());
}
xml.appendClose();
// Render margin
MarginRendererUtil.renderMargin(menu, renderContext);
paintChildren(menu, renderContext);
xml.appendEndTag("ui:menu");
}
}
| gpl-3.0 |
beppec56/core | wizards/com/sun/star/wizards/document/Control.java | 12038 | /*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
package com.sun.star.wizards.document;
import com.sun.star.awt.Point;
import com.sun.star.awt.Size;
import com.sun.star.awt.XControl;
import com.sun.star.awt.XControlModel;
import com.sun.star.awt.XLayoutConstrains;
import com.sun.star.awt.XWindowPeer;
import com.sun.star.beans.XPropertySet;
import com.sun.star.beans.XPropertySetInfo;
import com.sun.star.container.XNameAccess;
import com.sun.star.container.XNameContainer;
import com.sun.star.wizards.common.*;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.AnyConverter;
import com.sun.star.drawing.XShapes;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.util.Date;
import com.sun.star.util.Time;
public class Control extends Shape
{
XControlModel xControlModel;
private XControl xControl;
public XPropertySet xPropertySet;
XWindowPeer xWindowPeer;
private static final int SOMAXTEXTSIZE = 50;
private int icontroltype;
private XNameContainer xFormName;
private static final int IIMGFIELDWIDTH = 3000;
public Control()
{
}
public Control(FormHandler _oFormHandler, String _sServiceName, Point _aPoint)
{
super(_oFormHandler, _sServiceName, _aPoint, null);
}
public Control(FormHandler _oFormHandler, XNameContainer _xFormName, int _icontroltype, String _FieldName, Point _aPoint, Size _aSize)
{
super(_oFormHandler, _aPoint, _aSize);
xFormName = _xFormName;
createControl(_icontroltype, null, _FieldName);
}
public Control(FormHandler _oFormHandler, int _icontroltype, Point _aPoint, Size _aSize)
{
super(_oFormHandler, _aPoint, _aSize);
createControl(_icontroltype, null, null);
}
private void createControl(int _icontroltype, XShapes _xGroupShapes, String _FieldName)
{
try
{
icontroltype = _icontroltype;
String sServiceName = oFormHandler.sModelServices[icontroltype];
Object oControlModel = oFormHandler.xMSFDoc.createInstance(sServiceName);
xControlModel = UnoRuntime.queryInterface( XControlModel.class, oControlModel );
xPropertySet = UnoRuntime.queryInterface( XPropertySet.class, oControlModel );
XPropertySetInfo xPSI = xPropertySet.getPropertySetInfo();
if ( xPSI.hasPropertyByName( "MouseWheelBehavior" ) )
xPropertySet.setPropertyValue( "MouseWheelBehavior", Short.valueOf( com.sun.star.awt.MouseWheelBehavior.SCROLL_DISABLED ) );
insertControlInContainer(_FieldName);
xControlShape.setControl(xControlModel);
if (_xGroupShapes == null)
{
oFormHandler.xDrawPage.add(xShape);
}
else
{
_xGroupShapes.add(xShape);
}
xControl = oFormHandler.xControlAccess.getControl(xControlModel);
UnoRuntime.queryInterface( XPropertySet.class, xControl );
xWindowPeer = xControl.getPeer();
}
catch (Exception e)
{
e.printStackTrace(System.err);
}
}
private void insertControlInContainer(String _fieldname)
{
try
{
if (xFormName != null)
{
XNameAccess xNameAccess = UnoRuntime.queryInterface(XNameAccess.class, xFormName);
String sControlName = Desktop.getUniqueName(xNameAccess, getControlName(_fieldname));
xPropertySet.setPropertyValue(PropertyNames.PROPERTY_NAME, sControlName);
xFormName.insertByName(sControlName, xControlModel);
}
}
catch (Exception e)
{
e.printStackTrace(System.err);
}
}
private String getControlName(String _fieldname)
{
String controlname = PropertyNames.EMPTY_STRING;
switch (getControlType())
{
case FormHandler.SOLABEL:
controlname = "lbl" + _fieldname;
break;
case FormHandler.SOTEXTBOX:
controlname = "txt" + _fieldname;
break;
case FormHandler.SOCHECKBOX:
controlname = "chk" + _fieldname;
break;
case FormHandler.SODATECONTROL:
controlname = "dat" + _fieldname;
break;
case FormHandler.SOTIMECONTROL:
controlname = "tim" + _fieldname;
break;
case FormHandler.SONUMERICCONTROL:
controlname = "fmt" + _fieldname;
break;
case FormHandler.SOGRIDCONTROL:
controlname = "grd" + _fieldname;
break;
case FormHandler.SOIMAGECONTROL:
controlname = "img" + _fieldname;
break;
default:
controlname = "ctrl" + _fieldname;
}
return controlname;
}
public int getPreferredWidth(String sText)
{
Size aPeerSize = getPreferredSize(sText);
return ((aPeerSize.Width + 10) * oFormHandler.getXPixelFactor());
}
public int getPreferredHeight(String sText)
{
Size aPeerSize = getPreferredSize(sText);
if (getControlType() == FormHandler.SOCHECKBOX)
{
return (aPeerSize.Height * oFormHandler.getXPixelFactor());
}
else
{
return ((aPeerSize.Height + 2) * oFormHandler.getXPixelFactor());
}
}
public int getPreferredWidth()
{
if (getControlType() == FormHandler.SOIMAGECONTROL)
{
return IIMGFIELDWIDTH;
}
else
{
Size aPeerSize = getPeerSize();
int nWidth;
if (aPeerSize == null)
nWidth = 0;
else
nWidth = aPeerSize.Width;
// We increase the preferred Width a bit so that the control does not become too small
// when we change the border from "3D" to "Flat"
if (getControlType() == FormHandler.SOCHECKBOX)
{
return nWidth * oFormHandler.getXPixelFactor();
}
else
{
return (nWidth * oFormHandler.getXPixelFactor()) + 200;
}
}
}
public int getPreferredHeight()
{
if (getControlType() == FormHandler.SOIMAGECONTROL)
{
return 2000;
}
else
{
Size aPeerSize = getPeerSize();
int nHeight;
if (aPeerSize == null)
nHeight = 0;
else
nHeight = aPeerSize.Height;
// We increase the preferred Height a bit so that the control does not become too small
// when we change the border from "3D" to "Flat"
return ((nHeight + 1) * oFormHandler.getYPixelFactor());
}
}
private Size getPreferredSize(String sText)
{
try
{
if (xPropertySet.getPropertySetInfo().hasPropertyByName("Text"))
{
xPropertySet.setPropertyValue("Text", sText);
}
else if (xPropertySet.getPropertySetInfo().hasPropertyByName(PropertyNames.PROPERTY_LABEL))
{
xPropertySet.setPropertyValue(PropertyNames.PROPERTY_LABEL, sText);
}
else
{
throw new IllegalArgumentException();
}
}
catch (Exception e)
{
e.printStackTrace(System.err);
}
return getPeer().getPreferredSize();
}
public void setPropertyValue(String _sPropertyName, Object _aPropertyValue) throws Exception
{
if (xPropertySet.getPropertySetInfo().hasPropertyByName(_sPropertyName))
{
xPropertySet.setPropertyValue(_sPropertyName, _aPropertyValue);
}
}
/** the peer should be retrieved every time before it is used because it
* might be disposed otherwise
*/
private XLayoutConstrains getPeer()
{
return UnoRuntime.queryInterface(XLayoutConstrains.class, xControl.getPeer());
}
private Size getPeerSize()
{
try
{
Size aPreferredSize = null;
double dblEffMax = 0;
if (xPropertySet.getPropertySetInfo().hasPropertyByName("EffectiveMax"))
{
if (xPropertySet.getPropertyValue("EffectiveMax") != com.sun.star.uno.Any.VOID)
{
dblEffMax = AnyConverter.toDouble(xPropertySet.getPropertyValue("EffectiveMax"));
}
if (dblEffMax == 0)
{
// This is relevant for decimal fields
xPropertySet.setPropertyValue("EffectiveValue", new Double(99999));
}
else
{
xPropertySet.setPropertyValue("EffectiveValue", new Double(dblEffMax)); //new Double(100000.2));
}
aPreferredSize = getPeer().getPreferredSize();
xPropertySet.setPropertyValue("EffectiveValue", com.sun.star.uno.Any.VOID);
}
else if (getControlType() == FormHandler.SOCHECKBOX)
{
aPreferredSize = getPeer().getPreferredSize();
}
else if (getControlType() == FormHandler.SODATECONTROL)
{
Date d = new Date();
d.Day = 30;
d.Month = 12;
d.Year = 9999;
xPropertySet.setPropertyValue("Date", d);
aPreferredSize = getPeer().getPreferredSize();
xPropertySet.setPropertyValue("Date", com.sun.star.uno.Any.VOID);
}
else if (getControlType() == FormHandler.SOTIMECONTROL)
{
Time t = new Time();
t.NanoSeconds = 999999999;
t.Seconds = 59;
t.Minutes = 59;
t.Hours = 22;
xPropertySet.setPropertyValue("Time", t);
aPreferredSize = getPeer().getPreferredSize();
xPropertySet.setPropertyValue("Time", com.sun.star.uno.Any.VOID);
}
else
{
String stext;
short iTextLength = AnyConverter.toShort(xPropertySet.getPropertyValue("MaxTextLen"));
if (iTextLength < SOMAXTEXTSIZE)
{
stext = FormHandler.SOSIZETEXT.substring(0, SOMAXTEXTSIZE);
}
else
{
stext = FormHandler.SOSIZETEXT.substring(0, iTextLength);
}
xPropertySet.setPropertyValue("Text", stext);
aPreferredSize = getPeer().getPreferredSize();
xPropertySet.setPropertyValue("Text", PropertyNames.EMPTY_STRING);
}
return aPreferredSize;
}
catch (Exception e)
{
e.printStackTrace(System.err);
return null;
}
}
public int getControlType()
{
return icontroltype;
}
}
| gpl-3.0 |
happyjack27/autoredistrict | src/org/apache/commons/math3/stat/descriptive/SummaryStatistics.java | 26836 | /*
* 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.math3.stat.descriptive;
import java.io.Serializable;
import org.apache.commons.math3.exception.MathIllegalStateException;
import org.apache.commons.math3.exception.NullArgumentException;
import org.apache.commons.math3.exception.util.LocalizedFormats;
import org.apache.commons.math3.stat.descriptive.moment.GeometricMean;
import org.apache.commons.math3.stat.descriptive.moment.Mean;
import org.apache.commons.math3.stat.descriptive.moment.SecondMoment;
import org.apache.commons.math3.stat.descriptive.moment.Variance;
import org.apache.commons.math3.stat.descriptive.rank.Max;
import org.apache.commons.math3.stat.descriptive.rank.Min;
import org.apache.commons.math3.stat.descriptive.summary.Sum;
import org.apache.commons.math3.stat.descriptive.summary.SumOfLogs;
import org.apache.commons.math3.stat.descriptive.summary.SumOfSquares;
import org.apache.commons.math3.util.MathUtils;
import org.apache.commons.math3.util.Precision;
import org.apache.commons.math3.util.FastMath;
/**
* <p>
* Computes summary statistics for a stream of data values added using the
* {@link #addValue(double) addValue} method. The data values are not stored in
* memory, so this class can be used to compute statistics for very large data
* streams.
* </p>
* <p>
* The {@link StorelessUnivariateStatistic} instances used to maintain summary
* state and compute statistics are configurable via setters. For example, the
* default implementation for the variance can be overridden by calling
* {@link #setVarianceImpl(StorelessUnivariateStatistic)}. Actual parameters to
* these methods must implement the {@link StorelessUnivariateStatistic}
* interface and configuration must be completed before <code>addValue</code>
* is called. No configuration is necessary to use the default, commons-math
* provided implementations.
* </p>
* <p>
* Note: This class is not thread-safe. Use
* {@link SynchronizedSummaryStatistics} if concurrent access from multiple
* threads is required.
* </p>
*/
public class SummaryStatistics implements StatisticalSummary, Serializable {
/** Serialization UID */
private static final long serialVersionUID = -2021321786743555871L;
/** count of values that have been added */
private long n = 0;
/** SecondMoment is used to compute the mean and variance */
private SecondMoment secondMoment = new SecondMoment();
/** sum of values that have been added */
private Sum sum = new Sum();
/** sum of the square of each value that has been added */
private SumOfSquares sumsq = new SumOfSquares();
/** min of values that have been added */
private Min min = new Min();
/** max of values that have been added */
private Max max = new Max();
/** sumLog of values that have been added */
private SumOfLogs sumLog = new SumOfLogs();
/** geoMean of values that have been added */
private GeometricMean geoMean = new GeometricMean(sumLog);
/** mean of values that have been added */
private Mean mean = new Mean(secondMoment);
/** variance of values that have been added */
private Variance variance = new Variance(secondMoment);
/** Sum statistic implementation - can be reset by setter. */
private StorelessUnivariateStatistic sumImpl = sum;
/** Sum of squares statistic implementation - can be reset by setter. */
private StorelessUnivariateStatistic sumsqImpl = sumsq;
/** Minimum statistic implementation - can be reset by setter. */
private StorelessUnivariateStatistic minImpl = min;
/** Maximum statistic implementation - can be reset by setter. */
private StorelessUnivariateStatistic maxImpl = max;
/** Sum of log statistic implementation - can be reset by setter. */
private StorelessUnivariateStatistic sumLogImpl = sumLog;
/** Geometric mean statistic implementation - can be reset by setter. */
private StorelessUnivariateStatistic geoMeanImpl = geoMean;
/** Mean statistic implementation - can be reset by setter. */
private StorelessUnivariateStatistic meanImpl = mean;
/** Variance statistic implementation - can be reset by setter. */
private StorelessUnivariateStatistic varianceImpl = variance;
/**
* Construct a SummaryStatistics instance
*/
public SummaryStatistics() {
}
/**
* A copy constructor. Creates a deep-copy of the {@code original}.
*
* @param original the {@code SummaryStatistics} instance to copy
* @throws NullArgumentException if original is null
*/
public SummaryStatistics(SummaryStatistics original) throws NullArgumentException {
copy(original, this);
}
/**
* Return a {@link StatisticalSummaryValues} instance reporting current
* statistics.
* @return Current values of statistics
*/
public StatisticalSummary getSummary() {
return new StatisticalSummaryValues(getMean(), getVariance(), getN(),
getMax(), getMin(), getSum());
}
/**
* Add a value to the data
* @param value the value to add
*/
public void addValue(double value) {
sumImpl.increment(value);
sumsqImpl.increment(value);
minImpl.increment(value);
maxImpl.increment(value);
sumLogImpl.increment(value);
secondMoment.increment(value);
// If mean, variance or geomean have been overridden,
// need to increment these
if (meanImpl != mean) {
meanImpl.increment(value);
}
if (varianceImpl != variance) {
varianceImpl.increment(value);
}
if (geoMeanImpl != geoMean) {
geoMeanImpl.increment(value);
}
n++;
}
/**
* Returns the number of available values
* @return The number of available values
*/
public long getN() {
return n;
}
/**
* Returns the sum of the values that have been added
* @return The sum or <code>Double.NaN</code> if no values have been added
*/
public double getSum() {
return sumImpl.getResult();
}
/**
* Returns the sum of the squares of the values that have been added.
* <p>
* Double.NaN is returned if no values have been added.
* </p>
* @return The sum of squares
*/
public double getSumsq() {
return sumsqImpl.getResult();
}
/**
* Returns the mean of the values that have been added.
* <p>
* Double.NaN is returned if no values have been added.
* </p>
* @return the mean
*/
public double getMean() {
return meanImpl.getResult();
}
/**
* Returns the standard deviation of the values that have been added.
* <p>
* Double.NaN is returned if no values have been added.
* </p>
* @return the standard deviation
*/
public double getStandardDeviation() {
double stdDev = Double.NaN;
if (getN() > 0) {
if (getN() > 1) {
stdDev = FastMath.sqrt(getVariance());
} else {
stdDev = 0.0;
}
}
return stdDev;
}
/**
* Returns the quadratic mean, a.k.a.
* <a href="http://mathworld.wolfram.com/Root-Mean-Square.html">
* root-mean-square</a> of the available values
* @return The quadratic mean or {@code Double.NaN} if no values
* have been added.
*/
public double getQuadraticMean() {
final long size = getN();
return size > 0 ? FastMath.sqrt(getSumsq() / size) : Double.NaN;
}
/**
* Returns the (sample) variance of the available values.
*
* <p>This method returns the bias-corrected sample variance (using {@code n - 1} in
* the denominator). Use {@link #getPopulationVariance()} for the non-bias-corrected
* population variance.</p>
*
* <p>Double.NaN is returned if no values have been added.</p>
*
* @return the variance
*/
public double getVariance() {
return varianceImpl.getResult();
}
/**
* Returns the <a href="http://en.wikibooks.org/wiki/Statistics/Summary/Variance">
* population variance</a> of the values that have been added.
*
* <p>Double.NaN is returned if no values have been added.</p>
*
* @return the population variance
*/
public double getPopulationVariance() {
Variance populationVariance = new Variance(secondMoment);
populationVariance.setBiasCorrected(false);
return populationVariance.getResult();
}
/**
* Returns the maximum of the values that have been added.
* <p>
* Double.NaN is returned if no values have been added.
* </p>
* @return the maximum
*/
public double getMax() {
return maxImpl.getResult();
}
/**
* Returns the minimum of the values that have been added.
* <p>
* Double.NaN is returned if no values have been added.
* </p>
* @return the minimum
*/
public double getMin() {
return minImpl.getResult();
}
/**
* Returns the geometric mean of the values that have been added.
* <p>
* Double.NaN is returned if no values have been added.
* </p>
* @return the geometric mean
*/
public double getGeometricMean() {
return geoMeanImpl.getResult();
}
/**
* Returns the sum of the logs of the values that have been added.
* <p>
* Double.NaN is returned if no values have been added.
* </p>
* @return the sum of logs
* @since 1.2
*/
public double getSumOfLogs() {
return sumLogImpl.getResult();
}
/**
* Returns a statistic related to the Second Central Moment. Specifically,
* what is returned is the sum of squared deviations from the sample mean
* among the values that have been added.
* <p>
* Returns <code>Double.NaN</code> if no data values have been added and
* returns <code>0</code> if there is just one value in the data set.</p>
* <p>
* @return second central moment statistic
* @since 2.0
*/
public double getSecondMoment() {
return secondMoment.getResult();
}
/**
* Generates a text report displaying summary statistics from values that
* have been added.
* @return String with line feeds displaying statistics
* @since 1.2
*/
@Override
public String toString() {
StringBuilder outBuffer = new StringBuilder();
String endl = "\n";
outBuffer.append("SummaryStatistics:").append(endl);
outBuffer.append("n: ").append(getN()).append(endl);
outBuffer.append("min: ").append(getMin()).append(endl);
outBuffer.append("max: ").append(getMax()).append(endl);
outBuffer.append("sum: ").append(getSum()).append(endl);
outBuffer.append("mean: ").append(getMean()).append(endl);
outBuffer.append("geometric mean: ").append(getGeometricMean())
.append(endl);
outBuffer.append("variance: ").append(getVariance()).append(endl);
outBuffer.append("population variance: ").append(getPopulationVariance()).append(endl);
outBuffer.append("second moment: ").append(getSecondMoment()).append(endl);
outBuffer.append("sum of squares: ").append(getSumsq()).append(endl);
outBuffer.append("standard deviation: ").append(getStandardDeviation())
.append(endl);
outBuffer.append("sum of logs: ").append(getSumOfLogs()).append(endl);
return outBuffer.toString();
}
/**
* Resets all statistics and storage
*/
public void clear() {
this.n = 0;
minImpl.clear();
maxImpl.clear();
sumImpl.clear();
sumLogImpl.clear();
sumsqImpl.clear();
geoMeanImpl.clear();
secondMoment.clear();
if (meanImpl != mean) {
meanImpl.clear();
}
if (varianceImpl != variance) {
varianceImpl.clear();
}
}
/**
* Returns true iff <code>object</code> is a
* <code>SummaryStatistics</code> instance and all statistics have the
* same values as this.
* @param object the object to test equality against.
* @return true if object equals this
*/
@Override
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof SummaryStatistics == false) {
return false;
}
SummaryStatistics stat = (SummaryStatistics)object;
return Precision.equalsIncludingNaN(stat.getGeometricMean(), getGeometricMean()) &&
Precision.equalsIncludingNaN(stat.getMax(), getMax()) &&
Precision.equalsIncludingNaN(stat.getMean(), getMean()) &&
Precision.equalsIncludingNaN(stat.getMin(), getMin()) &&
Precision.equalsIncludingNaN(stat.getN(), getN()) &&
Precision.equalsIncludingNaN(stat.getSum(), getSum()) &&
Precision.equalsIncludingNaN(stat.getSumsq(), getSumsq()) &&
Precision.equalsIncludingNaN(stat.getVariance(), getVariance());
}
/**
* Returns hash code based on values of statistics
* @return hash code
*/
@Override
public int hashCode() {
int result = 31 + MathUtils.hash(getGeometricMean());
result = result * 31 + MathUtils.hash(getGeometricMean());
result = result * 31 + MathUtils.hash(getMax());
result = result * 31 + MathUtils.hash(getMean());
result = result * 31 + MathUtils.hash(getMin());
result = result * 31 + MathUtils.hash(getN());
result = result * 31 + MathUtils.hash(getSum());
result = result * 31 + MathUtils.hash(getSumsq());
result = result * 31 + MathUtils.hash(getVariance());
return result;
}
// Getters and setters for statistics implementations
/**
* Returns the currently configured Sum implementation
* @return the StorelessUnivariateStatistic implementing the sum
* @since 1.2
*/
public StorelessUnivariateStatistic getSumImpl() {
return sumImpl;
}
/**
* <p>
* Sets the implementation for the Sum.
* </p>
* <p>
* This method cannot be activated after data has been added - i.e.,
* after {@link #addValue(double) addValue} has been used to add data.
* If it is activated after data has been added, an IllegalStateException
* will be thrown.
* </p>
* @param sumImpl the StorelessUnivariateStatistic instance to use for
* computing the Sum
* @throws MathIllegalStateException if data has already been added (i.e if n >0)
* @since 1.2
*/
public void setSumImpl(StorelessUnivariateStatistic sumImpl)
throws MathIllegalStateException {
checkEmpty();
this.sumImpl = sumImpl;
}
/**
* Returns the currently configured sum of squares implementation
* @return the StorelessUnivariateStatistic implementing the sum of squares
* @since 1.2
*/
public StorelessUnivariateStatistic getSumsqImpl() {
return sumsqImpl;
}
/**
* <p>
* Sets the implementation for the sum of squares.
* </p>
* <p>
* This method cannot be activated after data has been added - i.e.,
* after {@link #addValue(double) addValue} has been used to add data.
* If it is activated after data has been added, an IllegalStateException
* will be thrown.
* </p>
* @param sumsqImpl the StorelessUnivariateStatistic instance to use for
* computing the sum of squares
* @throws MathIllegalStateException if data has already been added (i.e if n > 0)
* @since 1.2
*/
public void setSumsqImpl(StorelessUnivariateStatistic sumsqImpl)
throws MathIllegalStateException {
checkEmpty();
this.sumsqImpl = sumsqImpl;
}
/**
* Returns the currently configured minimum implementation
* @return the StorelessUnivariateStatistic implementing the minimum
* @since 1.2
*/
public StorelessUnivariateStatistic getMinImpl() {
return minImpl;
}
/**
* <p>
* Sets the implementation for the minimum.
* </p>
* <p>
* This method cannot be activated after data has been added - i.e.,
* after {@link #addValue(double) addValue} has been used to add data.
* If it is activated after data has been added, an IllegalStateException
* will be thrown.
* </p>
* @param minImpl the StorelessUnivariateStatistic instance to use for
* computing the minimum
* @throws MathIllegalStateException if data has already been added (i.e if n > 0)
* @since 1.2
*/
public void setMinImpl(StorelessUnivariateStatistic minImpl)
throws MathIllegalStateException {
checkEmpty();
this.minImpl = minImpl;
}
/**
* Returns the currently configured maximum implementation
* @return the StorelessUnivariateStatistic implementing the maximum
* @since 1.2
*/
public StorelessUnivariateStatistic getMaxImpl() {
return maxImpl;
}
/**
* <p>
* Sets the implementation for the maximum.
* </p>
* <p>
* This method cannot be activated after data has been added - i.e.,
* after {@link #addValue(double) addValue} has been used to add data.
* If it is activated after data has been added, an IllegalStateException
* will be thrown.
* </p>
* @param maxImpl the StorelessUnivariateStatistic instance to use for
* computing the maximum
* @throws MathIllegalStateException if data has already been added (i.e if n > 0)
* @since 1.2
*/
public void setMaxImpl(StorelessUnivariateStatistic maxImpl)
throws MathIllegalStateException {
checkEmpty();
this.maxImpl = maxImpl;
}
/**
* Returns the currently configured sum of logs implementation
* @return the StorelessUnivariateStatistic implementing the log sum
* @since 1.2
*/
public StorelessUnivariateStatistic getSumLogImpl() {
return sumLogImpl;
}
/**
* <p>
* Sets the implementation for the sum of logs.
* </p>
* <p>
* This method cannot be activated after data has been added - i.e.,
* after {@link #addValue(double) addValue} has been used to add data.
* If it is activated after data has been added, an IllegalStateException
* will be thrown.
* </p>
* @param sumLogImpl the StorelessUnivariateStatistic instance to use for
* computing the log sum
* @throws MathIllegalStateException if data has already been added (i.e if n > 0)
* @since 1.2
*/
public void setSumLogImpl(StorelessUnivariateStatistic sumLogImpl)
throws MathIllegalStateException {
checkEmpty();
this.sumLogImpl = sumLogImpl;
geoMean.setSumLogImpl(sumLogImpl);
}
/**
* Returns the currently configured geometric mean implementation
* @return the StorelessUnivariateStatistic implementing the geometric mean
* @since 1.2
*/
public StorelessUnivariateStatistic getGeoMeanImpl() {
return geoMeanImpl;
}
/**
* <p>
* Sets the implementation for the geometric mean.
* </p>
* <p>
* This method cannot be activated after data has been added - i.e.,
* after {@link #addValue(double) addValue} has been used to add data.
* If it is activated after data has been added, an IllegalStateException
* will be thrown.
* </p>
* @param geoMeanImpl the StorelessUnivariateStatistic instance to use for
* computing the geometric mean
* @throws MathIllegalStateException if data has already been added (i.e if n > 0)
* @since 1.2
*/
public void setGeoMeanImpl(StorelessUnivariateStatistic geoMeanImpl)
throws MathIllegalStateException {
checkEmpty();
this.geoMeanImpl = geoMeanImpl;
}
/**
* Returns the currently configured mean implementation
* @return the StorelessUnivariateStatistic implementing the mean
* @since 1.2
*/
public StorelessUnivariateStatistic getMeanImpl() {
return meanImpl;
}
/**
* <p>
* Sets the implementation for the mean.
* </p>
* <p>
* This method cannot be activated after data has been added - i.e.,
* after {@link #addValue(double) addValue} has been used to add data.
* If it is activated after data has been added, an IllegalStateException
* will be thrown.
* </p>
* @param meanImpl the StorelessUnivariateStatistic instance to use for
* computing the mean
* @throws MathIllegalStateException if data has already been added (i.e if n > 0)
* @since 1.2
*/
public void setMeanImpl(StorelessUnivariateStatistic meanImpl)
throws MathIllegalStateException {
checkEmpty();
this.meanImpl = meanImpl;
}
/**
* Returns the currently configured variance implementation
* @return the StorelessUnivariateStatistic implementing the variance
* @since 1.2
*/
public StorelessUnivariateStatistic getVarianceImpl() {
return varianceImpl;
}
/**
* <p>
* Sets the implementation for the variance.
* </p>
* <p>
* This method cannot be activated after data has been added - i.e.,
* after {@link #addValue(double) addValue} has been used to add data.
* If it is activated after data has been added, an IllegalStateException
* will be thrown.
* </p>
* @param varianceImpl the StorelessUnivariateStatistic instance to use for
* computing the variance
* @throws MathIllegalStateException if data has already been added (i.e if n > 0)
* @since 1.2
*/
public void setVarianceImpl(StorelessUnivariateStatistic varianceImpl)
throws MathIllegalStateException {
checkEmpty();
this.varianceImpl = varianceImpl;
}
/**
* Throws IllegalStateException if n > 0.
* @throws MathIllegalStateException if data has been added
*/
private void checkEmpty() throws MathIllegalStateException {
if (n > 0) {
throw new MathIllegalStateException(
LocalizedFormats.VALUES_ADDED_BEFORE_CONFIGURING_STATISTIC, n);
}
}
/**
* Returns a copy of this SummaryStatistics instance with the same internal state.
*
* @return a copy of this
*/
public SummaryStatistics copy() {
SummaryStatistics result = new SummaryStatistics();
// No try-catch or advertised exception because arguments are guaranteed non-null
copy(this, result);
return result;
}
/**
* Copies source to dest.
* <p>Neither source nor dest can be null.</p>
*
* @param source SummaryStatistics to copy
* @param dest SummaryStatistics to copy to
* @throws NullArgumentException if either source or dest is null
*/
public static void copy(SummaryStatistics source, SummaryStatistics dest)
throws NullArgumentException {
MathUtils.checkNotNull(source);
MathUtils.checkNotNull(dest);
dest.maxImpl = source.maxImpl.copy();
dest.minImpl = source.minImpl.copy();
dest.sumImpl = source.sumImpl.copy();
dest.sumLogImpl = source.sumLogImpl.copy();
dest.sumsqImpl = source.sumsqImpl.copy();
dest.secondMoment = source.secondMoment.copy();
dest.n = source.n;
// Keep commons-math supplied statistics with embedded moments in synch
if (source.getVarianceImpl() instanceof Variance) {
dest.varianceImpl = new Variance(dest.secondMoment);
} else {
dest.varianceImpl = source.varianceImpl.copy();
}
if (source.meanImpl instanceof Mean) {
dest.meanImpl = new Mean(dest.secondMoment);
} else {
dest.meanImpl = source.meanImpl.copy();
}
if (source.getGeoMeanImpl() instanceof GeometricMean) {
dest.geoMeanImpl = new GeometricMean((SumOfLogs) dest.sumLogImpl);
} else {
dest.geoMeanImpl = source.geoMeanImpl.copy();
}
// Make sure that if stat == statImpl in source, same
// holds in dest; otherwise copy stat
if (source.geoMean == source.geoMeanImpl) {
dest.geoMean = (GeometricMean) dest.geoMeanImpl;
} else {
GeometricMean.copy(source.geoMean, dest.geoMean);
}
if (source.max == source.maxImpl) {
dest.max = (Max) dest.maxImpl;
} else {
Max.copy(source.max, dest.max);
}
if (source.mean == source.meanImpl) {
dest.mean = (Mean) dest.meanImpl;
} else {
Mean.copy(source.mean, dest.mean);
}
if (source.min == source.minImpl) {
dest.min = (Min) dest.minImpl;
} else {
Min.copy(source.min, dest.min);
}
if (source.sum == source.sumImpl) {
dest.sum = (Sum) dest.sumImpl;
} else {
Sum.copy(source.sum, dest.sum);
}
if (source.variance == source.varianceImpl) {
dest.variance = (Variance) dest.varianceImpl;
} else {
Variance.copy(source.variance, dest.variance);
}
if (source.sumLog == source.sumLogImpl) {
dest.sumLog = (SumOfLogs) dest.sumLogImpl;
} else {
SumOfLogs.copy(source.sumLog, dest.sumLog);
}
if (source.sumsq == source.sumsqImpl) {
dest.sumsq = (SumOfSquares) dest.sumsqImpl;
} else {
SumOfSquares.copy(source.sumsq, dest.sumsq);
}
}
}
| gpl-3.0 |
bowzheng/AIM4_delay | src/main/java/aim4/im/IntersectionManager.java | 9605 | /*
Copyright (c) 2011 Tsz-Chiu Au, Peter Stone
University of Texas at Austin
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. Neither the name of the University of Texas at Austin 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 THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package aim4.im;
import java.awt.Shape;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.Collections;
import java.util.List;
import aim4.map.Road;
import aim4.map.lane.Lane;
import aim4.util.Registry;
import aim4.util.Util;
import aim4.vehicle.VehicleSimView;
/**
* An agent to manage an intersection. This is an abstract class
* that sets up the properties of the intersection when it is created.
*/
public class IntersectionManager {
/////////////////////////////////
// PRIVATE FIELDS
/////////////////////////////////
/** The ID number of this intersection manager. */
protected int id;
/** the current time of the intersection manager */
protected double currentTime;
/**
* The intersection managed by this intersection manager.
*/
private Intersection intersection;
/**
* The path model of the intersection.
*/
private TrackModel trackModel;
/////////////////////////////////
// CLASS CONSTRUCTORS
/////////////////////////////////
/**
* Create an intersection manager.
*
* @param intersection an intersection
* @param trackModel a path model of the intersection
* @param currentTime the current time
* @param imRegistry an intersection manager registry
*/
public IntersectionManager(Intersection intersection,
TrackModel trackModel,
double currentTime,
Registry<IntersectionManager> imRegistry) {
assert(trackModel.getIntersection() == intersection);
this.intersection = intersection;
this.trackModel = trackModel;
this.currentTime = currentTime;
this.id = imRegistry.register(this);
// Register the intersection manager with the lanes
registerWithLanes();
}
/**
* Register this IntersectionManager with each of the Lanes that it manages.
*/
private void registerWithLanes() {
for(Lane lane : intersection.getLanes()) {
lane.getLaneIM().registerIntersectionManager(this);
}
}
/////////////////////////////////
// PUBLIC METHODS
/////////////////////////////////
/**
* Take any actions for a certain period of time.
*
* @param timeStep the size of the time step to simulate, in seconds
*/
public void act(double timeStep) {
currentTime += timeStep;
}
/**
* Get the unique ID number of this IntersectionManager.
*
* @return the ID number of this IntersectionManager
*/
public int getId() {
return id;
}
/**
* Get the current time.
*
* @return the current time.
*/
public double getCurrentTime() {
return currentTime;
}
/////////////////////////////////
// PUBLIC METHODS
/////////////////////////////////
// intersection
/**
* Get the intersection managed by this intersection manager.
*
* @return the intersection managed by this intersection manager
*/
public Intersection getIntersection() {
return intersection;
}
/**
* Get the track model.
*
* @return the track model
*/
public TrackModel getTrackModel() {
return trackModel;
}
/**
* Whether or not this IntersectionManager manages the given Road.
*
* @param r the Road
* @return whether this IntersectionManager manages the given Road
*/
public boolean manages(Road r) {
return intersection.getLanes().contains(r.getIndexLane());
}
/**
* Whether or not this IntersectionManager manages the given Lane.
*
* @param l the Lane
* @return whether this IntersectionManager manages the given Lane
*/
public boolean manages(Lane l) {
return intersection.getLanes().contains(l);
}
/**
* Determine whether the given Vehicle is currently entirely contained
* within the Area governed by this IntersectionManager.
*
* @param vehicle the Vehicle
* @return whether the Vehicle is currently entirely contained within
* the Area governed by this IntersectionManager
*/
public boolean contains(VehicleSimView vehicle) {
// Get all corners of the vehicle and make sure they are inside the
// intersection.
for(Point2D corner : vehicle.getCornerPoints()) {
if (!intersection.getArea().contains(corner)) {
return false;
}
}
// If all corners are inside, the whole thing is considered inside.
return true;
}
/**
* Determine whether the given Rectangle intersects the Area governed
* by this IntersectionManager.
*
* @param rectangle the Rectangle
* @return whether the Rectangle intersects the Area governed by
* this IntersectionManager
*/
public boolean intersects(Rectangle2D rectangle) {
// Just call the Area method, so we don't have to clone the area.
// Make sure not to use "intersect" which is destructive.
return intersection.getArea().intersects(rectangle);
}
/**
* Given an arrival Lane and a departure Road, get an ordered List of Lanes
* that represents the Lanes from highest to lowest priority based on
* distance from the arrival Lane.
*
* @param arrivalLane the Lane in which the vehicle is arriving
* @param departure the Road by which the vehicle is departing
* @return the ordered List of Lanes, by priority, into which the
* vehicle should try to turn
*/
public List<Lane> getSortedDepartureLanes(Lane arrivalLane, Road departure) {
return trackModel.getSortedDepartureLanes(arrivalLane, departure);
}
/**
* Get the distance from the entry of the given Road, to the departure of
* the other given Road.
*
* @param arrival the arrival Road
* @param departure the departure Road
* @return the distance from the entry of the arrival Road to the
* exit of the departure Road
*/
public double traversalDistance(Road arrival, Road departure) {
return trackModel.traversalDistance(arrival, departure);
}
/**
* Get the distance from the entry of the given Lane, to the departure of
* the other given Lane, if traveling along segments through their point
* of intersection.
*
* @param arrival the arrival Lane
* @param departure the departure Lane
* @return the distance from the entry of the arrival Lane to the
* exit of the departure Lane through their intersection
*/
public double traversalDistance(Lane arrival, Lane departure) {
return trackModel.traversalDistance(arrival, departure);
}
/**
* Get the distance from the entry of the Lane with the first given ID, to
* the departure of the Lane with the other given ID, if traveling along
* segments through their point of intersection.
*
* @param arrivalID the ID number of the arrival Lane
* @param departureID the ID number of the departure Lane
* @return the distance from the entry of the arrival Lane to the
* exit of the departure Lane through their intersection
*/
public double traversalDistance(int arrivalID, int departureID) {
return trackModel.traversalDistance(arrivalID, departureID);
}
/////////////////////////////////
// PUBLIC METHODS
/////////////////////////////////
// statistics
/**
* Print the collected data to a file
*
* @param outFileName the name of the file to which the data are outputted.
*/
public void printData(String outFileName) {}
/////////////////////////////////
// DEBUG
/////////////////////////////////
/**
* Check whether this intersection manager's time is current.
*
* @param currentTime the current time
*/
public void checkCurrentTime(double currentTime) {
assert Util.isDoubleEqual(currentTime, this.currentTime);
}
/**
* Get any shapes to display for debugging purposes.
*
* @return any shapes to display for debugging purposes
*/
public List<? extends Shape> getDebugShapes() {
return Collections.emptyList(); // Nothing by default
}
}
| gpl-3.0 |
jmcPereira/overture | ide/ui/src/main/java/org/overture/ide/ui/navigator/VdmDropAdapterAssistent.java | 18895 | /*
* #%~
* org.overture.ide.ui
* %%
* Copyright (C) 2008 - 2014 Overture
* %%
* 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/gpl-3.0.html>.
* #~%
*/
package org.overture.ide.ui.navigator;
import java.util.ArrayList;
import java.util.Iterator;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.TransferData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.CopyFilesAndFoldersOperation;
import org.eclipse.ui.actions.MoveFilesAndFoldersOperation;
import org.eclipse.ui.actions.ReadOnlyStateChecker;
import org.eclipse.ui.internal.navigator.Policy;
import org.eclipse.ui.internal.navigator.resources.plugin.WorkbenchNavigatorMessages;
import org.eclipse.ui.internal.navigator.resources.plugin.WorkbenchNavigatorPlugin;
import org.eclipse.ui.navigator.CommonDropAdapter;
import org.eclipse.ui.navigator.CommonDropAdapterAssistant;
import org.eclipse.ui.part.ResourceTransfer;
@SuppressWarnings("restriction")
public class VdmDropAdapterAssistent extends CommonDropAdapterAssistant {
private static final IResource[] NO_RESOURCES = new IResource[0];
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.navigator.CommonDropAdapterAssistant#isSupportedType(org
* .eclipse.swt.dnd.TransferData)
*/
@Override
public boolean isSupportedType(TransferData aTransferType) {
return super.isSupportedType(aTransferType)
|| FileTransfer.getInstance().isSupportedType(aTransferType);
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.navigator.CommonDropAdapterAssistant#validateDrop(java
* .lang.Object, int, org.eclipse.swt.dnd.TransferData)
*/
public IStatus validateDrop(Object target, int aDropOperation,
TransferData transferType) {
// if (VdmUIPlugin.DEBUG)
// System.out.println("Target Object for drop: "
// + target.getClass().toString());
if (target instanceof IVdmContainer) {
target = ((IVdmContainer) target).getContainer();
}
if (!(target instanceof IResource)) {
return WorkbenchNavigatorPlugin
.createStatus(
IStatus.INFO,
0,
WorkbenchNavigatorMessages.DropAdapter_targetMustBeResource,
null);
}
IResource resource = (IResource) target;
if (!resource.isAccessible()) {
return WorkbenchNavigatorPlugin
.createErrorStatus(
0,
WorkbenchNavigatorMessages.DropAdapter_canNotDropIntoClosedProject,
null);
}
IContainer destination = getActualTarget(resource);
if (destination.getType() == IResource.ROOT) {
return WorkbenchNavigatorPlugin
.createErrorStatus(
0,
WorkbenchNavigatorMessages.DropAdapter_resourcesCanNotBeSiblings,
null);
}
String message = null;
// drag within Eclipse?
if (LocalSelectionTransfer.getTransfer().isSupportedType(transferType)) {
IResource[] selectedResources = getSelectedResources();
boolean bProjectDrop = false;
for (int iRes = 0; iRes < selectedResources.length; iRes++) {
IResource res = selectedResources[iRes];
if (res instanceof IProject) {
bProjectDrop = true;
}
}
if (bProjectDrop) {
// drop of projects not supported on other IResources
// "Path for project must have only one segment."
message = WorkbenchNavigatorMessages.DropAdapter_canNotDropProjectIntoProject;
} else {
if (selectedResources.length == 0) {
message = WorkbenchNavigatorMessages.DropAdapter_dropOperationErrorOther;
} else {
CopyFilesAndFoldersOperation operation;
if (aDropOperation == DND.DROP_COPY) {
if (Policy.DEBUG_DND) {
System.out
.println("ResourceDropAdapterAssistant.validateDrop validating COPY."); //$NON-NLS-1$
}
operation = new CopyFilesAndFoldersOperation(getShell());
} else {
if (Policy.DEBUG_DND) {
System.out
.println("ResourceDropAdapterAssistant.validateDrop validating MOVE."); //$NON-NLS-1$
}
operation = new MoveFilesAndFoldersOperation(getShell());
}
message = operation.validateDestination(destination,
selectedResources);
}
}
} // file import?
else if (FileTransfer.getInstance().isSupportedType(transferType)) {
String[] sourceNames = (String[]) FileTransfer.getInstance()
.nativeToJava(transferType);
if (sourceNames == null) {
// source names will be null on Linux. Use empty names to do
// destination validation.
// Fixes bug 29778
sourceNames = new String[0];
}
CopyFilesAndFoldersOperation copyOperation = new CopyFilesAndFoldersOperation(
getShell());
message = copyOperation.validateImportDestination(destination,
sourceNames);
}
if (message != null) {
return WorkbenchNavigatorPlugin.createErrorStatus(0, message, null);
}
return Status.OK_STATUS;
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.ui.navigator.CommonDropAdapterAssistant#handleDrop(
* CommonDropAdapter, DropTargetEvent, Object)
*/
public IStatus handleDrop(CommonDropAdapter aDropAdapter,
DropTargetEvent aDropTargetEvent, Object aTarget) {
// if (VdmUIPlugin.DEBUG)
// System.out.println("Target Object for drop: "
// + aTarget.getClass().toString());
if (Policy.DEBUG_DND) {
System.out
.println("ResourceDropAdapterAssistant.handleDrop (begin)"); //$NON-NLS-1$
}
// alwaysOverwrite = false;
if (aDropAdapter.getCurrentTarget() == null
|| aDropTargetEvent.data == null) {
return Status.CANCEL_STATUS;
}
IStatus status = null;
IResource[] resources = null;
TransferData currentTransfer = aDropAdapter.getCurrentTransfer();
if (LocalSelectionTransfer.getTransfer().isSupportedType(
currentTransfer)) {
resources = getSelectedResources();
aDropTargetEvent.detail = DND.DROP_NONE;
} else if (ResourceTransfer.getInstance().isSupportedType(
currentTransfer)) {
resources = (IResource[]) aDropTargetEvent.data;
}
if (FileTransfer.getInstance().isSupportedType(currentTransfer)) {
status = performFileDrop(aDropAdapter, aDropTargetEvent.data);
} else if (resources != null && resources.length > 0) {
if (aDropAdapter.getCurrentOperation() == DND.DROP_COPY) {
if (Policy.DEBUG_DND) {
System.out
.println("ResourceDropAdapterAssistant.handleDrop executing COPY."); //$NON-NLS-1$
}
status = performResourceCopy(aDropAdapter, getShell(),
resources);
} else {
if (Policy.DEBUG_DND) {
System.out
.println("ResourceDropAdapterAssistant.handleDrop executing MOVE."); //$NON-NLS-1$
}
status = performResourceMove(aDropAdapter, resources);
}
}
openError(status);
IContainer target = null;
if (aDropAdapter.getCurrentTarget() instanceof IVdmContainer) {
target = ((IVdmContainer) aDropAdapter.getCurrentTarget())
.getContainer();
} else {
target = getActualTarget((IResource) aDropAdapter.getCurrentTarget());
}
if (target != null && target.isAccessible()) {
try {
target.refreshLocal(IResource.DEPTH_ONE, null);
} catch (CoreException e) {
}
}
return status;
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.ui.navigator.CommonDropAdapterAssistant#
* validatePluginTransferDrop
* (org.eclipse.jface.viewers.IStructuredSelection, java.lang.Object)
*/
public IStatus validatePluginTransferDrop(
IStructuredSelection aDragSelection, Object aDropTarget) {
if (!(aDropTarget instanceof IResource)) {
return WorkbenchNavigatorPlugin
.createStatus(
IStatus.INFO,
0,
WorkbenchNavigatorMessages.DropAdapter_targetMustBeResource,
null);
}
IResource resource = (IResource) aDropTarget;
if (!resource.isAccessible()) {
return WorkbenchNavigatorPlugin
.createErrorStatus(
0,
WorkbenchNavigatorMessages.DropAdapter_canNotDropIntoClosedProject,
null);
}
IContainer destination = getActualTarget(resource);
if (destination.getType() == IResource.ROOT) {
return WorkbenchNavigatorPlugin
.createErrorStatus(
0,
WorkbenchNavigatorMessages.DropAdapter_resourcesCanNotBeSiblings,
null);
}
IResource[] selectedResources = getSelectedResources(aDragSelection);
String message = null;
if (selectedResources.length == 0) {
message = WorkbenchNavigatorMessages.DropAdapter_dropOperationErrorOther;
} else {
MoveFilesAndFoldersOperation operation;
operation = new MoveFilesAndFoldersOperation(getShell());
message = operation.validateDestination(destination,
selectedResources);
}
if (message != null) {
return WorkbenchNavigatorPlugin.createErrorStatus(0, message, null);
}
return Status.OK_STATUS;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.navigator.CommonDropAdapterAssistant#handlePluginTransferDrop
* (org.eclipse.jface.viewers.IStructuredSelection, java.lang.Object)
*/
public IStatus handlePluginTransferDrop(
IStructuredSelection aDragSelection, Object aDropTarget) {
IContainer target = getActualTarget((IResource) aDropTarget);
IResource[] resources = getSelectedResources(aDragSelection);
MoveFilesAndFoldersOperation operation = new MoveFilesAndFoldersOperation(
getShell());
operation.copyResources(resources, target);
if (target != null && target.isAccessible()) {
try {
target.refreshLocal(IResource.DEPTH_ONE, null);
} catch (CoreException e) {
}
}
return Status.OK_STATUS;
}
/**
* Returns the actual target of the drop, given the resource under the
* mouse. If the mouse target is a file, then the drop actually occurs in
* its parent. If the drop location is before or after the mouse target and
* feedback is enabled, the target is also the parent.
*/
private IContainer getActualTarget(IResource mouseTarget) {
/* if cursor is on a file, return the parent */
if (mouseTarget.getType() == IResource.FILE) {
return mouseTarget.getParent();
}
/* otherwise the mouseTarget is the real target */
return (IContainer) mouseTarget;
}
/**
* Returns the resource selection from the LocalSelectionTransfer.
*
* @return the resource selection from the LocalSelectionTransfer
*/
private IResource[] getSelectedResources() {
ISelection selection = LocalSelectionTransfer.getTransfer()
.getSelection();
if (selection instanceof IStructuredSelection) {
return getSelectedResources((IStructuredSelection) selection);
}
return NO_RESOURCES;
}
/**
* Returns the resource selection from the LocalSelectionTransfer.
*
* @return the resource selection from the LocalSelectionTransfer
*/
@SuppressWarnings("unchecked")
private IResource[] getSelectedResources(IStructuredSelection selection) {
ArrayList<Object> selectedResources = new ArrayList<Object>();
for (Iterator<Object> i = selection.iterator(); i.hasNext();) {
Object o = i.next();
if (o instanceof IResource) {
selectedResources.add(o);
} else if (o instanceof IAdaptable) {
IAdaptable a = (IAdaptable) o;
IResource r = (IResource) a.getAdapter(IResource.class);
if (r != null) {
selectedResources.add(r);
}
}
}
return (IResource[]) selectedResources
.toArray(new IResource[selectedResources.size()]);
}
/**
* Performs a resource copy
*/
private IStatus performResourceCopy(CommonDropAdapter dropAdapter,
Shell shell, IResource[] sources) {
MultiStatus problems = new MultiStatus(PlatformUI.PLUGIN_ID, 1,
WorkbenchNavigatorMessages.DropAdapter_problemsMoving, null);
mergeStatus(problems, validateTarget(dropAdapter.getCurrentTarget(),
dropAdapter.getCurrentTransfer(), dropAdapter
.getCurrentOperation()));
IContainer target = null;
if (dropAdapter.getCurrentTarget() instanceof IVdmContainer) {
target = ((IVdmContainer) dropAdapter.getCurrentTarget())
.getContainer();
} else {
target = getActualTarget((IResource) dropAdapter.getCurrentTarget());
}
CopyFilesAndFoldersOperation operation = new CopyFilesAndFoldersOperation(
shell);
operation.copyResources(sources, target);
return problems;
}
/**
* Performs a resource move
*/
private IStatus performResourceMove(CommonDropAdapter dropAdapter,
IResource[] sources) {
MultiStatus problems = new MultiStatus(PlatformUI.PLUGIN_ID, 1,
WorkbenchNavigatorMessages.DropAdapter_problemsMoving, null);
mergeStatus(problems, validateTarget(dropAdapter.getCurrentTarget(),
dropAdapter.getCurrentTransfer(), dropAdapter
.getCurrentOperation()));
IContainer target = null;
if (dropAdapter.getCurrentTarget() instanceof IVdmContainer) {
target = ((IVdmContainer) dropAdapter.getCurrentTarget())
.getContainer();
} else {
target = getActualTarget((IResource) dropAdapter.getCurrentTarget());
}
ReadOnlyStateChecker checker = new ReadOnlyStateChecker(getShell(),
WorkbenchNavigatorMessages.MoveResourceAction_title,
WorkbenchNavigatorMessages.MoveResourceAction_checkMoveMessage);
sources = checker.checkReadOnlyResources(sources);
MoveFilesAndFoldersOperation operation = new MoveFilesAndFoldersOperation(
getShell());
operation.copyResources(sources, target);
return problems;
}
/**
* Performs a drop using the FileTransfer transfer type.
*/
private IStatus performFileDrop(CommonDropAdapter anAdapter, Object data) {
MultiStatus problems = new MultiStatus(PlatformUI.PLUGIN_ID, 0,
WorkbenchNavigatorMessages.DropAdapter_problemImporting, null);
mergeStatus(problems,
validateTarget(anAdapter.getCurrentTarget(), anAdapter
.getCurrentTransfer(), anAdapter.getCurrentOperation()));
IContainer target = null;
if (anAdapter.getCurrentTarget() instanceof IVdmContainer) {
target = ((IVdmContainer) anAdapter.getCurrentTarget())
.getContainer();
} else {
target = getActualTarget((IResource) anAdapter.getCurrentTarget());
}
final IContainer ftarget = target;
final String[] names = (String[]) data;
// Run the import operation asynchronously.
// Otherwise the drag source (e.g., Windows Explorer) will be blocked
// while the operation executes. Fixes bug 16478.
Display.getCurrent().asyncExec(new Runnable() {
public void run() {
getShell().forceActive();
CopyFilesAndFoldersOperation operation = new CopyFilesAndFoldersOperation(
getShell());
operation.copyFiles(names, ftarget);
}
});
return problems;
}
/**
* Ensures that the drop target meets certain criteria
*/
private IStatus validateTarget(Object target, TransferData transferType,
int dropOperation) {
if (target instanceof IVdmContainer) {
target = ((IVdmContainer) target).getContainer();
}
if (!(target instanceof IResource)) {
return WorkbenchNavigatorPlugin
.createInfoStatus(WorkbenchNavigatorMessages.DropAdapter_targetMustBeResource);
}
IResource resource = (IResource) target;
if (!resource.isAccessible()) {
return WorkbenchNavigatorPlugin
.createErrorStatus(WorkbenchNavigatorMessages.DropAdapter_canNotDropIntoClosedProject);
}
IContainer destination = getActualTarget(resource);
if (destination.getType() == IResource.ROOT) {
return WorkbenchNavigatorPlugin
.createErrorStatus(WorkbenchNavigatorMessages.DropAdapter_resourcesCanNotBeSiblings);
}
String message = null;
// drag within Eclipse?
if (LocalSelectionTransfer.getTransfer().isSupportedType(transferType)) {
IResource[] selectedResources = getSelectedResources();
if (selectedResources.length == 0) {
message = WorkbenchNavigatorMessages.DropAdapter_dropOperationErrorOther;
} else {
CopyFilesAndFoldersOperation operation;
if (dropOperation == DND.DROP_COPY) {
operation = new CopyFilesAndFoldersOperation(getShell());
} else {
operation = new MoveFilesAndFoldersOperation(getShell());
}
message = operation.validateDestination(destination,
selectedResources);
}
} // file import?
else if (FileTransfer.getInstance().isSupportedType(transferType)) {
String[] sourceNames = (String[]) FileTransfer.getInstance()
.nativeToJava(transferType);
if (sourceNames == null) {
// source names will be null on Linux. Use empty names to do
// destination validation.
// Fixes bug 29778
sourceNames = new String[0];
}
CopyFilesAndFoldersOperation copyOperation = new CopyFilesAndFoldersOperation(
getShell());
message = copyOperation.validateImportDestination(destination,
sourceNames);
}
if (message != null) {
return WorkbenchNavigatorPlugin.createErrorStatus(message);
}
return Status.OK_STATUS;
}
/**
* Adds the given status to the list of problems. Discards OK statuses. If
* the status is a multi-status, only its children are added.
*/
private void mergeStatus(MultiStatus status, IStatus toMerge) {
if (!toMerge.isOK()) {
status.merge(toMerge);
}
}
/**
* Opens an error dialog if necessary. Takes care of complex rules necessary
* for making the error dialog look nice.
*/
private void openError(IStatus status) {
if (status == null) {
return;
}
String genericTitle = WorkbenchNavigatorMessages.DropAdapter_title;
int codes = IStatus.ERROR | IStatus.WARNING;
// simple case: one error, not a multistatus
if (!status.isMultiStatus()) {
ErrorDialog
.openError(getShell(), genericTitle, null, status, codes);
return;
}
// one error, single child of multistatus
IStatus[] children = status.getChildren();
if (children.length == 1) {
ErrorDialog.openError(getShell(), status.getMessage(), null,
children[0], codes);
return;
}
// several problems
ErrorDialog.openError(getShell(), genericTitle, null, status, codes);
}
}
| gpl-3.0 |
Scrik/Cauldron-1 | eclipse/cauldron/src/main/java/net/minecraft/world/gen/feature/WorldGenTaiga1.java | 4520 | package net.minecraft.world.gen.feature;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.BlockSapling;
import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
public class WorldGenTaiga1 extends WorldGenAbstractTree
{
private static final String __OBFID = "CL_00000427";
public WorldGenTaiga1()
{
super(false);
}
public boolean generate(World p_76484_1_, Random p_76484_2_, int p_76484_3_, int p_76484_4_, int p_76484_5_)
{
int l = p_76484_2_.nextInt(5) + 7;
int i1 = l - p_76484_2_.nextInt(2) - 3;
int j1 = l - i1;
int k1 = 1 + p_76484_2_.nextInt(j1 + 1);
boolean flag = true;
if (p_76484_4_ >= 1 && p_76484_4_ + l + 1 <= 256)
{
int i2;
int j2;
int i3;
for (int l1 = p_76484_4_; l1 <= p_76484_4_ + 1 + l && flag; ++l1)
{
boolean flag1 = true;
if (l1 - p_76484_4_ < i1)
{
i3 = 0;
}
else
{
i3 = k1;
}
for (i2 = p_76484_3_ - i3; i2 <= p_76484_3_ + i3 && flag; ++i2)
{
for (j2 = p_76484_5_ - i3; j2 <= p_76484_5_ + i3 && flag; ++j2)
{
if (l1 >= 0 && l1 < 256)
{
Block block = p_76484_1_.getBlock(i2, l1, j2);
if (!this.isReplaceable(p_76484_1_, i2, l1, j2))
{
flag = false;
}
}
else
{
flag = false;
}
}
}
}
if (!flag)
{
return false;
}
else
{
Block block1 = p_76484_1_.getBlock(p_76484_3_, p_76484_4_ - 1, p_76484_5_);
boolean isSoil = block1.canSustainPlant(p_76484_1_, p_76484_3_, p_76484_4_ - 1, p_76484_5_, ForgeDirection.UP, (BlockSapling)Blocks.sapling);
if (isSoil && p_76484_4_ < 256 - l - 1)
{
block1.onPlantGrow(p_76484_1_, p_76484_3_, p_76484_4_ - 1, p_76484_5_, p_76484_3_, p_76484_4_, p_76484_5_);
i3 = 0;
for (i2 = p_76484_4_ + l; i2 >= p_76484_4_ + i1; --i2)
{
for (j2 = p_76484_3_ - i3; j2 <= p_76484_3_ + i3; ++j2)
{
int j3 = j2 - p_76484_3_;
for (int k2 = p_76484_5_ - i3; k2 <= p_76484_5_ + i3; ++k2)
{
int l2 = k2 - p_76484_5_;
if ((Math.abs(j3) != i3 || Math.abs(l2) != i3 || i3 <= 0) && p_76484_1_.getBlock(j2, i2, k2).canBeReplacedByLeaves(p_76484_1_, j2, i2, k2))
{
this.setBlockAndNotifyAdequately(p_76484_1_, j2, i2, k2, Blocks.leaves, 1);
}
}
}
if (i3 >= 1 && i2 == p_76484_4_ + i1 + 1)
{
--i3;
}
else if (i3 < k1)
{
++i3;
}
}
for (i2 = 0; i2 < l - 1; ++i2)
{
Block block2 = p_76484_1_.getBlock(p_76484_3_, p_76484_4_ + i2, p_76484_5_);
if (block2.isAir(p_76484_1_, p_76484_3_, p_76484_4_ + i2, p_76484_5_) || block2.isLeaves(p_76484_1_, p_76484_3_, p_76484_4_ + i2, p_76484_5_))
{
this.setBlockAndNotifyAdequately(p_76484_1_, p_76484_3_, p_76484_4_ + i2, p_76484_5_, Blocks.log, 1);
}
}
return true;
}
else
{
return false;
}
}
}
else
{
return false;
}
}
} | gpl-3.0 |
marcocast/scheduling | rm/rm-server/src/main/java/org/ow2/proactive/resourcemanager/nodesource/policy/CronPolicy.java | 5347 | /*
* ProActive Parallel Suite(TM):
* The Open Source library for parallel and distributed
* Workflows & Scheduling, Orchestration, Cloud Automation
* and Big Data Analysis on Enterprise Grids & Clouds.
*
* Copyright (c) 2007 - 2017 ActiveEon
* Contact: contact@activeeon.com
*
* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation: version 3 of
* the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*/
package org.ow2.proactive.resourcemanager.nodesource.policy;
import org.apache.log4j.Logger;
import org.objectweb.proactive.Body;
import org.objectweb.proactive.InitActive;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.core.util.wrapper.BooleanWrapper;
import org.objectweb.proactive.extensions.annotation.ActiveObject;
import org.ow2.proactive.resourcemanager.authentication.Client;
import org.ow2.proactive.resourcemanager.nodesource.common.Configurable;
import it.sauronsoftware.cron4j.Scheduler;
/**
*
* Allocated nodes for specified time slot: from "acquire time" to "release time" with specified period.
* Remove nodes preemptively if "preemptive" parameter is set to true. <br>
* If period is zero then acquisition will be performed once. <br>
*
* NOTE: difference between acquire and release time have to be bigger than time required
* to nodes all acquisition. Period have to be enough to release all nodes.
*
*/
@ActiveObject
public class CronPolicy extends NodeSourcePolicy implements InitActive {
protected static Logger logger = Logger.getLogger(CronPolicy.class);
/**
* Initial time for nodes acquisition
*/
@Configurable(description = "Time of the nodes acquisition (crontab format)")
private String nodeAcquision = "* * * * *";
@Configurable(description = "Time of the nodes removal (crontab format)")
private String nodeRemoval = "* * * * *";
/**
* The way of nodes removing
*/
@Configurable(description = "the mode how nodes are removed")
private boolean preemptive = false;
@Configurable(description = "Start deployment immediately")
private boolean forceDeployment = false;
private Scheduler cronScheduler;
/**
* Active object stub
*/
private CronPolicy thisStub;
/**
* Proactive default constructor
*/
public CronPolicy() {
}
/**
* Configure a policy with given parameters.
* @param policyParameters parameters defined by user
*/
@Override
public BooleanWrapper configure(Object... policyParameters) {
super.configure(policyParameters);
try {
cronScheduler = new Scheduler();
int index = 2;
nodeAcquision = policyParameters[index++].toString();
nodeRemoval = policyParameters[index++].toString();
preemptive = Boolean.parseBoolean(policyParameters[index++].toString());
forceDeployment = Boolean.parseBoolean(policyParameters[index++].toString());
} catch (Throwable t) {
throw new IllegalArgumentException(t);
}
return new BooleanWrapper(true);
}
/**
* Initializes stub to this active object
*/
public void initActivity(Body body) {
thisStub = (CronPolicy) PAActiveObject.getStubOnThis();
}
/**
* Activates the policy. Schedules acquire/release tasks with specified period.
*/
@Override
public BooleanWrapper activate() {
cronScheduler.schedule(nodeAcquision, new Runnable() {
public void run() {
logger.info("Acquiring nodes");
thisStub.acquireAllNodes();
}
});
cronScheduler.schedule(nodeRemoval, new Runnable() {
public void run() {
logger.info("Removing nodes");
thisStub.removeAllNodes(preemptive);
}
});
cronScheduler.start();
if (forceDeployment) {
logger.info("Acquiring nodes");
thisStub.acquireAllNodes();
}
return new BooleanWrapper(true);
}
/**
* Shutdown the policy and clears the timer.
*/
@Override
public void shutdown(Client initiator) {
cronScheduler.stop();
super.shutdown(initiator);
}
/**
* Policy description for UI
* @return policy description
*/
@Override
public String getDescription() {
return "Acquires and releases nodes at specified time.";
}
/**
* Policy string representation.
*/
@Override
public String toString() {
return super.toString() + " acquisiotion at [" + nodeAcquision + "]" + ", removal at [" + nodeRemoval +
"], preemptive: " + preemptive;
}
}
| agpl-3.0 |
deerwalk/voltdb | third_party/java/src/com/google_voltpatches/common/cache/Striped64.java | 13453 | /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
/*
* Source:
* http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/Striped64.java?revision=1.9
*/
package com.google_voltpatches.common.cache;
import com.google_voltpatches.common.annotations.GwtIncompatible;
import java.util.Random;
/**
* A package-local class holding common representation and mechanics
* for classes supporting dynamic striping on 64bit values. The class
* extends Number so that concrete subclasses must publicly do so.
*/
@GwtIncompatible
abstract class Striped64 extends Number {
/*
* This class maintains a lazily-initialized table of atomically
* updated variables, plus an extra "base" field. The table size
* is a power of two. Indexing uses masked per-thread hash codes.
* Nearly all declarations in this class are package-private,
* accessed directly by subclasses.
*
* Table entries are of class Cell; a variant of AtomicLong padded
* to reduce cache contention on most processors. Padding is
* overkill for most Atomics because they are usually irregularly
* scattered in memory and thus don't interfere much with each
* other. But Atomic objects residing in arrays will tend to be
* placed adjacent to each other, and so will most often share
* cache lines (with a huge negative performance impact) without
* this precaution.
*
* In part because Cells are relatively large, we avoid creating
* them until they are needed. When there is no contention, all
* updates are made to the base field. Upon first contention (a
* failed CAS on base update), the table is initialized to size 2.
* The table size is doubled upon further contention until
* reaching the nearest power of two greater than or equal to the
* number of CPUS. Table slots remain empty (null) until they are
* needed.
*
* A single spinlock ("busy") is used for initializing and
* resizing the table, as well as populating slots with new Cells.
* There is no need for a blocking lock; when the lock is not
* available, threads try other slots (or the base). During these
* retries, there is increased contention and reduced locality,
* which is still better than alternatives.
*
* Per-thread hash codes are initialized to random values.
* Contention and/or table collisions are indicated by failed
* CASes when performing an update operation (see method
* retryUpdate). Upon a collision, if the table size is less than
* the capacity, it is doubled in size unless some other thread
* holds the lock. If a hashed slot is empty, and lock is
* available, a new Cell is created. Otherwise, if the slot
* exists, a CAS is tried. Retries proceed by "double hashing",
* using a secondary hash (Marsaglia XorShift) to try to find a
* free slot.
*
* The table size is capped because, when there are more threads
* than CPUs, supposing that each thread were bound to a CPU,
* there would exist a perfect hash function mapping threads to
* slots that eliminates collisions. When we reach capacity, we
* search for this mapping by randomly varying the hash codes of
* colliding threads. Because search is random, and collisions
* only become known via CAS failures, convergence can be slow,
* and because threads are typically not bound to CPUS forever,
* may not occur at all. However, despite these limitations,
* observed contention rates are typically low in these cases.
*
* It is possible for a Cell to become unused when threads that
* once hashed to it terminate, as well as in the case where
* doubling the table causes no thread to hash to it under
* expanded mask. We do not try to detect or remove such cells,
* under the assumption that for long-running instances, observed
* contention levels will recur, so the cells will eventually be
* needed again; and for short-lived ones, it does not matter.
*/
/**
* Padded variant of AtomicLong supporting only raw accesses plus CAS.
* The value field is placed between pads, hoping that the JVM doesn't
* reorder them.
*
* JVM intrinsics note: It would be possible to use a release-only
* form of CAS here, if it were provided.
*/
static final class Cell {
volatile long p0, p1, p2, p3, p4, p5, p6;
volatile long value;
volatile long q0, q1, q2, q3, q4, q5, q6;
Cell(long x) { value = x; }
final boolean cas(long cmp, long val) {
return UNSAFE.compareAndSwapLong(this, valueOffset, cmp, val);
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long valueOffset;
static {
try {
UNSAFE = getUnsafe();
Class<?> ak = Cell.class;
valueOffset = UNSAFE.objectFieldOffset
(ak.getDeclaredField("value"));
} catch (Exception e) {
throw new Error(e);
}
}
}
/**
* ThreadLocal holding a single-slot int array holding hash code.
* Unlike the JDK8 version of this class, we use a suboptimal
* int[] representation to avoid introducing a new type that can
* impede class-unloading when ThreadLocals are not removed.
*/
static final ThreadLocal<int[]> threadHashCode = new ThreadLocal<int[]>();
/**
* Generator of new random hash codes
*/
static final Random rng = new Random();
/** Number of CPUS, to place bound on table size */
static final int NCPU = Runtime.getRuntime().availableProcessors();
/**
* Table of cells. When non-null, size is a power of 2.
*/
transient volatile Cell[] cells;
/**
* Base value, used mainly when there is no contention, but also as
* a fallback during table initialization races. Updated via CAS.
*/
transient volatile long base;
/**
* Spinlock (locked via CAS) used when resizing and/or creating Cells.
*/
transient volatile int busy;
/**
* Package-private default constructor
*/
Striped64() {
}
/**
* CASes the base field.
*/
final boolean casBase(long cmp, long val) {
return UNSAFE.compareAndSwapLong(this, baseOffset, cmp, val);
}
/**
* CASes the busy field from 0 to 1 to acquire lock.
*/
final boolean casBusy() {
return UNSAFE.compareAndSwapInt(this, busyOffset, 0, 1);
}
/**
* Computes the function of current and new value. Subclasses
* should open-code this update function for most uses, but the
* virtualized form is needed within retryUpdate.
*
* @param currentValue the current value (of either base or a cell)
* @param newValue the argument from a user update call
* @return result of the update function
*/
abstract long fn(long currentValue, long newValue);
/**
* Handles cases of updates involving initialization, resizing,
* creating new Cells, and/or contention. See above for
* explanation. This method suffers the usual non-modularity
* problems of optimistic retry code, relying on rechecked sets of
* reads.
*
* @param x the value
* @param hc the hash code holder
* @param wasUncontended false if CAS failed before call
*/
final void retryUpdate(long x, int[] hc, boolean wasUncontended) {
int h;
if (hc == null) {
threadHashCode.set(hc = new int[1]); // Initialize randomly
int r = rng.nextInt(); // Avoid zero to allow xorShift rehash
h = hc[0] = (r == 0) ? 1 : r;
}
else
h = hc[0];
boolean collide = false; // True if last slot nonempty
for (;;) {
Cell[] as; Cell a; int n; long v;
if ((as = cells) != null && (n = as.length) > 0) {
if ((a = as[(n - 1) & h]) == null) {
if (busy == 0) { // Try to attach new Cell
Cell r = new Cell(x); // Optimistically create
if (busy == 0 && casBusy()) {
boolean created = false;
try { // Recheck under lock
Cell[] rs; int m, j;
if ((rs = cells) != null &&
(m = rs.length) > 0 &&
rs[j = (m - 1) & h] == null) {
rs[j] = r;
created = true;
}
} finally {
busy = 0;
}
if (created)
break;
continue; // Slot is now non-empty
}
}
collide = false;
}
else if (!wasUncontended) // CAS already known to fail
wasUncontended = true; // Continue after rehash
else if (a.cas(v = a.value, fn(v, x)))
break;
else if (n >= NCPU || cells != as)
collide = false; // At max size or stale
else if (!collide)
collide = true;
else if (busy == 0 && casBusy()) {
try {
if (cells == as) { // Expand table unless stale
Cell[] rs = new Cell[n << 1];
for (int i = 0; i < n; ++i)
rs[i] = as[i];
cells = rs;
}
} finally {
busy = 0;
}
collide = false;
continue; // Retry with expanded table
}
h ^= h << 13; // Rehash
h ^= h >>> 17;
h ^= h << 5;
hc[0] = h; // Record index for next time
}
else if (busy == 0 && cells == as && casBusy()) {
boolean init = false;
try { // Initialize table
if (cells == as) {
Cell[] rs = new Cell[2];
rs[h & 1] = new Cell(x);
cells = rs;
init = true;
}
} finally {
busy = 0;
}
if (init)
break;
}
else if (casBase(v = base, fn(v, x)))
break; // Fall back on using base
}
}
/**
* Sets base and all cells to the given value.
*/
final void internalReset(long initialValue) {
Cell[] as = cells;
base = initialValue;
if (as != null) {
int n = as.length;
for (int i = 0; i < n; ++i) {
Cell a = as[i];
if (a != null)
a.value = initialValue;
}
}
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long baseOffset;
private static final long busyOffset;
static {
try {
UNSAFE = getUnsafe();
Class<?> sk = Striped64.class;
baseOffset = UNSAFE.objectFieldOffset
(sk.getDeclaredField("base"));
busyOffset = UNSAFE.objectFieldOffset
(sk.getDeclaredField("busy"));
} catch (Exception e) {
throw new Error(e);
}
}
/**
* Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
* Replace with a simple call to Unsafe.getUnsafe when integrating
* into a jdk.
*
* @return a sun.misc.Unsafe
*/
private static sun.misc.Unsafe getUnsafe() {
try {
return sun.misc.Unsafe.getUnsafe();
} catch (SecurityException tryReflectionInstead) {}
try {
return java.security.AccessController.doPrivileged
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
public sun.misc.Unsafe run() throws Exception {
Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
for (java.lang.reflect.Field f : k.getDeclaredFields()) {
f.setAccessible(true);
Object x = f.get(null);
if (k.isInstance(x))
return k.cast(x);
}
throw new NoSuchFieldError("the Unsafe");
}});
} catch (java.security.PrivilegedActionException e) {
throw new RuntimeException("Could not initialize intrinsics",
e.getCause());
}
}
}
| agpl-3.0 |
sanjupolus/KC6.oLatest | coeus-impl/src/main/java/org/kuali/coeus/common/committee/impl/rule/event/CommitteeActionViewBatchCorrespondenceEvent.java | 2670 | /*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2015 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.coeus.common.committee.impl.rule.event;
import org.kuali.coeus.common.committee.impl.bo.CommitteeBatchCorrespondenceBase;
import org.kuali.coeus.common.committee.impl.rules.CommitteeActionPrintCommitteeDocumentRule;
import org.kuali.coeus.common.committee.impl.rules.CommitteeActionViewBatchCorrespondenceRule;
import org.kuali.coeus.sys.framework.rule.KcBusinessRule;
import org.kuali.rice.krad.document.Document;
import java.util.List;
public class CommitteeActionViewBatchCorrespondenceEvent extends CommitteeActionsEventBase<CommitteeActionPrintCommitteeDocumentRule> {
private static final String MSG = "view batch correspondence";
private List<CommitteeBatchCorrespondenceBase> committeeBatchCorrespondences;
private boolean viewGenerated;
public CommitteeActionViewBatchCorrespondenceEvent(String errorPathPrefix, Document document, List<CommitteeBatchCorrespondenceBase> committeeBatchCorrespondences, boolean viewGenerated) {
super(MSG + getDocumentId(document), errorPathPrefix, document);
setCommitteeBatchCorrespondences(committeeBatchCorrespondences);
setViewGenerated(viewGenerated);
}
@SuppressWarnings("unchecked")
@Override
public KcBusinessRule getRule() {
return new CommitteeActionViewBatchCorrespondenceRule();
}
public List<CommitteeBatchCorrespondenceBase> getCommitteeBatchCorrespondences() {
return committeeBatchCorrespondences;
}
public void setCommitteeBatchCorrespondences(List<CommitteeBatchCorrespondenceBase> committeeBatchCorrespondences) {
this.committeeBatchCorrespondences = committeeBatchCorrespondences;
}
public void setViewGenerated(boolean viewGenerated) {
this.viewGenerated = viewGenerated;
}
public boolean isViewGenerated() {
return viewGenerated;
}
}
| agpl-3.0 |
another-dave/checkstyle | src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheckTest.java | 5458 | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2015 the original author or authors.
//
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.coding;
import static com.puppycrawl.tools.checkstyle.checks.coding.ReturnCountCheck.MSG_KEY;
import java.io.File;
import org.junit.Assert;
import org.junit.Test;
import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
public class ReturnCountCheckTest extends BaseCheckTestSupport {
@Test
public void testDefault() throws Exception {
final DefaultConfiguration checkConfig =
createCheckConfig(ReturnCountCheck.class);
final String[] expected = {
"18:5: " + getCheckMessage(MSG_KEY, 7, 2),
"35:17: " + getCheckMessage(MSG_KEY, 6, 2),
};
verify(checkConfig, getPath("coding" + File.separator + "InputReturnCount.java"), expected);
}
@Test
public void testFormat() throws Exception {
final DefaultConfiguration checkConfig =
createCheckConfig(ReturnCountCheck.class);
checkConfig.addAttribute("format", "^$");
final String[] expected = {
"5:5: " + getCheckMessage(MSG_KEY, 7, 2),
"18:5: " + getCheckMessage(MSG_KEY, 7, 2),
"35:17: " + getCheckMessage(MSG_KEY, 6, 2),
};
verify(checkConfig, getPath("coding" + File.separator + "InputReturnCount.java"), expected);
}
@Test
public void testMethodsAndLambdas() throws Exception {
final DefaultConfiguration checkConfig = createCheckConfig(ReturnCountCheck.class);
checkConfig.addAttribute("max", "1");
final String[] expected = {
"14:55: " + getCheckMessage(MSG_KEY, 2, 1),
"26:49: " + getCheckMessage(MSG_KEY, 2, 1),
"33:42: " + getCheckMessage(MSG_KEY, 3, 1),
"40:5: " + getCheckMessage(MSG_KEY, 2, 1),
"48:57: " + getCheckMessage(MSG_KEY, 2, 1),
};
verify(checkConfig, new File("src/test/resources-noncompilable/com/puppycrawl/tools/"
+ "checkstyle/coding/InputReturnCountLambda.java").getCanonicalPath(), expected);
}
@Test
public void testLambdasOnly() throws Exception {
final DefaultConfiguration checkConfig = createCheckConfig(ReturnCountCheck.class);
checkConfig.addAttribute("tokens", "LAMBDA");
final String[] expected = {
"33:42: " + getCheckMessage(MSG_KEY, 3, 2),
};
verify(checkConfig, new File("src/test/resources-noncompilable/com/puppycrawl/tools/"
+ "checkstyle/coding/InputReturnCountLambda.java").getCanonicalPath(), expected);
}
@Test
public void testMethodsOnly() throws Exception {
final DefaultConfiguration checkConfig = createCheckConfig(ReturnCountCheck.class);
checkConfig.addAttribute("tokens", "METHOD_DEF");
final String[] expected = {
"25:5: " + getCheckMessage(MSG_KEY, 3, 2),
"32:5: " + getCheckMessage(MSG_KEY, 4, 2),
"40:5: " + getCheckMessage(MSG_KEY, 4, 2),
"55:5: " + getCheckMessage(MSG_KEY, 3, 2),
};
verify(checkConfig, new File("src/test/resources-noncompilable/com/puppycrawl/tools/"
+ "checkstyle/coding/InputReturnCountLambda.java").getCanonicalPath(), expected);
}
@Test
public void testWithReturnOnlyAsTokens() throws Exception {
final DefaultConfiguration checkConfig = createCheckConfig(ReturnCountCheck.class);
checkConfig.addAttribute("tokens", "LITERAL_RETURN");
final String[] expected = {
};
verify(checkConfig, new File("src/test/resources-noncompilable/com/puppycrawl/tools/"
+ "checkstyle/coding/InputReturnCountLambda.java").getCanonicalPath(), expected);
}
@Test
public void testImproperToken() throws Exception {
ReturnCountCheck check = new ReturnCountCheck();
DetailAST classDefAst = new DetailAST();
classDefAst.setType(TokenTypes.CLASS_DEF);
try {
check.visitToken(classDefAst);
Assert.fail();
}
catch (IllegalStateException e) {
// it is OK
}
try {
check.leaveToken(classDefAst);
Assert.fail();
}
catch (IllegalStateException e) {
// it is OK
}
}
}
| lgpl-2.1 |
zebrafishmine/intermine | bio/webapp/src/org/intermine/bio/web/displayer/MinePathwaysDisplayer.java | 7457 | package org.intermine.bio.web.displayer;
/*
* Copyright (C) 2002-2016 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.api.InterMineAPI;
import org.intermine.api.mines.FriendlyMineManager;
import org.intermine.api.mines.Mine;
import org.intermine.api.profile.ProfileManager;
import org.intermine.api.query.PathQueryExecutor;
import org.intermine.api.results.ExportResultsIterator;
import org.intermine.api.results.ResultElement;
import org.intermine.model.bio.Gene;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.pathquery.Constraints;
import org.intermine.pathquery.OrderDirection;
import org.intermine.pathquery.PathQuery;
import org.intermine.util.CacheMap;
import org.intermine.metadata.StringUtil;
import org.intermine.metadata.Util;
import org.intermine.web.displayer.ReportDisplayer;
import org.intermine.web.logic.config.ReportDisplayerConfig;
import org.intermine.web.logic.results.ReportObject;
import org.intermine.web.logic.session.SessionMethods;
/**
* For all friendly mines, query for pathways
*
* @author Julie Sullivan
*/
public class MinePathwaysDisplayer extends ReportDisplayer
{
private static Map<ReportObject, Map<Mine, String>> minePathwayCache
= new CacheMap<ReportObject, Map<Mine, String>>();
private static Map<ReportObject, Mine> localMineCache = new CacheMap<ReportObject, Mine>();
protected static final Logger LOG = Logger.getLogger(MinePathwaysDisplayer.class);
/**
* Construct with config and the InterMineAPI.
*
* @param config to describe the report displayer
* @param im the InterMine API
*/
public MinePathwaysDisplayer(ReportDisplayerConfig config, InterMineAPI im) {
super(config, im);
}
@Override
public void display(HttpServletRequest request, ReportObject reportObject) {
Gene gene = (Gene) reportObject.getObject();
request.setAttribute("gene", gene);
Map<Mine, String> mineToOrthologues = null;
//Mine localMine = null;
Mine localMine = null;
if (minePathwayCache.get(reportObject) != null) {
mineToOrthologues = minePathwayCache.get(reportObject);
} else {
Map<String, Set<String>> orthologues = getLocalHomologues(gene);
HttpSession session = request.getSession();
ServletContext servletContext = session.getServletContext();
final Properties webProperties = SessionMethods.getWebProperties(servletContext);
final FriendlyMineManager linkManager
= FriendlyMineManager.getInstance(im, webProperties);
Collection<Mine> mines = linkManager.getFriendlyMines();
mineToOrthologues = buildHomologueMap(mines, orthologues);
localMine = linkManager.getLocalMine();
minePathwayCache.put(reportObject, mineToOrthologues);
}
if (localMineCache.get(reportObject) != null) {
localMine = localMineCache.get(reportObject);
} else {
HttpSession session = request.getSession();
ServletContext servletContext = session.getServletContext();
final Properties webProperties = SessionMethods.getWebProperties(servletContext);
final FriendlyMineManager linkManager
= FriendlyMineManager.getInstance(im, webProperties);
localMine = linkManager.getLocalMine();
localMineCache.put(reportObject, localMine);
}
request.setAttribute("minesForPathways", mineToOrthologues);
request.setAttribute("localMine", localMine);
}
/* Using the provided list of organisms available in this mine, build list of genes to query
* in each mine.
*/
private Map<Mine, String> buildHomologueMap(Collection<Mine> mines,
Map<String, Set<String>> orthologues) {
Map<Mine, String> mineToOrthologues = new HashMap<Mine, String>();
// for each mine,
for (Mine mine : mines) {
// organism(s) available in mine
Set<String> remoteMineOrganisms = mine.getDefaultValues();
StringBuffer genes = new StringBuffer();
// loop through all of the orthologues available in local mine. on match, copy over
for (Map.Entry<String, Set<String>> entry : orthologues.entrySet()) {
// this mine has genes for these organisms, put in list
if (remoteMineOrganisms.contains(entry.getKey())) {
// flatten so we can use array in js
if (genes.length() > 0) {
genes.append(",");
}
genes.append(StringUtil.join(entry.getValue(), ","));
}
}
if (genes.length() > 0) {
mineToOrthologues.put(mine, genes.toString());
} else {
mineToOrthologues.put(mine, "");
}
}
return mineToOrthologues;
}
private PathQuery getQuery(Gene gene) {
PathQuery q = new PathQuery(im.getModel());
q.addViews("Gene.homologues.homologue.primaryIdentifier",
"Gene.homologues.homologue.secondaryIdentifier",
"Gene.homologues.homologue.organism.shortName");
q.addConstraint(Constraints.eq("Gene.primaryIdentifier", gene.getPrimaryIdentifier()));
q.addOrderBy("Gene.homologues.homologue.organism.shortName", OrderDirection.ASC);
return q;
}
private Map<String, Set<String>> getLocalHomologues(Gene gene) {
Map<String, Set<String>> orthologues = new HashMap<String, Set<String>>();
ProfileManager profileManager = im.getProfileManager();
PathQueryExecutor executor = im.getPathQueryExecutor(profileManager.getSuperuserProfile());
PathQuery q = null;
try {
q = getQuery(gene);
} catch (Exception e) {
return Collections.emptyMap();
}
if (!q.isValid()) {
return Collections.emptyMap();
}
ExportResultsIterator it;
try {
it = executor.execute(q);
} catch (ObjectStoreException e) {
throw new RuntimeException(e);
}
while (it.hasNext()) {
List<ResultElement> row = it.next();
String identifier = (String) row.get(0).getField();
String secondaryIdentifier = (String) row.get(1).getField();
String organism = (String) row.get(2).getField();
if (!StringUtils.isEmpty(identifier)) {
Util.addToSetMap(orthologues, organism, identifier);
} else if (!StringUtils.isEmpty(secondaryIdentifier)) {
Util.addToSetMap(orthologues, organism, secondaryIdentifier);
}
}
return orthologues;
}
}
| lgpl-2.1 |
bluenote10/TuxguitarParser | tuxguitar-src/TuxGuitar/src/org/herac/tuxguitar/app/action/impl/edit/TGSetNaturalKeyAction.java | 735 | package org.herac.tuxguitar.app.action.impl.edit;
import org.herac.tuxguitar.action.TGActionContext;
import org.herac.tuxguitar.app.view.component.tab.TablatureEditor;
import org.herac.tuxguitar.editor.action.TGActionBase;
import org.herac.tuxguitar.util.TGContext;
public class TGSetNaturalKeyAction extends TGActionBase{
public static final String NAME = "action.edit.set-natural-key";
public TGSetNaturalKeyAction(TGContext context) {
super(context, NAME);
}
protected void processAction(TGActionContext context){
TablatureEditor tablatureEditor = TablatureEditor.getInstance(getContext());
tablatureEditor.getTablature().getEditorKit().setNatural(!tablatureEditor.getTablature().getEditorKit().isNatural());
}
}
| lgpl-2.1 |
paiyetan/glycoworkbench | src/org/eurocarbdb/application/glycoworkbench/plugin/DictionaryStructureGenerator.java | 3056 | /*
* EuroCarbDB, a framework for carbohydrate bioinformatics
*
* Copyright (c) 2006-2009, Eurocarb project, or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
* A copy of this license accompanies this distribution in the file LICENSE.txt.
*
* 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.
*
* Last commit: $Rev$ by $Author$ on $Date:: $
*/
/**
@author Alessio Ceroni (a.ceroni@imperial.ac.uk)
*/
package org.eurocarbdb.application.glycoworkbench.plugin;
import org.eurocarbdb.application.glycoworkbench.*;
import org.eurocarbdb.application.glycanbuilder.*;
import java.util.*;
public class DictionaryStructureGenerator implements StructureGenerator {
private Collection<StructureDictionary> dictionaries = null;
private MassOptions mass_opt = null;
private Iterator<StructureDictionary> sdi = null;
private Iterator<StructureType> sti = null;
private StructureDictionary last_dict = null;
private StructureType last_type = null;
public DictionaryStructureGenerator() {
dictionaries = new Vector<StructureDictionary>();
}
public DictionaryStructureGenerator(StructureDictionary dict) {
if( dict!=null )
dictionaries = Collections.singleton(dict);
else
dictionaries = new Vector<StructureDictionary>();
}
public DictionaryStructureGenerator(Collection<StructureDictionary> dicts) {
if( dicts!=null )
dictionaries = dicts;
else
dictionaries = new Vector<StructureDictionary>();
}
public void add(StructureDictionary dict) {
dictionaries.add(dict);
}
public void start(MassOptions _mass_opt) {
mass_opt = _mass_opt;
sdi = dictionaries.iterator();
sti = null;
last_dict = null;
last_type = null;
}
public FragmentEntry next(boolean backtrack) {
for(;;) {
if( sti==null || !sti.hasNext() ) {
if( sdi.hasNext() ) {
last_dict = sdi.next();
sti = last_dict.iterator();
}
else
return null;
}
else {
try {
last_type = sti.next();
return last_type.generateFragmentEntry(mass_opt);
}
catch(Exception e) {
LogUtils.report(e);
return null;
}
}
}
}
public double computeScore(Glycan structure) {
if( last_dict!=null && last_dict.getScorer()!=null )
return last_dict.getScorer().computeScore(structure);
return 0.;
}
}
| lgpl-3.0 |
kishorvpatil/incubator-storm | storm-client/src/jvm/org/apache/storm/trident/planner/processor/PartitionPersistProcessor.java | 4450 | /**
* 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.storm.trident.planner.processor;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.trident.operation.TridentOperationContext;
import org.apache.storm.trident.planner.ProcessorContext;
import org.apache.storm.trident.planner.TridentProcessor;
import org.apache.storm.trident.state.State;
import org.apache.storm.trident.state.StateUpdater;
import org.apache.storm.trident.topology.TransactionAttempt;
import org.apache.storm.trident.tuple.TridentTuple;
import org.apache.storm.trident.tuple.TridentTuple.Factory;
import org.apache.storm.trident.tuple.TridentTupleView.ProjectionFactory;
import org.apache.storm.tuple.Fields;
public class PartitionPersistProcessor implements TridentProcessor {
StateUpdater updater;
State state;
String stateId;
TridentContext context;
Fields inputFields;
ProjectionFactory projection;
FreshCollector collector;
public PartitionPersistProcessor(String stateId, Fields inputFields, StateUpdater updater) {
this.updater = updater;
this.stateId = stateId;
this.inputFields = inputFields;
}
@Override
public void prepare(Map<String, Object> conf, TopologyContext context, TridentContext tridentContext) {
List<Factory> parents = tridentContext.getParentTupleFactories();
if (parents.size() != 1) {
throw new RuntimeException("Partition persist operation can only have one parent");
}
this.context = tridentContext;
state = (State) context.getTaskData(stateId);
projection = new ProjectionFactory(parents.get(0), inputFields);
collector = new FreshCollector(tridentContext);
updater.prepare(conf, new TridentOperationContext(context, projection));
}
@Override
public void cleanup() {
updater.cleanup();
}
@Override
public void startBatch(ProcessorContext processorContext) {
processorContext.state[context.getStateIndex()] = new ArrayList<TridentTuple>();
}
@Override
public void execute(ProcessorContext processorContext, String streamId, TridentTuple tuple) {
((List) processorContext.state[context.getStateIndex()]).add(projection.create(tuple));
}
@Override
public void flush() {
// NO-OP
}
@Override
public void finishBatch(ProcessorContext processorContext) {
collector.setContext(processorContext);
Object batchId = processorContext.batchId;
// since this processor type is a committer, this occurs in the commit phase
List<TridentTuple> buffer = (List) processorContext.state[context.getStateIndex()];
// don't update unless there are tuples
// this helps out with things like global partition persist, where multiple tasks may still
// exist for this processor. Only want the global one to do anything
// this is also a helpful optimization that state implementations don't need to manually do
if (buffer.size() > 0) {
Long txid = null;
// this is to support things like persisting off of drpc stream, which is inherently unreliable
// and won't have a tx attempt
if (batchId instanceof TransactionAttempt) {
txid = ((TransactionAttempt) batchId).getTransactionId();
}
state.beginCommit(txid);
updater.updateState(state, buffer, collector);
state.commit(txid);
}
}
@Override
public Factory getOutputFactory() {
return collector.getOutputFactory();
}
}
| apache-2.0 |
DariusX/camel | core/camel-core/src/test/java/org/apache/camel/processor/async/AsyncEndpointTryCatchFinallyTest.java | 2769 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.processor.async;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;
public class AsyncEndpointTryCatchFinallyTest extends ContextTestSupport {
private static String beforeThreadName;
private static String afterThreadName;
@Test
public void testAsyncEndpoint() throws Exception {
getMockEndpoint("mock:before").expectedBodiesReceived("Hello Camel");
getMockEndpoint("mock:after").expectedBodiesReceived("Hello Camel");
getMockEndpoint("mock:result").expectedBodiesReceived("Bye World");
String reply = template.requestBody("direct:start", "Hello Camel", String.class);
assertEquals("Bye World", reply);
assertMockEndpointsSatisfied();
assertFalse("Should use different threads", beforeThreadName.equalsIgnoreCase(afterThreadName));
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
context.addComponent("async", new MyAsyncComponent());
from("direct:start").to("mock:before").to("log:before").doTry().process(new Processor() {
public void process(Exchange exchange) throws Exception {
beforeThreadName = Thread.currentThread().getName();
}
}).to("async:bye:camel?failFirstAttempts=1").doCatch(Exception.class).process(new Processor() {
public void process(Exchange exchange) throws Exception {
afterThreadName = Thread.currentThread().getName();
}
}).doFinally().to("log:after").to("mock:after").transform(constant("Bye World")).end().to("mock:result");
}
};
}
}
| apache-2.0 |
AdobeDon/fastcanvas-phonegapbuild | Android/src/com/adobe/plugins/FastCanvasTextureDimension.java | 738 | /*
Copyright 2013 Adobe Systems Inc.;
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.adobe.plugins;
// Out param for FastCanvasJNI.addPngTexture
public class FastCanvasTextureDimension {
public int width;
public int height;
}
| apache-2.0 |
StrategyObject/fop | src/sandbox/org/apache/fop/render/svg/SVGSVGHandler.java | 3259 | /*
* 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.
*/
/* $Id$ */
package org.apache.fop.render.svg;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.svg.SVGDocument;
import org.w3c.dom.svg.SVGElement;
import org.w3c.dom.svg.SVGSVGElement;
import org.apache.batik.anim.dom.SVGDOMImplementation;
import org.apache.batik.dom.util.DOMUtilities;
import org.apache.batik.dom.util.XMLSupport;
import org.apache.fop.render.Renderer;
import org.apache.fop.render.RendererContext;
import org.apache.fop.render.XMLHandler;
/** The svg:svg element handler. */
public class SVGSVGHandler implements XMLHandler, SVGRendererContextConstants {
/** {@inheritDoc} */
public void handleXML(RendererContext context,
org.w3c.dom.Document doc, String ns) throws Exception {
if (getNamespace().equals(ns)) {
if (!(doc instanceof SVGDocument)) {
DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
doc = DOMUtilities.deepCloneDocument(doc, impl);
}
SVGSVGElement svg = ((SVGDocument) doc).getRootElement();
SVGDocument targetDoc = (SVGDocument)context.getProperty(SVG_DOCUMENT);
SVGElement currentPageG = (SVGElement)context.getProperty(SVG_PAGE_G);
Element view = targetDoc.createElementNS(getNamespace(), "svg");
Node newsvg = targetDoc.importNode(svg, true);
//view.setAttributeNS(null, "viewBox", "0 0 ");
int xpos = ((Integer)context.getProperty(XPOS)).intValue();
int ypos = ((Integer)context.getProperty(YPOS)).intValue();
view.setAttributeNS(null, "x", "" + xpos / 1000f);
view.setAttributeNS(null, "y", "" + ypos / 1000f);
// this fixes a problem where the xmlns is repeated sometimes
Element ele = (Element) newsvg;
ele.setAttributeNS(XMLSupport.XMLNS_NAMESPACE_URI, "xmlns",
getNamespace());
if (ele.hasAttributeNS(null, "xmlns")) {
ele.removeAttributeNS(null, "xmlns");
}
view.appendChild(newsvg);
currentPageG.appendChild(view);
}
}
/** {@inheritDoc} */
public boolean supportsRenderer(Renderer renderer) {
return (renderer instanceof SVGRenderer);
}
/** {@inheritDoc} */
public String getNamespace() {
return SVGRenderer.MIME_TYPE;
}
}
| apache-2.0 |
jiaqifeng/pinpoint | web/src/main/java/com/navercorp/pinpoint/web/vo/stat/SampledDeadlock.java | 2418 | /*
* Copyright 2017 NAVER 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.
*/
package com.navercorp.pinpoint.web.vo.stat;
import com.navercorp.pinpoint.web.vo.chart.Point;
import com.navercorp.pinpoint.web.vo.stat.chart.agent.AgentStatPoint;
import java.util.Objects;
/**
* @author Taejin Koo
*/
public class SampledDeadlock implements SampledAgentStatDataPoint {
public static final int UNCOLLECTED_COUNT = -1;
public static final Point.UncollectedPointCreator<AgentStatPoint<Integer>> UNCOLLECTED_POINT_CREATOR = new Point.UncollectedPointCreator<AgentStatPoint<Integer>>() {
@Override
public AgentStatPoint<Integer> createUnCollectedPoint(long xVal) {
return new AgentStatPoint<>(xVal, UNCOLLECTED_COUNT);
}
};
private final AgentStatPoint<Integer> deadlockedThreadCount;
public SampledDeadlock(AgentStatPoint<Integer> deadlockedThreadCount) {
this.deadlockedThreadCount = Objects.requireNonNull(deadlockedThreadCount, "deadlockedThreadCount must not be null");
}
public AgentStatPoint<Integer> getDeadlockedThreadCount() {
return deadlockedThreadCount;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SampledDeadlock that = (SampledDeadlock) o;
return deadlockedThreadCount != null ? deadlockedThreadCount.equals(that.deadlockedThreadCount) : that.deadlockedThreadCount == null;
}
@Override
public int hashCode() {
return deadlockedThreadCount != null ? deadlockedThreadCount.hashCode() : 0;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("SampledDeadlock{");
sb.append("deadlockedThreadCount=").append(deadlockedThreadCount);
sb.append('}');
return sb.toString();
}
}
| apache-2.0 |
thinker0/aurora | src/main/java/org/apache/aurora/scheduler/http/api/ApiModule.java | 5554 | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aurora.scheduler.http.api;
import java.nio.charset.StandardCharsets;
import javax.inject.Singleton;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.MediaType;
import com.google.inject.Provides;
import com.google.inject.servlet.ServletModule;
import org.apache.aurora.gen.AuroraAdmin;
import org.apache.aurora.scheduler.http.CorsFilter;
import org.apache.aurora.scheduler.http.LeaderRedirectFilter;
import org.apache.aurora.scheduler.http.api.TContentAwareServlet.ContentFactoryPair;
import org.apache.aurora.scheduler.http.api.TContentAwareServlet.InputConfig;
import org.apache.aurora.scheduler.http.api.TContentAwareServlet.OutputConfig;
import org.apache.aurora.scheduler.thrift.aop.AnnotatedAuroraAdmin;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TJSONProtocol;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.util.resource.Resource;
public class ApiModule extends ServletModule {
public static final String API_PATH = "/api";
private static final MediaType GENERIC_JSON = MediaType.JSON_UTF_8.withoutParameters();
private static final MediaType GENERIC_THRIFT = MediaType.create("application", "x-thrift");
private static final MediaType THRIFT_JSON = MediaType
.create("application", "vnd.apache.thrift.json");
private static final MediaType THRIFT_JSON_UTF_8 = MediaType
.create("application", "vnd.apache.thrift.json")
.withCharset(StandardCharsets.UTF_8);
private static final MediaType THRIFT_BINARY = MediaType
.create("application", "vnd.apache.thrift.binary");
@Parameters(separators = "=")
public static class Options {
/**
* Set the {@code Access-Control-Allow-Origin} header for API requests. See
* http://www.w3.org/TR/cors/
*/
@Parameter(names = "-enable_cors_for",
description = "List of domains for which CORS support should be enabled.")
public String enableCorsFor;
}
private final Options options;
public ApiModule(Options options) {
this.options = options;
}
private static final String API_CLIENT_ROOT = Resource
.newClassPathResource("org/apache/aurora/scheduler/gen/client")
.toString();
@Override
protected void configureServlets() {
if (options.enableCorsFor != null) {
filter(API_PATH).through(new CorsFilter(options.enableCorsFor));
}
serve(API_PATH).with(TContentAwareServlet.class);
filter(ApiBeta.PATH, ApiBeta.PATH + "/*").through(LeaderRedirectFilter.class);
bind(ApiBeta.class);
serve("/apiclient", "/apiclient/*")
.with(new DefaultServlet(), ImmutableMap.<String, String>builder()
.put("resourceBase", API_CLIENT_ROOT)
.put("pathInfoOnly", "true")
.put("dirAllowed", "false")
.build());
}
@Provides
@Singleton
TContentAwareServlet provideApiThriftServlet(AnnotatedAuroraAdmin schedulerThriftInterface) {
/*
* For backwards compatibility the servlet is configured to assume `application/x-thrift` and
* `application/json` have TJSON bodies.
*
* Requests that have the registered MIME type for apache thrift are mapped to their respective
* protocols. See
* http://www.iana.org/assignments/media-types/application/vnd.apache.thrift.binary and
* http://www.iana.org/assignments/media-types/application/vnd.apache.thrift.json for details.
*
* Responses have the registered MIME type so the client can decode appropriately.
*
* The Accept header is used to determine the response type. By default JSON is sent for any
* value except for the binary thrift header.
*/
ContentFactoryPair jsonFactory = new ContentFactoryPair(
new TJSONProtocol.Factory(),
THRIFT_JSON);
ContentFactoryPair binFactory = new ContentFactoryPair(
new TBinaryProtocol.Factory(),
THRIFT_BINARY);
// Which factory to use based on the Content-Type header of the request for reading the request.
InputConfig inputConfig = new InputConfig(GENERIC_THRIFT, ImmutableMap.of(
GENERIC_JSON, jsonFactory,
GENERIC_THRIFT, jsonFactory,
THRIFT_JSON, jsonFactory,
THRIFT_JSON_UTF_8, jsonFactory,
THRIFT_BINARY, binFactory
));
// Which factory to use based on the Accept header of the request for the response.
OutputConfig outputConfig = new OutputConfig(GENERIC_JSON, ImmutableMap.of(
GENERIC_JSON, jsonFactory,
GENERIC_THRIFT, jsonFactory,
THRIFT_JSON, jsonFactory,
THRIFT_JSON_UTF_8, jsonFactory,
THRIFT_BINARY, binFactory
));
// A request without a Content-Type (like from curl) should be treated as GENERIC_THRIFT
return new TContentAwareServlet(
new AuroraAdmin.Processor<>(schedulerThriftInterface),
inputConfig,
outputConfig);
}
}
| apache-2.0 |
mkjellman/cassandra | src/java/org/apache/cassandra/db/MutationVerbHandler.java | 3319 | /*
* 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.cassandra.db;
import java.io.IOException;
import java.util.Iterator;
import org.apache.cassandra.exceptions.WriteTimeoutException;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.net.*;
import org.apache.cassandra.tracing.Tracing;
public class MutationVerbHandler implements IVerbHandler<Mutation>
{
private void reply(int id, InetAddressAndPort replyTo)
{
Tracing.trace("Enqueuing response to {}", replyTo);
MessagingService.instance().sendReply(WriteResponse.createMessage(), id, replyTo);
}
private void failed()
{
Tracing.trace("Payload application resulted in WriteTimeout, not replying");
}
public void doVerb(MessageIn<Mutation> message, int id) throws IOException
{
// Check if there were any forwarding headers in this message
InetAddressAndPort from = (InetAddressAndPort)message.parameters.get(ParameterType.FORWARD_FROM);
InetAddressAndPort replyTo;
if (from == null)
{
replyTo = message.from;
ForwardToContainer forwardTo = (ForwardToContainer)message.parameters.get(ParameterType.FORWARD_TO);
if (forwardTo != null)
forwardToLocalNodes(message.payload, message.verb, forwardTo, message.from);
}
else
{
replyTo = from;
}
try
{
message.payload.applyFuture().thenAccept(o -> reply(id, replyTo)).exceptionally(wto -> {
failed();
return null;
});
}
catch (WriteTimeoutException wto)
{
failed();
}
}
private static void forwardToLocalNodes(Mutation mutation, MessagingService.Verb verb, ForwardToContainer forwardTo, InetAddressAndPort from) throws IOException
{
// tell the recipients who to send their ack to
MessageOut<Mutation> message = new MessageOut<>(verb, mutation, Mutation.serializer).withParameter(ParameterType.FORWARD_FROM, from);
Iterator<InetAddressAndPort> iterator = forwardTo.targets.iterator();
// Send a message to each of the addresses on our Forward List
for (int i = 0; i < forwardTo.targets.size(); i++)
{
InetAddressAndPort address = iterator.next();
Tracing.trace("Enqueuing forwarded write to {}", address);
MessagingService.instance().sendOneWay(message, forwardTo.messageIds[i], address);
}
}
}
| apache-2.0 |
ImpalaToGo/ImpalaToGo | fe/src/main/java/com/cloudera/impala/planner/ScanNode.java | 4971 | // Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.impala.planner;
import java.util.List;
import com.cloudera.impala.analysis.SlotDescriptor;
import com.cloudera.impala.analysis.TupleDescriptor;
import com.cloudera.impala.thrift.TExplainLevel;
import com.cloudera.impala.thrift.TNetworkAddress;
import com.cloudera.impala.thrift.TScanRangeLocations;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
/**
* Representation of the common elements of all scan nodes.
*/
abstract public class ScanNode extends PlanNode {
protected final TupleDescriptor desc_;
// Total number of rows this node is expected to process
protected long inputCardinality_ = -1;
// Counter indicating if partitions have missing statistics
protected int numPartitionsMissingStats_ = 0;
// List of scan-range locations. Populated in init().
protected List<TScanRangeLocations> scanRanges_;
public ScanNode(PlanNodeId id, TupleDescriptor desc, String displayName) {
super(id, desc.getId().asList(), displayName);
desc_ = desc;
}
public TupleDescriptor getTupleDesc() { return desc_; }
/**
* Returns all scan ranges plus their locations.
*/
public List<TScanRangeLocations> getScanRangeLocations() {
Preconditions.checkNotNull(scanRanges_, "Need to call init() first.");
return scanRanges_;
}
@Override
protected String debugString() {
return Objects.toStringHelper(this)
.add("tid", desc_.getId().asInt())
.add("tblName", desc_.getTable().getFullName())
.add("keyRanges", "")
.addValue(super.debugString())
.toString();
}
/**
* Returns the explain string for table and columns stats to be included into the
* a ScanNode's explain string. The given prefix is prepended to each of the lines.
* The prefix is used for proper formatting when the string returned by this method
* is embedded in a query's explain plan.
*/
protected String getStatsExplainString(String prefix, TExplainLevel detailLevel) {
StringBuilder output = new StringBuilder();
// Table stats.
if (desc_.getTable().getNumRows() == -1) {
output.append(prefix + "table stats: unavailable");
} else {
output.append(prefix + "table stats: " + desc_.getTable().getNumRows() +
" rows total");
if (numPartitionsMissingStats_ > 0) {
output.append(" (" + numPartitionsMissingStats_ + " partition(s) missing stats)");
}
}
output.append("\n");
// Column stats.
List<String> columnsMissingStats = Lists.newArrayList();
for (SlotDescriptor slot: desc_.getSlots()) {
if (!slot.getStats().hasStats()) {
columnsMissingStats.add(slot.getColumn().getName());
}
}
if (columnsMissingStats.isEmpty()) {
output.append(prefix + "column stats: all");
} else if (columnsMissingStats.size() == desc_.getSlots().size()) {
output.append(prefix + "column stats: unavailable");
} else {
output.append(String.format("%scolumns missing stats: %s", prefix,
Joiner.on(", ").join(columnsMissingStats)));
}
return output.toString();
}
/**
* Returns true if the table underlying this scan is missing table stats
* or column stats relevant to this scan node.
*/
public boolean isTableMissingStats() {
return isTableMissingColumnStats() || isTableMissingTableStats();
}
public boolean isTableMissingTableStats() {
if (desc_.getTable().getNumRows() == -1) return true;
return numPartitionsMissingStats_ > 0;
}
public boolean isTableMissingColumnStats() {
for (SlotDescriptor slot: desc_.getSlots()) {
if (!slot.getStats().hasStats()) return true;
}
return false;
}
/**
* Helper function to parse a "host:port" address string into TNetworkAddress
* This is called with ipaddress:port when doing scan range assignment.
*/
protected static TNetworkAddress addressToTNetworkAddress(String address) {
TNetworkAddress result = new TNetworkAddress();
String[] hostPort = address.split(":");
result.hostname = hostPort[0];
result.port = Integer.parseInt(hostPort[1]);
return result;
}
@Override
public long getInputCardinality() {
if (getConjuncts().isEmpty() && hasLimit()) return getLimit();
return inputCardinality_;
}
}
| apache-2.0 |
shurun19851206/ignite | modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryManager.java | 27338 | /*
* 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.ignite.internal.processors.cache.query.continuous;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import javax.cache.configuration.CacheEntryListenerConfiguration;
import javax.cache.event.CacheEntryCreatedListener;
import javax.cache.event.CacheEntryEvent;
import javax.cache.event.CacheEntryEventFilter;
import javax.cache.event.CacheEntryExpiredListener;
import javax.cache.event.CacheEntryListener;
import javax.cache.event.CacheEntryRemovedListener;
import javax.cache.event.CacheEntryUpdatedListener;
import javax.cache.event.EventType;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.cache.CacheEntryEventSerializableFilter;
import org.apache.ignite.cache.query.ContinuousQuery;
import org.apache.ignite.cluster.ClusterGroup;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.cluster.ClusterTopologyException;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.CacheObject;
import org.apache.ignite.internal.processors.cache.GridCacheEntryEx;
import org.apache.ignite.internal.processors.cache.GridCacheManagerAdapter;
import org.apache.ignite.internal.processors.cache.KeyCacheObject;
import org.apache.ignite.internal.processors.continuous.GridContinuousHandler;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.plugin.security.SecurityPermission;
import org.apache.ignite.resources.LoggerResource;
import org.jsr166.ConcurrentHashMap8;
import static javax.cache.event.EventType.CREATED;
import static javax.cache.event.EventType.EXPIRED;
import static javax.cache.event.EventType.REMOVED;
import static javax.cache.event.EventType.UPDATED;
import static org.apache.ignite.events.EventType.EVT_CACHE_QUERY_OBJECT_READ;
import static org.apache.ignite.internal.GridTopic.TOPIC_CACHE;
/**
* Continuous queries manager.
*/
public class CacheContinuousQueryManager extends GridCacheManagerAdapter {
/** */
private static final byte CREATED_FLAG = 0b0001;
/** */
private static final byte UPDATED_FLAG = 0b0010;
/** */
private static final byte REMOVED_FLAG = 0b0100;
/** */
private static final byte EXPIRED_FLAG = 0b1000;
/** Listeners. */
private final ConcurrentMap<UUID, CacheContinuousQueryListener> lsnrs = new ConcurrentHashMap8<>();
/** Listeners count. */
private final AtomicInteger lsnrCnt = new AtomicInteger();
/** Internal entries listeners. */
private final ConcurrentMap<UUID, CacheContinuousQueryListener> intLsnrs = new ConcurrentHashMap8<>();
/** Internal listeners count. */
private final AtomicInteger intLsnrCnt = new AtomicInteger();
/** Query sequence number for message topic. */
private final AtomicLong seq = new AtomicLong();
/** JCache listeners. */
private final ConcurrentMap<CacheEntryListenerConfiguration, JCacheQuery> jCacheLsnrs =
new ConcurrentHashMap8<>();
/** Ordered topic prefix. */
private String topicPrefix;
/** {@inheritDoc} */
@Override protected void start0() throws IgniteCheckedException {
// Append cache name to the topic.
topicPrefix = "CONTINUOUS_QUERY" + (cctx.name() == null ? "" : "_" + cctx.name());
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override protected void onKernalStart0() throws IgniteCheckedException {
Iterable<CacheEntryListenerConfiguration> cfgs = cctx.config().getCacheEntryListenerConfigurations();
if (cfgs != null) {
for (CacheEntryListenerConfiguration cfg : cfgs)
executeJCacheQuery(cfg, true);
}
}
/** {@inheritDoc} */
@Override protected void onKernalStop0(boolean cancel) {
super.onKernalStop0(cancel);
for (JCacheQuery lsnr : jCacheLsnrs.values()) {
try {
lsnr.cancel();
}
catch (IgniteCheckedException e) {
if (log.isDebugEnabled())
log.debug("Failed to stop JCache entry listener: " + e.getMessage());
}
}
}
/**
* @param e Cache entry.
* @param key Key.
* @param newVal New value.
* @param oldVal Old value.
* @param preload Whether update happened during preloading.
* @throws IgniteCheckedException In case of error.
*/
public void onEntryUpdated(GridCacheEntryEx e,
KeyCacheObject key,
CacheObject newVal,
CacheObject oldVal,
boolean preload)
throws IgniteCheckedException
{
assert e != null;
assert key != null;
boolean internal = e.isInternal() || !e.context().userCache();
if (preload && !internal)
return;
ConcurrentMap<UUID, CacheContinuousQueryListener> lsnrCol;
if (internal)
lsnrCol = intLsnrCnt.get() > 0 ? intLsnrs : null;
else
lsnrCol = lsnrCnt.get() > 0 ? lsnrs : null;
if (F.isEmpty(lsnrCol))
return;
boolean hasNewVal = newVal != null;
boolean hasOldVal = oldVal != null;
if (!hasNewVal && !hasOldVal)
return;
EventType evtType = !hasNewVal ? REMOVED : !hasOldVal ? CREATED : UPDATED;
boolean initialized = false;
boolean primary = cctx.affinity().primary(cctx.localNode(), key, AffinityTopologyVersion.NONE);
boolean recordIgniteEvt = !internal && cctx.gridEvents().isRecordable(EVT_CACHE_QUERY_OBJECT_READ);
for (CacheContinuousQueryListener lsnr : lsnrCol.values()) {
if (preload && !lsnr.notifyExisting())
continue;
if (!initialized) {
if (lsnr.oldValueRequired()) {
oldVal = (CacheObject)cctx.unwrapTemporary(oldVal);
if (oldVal != null)
oldVal.finishUnmarshal(cctx.cacheObjectContext(), cctx.deploy().globalLoader());
}
if (newVal != null)
newVal.finishUnmarshal(cctx.cacheObjectContext(), cctx.deploy().globalLoader());
initialized = true;
}
CacheContinuousQueryEntry e0 = new CacheContinuousQueryEntry(
cctx.cacheId(),
evtType,
key,
newVal,
lsnr.oldValueRequired() ? oldVal : null);
CacheContinuousQueryEvent evt = new CacheContinuousQueryEvent<>(
cctx.kernalContext().cache().jcache(cctx.name()), cctx, e0);
lsnr.onEntryUpdated(evt, primary, recordIgniteEvt);
}
}
/**
* @param e Entry.
* @param key Key.
* @param oldVal Old value.
* @throws IgniteCheckedException In case of error.
*/
public void onEntryExpired(GridCacheEntryEx e, KeyCacheObject key, CacheObject oldVal)
throws IgniteCheckedException {
assert e != null;
assert key != null;
if (e.isInternal())
return;
ConcurrentMap<UUID, CacheContinuousQueryListener> lsnrCol = lsnrCnt.get() > 0 ? lsnrs : null;
if (F.isEmpty(lsnrCol))
return;
if (cctx.isReplicated() || cctx.affinity().primary(cctx.localNode(), key, AffinityTopologyVersion.NONE)) {
boolean primary = cctx.affinity().primary(cctx.localNode(), key, AffinityTopologyVersion.NONE);
boolean recordIgniteEvt = cctx.gridEvents().isRecordable(EVT_CACHE_QUERY_OBJECT_READ);
boolean initialized = false;
for (CacheContinuousQueryListener lsnr : lsnrCol.values()) {
if (!initialized) {
if (lsnr.oldValueRequired())
oldVal = (CacheObject)cctx.unwrapTemporary(oldVal);
if (oldVal != null)
oldVal.finishUnmarshal(cctx.cacheObjectContext(), cctx.deploy().globalLoader());
initialized = true;
}
CacheContinuousQueryEntry e0 = new CacheContinuousQueryEntry(
cctx.cacheId(),
EXPIRED,
key,
null,
lsnr.oldValueRequired() ? oldVal : null);
CacheContinuousQueryEvent evt = new CacheContinuousQueryEvent(
cctx.kernalContext().cache().jcache(cctx.name()), cctx, e0);
lsnr.onEntryUpdated(evt, primary, recordIgniteEvt);
}
}
}
/**
* @param locLsnr Local listener.
* @param rmtFilter Remote filter.
* @param bufSize Buffer size.
* @param timeInterval Time interval.
* @param autoUnsubscribe Auto unsubscribe flag.
* @param grp Cluster group.
* @return Continuous routine ID.
* @throws IgniteCheckedException In case of error.
*/
public UUID executeQuery(CacheEntryUpdatedListener locLsnr,
CacheEntryEventSerializableFilter rmtFilter,
int bufSize,
long timeInterval,
boolean autoUnsubscribe,
ClusterGroup grp) throws IgniteCheckedException
{
return executeQuery0(
locLsnr,
rmtFilter,
bufSize,
timeInterval,
autoUnsubscribe,
false,
false,
true,
false,
true,
grp);
}
/**
* @param locLsnr Local listener.
* @param rmtFilter Remote filter.
* @param loc Local flag.
* @param notifyExisting Notify existing flag.
* @return Continuous routine ID.
* @throws IgniteCheckedException In case of error.
*/
public UUID executeInternalQuery(CacheEntryUpdatedListener<?, ?> locLsnr,
CacheEntryEventSerializableFilter rmtFilter,
boolean loc,
boolean notifyExisting)
throws IgniteCheckedException
{
return executeQuery0(
locLsnr,
rmtFilter,
ContinuousQuery.DFLT_PAGE_SIZE,
ContinuousQuery.DFLT_TIME_INTERVAL,
ContinuousQuery.DFLT_AUTO_UNSUBSCRIBE,
true,
notifyExisting,
true,
false,
true,
loc ? cctx.grid().cluster().forLocal() : null);
}
/**
* @param routineId Consume ID.
*/
public void cancelInternalQuery(UUID routineId) {
try {
cctx.kernalContext().continuous().stopRoutine(routineId).get();
}
catch (IgniteCheckedException | IgniteException e) {
if (log.isDebugEnabled())
log.debug("Failed to stop internal continuous query: " + e.getMessage());
}
}
/**
* @param cfg Listener configuration.
* @param onStart Whether listener is created on node start.
* @throws IgniteCheckedException If failed.
*/
public void executeJCacheQuery(CacheEntryListenerConfiguration cfg, boolean onStart)
throws IgniteCheckedException {
JCacheQuery lsnr = new JCacheQuery(cfg, onStart);
JCacheQuery old = jCacheLsnrs.putIfAbsent(cfg, lsnr);
if (old != null)
throw new IllegalArgumentException("Listener is already registered for configuration: " + cfg);
try {
lsnr.execute();
}
catch (IgniteCheckedException e) {
cancelJCacheQuery(cfg);
throw e;
}
}
/**
* @param cfg Listener configuration.
* @throws IgniteCheckedException In case of error.
*/
public void cancelJCacheQuery(CacheEntryListenerConfiguration cfg) throws IgniteCheckedException {
JCacheQuery lsnr = jCacheLsnrs.remove(cfg);
if (lsnr != null)
lsnr.cancel();
}
/**
* @param locLsnr Local listener.
* @param rmtFilter Remote filter.
* @param bufSize Buffer size.
* @param timeInterval Time interval.
* @param autoUnsubscribe Auto unsubscribe flag.
* @param internal Internal flag.
* @param notifyExisting Notify existing flag.
* @param oldValRequired Old value required flag.
* @param sync Synchronous flag.
* @param ignoreExpired Ignore expired event flag.
* @param grp Cluster group.
* @return Continuous routine ID.
* @throws IgniteCheckedException In case of error.
*/
private UUID executeQuery0(CacheEntryUpdatedListener locLsnr,
final CacheEntryEventSerializableFilter rmtFilter,
int bufSize,
long timeInterval,
boolean autoUnsubscribe,
boolean internal,
boolean notifyExisting,
boolean oldValRequired,
boolean sync,
boolean ignoreExpired,
ClusterGroup grp) throws IgniteCheckedException
{
cctx.checkSecurity(SecurityPermission.CACHE_READ);
if (grp == null)
grp = cctx.kernalContext().grid().cluster();
Collection<ClusterNode> nodes = grp.nodes();
if (nodes.isEmpty())
throw new ClusterTopologyException("Failed to execute continuous query (empty cluster group is " +
"provided).");
boolean skipPrimaryCheck = false;
switch (cctx.config().getCacheMode()) {
case LOCAL:
if (!nodes.contains(cctx.localNode()))
throw new ClusterTopologyException("Continuous query for LOCAL cache can be executed " +
"only locally (provided projection contains remote nodes only).");
else if (nodes.size() > 1)
U.warn(log, "Continuous query for LOCAL cache will be executed locally (provided projection is " +
"ignored).");
grp = grp.forNode(cctx.localNode());
break;
case REPLICATED:
if (nodes.size() == 1 && F.first(nodes).equals(cctx.localNode()))
skipPrimaryCheck = cctx.affinityNode();
break;
}
int taskNameHash = !internal && cctx.kernalContext().security().enabled() ?
cctx.kernalContext().job().currentTaskNameHash() : 0;
GridContinuousHandler hnd = new CacheContinuousQueryHandler(
cctx.name(),
TOPIC_CACHE.topic(topicPrefix, cctx.localNodeId(), seq.getAndIncrement()),
locLsnr,
rmtFilter,
internal,
notifyExisting,
oldValRequired,
sync,
ignoreExpired,
taskNameHash,
skipPrimaryCheck);
UUID id = cctx.kernalContext().continuous().startRoutine(hnd, bufSize, timeInterval,
autoUnsubscribe, grp.predicate()).get();
if (notifyExisting) {
final Iterator<GridCacheEntryEx> it = cctx.cache().allEntries().iterator();
locLsnr.onUpdated(new Iterable<CacheEntryEvent>() {
@Override public Iterator<CacheEntryEvent> iterator() {
return new Iterator<CacheEntryEvent>() {
private CacheContinuousQueryEvent next;
{
advance();
}
@Override public boolean hasNext() {
return next != null;
}
@Override public CacheEntryEvent next() {
if (!hasNext())
throw new NoSuchElementException();
CacheEntryEvent next0 = next;
advance();
return next0;
}
@Override public void remove() {
throw new UnsupportedOperationException();
}
private void advance() {
next = null;
while (next == null) {
if (!it.hasNext())
break;
GridCacheEntryEx e = it.next();
next = new CacheContinuousQueryEvent<>(
cctx.kernalContext().cache().jcache(cctx.name()),
cctx,
new CacheContinuousQueryEntry(cctx.cacheId(), CREATED, e.key(), e.rawGet(), null));
if (rmtFilter != null && !rmtFilter.evaluate(next))
next = null;
}
}
};
}
});
}
return id;
}
/**
* @param lsnrId Listener ID.
* @param lsnr Listener.
* @param internal Internal flag.
* @return Whether listener was actually registered.
*/
GridContinuousHandler.RegisterStatus registerListener(UUID lsnrId,
CacheContinuousQueryListener lsnr,
boolean internal) {
boolean added;
if (internal) {
added = intLsnrs.putIfAbsent(lsnrId, lsnr) == null;
if (added)
intLsnrCnt.incrementAndGet();
}
else {
added = lsnrs.putIfAbsent(lsnrId, lsnr) == null;
if (added) {
lsnrCnt.incrementAndGet();
lsnr.onExecution();
}
}
return added ? GridContinuousHandler.RegisterStatus.REGISTERED : GridContinuousHandler.RegisterStatus.NOT_REGISTERED;
}
/**
* @param internal Internal flag.
* @param id Listener ID.
*/
void unregisterListener(boolean internal, UUID id) {
CacheContinuousQueryListener lsnr;
if (internal) {
if ((lsnr = intLsnrs.remove(id)) != null) {
intLsnrCnt.decrementAndGet();
lsnr.onUnregister();
}
}
else {
if ((lsnr = lsnrs.remove(id)) != null) {
lsnrCnt.decrementAndGet();
lsnr.onUnregister();
}
}
}
/**
*/
private class JCacheQuery {
/** */
private final CacheEntryListenerConfiguration cfg;
/** */
private final boolean onStart;
/** */
private volatile UUID routineId;
/**
* @param cfg Listener configuration.
* @param onStart {@code True} if executed on cache start.
*/
private JCacheQuery(CacheEntryListenerConfiguration cfg, boolean onStart) {
this.cfg = cfg;
this.onStart = onStart;
}
/**
* @throws IgniteCheckedException In case of error.
*/
@SuppressWarnings("unchecked")
void execute() throws IgniteCheckedException {
if (!onStart)
cctx.config().addCacheEntryListenerConfiguration(cfg);
CacheEntryListener locLsnrImpl = (CacheEntryListener)cfg.getCacheEntryListenerFactory().create();
if (locLsnrImpl == null)
throw new IgniteCheckedException("Local CacheEntryListener is mandatory and can't be null.");
byte types = 0;
types |= locLsnrImpl instanceof CacheEntryCreatedListener ? CREATED_FLAG : 0;
types |= locLsnrImpl instanceof CacheEntryUpdatedListener ? UPDATED_FLAG : 0;
types |= locLsnrImpl instanceof CacheEntryRemovedListener ? REMOVED_FLAG : 0;
types |= locLsnrImpl instanceof CacheEntryExpiredListener ? EXPIRED_FLAG : 0;
if (types == 0)
throw new IgniteCheckedException("Listener must implement one of CacheEntryListener sub-interfaces.");
CacheEntryUpdatedListener locLsnr = new JCacheQueryLocalListener(
locLsnrImpl,
log);
CacheEntryEventFilter fltr = null;
if (cfg.getCacheEntryEventFilterFactory() != null) {
fltr = (CacheEntryEventFilter) cfg.getCacheEntryEventFilterFactory().create();
if (!(fltr instanceof Serializable))
throw new IgniteCheckedException("Cache entry event filter must implement java.io.Serializable: " + fltr);
}
CacheEntryEventSerializableFilter rmtFilter = new JCacheQueryRemoteFilter(fltr, types);
routineId = executeQuery0(
locLsnr,
rmtFilter,
ContinuousQuery.DFLT_PAGE_SIZE,
ContinuousQuery.DFLT_TIME_INTERVAL,
ContinuousQuery.DFLT_AUTO_UNSUBSCRIBE,
false,
false,
cfg.isOldValueRequired(),
cfg.isSynchronous(),
false,
null);
}
/**
* @throws IgniteCheckedException In case of error.
*/
@SuppressWarnings("unchecked")
void cancel() throws IgniteCheckedException {
UUID routineId0 = routineId;
if (routineId0 != null)
cctx.kernalContext().continuous().stopRoutine(routineId0).get();
cctx.config().removeCacheEntryListenerConfiguration(cfg);
}
}
/**
*/
private static class JCacheQueryLocalListener<K, V> implements CacheEntryUpdatedListener<K, V> {
/** */
private final CacheEntryListener<K, V> impl;
/** */
private final IgniteLogger log;
/**
* @param impl Listener.
*/
JCacheQueryLocalListener(CacheEntryListener<K, V> impl, IgniteLogger log) {
assert impl != null;
assert log != null;
this.impl = impl;
this.log = log;
}
/** {@inheritDoc} */
@Override public void onUpdated(Iterable<CacheEntryEvent<? extends K, ? extends V>> evts) {
for (CacheEntryEvent<? extends K, ? extends V> evt : evts) {
try {
switch (evt.getEventType()) {
case CREATED:
assert impl instanceof CacheEntryCreatedListener;
((CacheEntryCreatedListener<K, V>)impl).onCreated(singleton(evt));
break;
case UPDATED:
assert impl instanceof CacheEntryUpdatedListener;
((CacheEntryUpdatedListener<K, V>)impl).onUpdated(singleton(evt));
break;
case REMOVED:
assert impl instanceof CacheEntryRemovedListener;
((CacheEntryRemovedListener<K, V>)impl).onRemoved(singleton(evt));
break;
case EXPIRED:
assert impl instanceof CacheEntryExpiredListener;
((CacheEntryExpiredListener<K, V>)impl).onExpired(singleton(evt));
break;
default:
throw new IllegalStateException("Unknown type: " + evt.getEventType());
}
}
catch (Exception e) {
U.error(log, "CacheEntryListener failed: " + e);
}
}
}
/**
* @param evt Event.
* @return Singleton iterable.
*/
@SuppressWarnings("unchecked")
private Iterable<CacheEntryEvent<? extends K, ? extends V>> singleton(
CacheEntryEvent<? extends K, ? extends V> evt) {
assert evt instanceof CacheContinuousQueryEvent;
Collection<CacheEntryEvent<? extends K, ? extends V>> evts = new ArrayList<>(1);
evts.add(evt);
return evts;
}
}
/**
*/
private static class JCacheQueryRemoteFilter implements CacheEntryEventSerializableFilter, Externalizable {
/** */
private static final long serialVersionUID = 0L;
/** */
private CacheEntryEventFilter impl;
/** */
private byte types;
/** */
@LoggerResource
private IgniteLogger log;
/**
* For {@link Externalizable}.
*/
public JCacheQueryRemoteFilter() {
// no-op.
}
/**
* @param impl Filter.
* @param types Types.
*/
JCacheQueryRemoteFilter(CacheEntryEventFilter impl, byte types) {
assert types != 0;
this.impl = impl;
this.types = types;
}
/** {@inheritDoc} */
@Override public boolean evaluate(CacheEntryEvent evt) {
try {
return (types & flag(evt.getEventType())) != 0 && (impl == null || impl.evaluate(evt));
}
catch (Exception e) {
U.error(log, "CacheEntryEventFilter failed: " + e);
return true;
}
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(impl);
out.writeByte(types);
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
impl = (CacheEntryEventFilter)in.readObject();
types = in.readByte();
}
/**
* @param evtType Type.
* @return Flag value.
*/
private byte flag(EventType evtType) {
switch (evtType) {
case CREATED:
return CREATED_FLAG;
case UPDATED:
return UPDATED_FLAG;
case REMOVED:
return REMOVED_FLAG;
case EXPIRED:
return EXPIRED_FLAG;
default:
throw new IllegalStateException("Unknown type: " + evtType);
}
}
}
} | apache-2.0 |
PramodSSImmaneni/apex-malhar | library/src/test/java/org/apache/hadoop/io/file/tfile/TestTFileJClassComparatorByteArrays.java | 1870 | /**
* 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.io.file.tfile;
import java.io.IOException;
import java.io.Serializable;
import org.apache.hadoop.io.RawComparator;
import org.apache.hadoop.io.WritableComparator;
/**
*
* Byte arrays test case class using GZ compression codec, base class of none
* and LZO compression classes.
*
*/
public class TestTFileJClassComparatorByteArrays extends TestDTFileByteArrays {
/**
* Test non-compression codec, using the same test cases as in the ByteArrays.
*/
@Override
public void setUp() throws IOException {
init(Compression.Algorithm.GZ.getName(),
"jclass: org.apache.hadoop.io.file.tfile.MyComparator");
super.setUp();
}
}
class MyComparator implements RawComparator<byte[]>, Serializable {
@Override
public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
return WritableComparator.compareBytes(b1, s1, l1, b2, s2, l2);
}
@Override
public int compare(byte[] o1, byte[] o2) {
return WritableComparator.compareBytes(o1, 0, o1.length, o2, 0, o2.length);
}
}
| apache-2.0 |
emre-aydin/hazelcast | hazelcast/src/test/java/com/hazelcast/client/listeners/ListenerTests.java | 4528 | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.listeners;
import com.hazelcast.client.impl.clientside.HazelcastClientInstanceImpl;
import com.hazelcast.client.test.ClientTestSupport;
import com.hazelcast.client.test.TestHazelcastFactory;
import com.hazelcast.core.EntryAdapter;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.internal.util.UuidUtil;
import com.hazelcast.map.IMap;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.After;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.LinkedList;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static junit.framework.TestCase.assertTrue;
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class ListenerTests extends ClientTestSupport {
private TestHazelcastFactory factory = new TestHazelcastFactory();
@After
public void tearDown() {
factory.terminateAll();
}
@Test
public void testSmartListenerRegister_whenNodeLeft() {
int nodeCount = 5;
for (int i = 0; i < nodeCount - 1; i++) {
factory.newHazelcastInstance();
}
final HazelcastInstance node = factory.newHazelcastInstance();
HazelcastInstance client = factory.newHazelcastClient();
IMap<Object, Object> map = client.getMap("test");
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.schedule(new Runnable() {
@Override
public void run() {
node.getLifecycleService().terminate();
}
}, 500, TimeUnit.MILLISECONDS);
EntryAdapter listener = new EntryAdapter();
LinkedList<UUID> registrationIds = new LinkedList<UUID>();
while (client.getCluster().getMembers().size() == nodeCount) {
registrationIds.add(map.addEntryListener(listener, false));
}
for (UUID registrationId : registrationIds) {
assertTrue(map.removeEntryListener(registrationId));
}
executorService.shutdown();
}
@Test
public void testSmartListenerRegister_whenNodeJoined() {
int nodeCount = 5;
for (int i = 0; i < nodeCount - 1; i++) {
factory.newHazelcastInstance();
}
HazelcastInstance client = factory.newHazelcastClient();
IMap<Object, Object> map = client.getMap("test");
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.schedule(new Runnable() {
@Override
public void run() {
factory.newHazelcastInstance();
}
}, 500, TimeUnit.MILLISECONDS);
EntryAdapter listener = new EntryAdapter();
LinkedList<UUID> registrationIds = new LinkedList<UUID>();
HazelcastClientInstanceImpl clientInstance = getHazelcastClientInstanceImpl(client);
while (clientInstance.getConnectionManager().getActiveConnections().size() < nodeCount) {
registrationIds.add(map.addEntryListener(listener, false));
}
for (UUID registrationId : registrationIds) {
assertTrue(map.removeEntryListener(registrationId));
}
executorService.shutdown();
}
@Test
public void testRemoveListenerOnClosedClient() {
factory.newHazelcastInstance();
HazelcastInstance client = factory.newHazelcastClient();
IMap<Object, Object> map = client.getMap("test");
client.shutdown();
assertTrue(map.removeEntryListener(UuidUtil.newUnsecureUUID()));
}
}
| apache-2.0 |
chtyim/cdap | cdap-data-fabric/src/main/java/co/cask/cdap/data/stream/service/upload/FileContentWriter.java | 4335 | /*
* Copyright © 2015 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package co.cask.cdap.data.stream.service.upload;
import co.cask.cdap.common.NotFoundException;
import co.cask.cdap.common.io.Locations;
import co.cask.cdap.data.stream.StreamDataFileConstants;
import co.cask.cdap.data.stream.StreamDataFileWriter;
import co.cask.cdap.data.stream.service.ConcurrentStreamWriter;
import co.cask.cdap.data.stream.service.MutableStreamEvent;
import co.cask.cdap.data.stream.service.MutableStreamEventData;
import co.cask.cdap.data2.transaction.stream.StreamConfig;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.google.common.io.Closeables;
import org.apache.twill.filesystem.Location;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.Map;
/**
* Implementation of {@link ContentWriter} that writes to stream file directly.
*/
final class FileContentWriter implements ContentWriter {
private final StreamConfig streamConfig;
private final ConcurrentStreamWriter streamWriter;
private final MutableStreamEventData streamEventData;
private final MutableStreamEvent streamEvent;
private final Location eventFile;
private final Location indexFile;
private final StreamDataFileWriter writer;
private long eventCount;
FileContentWriter(StreamConfig streamConfig, ConcurrentStreamWriter streamWriter,
Location directory, Map<String, String> headers) throws IOException {
this.streamConfig = streamConfig;
this.streamWriter = streamWriter;
this.streamEventData = new MutableStreamEventData();
this.streamEvent = new MutableStreamEvent();
directory.mkdirs();
this.eventFile = directory.append("upload.dat");
this.indexFile = directory.append("upload.idx");
Map<String, String> properties = createStreamFileProperties(headers);
properties.put(StreamDataFileConstants.Property.Key.UNI_TIMESTAMP,
StreamDataFileConstants.Property.Value.CLOSE_TIMESTAMP);
this.writer = new StreamDataFileWriter(Locations.newOutputSupplier(eventFile),
Locations.newOutputSupplier(indexFile),
streamConfig.getIndexInterval(),
properties);
}
private Map<String, String> createStreamFileProperties(Map<String, String> headers) {
// Prepend "event." to each header key
Map<String, String> properties = Maps.newHashMap();
for (Map.Entry<String, String> entry : headers.entrySet()) {
properties.put(StreamDataFileConstants.Property.Key.EVENT_HEADER_PREFIX + entry.getKey(), entry.getValue());
}
return properties;
}
@Override
public void append(ByteBuffer body, boolean immutable) throws IOException {
doAppend(body, System.currentTimeMillis());
}
@Override
public void appendAll(Iterator<ByteBuffer> bodies, boolean immutable) throws IOException {
long timestamp = System.currentTimeMillis();
while (bodies.hasNext()) {
doAppend(bodies.next(), timestamp);
}
}
@Override
public void cancel() {
Closeables.closeQuietly(writer);
Locations.deleteQuietly(Locations.getParent(eventFile), true);
}
@Override
public void close() throws IOException {
try {
writer.flush();
streamWriter.appendFile(streamConfig.getStreamId(), eventFile, indexFile, eventCount, writer);
} catch (NotFoundException e) {
throw Throwables.propagate(e);
} finally {
Locations.deleteQuietly(Locations.getParent(eventFile), true);
}
}
private void doAppend(ByteBuffer body, long timestamp) throws IOException {
writer.append(streamEvent.set(streamEventData.setBody(body), timestamp));
eventCount++;
}
}
| apache-2.0 |
shroman/ignite | modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/twostep/CacheQueryMemoryLeakTest.java | 5017 | /*
* 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.ignite.internal.processors.query.h2.twostep;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.QueryEntity;
import org.apache.ignite.cache.query.Query;
import org.apache.ignite.cache.query.QueryCursor;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.cache.query.annotations.QuerySqlField;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.processors.cache.index.AbstractIndexingCommonTest;
import org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing;
import org.apache.ignite.testframework.GridTestUtils;
import org.junit.Test;
/** */
public class CacheQueryMemoryLeakTest extends AbstractIndexingCommonTest {
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration igniteCfg = super.getConfiguration(igniteInstanceName);
if (igniteInstanceName.equals("client"))
igniteCfg.setClientMode(true);
return igniteCfg;
}
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
stopAllGrids();
}
/**
* Check, that query results are not accumulated, when result set size is a multiple of a {@link Query#pageSize}.
*
* @throws Exception If failed.
*/
@Test
public void testResultIsMultipleOfPage() throws Exception {
IgniteEx srv = (IgniteEx)startGrid("server");
Ignite client = startGrid("client");
IgniteCache<Integer, Person> cache = startPeopleCache(client);
int pages = 3;
int pageSize = 1024;
for (int i = 0; i < pages * pageSize; i++) {
Person p = new Person("Person #" + i, 25);
cache.put(i, p);
}
for (int i = 0; i < 100; i++) {
Query<List<?>> qry = new SqlFieldsQuery("select * from people");
qry.setPageSize(pageSize);
QueryCursor<List<?>> cursor = cache.query(qry);
cursor.getAll();
cursor.close();
}
assertTrue("MapNodeResults is not cleared on the map node.", isMapNodeResultsEmpty(srv));
}
/**
* @param node Ignite node.
* @return {@code True}, if all MapQueryResults are removed from internal node's structures. {@code False}
* otherwise.
*/
private boolean isMapNodeResultsEmpty(IgniteEx node) {
IgniteH2Indexing idx = (IgniteH2Indexing)node.context().query().getIndexing();
GridMapQueryExecutor mapQryExec = idx.mapQueryExecutor();
Map<UUID, MapNodeResults> qryRess =
GridTestUtils.getFieldValue(mapQryExec, GridMapQueryExecutor.class, "qryRess");
for (MapNodeResults nodeRess : qryRess.values()) {
Map<MapRequestKey, MapQueryResults> nodeQryRess =
GridTestUtils.getFieldValue(nodeRess, MapNodeResults.class, "res");
if (!nodeQryRess.isEmpty())
return false;
}
return true;
}
/**
* @param node Ignite instance.
* @return Cache.
*/
private static IgniteCache<Integer, Person> startPeopleCache(Ignite node) {
CacheConfiguration<Integer, Person> cacheCfg = new CacheConfiguration<>("people");
QueryEntity qe = new QueryEntity(Integer.class, Person.class);
qe.setTableName("people");
cacheCfg.setQueryEntities(Collections.singleton(qe));
cacheCfg.setSqlSchema("PUBLIC");
return node.getOrCreateCache(cacheCfg);
}
/** */
@SuppressWarnings("unused")
public static class Person {
/** */
@QuerySqlField
private String name;
/** */
@QuerySqlField
private int age;
/**
* @param name Name.
* @param age Age.
*/
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
}
| apache-2.0 |
mxm/incubator-beam | runners/gearpump/src/test/java/org/apache/beam/runners/gearpump/translators/ReadUnboundedTranslatorTest.java | 2933 | /*
* 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.beam.runners.gearpump.translators;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.apache.beam.runners.gearpump.GearpumpPipelineOptions;
import org.apache.beam.runners.gearpump.translators.io.UnboundedSourceWrapper;
import org.apache.beam.sdk.io.Read;
import org.apache.beam.sdk.io.UnboundedSource;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.values.PValue;
import org.apache.gearpump.streaming.dsl.javaapi.JavaStream;
import org.apache.gearpump.streaming.source.DataSource;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
/** Tests for {@link ReadUnboundedTranslator}. */
public class ReadUnboundedTranslatorTest {
private static class UnboundedSourceWrapperMatcher extends ArgumentMatcher<DataSource> {
@Override
public boolean matches(Object o) {
return o instanceof UnboundedSourceWrapper;
}
}
@Test
@SuppressWarnings({"rawtypes", "unchecked"})
public void testTranslate() {
ReadUnboundedTranslator translator = new ReadUnboundedTranslator();
GearpumpPipelineOptions options =
PipelineOptionsFactory.create().as(GearpumpPipelineOptions.class);
Read.Unbounded transform = mock(Read.Unbounded.class);
UnboundedSource source = mock(UnboundedSource.class);
when(transform.getSource()).thenReturn(source);
TranslationContext translationContext = mock(TranslationContext.class);
when(translationContext.getPipelineOptions()).thenReturn(options);
JavaStream stream = mock(JavaStream.class);
PValue mockOutput = mock(PValue.class);
when(translationContext.getOutput()).thenReturn(mockOutput);
when(translationContext.getSourceStream(any(DataSource.class))).thenReturn(stream);
translator.translate(transform, translationContext);
verify(translationContext).getSourceStream(argThat(new UnboundedSourceWrapperMatcher()));
verify(translationContext).setOutputStream(mockOutput, stream);
}
}
| apache-2.0 |
asedunov/intellij-community | json/src/com/jetbrains/jsonSchema/UserDefinedJsonSchemaConfiguration.java | 7805 | /*
* 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.jetbrains.jsonSchema;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.AtomicClearableLazyValue;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.PairProcessor;
import com.intellij.util.PatternUtil;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xmlb.annotations.Tag;
import com.intellij.util.xmlb.annotations.Transient;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
/**
* @author Irina.Chernushina on 4/19/2017.
*/
@Tag("SchemaInfo")
public class UserDefinedJsonSchemaConfiguration {
private final static Comparator<Item> ITEM_COMPARATOR = (o1, o2) -> {
if (o1.pattern != o2.pattern) return o1.pattern ? -1 : 1;
if (o1.directory != o2.directory) return o1.directory ? -1 : 1;
return o1.path.compareToIgnoreCase(o2.path);
};
public String name;
public String relativePathToSchema;
public boolean applicationLevel;
public List<Item> patterns = new SmartList<>();
@Transient
private final AtomicClearableLazyValue<List<PairProcessor<Project, VirtualFile>>> myCalculatedPatterns =
new AtomicClearableLazyValue<List<PairProcessor<Project, VirtualFile>>>() {
@NotNull
@Override
protected List<PairProcessor<Project, VirtualFile>> compute() {
return recalculatePatterns();
}
};
public UserDefinedJsonSchemaConfiguration() {
}
public UserDefinedJsonSchemaConfiguration(@NotNull String name, @NotNull String relativePathToSchema,
boolean applicationLevel, @Nullable List<Item> patterns) {
this.name = name;
this.relativePathToSchema = relativePathToSchema;
this.applicationLevel = applicationLevel;
setPatterns(patterns);
}
public String getName() {
return name;
}
public void setName(@NotNull String name) {
this.name = name;
}
public String getRelativePathToSchema() {
return relativePathToSchema;
}
public void setRelativePathToSchema(String relativePathToSchema) {
this.relativePathToSchema = relativePathToSchema;
}
public boolean isApplicationLevel() {
return applicationLevel;
}
public void setApplicationLevel(boolean applicationLevel) {
this.applicationLevel = applicationLevel;
}
public List<Item> getPatterns() {
return patterns;
}
public void setPatterns(@Nullable List<Item> patterns) {
this.patterns.clear();
if (patterns != null) this.patterns.addAll(patterns);
Collections.sort(this.patterns, ITEM_COMPARATOR);
myCalculatedPatterns.drop();
}
@NotNull
public List<PairProcessor<Project, VirtualFile>> getCalculatedPatterns() {
return myCalculatedPatterns.getValue();
}
private List<PairProcessor<Project, VirtualFile>> recalculatePatterns() {
final List<PairProcessor<Project, VirtualFile>> result = new SmartList<>();
for (final Item pattern : patterns) {
if (pattern.pattern) {
result.add(new PairProcessor<Project, VirtualFile>() {
private final Matcher matcher = PatternUtil.fromMask(pattern.path).matcher("");
@Override
public boolean process(Project project, VirtualFile file) {
matcher.reset(file.getName());
return matcher.matches();
}
});
}
else if (pattern.directory) {
result.add((project, vfile) -> {
final VirtualFile relativeFile = getRelativeFile(project, pattern);
return relativeFile != null && VfsUtilCore.isAncestor(relativeFile, vfile, true);
});
}
else {
result.add((project, vfile) -> vfile.equals(getRelativeFile(project, pattern)));
}
}
return result;
}
@Nullable
private static VirtualFile getRelativeFile(@NotNull final Project project, @NotNull final Item pattern) {
if (project.getBasePath() == null) {
return null;
}
final String path = FileUtilRt.toSystemIndependentName(StringUtil.notNullize(pattern.path));
final List<String> parts = ContainerUtil.filter(StringUtil.split(path, "/"), s -> !".".equals(s));
if (parts.isEmpty()) {
return project.getBaseDir();
}
else {
return VfsUtil.findRelativeFile(project.getBaseDir(), ArrayUtil.toStringArray(parts));
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserDefinedJsonSchemaConfiguration info = (UserDefinedJsonSchemaConfiguration)o;
if (applicationLevel != info.applicationLevel) return false;
if (name != null ? !name.equals(info.name) : info.name != null) return false;
if (relativePathToSchema != null
? !relativePathToSchema.equals(info.relativePathToSchema)
: info.relativePathToSchema != null) {
return false;
}
if (patterns != null ? !patterns.equals(info.patterns) : info.patterns != null) return false;
return true;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (relativePathToSchema != null ? relativePathToSchema.hashCode() : 0);
result = 31 * result + (applicationLevel ? 1 : 0);
result = 31 * result + (patterns != null ? patterns.hashCode() : 0);
return result;
}
public static class Item {
public String path;
public boolean pattern;
public boolean directory;
public Item() {
}
public Item(String path, boolean isPattern, boolean isDirectory) {
this.path = path;
pattern = isPattern;
directory = isDirectory;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public boolean isPattern() {
return pattern;
}
public void setPattern(boolean pattern) {
this.pattern = pattern;
}
public boolean isDirectory() {
return directory;
}
public void setDirectory(boolean directory) {
this.directory = directory;
}
public String getPresentation() {
final String prefix = pattern ? "Pattern: " : (directory ? "Directory: " : "File: ");
return prefix + path;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Item item = (Item)o;
if (pattern != item.pattern) return false;
if (directory != item.directory) return false;
if (path != null ? !path.equals(item.path) : item.path != null) return false;
return true;
}
@Override
public int hashCode() {
int result = path != null ? path.hashCode() : 0;
result = 31 * result + (pattern ? 1 : 0);
result = 31 * result + (directory ? 1 : 0);
return result;
}
}
}
| apache-2.0 |
goodwinnk/intellij-community | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/settings/SubCompositeConfigurable.java | 4923 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.xdebugger.impl.settings;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.ui.VerticalFlowLayout;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.xdebugger.settings.DebuggerConfigurableProvider;
import com.intellij.xdebugger.settings.DebuggerSettingsCategory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.List;
abstract class SubCompositeConfigurable implements SearchableConfigurable.Parent {
protected DataViewsConfigurableUi root;
protected Configurable[] children;
protected JComponent rootComponent;
@Override
public boolean hasOwnContent() {
return true;
}
@Nullable
@Override
public String getHelpTopic() {
getConfigurables();
return children != null && children.length == 1 ? children[0].getHelpTopic() : null;
}
@Override
public final void disposeUIResources() {
root = null;
rootComponent = null;
if (isChildrenMerged()) {
for (Configurable child : children) {
child.disposeUIResources();
}
}
children = null;
}
protected XDebuggerDataViewSettings getSettings() {
return null;
}
@Nullable
protected abstract DataViewsConfigurableUi createRootUi();
@NotNull
protected abstract DebuggerSettingsCategory getCategory();
private boolean isChildrenMerged() {
return children != null && children.length == 1;
}
@NotNull
@Override
public final Configurable[] getConfigurables() {
if (children == null) {
List<Configurable> configurables = DebuggerConfigurable.getConfigurables(getCategory());
children = configurables.toArray(new Configurable[0]);
}
return isChildrenMerged() ? DebuggerConfigurable.EMPTY_CONFIGURABLES : children;
}
@Nullable
@Override
public final JComponent createComponent() {
if (rootComponent == null) {
if (root == null) {
root = createRootUi();
}
getConfigurables();
if (isChildrenMerged()) {
if (children.length == 0) {
rootComponent = root == null ? null : root.getComponent();
}
else if (root == null && children.length == 1) {
rootComponent = children[0].createComponent();
}
else {
JPanel panel = new JPanel(new VerticalFlowLayout(0, 0));
if (root != null) {
JComponent c = root.getComponent();
c.setBorder(MergedCompositeConfigurable.BOTTOM_INSETS);
panel.add(c);
}
for (Configurable configurable : children) {
JComponent component = configurable.createComponent();
if (component != null) {
if (children[0] != configurable || !MergedCompositeConfigurable.isTargetedToProduct(configurable)) {
component.setBorder(IdeBorderFactory.createTitledBorder(configurable.getDisplayName(), false));
}
panel.add(component);
}
}
rootComponent = panel;
}
}
else {
rootComponent = root == null ? null : root.getComponent();
}
}
return rootComponent;
}
@Override
public final void reset() {
if (root != null) {
root.reset(getSettings());
}
if (isChildrenMerged()) {
for (Configurable child : children) {
child.reset();
}
}
}
@Override
public final boolean isModified() {
if (root != null && root.isModified(getSettings())) {
return true;
}
else if (isChildrenMerged()) {
for (Configurable child : children) {
if (child.isModified()) {
return true;
}
}
}
return false;
}
@Override
public final void apply() throws ConfigurationException {
if (root != null) {
root.apply(getSettings());
for (DebuggerConfigurableProvider provider : DebuggerConfigurableProvider.EXTENSION_POINT.getExtensions()) {
provider.generalApplied(getCategory());
}
}
if (isChildrenMerged()) {
for (Configurable child : children) {
if (child.isModified()) {
child.apply();
}
}
}
}
} | apache-2.0 |
charithag/iot-server-appliances | EU_Con_Hackathon/JAX-RS Service/src/main/java/org/wso2/carbon/device/mgt/iot/services/common/DevicesManagerService.java | 3027 | package org.wso2.carbon.device.mgt.iot.services.common;
import org.wso2.carbon.device.mgt.common.Device;
import javax.ws.rs.core.GenericEntity;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.iot.arduino.firealarm.constants.FireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.web.register.DeviceManagement;
import org.wso2.carbon.utils.CarbonUtils;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Created by ayyoobhamza on 5/29/15.
*/
public class DevicesManagerService {
@Path("/getDevices")
@GET
@Consumes("application/json")
@Produces("application/json")
public Device[] getDevices(@QueryParam("username") String username)
throws DeviceManagementException {
DeviceManagement deviceManagement = new DeviceManagement();
List<Device> devices = deviceManagement.getDevices(username);
return devices.toArray(new Device[]{});
}
@Path("/getDevices")
@GET
@Consumes("application/json")
@Produces("application/json")
public Device[] getDevicesByType(@QueryParam("type") String deviceType)
throws DeviceManagementException {
DeviceManagement deviceManagement = new DeviceManagement();
List<Device> devices = deviceManagement.getDevicesByType(deviceType);
return devices.toArray(new Device[]{});
}
@Path("/getDeviceTypes")
@GET
@Consumes("application/json")
@Produces("application/json")
public DeviceType[] getDeviceTypes()
throws DeviceManagementDAOException {
DeviceManagement deviceManagement = new DeviceManagement();
List<DeviceType> deviceTypes = deviceManagement.getDeviceTypes();
return deviceTypes.toArray(new DeviceType[]{});
}
public File downloadSketch(String owner, String deviceType, String deviceId, String token)
throws DeviceManagementException {
if (owner == null || deviceType == null) {
throw new DeviceManagementException("Invalid parameters for `owner` or `deviceType`");
}
String sep = File.separator;
String sketchFolder = "repository" + sep + "resources" + sep + "sketches";
String archivesPath = CarbonUtils.getCarbonHome() + sep + sketchFolder + sep + "archives"
+ sep + deviceId;
String templateSketchPath = sketchFolder + sep + deviceType;
Map<String, String> contextParams = new HashMap<String, String>();
contextParams.put("DEVICE_OWNER", owner);
contextParams.put("DEVICE_ID", deviceId);
contextParams.put("DEVICE_TOKEN", token);
DeviceManagement deviceManagement = new DeviceManagement();
File zipFile = deviceManagement.getSketchArchive(archivesPath, templateSketchPath,
contextParams);
return zipFile;
}
}
| apache-2.0 |
IllusionRom-deprecated/android_platform_tools_idea | plugins/ui-designer-core/src/com/intellij/designer/DesignerEditor.java | 3603 | /*
* Copyright 2000-2012 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.designer;
import com.intellij.designer.designSurface.DesignerEditorPanel;
import com.intellij.ide.structureView.StructureViewBuilder;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorLocation;
import com.intellij.openapi.fileEditor.FileEditorState;
import com.intellij.openapi.fileEditor.FileEditorStateLevel;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.UserDataHolderBase;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.LightVirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.beans.PropertyChangeListener;
/**
* @author Alexander Lobas
*/
public abstract class DesignerEditor extends UserDataHolderBase implements FileEditor {
private final DesignerEditorPanel myDesignerPanel;
public DesignerEditor(Project project, VirtualFile file) {
if (file instanceof LightVirtualFile) {
file = ((LightVirtualFile)file).getOriginalFile();
}
Module module = findModule(project, file);
if (module == null) {
throw new IllegalArgumentException("No module for file " + file + " in project " + project);
}
myDesignerPanel = createDesignerPanel(project, module, file);
}
@Nullable
protected Module findModule(Project project, VirtualFile file) {
return ModuleUtilCore.findModuleForFile(file, project);
}
@NotNull
protected abstract DesignerEditorPanel createDesignerPanel(Project project, Module module, VirtualFile file);
public final DesignerEditorPanel getDesignerPanel() {
return myDesignerPanel;
}
@NotNull
@Override
public final JComponent getComponent() {
return myDesignerPanel;
}
@Override
public final JComponent getPreferredFocusedComponent() {
return myDesignerPanel.getPreferredFocusedComponent();
}
@Override
public void dispose() {
myDesignerPanel.dispose();
}
@Override
public void selectNotify() {
myDesignerPanel.activate();
}
@Override
public void deselectNotify() {
myDesignerPanel.deactivate();
}
@Override
public boolean isValid() {
return myDesignerPanel.isEditorValid();
}
@Override
public boolean isModified() {
return false;
}
@Override
@NotNull
public FileEditorState getState(@NotNull FileEditorStateLevel level) {
return myDesignerPanel.createState();
}
@Override
public void setState(@NotNull FileEditorState state) {
}
@Override
public void addPropertyChangeListener(@NotNull PropertyChangeListener listener) {
}
@Override
public void removePropertyChangeListener(@NotNull PropertyChangeListener listener) {
}
@Override
public FileEditorLocation getCurrentLocation() {
return null;
}
@Override
public StructureViewBuilder getStructureViewBuilder() {
return null;
}
} | apache-2.0 |
chosen0ne/HouseMD | src/main/java/com/github/zhongl/housemd/command/Env.java | 2826 | /*
* Copyright 2013 zhongl
*
* 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.github.zhongl.housemd.command;
import com.github.zhongl.yascli.Command;
import com.github.zhongl.yascli.PrintOut;
import jline.console.completer.Completer;
import scala.Function0;
import java.util.*;
import static com.github.zhongl.yascli.JavaConvertions.*;
/**
* @author <a href="mailto:zhong.lunfu@gmail.com">zhongl<a>
*/
public class Env extends Command implements Completer {
private final Function0 regexable = flag(list("-e", "--regex"), "enable name as regex pattern.");
private final Function0<String> keyName = parameter("name", "system env key name.", none(String.class), manifest(String.class), defaultConverter());
public Env(PrintOut out) {
super("env", "display system env.", out);
}
@Override
public void run() {
if (is(regexable))
listEnvMatchs(get(keyName));
else
printEnvEquals(get(keyName));
}
private void printEnvEquals(String key) {
String value = System.getenv(key);
if (value == null) println("Invalid key " + key);
else println(key + " = " + value);
}
private void listEnvMatchs(String regex) {
SortedMap<String, String> sortedMap = new TreeMap<String, String>();
int maxKeyLength = 0;
for (String key : System.getenv().keySet()) {
if (!key.matches(regex)) continue;
maxKeyLength = Math.max(maxKeyLength, key.length());
sortedMap.put(key, System.getenv(key));
}
if (sortedMap.isEmpty()) return;
String format = "%1$-" + maxKeyLength + "s = %2$s";
for (String key : sortedMap.keySet())
println(String.format(format, key, sortedMap.get(key)));
}
@Override
public int complete(String buffer, int cursor, List<CharSequence> candidates) {
Map<String, String> env = System.getenv();
Set<String> keys = env.keySet();
TreeSet<String> sortedKeySet = new TreeSet<String>(keys);
SortedSet<String> tail = sortedKeySet.tailSet(buffer);
for (String k : tail) {
if (k.startsWith(buffer)) candidates.add(k);
}
if (candidates.isEmpty()) return -1;
return cursor - buffer.length();
}
}
| apache-2.0 |
dannyzhou98/Terasology | engine/src/main/java/org/terasology/physics/engine/PhysicsSystem.java | 12673 | /*
* Copyright 2016 MovingBlocks
*
* 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.terasology.physics.engine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.engine.Time;
import org.terasology.entitySystem.entity.EntityManager;
import org.terasology.entitySystem.entity.EntityRef;
import org.terasology.entitySystem.entity.lifecycleEvents.BeforeDeactivateComponent;
import org.terasology.entitySystem.entity.lifecycleEvents.OnActivatedComponent;
import org.terasology.entitySystem.entity.lifecycleEvents.OnChangedComponent;
import org.terasology.entitySystem.event.EventPriority;
import org.terasology.entitySystem.event.ReceiveEvent;
import org.terasology.entitySystem.systems.BaseComponentSystem;
import org.terasology.entitySystem.systems.RegisterMode;
import org.terasology.entitySystem.systems.RegisterSystem;
import org.terasology.entitySystem.systems.UpdateSubscriberSystem;
import org.terasology.logic.location.LocationComponent;
import org.terasology.logic.location.LocationResynchEvent;
import org.terasology.math.geom.Quat4f;
import org.terasology.math.geom.Vector3f;
import org.terasology.monitoring.PerformanceMonitor;
import org.terasology.network.NetworkComponent;
import org.terasology.network.NetworkSystem;
import org.terasology.physics.CollisionGroup;
import org.terasology.physics.HitResult;
import org.terasology.physics.StandardCollisionGroup;
import org.terasology.physics.components.RigidBodyComponent;
import org.terasology.physics.components.TriggerComponent;
import org.terasology.physics.events.ChangeVelocityEvent;
import org.terasology.physics.events.CollideEvent;
import org.terasology.physics.events.ForceEvent;
import org.terasology.physics.events.ImpulseEvent;
import org.terasology.physics.events.PhysicsResynchEvent;
import org.terasology.physics.events.ImpactEvent;
import org.terasology.physics.events.EntityImpactEvent;
import org.terasology.physics.events.BlockImpactEvent;
import org.terasology.registry.In;
import org.terasology.world.OnChangedBlock;
import org.terasology.world.WorldProvider;
import org.terasology.world.block.Block;
import org.terasology.world.block.BlockComponent;
import java.util.Iterator;
import java.util.List;
/**
* The PhysicsSystem is a bridging class between the event system and the
* physics engine. It translates events into changes to the physics engine and
* translates output of the physics engine into events. It also calls the update
* method of the PhysicsEngine every frame.
*
*/
@RegisterSystem
public class PhysicsSystem extends BaseComponentSystem implements UpdateSubscriberSystem {
private static final Logger logger = LoggerFactory.getLogger(PhysicsSystem.class);
private static final long TIME_BETWEEN_NETSYNCS = 500;
private static final CollisionGroup[] DEFAULT_COLLISION_GROUP = {StandardCollisionGroup.WORLD, StandardCollisionGroup.CHARACTER, StandardCollisionGroup.DEFAULT};
private static final float COLLISION_DAMPENING_MULTIPLIER = 0.5f;
@In
private Time time;
@In
private NetworkSystem networkSystem;
@In
private EntityManager entityManager;
@In
private PhysicsEngine physics;
@In
private WorldProvider worldProvider;
private long lastNetsync;
@Override
public void initialise() {
lastNetsync = 0;
}
@ReceiveEvent(components = {RigidBodyComponent.class, LocationComponent.class}, priority = EventPriority.PRIORITY_NORMAL)
public void newRigidBody(OnActivatedComponent event, EntityRef entity) {
//getter also creates the rigid body
physics.getRigidBody(entity);
}
@ReceiveEvent(components = {TriggerComponent.class, LocationComponent.class})
//update also creates the trigger
public void newTrigger(OnActivatedComponent event, EntityRef entity) {
physics.updateTrigger(entity);
}
@ReceiveEvent(components = {RigidBodyComponent.class})
public void onImpulse(ImpulseEvent event, EntityRef entity) {
physics.getRigidBody(entity).applyImpulse(event.getImpulse());
}
@ReceiveEvent(components = {RigidBodyComponent.class})
public void onForce(ForceEvent event, EntityRef entity) {
physics.getRigidBody(entity).applyForce(event.getForce());
}
@ReceiveEvent(components = {RigidBodyComponent.class})
public void onChangeVelocity(ChangeVelocityEvent event, EntityRef entity) {
if (event.getAngularVelocity() != null) {
physics.getRigidBody(entity).setAngularVelocity(event.getAngularVelocity());
}
if (event.getLinearVelocity() != null) {
physics.getRigidBody(entity).setLinearVelocity(event.getLinearVelocity());
}
}
@ReceiveEvent(components = {RigidBodyComponent.class, LocationComponent.class})
public void removeRigidBody(BeforeDeactivateComponent event, EntityRef entity) {
physics.removeRigidBody(entity);
}
@ReceiveEvent(components = {TriggerComponent.class, LocationComponent.class})
public void removeTrigger(BeforeDeactivateComponent event, EntityRef entity) {
physics.removeTrigger(entity);
}
@ReceiveEvent(components = {TriggerComponent.class, LocationComponent.class})
public void updateTrigger(OnChangedComponent event, EntityRef entity) {
physics.updateTrigger(entity);
}
@ReceiveEvent(components = {RigidBodyComponent.class, LocationComponent.class})
public void updateRigidBody(OnChangedComponent event, EntityRef entity) {
physics.updateRigidBody(entity);
}
@ReceiveEvent(components = {BlockComponent.class})
public void onBlockAltered(OnChangedBlock event, EntityRef entity) {
physics.awakenArea(event.getBlockPosition().toVector3f(), 0.6f);
}
@ReceiveEvent
public void onItemImpact(ImpactEvent event, EntityRef entity) {
RigidBody rigidBody = physics.getRigidBody(entity);
if (rigidBody != null) {
Vector3f vImpactNormal = new Vector3f(event.getImpactNormal());
Vector3f vImpactPoint = new Vector3f(event.getImpactPoint());
Vector3f vImpactSpeed = new Vector3f(event.getImpactSpeed());
float speedFactor = vImpactSpeed.length();
vImpactNormal.normalize();
vImpactSpeed.normalize();
float dotImpactNormal = vImpactSpeed.dot(vImpactNormal);
Vector3f impactResult = vImpactNormal.mul(dotImpactNormal);
impactResult = vImpactSpeed.sub(impactResult.mul(2.0f));
impactResult.normalize();
Vector3f vNewLocationVector = (new Vector3f(impactResult)).mul(event.getTravelDistance());
Vector3f vNewPosition = (new Vector3f(vImpactPoint)).add(vNewLocationVector);
Vector3f vNewVelocity = (new Vector3f(impactResult)).mul(speedFactor * COLLISION_DAMPENING_MULTIPLIER);
rigidBody.setLocation(vNewPosition);
rigidBody.setLinearVelocity(vNewVelocity);
rigidBody.setAngularVelocity(vNewVelocity);
}
}
@Override
public void update(float delta) {
PerformanceMonitor.startActivity("Physics Renderer");
physics.update(time.getGameDelta());
PerformanceMonitor.endActivity();
//Update the velocity from physics engine bodies to Components:
Iterator<EntityRef> iter = physics.physicsEntitiesIterator();
while (iter.hasNext()) {
EntityRef entity = iter.next();
RigidBodyComponent comp = entity.getComponent(RigidBodyComponent.class);
RigidBody body = physics.getRigidBody(entity);
if (body.isActive()) {
body.getLinearVelocity(comp.velocity);
body.getAngularVelocity(comp.angularVelocity);
Vector3f vLocation = Vector3f.zero();
body.getLocation(vLocation);
Vector3f vDirection = new Vector3f(comp.velocity);
float fDistanceThisFrame = vDirection.length();
vDirection.normalize();
fDistanceThisFrame = fDistanceThisFrame * delta;
while (true) {
HitResult hitInfo = physics.rayTrace(vLocation, vDirection, fDistanceThisFrame + 0.5f, DEFAULT_COLLISION_GROUP);
if (hitInfo.isHit()) {
Block hitBlock = worldProvider.getBlock(hitInfo.getBlockPosition());
if (hitBlock != null) {
Vector3f vTravelledDistance = vLocation.sub(hitInfo.getHitPoint());
float fTravelledDistance = vTravelledDistance.length();
if (fTravelledDistance > fDistanceThisFrame) {
break;
}
if (hitBlock.isPenetrable()) {
if (!hitInfo.getEntity().hasComponent(BlockComponent.class)) {
entity.send(new EntityImpactEvent(hitInfo.getHitPoint(), hitInfo.getHitNormal(), comp.velocity, fDistanceThisFrame, hitInfo.getEntity()));
break;
}
fDistanceThisFrame = fDistanceThisFrame - fTravelledDistance; // decrease the remaining distance to check if we hit a block
vLocation = hitInfo.getHitPoint();
} else {
entity.send(new BlockImpactEvent(hitInfo.getHitPoint(), hitInfo.getHitNormal(), comp.velocity, fDistanceThisFrame, hitInfo.getEntity()));
break;
}
} else {
break;
}
} else {
break;
}
}
}
}
if (networkSystem.getMode().isServer() && time.getGameTimeInMs() - TIME_BETWEEN_NETSYNCS > lastNetsync) {
sendSyncMessages();
lastNetsync = time.getGameTimeInMs();
}
List<CollisionPair> collisionPairs = physics.getCollisionPairs();
for (CollisionPair pair : collisionPairs) {
if (pair.b.exists()) {
pair.a.send(new CollideEvent(pair.b));
}
if (pair.a.exists()) {
pair.b.send(new CollideEvent(pair.a));
}
}
}
private void sendSyncMessages() {
Iterator<EntityRef> iter = physics.physicsEntitiesIterator();
while (iter.hasNext()) {
EntityRef entity = iter.next();
if (entity.hasComponent(NetworkComponent.class)) {
//TODO after implementing rigidbody interface
RigidBody body = physics.getRigidBody(entity);
if (body.isActive()) {
entity.send(new LocationResynchEvent(body.getLocation(new Vector3f()), body.getOrientation(new Quat4f())));
entity.send(new PhysicsResynchEvent(body.getLinearVelocity(new Vector3f()), body.getAngularVelocity(new Vector3f())));
}
}
}
}
@ReceiveEvent(components = {RigidBodyComponent.class, LocationComponent.class}, netFilter = RegisterMode.REMOTE_CLIENT)
public void resynchPhysics(PhysicsResynchEvent event, EntityRef entity) {
logger.debug("Received resynch event");
RigidBody body = physics.getRigidBody(entity);
body.setVelocity(event.getVelocity(), event.getAngularVelocity());
}
@ReceiveEvent(components = {RigidBodyComponent.class, LocationComponent.class}, netFilter = RegisterMode.REMOTE_CLIENT)
public void resynchLocation(LocationResynchEvent event, EntityRef entity) {
logger.debug("Received location resynch event");
RigidBody body = physics.getRigidBody(entity);
body.setTransform(event.getPosition(), event.getRotation());
}
public static class CollisionPair {
EntityRef a;
EntityRef b;
public CollisionPair(EntityRef a, EntityRef b) {
this.a = a;
this.b = b;
}
}
}
| apache-2.0 |
lqjack/fixflow | modules/fixflow-core/src/main/java/com/founder/fix/fixflow/core/impl/persistence/instance/VariablePersistence.java | 15023 | /**
* Copyright 1996-2013 Founder International 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.
*
* @author kenshin
*/
package com.founder.fix.fixflow.core.impl.persistence.instance;
//import java.io.ByteArrayInputStream;
//import java.io.ByteArrayOutputStream;
//import java.io.IOException;
//import java.io.ObjectInput;
//import java.io.ObjectInputStream;
//import java.io.ObjectOutput;
//import java.io.ObjectOutputStream;
//import java.sql.Connection;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//import com.founder.fix.fixflow.core.impl.command.QueryVariablesCommand;
//import com.founder.fix.fixflow.core.impl.datavariable.DataVariableEntity;
//import com.founder.fix.fixflow.core.impl.db.PersistentObject;
//import com.founder.fix.fixflow.core.impl.db.SqlCommand;
//import com.founder.fix.fixflow.core.impl.util.StringUtil;
//import com.founder.fix.fixflow.core.objkey.VariableObjKey;
public class VariablePersistence {
// protected Connection connection;
// protected SqlCommand sqlCommand;
//
// public VariablePersistence(Connection connection) {
// this.connection = connection;
// sqlCommand = new SqlCommand(connection);
// }
//
// public Map<String, Object> queryVariable(QueryVariablesCommand queryVariablesCommand) {
//
// Map<String, Object> returnValue = new HashMap<String, Object>();
//
// if (queryVariablesCommand == null) {
// return returnValue;
// }
// List<String> variableNames = queryVariablesCommand.getVariableNames();
//
// String sqlWhereQueryString = "";
// // 构建查询参数
// List<Object> objectParamWhere = new ArrayList<Object>();
//
// String processInstanceId = queryVariablesCommand.getProcessInstanceId();
// String tokenId = queryVariablesCommand.getTokenId();
// String taskInstanceId = queryVariablesCommand.getTaskInstanceId();
// String nodeId = queryVariablesCommand.getNodeId();
//
// if (processInstanceId == null) {
// sqlWhereQueryString = sqlWhereQueryString + " PROCESSINSTANCE_ID IS NULL AND ";
// } else {
// sqlWhereQueryString = sqlWhereQueryString + " PROCESSINSTANCE_ID=? AND ";
// objectParamWhere.add(processInstanceId);
// }
//
// if (tokenId == null) {
// sqlWhereQueryString = sqlWhereQueryString + " TOKEN_ID IS NULL AND ";
// } else {
// sqlWhereQueryString = sqlWhereQueryString + " TOKEN_ID=? AND";
// objectParamWhere.add(tokenId);
// }
//
// if (taskInstanceId == null) {
// sqlWhereQueryString = sqlWhereQueryString + " TASKINSTANCE_ID IS NULL AND ";
// } else {
// sqlWhereQueryString = sqlWhereQueryString + " TASKINSTANCE_ID=? AND ";
// objectParamWhere.add(taskInstanceId);
// }
//
// if (nodeId == null) {
// sqlWhereQueryString = sqlWhereQueryString + " NODE_ID IS NULL ";
// } else {
// sqlWhereQueryString = sqlWhereQueryString + " NODE_ID=? ";
// objectParamWhere.add(nodeId);
// }
//
// if (variableNames != null) {
// if (variableNames.size() > 0) {
// sqlWhereQueryString = sqlWhereQueryString + " AND (";
// }
//
// for (int i = 0; i < variableNames.size(); i++) {
//
// String variableName = variableNames.get(i);
//
// if (i == variableNames.size() - 1) {
// sqlWhereQueryString = sqlWhereQueryString + " VARIABLE_KEY=? ";
// } else {
// sqlWhereQueryString = sqlWhereQueryString + " VARIABLE_KEY=? OR ";
// }
//
// objectParamWhere.add(variableName);
// }
//
// if (variableNames.size() > 0) {
// sqlWhereQueryString = sqlWhereQueryString + " )";
// }
// }
//
// // 构建Where查询参数
// Object[] objectParamObj = new Object[objectParamWhere.size()];
// for (int i = 0; i < objectParamWhere.size(); i++) {
// objectParamObj[i] = objectParamWhere.get(i);
// }
//
// // 设置查询字符串
// String sqlText = "SELECT VARIABLE_KEY,VARIABLE_VALUE FROM " + VariableObjKey.VariableTableName() + " WHERE " + sqlWhereQueryString;
//
// List<Map<String, Object>> listMaps = sqlCommand.queryForList(sqlText, objectParamWhere);
//
// for (Map<String, Object> mapObj : listMaps) {
// String keyObj = StringUtil.getString(mapObj.get("VARIABLE_KEY"));
//
// byte[] bytes = (byte[]) mapObj.get("VARIABLE_VALUE");
// Object valueObj = bytesToObject(bytes);
// returnValue.put(keyObj, valueObj);
// }
// return returnValue;
// }
//
// public void saveVariable(PersistentObject persistentObject) {
//
// DataVariableEntity dataVariableEntity = (DataVariableEntity) persistentObject;
//
// if (dataVariableEntity == null) {
// return;
// }
// String sqlWhereQueryString = "";
// // 构建查询参数
// List<Object> objectParamWhere = new ArrayList<Object>();
// String variableKey = dataVariableEntity.getId();
// String processInstanceId = dataVariableEntity.getProcessInstanceId();
// String tokenId = dataVariableEntity.getTokenId();
// String taskInstanceId = dataVariableEntity.getTaskInstanceId();
// String nodeId = dataVariableEntity.getNodeId();
// String variableType = dataVariableEntity.getVariableType();
//
// if (processInstanceId == null) {
// sqlWhereQueryString = sqlWhereQueryString + " PROCESSINSTANCE_ID IS NULL AND ";
// } else {
// sqlWhereQueryString = sqlWhereQueryString + " PROCESSINSTANCE_ID=? AND ";
// objectParamWhere.add(processInstanceId);
// }
//
// if (tokenId == null) {
// sqlWhereQueryString = sqlWhereQueryString + " TOKEN_ID IS NULL AND ";
// } else {
// sqlWhereQueryString = sqlWhereQueryString + " TOKEN_ID=? AND";
// objectParamWhere.add(tokenId);
// }
//
// if (taskInstanceId == null) {
// sqlWhereQueryString = sqlWhereQueryString + " TASKINSTANCE_ID IS NULL AND ";
// } else {
// sqlWhereQueryString = sqlWhereQueryString + " TASKINSTANCE_ID=? AND ";
// objectParamWhere.add(taskInstanceId);
// }
//
// if (nodeId == null) {
// sqlWhereQueryString = sqlWhereQueryString + " NODE_ID IS NULL ";
// } else {
// sqlWhereQueryString = sqlWhereQueryString + " NODE_ID=? ";
// objectParamWhere.add(nodeId);
// }
//
// sqlWhereQueryString = sqlWhereQueryString + " AND VARIABLE_KEY=?";
//
// objectParamWhere.add(variableKey);
//
// // 设置查询字符串
// String sqlText = "SELECT count(1) FROM " + VariableObjKey.VariableTableName() + " WHERE " + sqlWhereQueryString;
//
// // 执行查询流程是Sql语句,判断流程实例是否存在于数据库中.
// int rowNum = Integer.parseInt(sqlCommand.queryForValue(sqlText, objectParamWhere).toString());
//
// if (rowNum == 0) {
// // 数据库不存在这个变量,则执行创建新变量的方法.
//
// insertVariable(processInstanceId, tokenId, taskInstanceId, nodeId, variableKey, dataVariableEntity.getExpressionValue(), variableType);
//
// } else {
// // 当数据库中已经存在这个变量
//
// updateVariable(processInstanceId, tokenId, taskInstanceId, nodeId, variableKey, dataVariableEntity.getExpressionValue(), sqlWhereQueryString,
// objectParamWhere, variableType);
//
// }
//
// }
//
// private void insertVariable(String processInstanceId, String tokenId, String taskInstanceId, String nodeId, String variableKey, Object variableValue,
// String variableType) {
//
// String processInstanceIdDb = processInstanceId;
// String tokenIdDb = tokenId;
// String taskInstanceIdDb = taskInstanceId;
// String nodeIdDb = nodeId;
//
// String variableKeyDb = variableKey;
// byte[] variableValueDb = ObjectToBytes(variableValue);
// String variableClassName = null;
// if (variableValue != null) {
// variableClassName = variableValue.getClass().getCanonicalName();
// }
//
// // 构建查询参数
// Map<String, Object> objectParam = new HashMap<String, Object>();
//
// objectParam.put(VariableObjKey.ProcessInstanceId().DataBaseKey(), processInstanceIdDb);
//
// objectParam.put(VariableObjKey.VariableKey().DataBaseKey(), variableKeyDb);
//
// objectParam.put(VariableObjKey.VariableValue().DataBaseKey(), variableValueDb);
//
// objectParam.put(VariableObjKey.VariableClassName().DataBaseKey(), variableClassName);
//
// objectParam.put(VariableObjKey.TaskInstanceId().DataBaseKey(), taskInstanceIdDb);
//
// objectParam.put(VariableObjKey.TokenId().DataBaseKey(), tokenIdDb);
//
// objectParam.put(VariableObjKey.NodeId().DataBaseKey(), nodeIdDb);
//
// objectParam.put(VariableObjKey.VariableType().DataBaseKey(), variableType);
//
// if (variableType != null && variableType.equals(DataVariableEntity.QUERY_DATA_KEY)) {
// objectParam.put(VariableObjKey.BizData().DataBaseKey(), StringUtil.getString(variableValue));
// }
//
// // 执行插入语句
// sqlCommand.insert(VariableObjKey.VariableTableName(), objectParam);
//
// }
//
// private void updateVariable(String processInstanceId, String tokenId, String taskInstanceId, String nodeId, String variableKey, Object variableValue,
// String updateWhereSql, List<Object> objectParamWhere, String variableType) {
//
// String variableKeyDb = variableKey;
// byte[] variableValueDb = ObjectToBytes(variableValue);
// String variableClassName = null;
// if (variableValue != null) {
// variableClassName = variableValue.getClass().getCanonicalName();
// }
//
// // 构建查询参数
// Map<String, Object> objectParam = new HashMap<String, Object>();
//
// objectParam.put(VariableObjKey.VariableKey().DataBaseKey(), variableKeyDb);
//
// objectParam.put(VariableObjKey.VariableValue().DataBaseKey(), variableValueDb);
//
// objectParam.put(VariableObjKey.VariableClassName().DataBaseKey(), variableClassName);
//
// objectParam.put(VariableObjKey.VariableType().DataBaseKey(), variableType);
//
// if (variableType != null && variableType.equals(DataVariableEntity.QUERY_DATA_KEY)) {
// objectParam.put(VariableObjKey.BizData().DataBaseKey(), StringUtil.getString(variableValue));
// }
//
// // 构建Where查询参数
// Object[] objectParamObj = new Object[objectParamWhere.size()];
// for (int i = 0; i < objectParamWhere.size(); i++) {
// objectParamObj[i] = objectParamWhere.get(i);
// }
//
// // 执行插入语句
// sqlCommand.update(VariableObjKey.VariableTableName(), objectParam, updateWhereSql, objectParamObj);
//
// }
//
// public void deleteVariable(QueryVariablesCommand queryVariablesCommand) {
//
// if (queryVariablesCommand == null) {
// return;
// }
// List<String> variableNames = queryVariablesCommand.getVariableNames();
//
// String sqlWhereQueryString = "";
// // 构建查询参数
// List<Object> objectParamWhere = new ArrayList<Object>();
//
// String processInstanceId = queryVariablesCommand.getProcessInstanceId();
// String tokenId = queryVariablesCommand.getTokenId();
// String taskInstanceId = queryVariablesCommand.getTaskInstanceId();
// String nodeId = queryVariablesCommand.getNodeId();
//
// if (processInstanceId == null) {
// sqlWhereQueryString = sqlWhereQueryString + " PROCESSINSTANCE_ID IS NULL AND ";
// } else {
// sqlWhereQueryString = sqlWhereQueryString + " PROCESSINSTANCE_ID=? AND ";
// objectParamWhere.add(processInstanceId);
// }
//
// if (tokenId == null) {
// sqlWhereQueryString = sqlWhereQueryString + " TOKEN_ID IS NULL AND ";
// } else {
// sqlWhereQueryString = sqlWhereQueryString + " TOKEN_ID=? AND";
// objectParamWhere.add(tokenId);
// }
//
// if (taskInstanceId == null) {
// sqlWhereQueryString = sqlWhereQueryString + " TASKINSTANCE_ID IS NULL AND ";
// } else {
// sqlWhereQueryString = sqlWhereQueryString + " TASKINSTANCE_ID=? AND ";
// objectParamWhere.add(taskInstanceId);
// }
//
// if (nodeId == null) {
// sqlWhereQueryString = sqlWhereQueryString + " NODE_ID IS NULL ";
// } else {
// sqlWhereQueryString = sqlWhereQueryString + " NODE_ID=? ";
// objectParamWhere.add(nodeId);
// }
//
// /*
// * sqlWhereQueryString = sqlWhereQueryString + " AND VARIABLE_KEY=?";
// *
// *
// * List<VariableFlowTypeEntity> variableFlowTypeEntities =
// * variableQueryEntity.getVariableFlowTypeEntities(); if
// * (variableFlowTypeEntities.size() == 0) { return; }
// */
//
// if (variableNames != null) {
// if (variableNames.size() > 0) {
// sqlWhereQueryString = sqlWhereQueryString + " AND (";
// }
//
// for (int i = 0; i < variableNames.size(); i++) {
//
// String variableName = variableNames.get(i);
//
// if (i == variableNames.size() - 1) {
// sqlWhereQueryString = sqlWhereQueryString + " VARIABLE_KEY=? ";
// } else {
// sqlWhereQueryString = sqlWhereQueryString + " VARIABLE_KEY=? OR ";
// }
//
// objectParamWhere.add(variableName);
// }
//
// if (variableNames.size() > 0) {
// sqlWhereQueryString = sqlWhereQueryString + " )";
// }
// }
//
// // 构建Where查询参数
// Object[] objectParamObj = new Object[objectParamWhere.size()];
// for (int i = 0; i < objectParamWhere.size(); i++) {
// objectParamObj[i] = objectParamWhere.get(i);
// }
// sqlCommand.delete(VariableObjKey.VariableTableName(), sqlWhereQueryString, objectParamObj);
//
// }
//
// public static byte[] ObjectToBytes(Object obj) {
//
// ObjectOutput out = null;
// try {
// ByteArrayOutputStream byteout = new ByteArrayOutputStream();
// out = new ObjectOutputStream(byteout);
// out.writeObject(obj);
// byte[] buf = byteout.toByteArray();
//
// return buf;
// } catch (IOException e) {
// return null;
// } finally {
// if (out != null) {
// try {
// out.close();
// } catch (IOException e) {
//
// }
// }
// }
// }
//
// /**
// * byte[] to long
// *
// * @param b
// * @return
// */
// public static Object bytesToObject(byte[] b) {
//
// if (b.length > 0) {
// ObjectInput in = null;
// try {
// ByteArrayInputStream byteIn = new ByteArrayInputStream(b);
// in = new ObjectInputStream(byteIn);
// Object obj = in.readObject();
//
// if (obj != null) {
// return obj;
// }
//
// } catch (IOException e) {
//
// } catch (ClassNotFoundException e) {
//
// } finally {
// if (in != null) {
// try {
// in.close();
// } catch (IOException e) {
//
// }
// }
// }
//
// return null;
// } else {
//
// return null;
// }
// }
}
| apache-2.0 |
AlexMinsk/camunda-bpm-platform | engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/JobRestServiceQueryTest.java | 27564 | /* 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.camunda.bpm.engine.rest;
import static com.jayway.restassured.RestAssured.expect;
import static com.jayway.restassured.RestAssured.given;
import static com.jayway.restassured.path.json.JsonPath.from;
import static org.fest.assertions.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import org.camunda.bpm.engine.impl.calendar.DateTimeUtil;
import org.camunda.bpm.engine.rest.exception.InvalidRequestException;
import org.camunda.bpm.engine.rest.helper.MockProvider;
import org.camunda.bpm.engine.rest.util.OrderingBuilder;
import org.camunda.bpm.engine.rest.util.container.TestContainerRule;
import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.runtime.JobQuery;
import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Response;
public class JobRestServiceQueryTest extends AbstractRestServiceTest {
@ClassRule
public static TestContainerRule rule = new TestContainerRule();
protected static final String JOBS_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/job";
protected static final String JOBS_QUERY_COUNT_URL = JOBS_RESOURCE_URL + "/count";
private JobQuery mockQuery;
private static final int MAX_RESULTS_TEN = 10;
private static final int FIRST_RESULTS_ZERO = 0;
protected static final long JOB_QUERY_MAX_PRIORITY = Long.MAX_VALUE;
protected static final long JOB_QUERY_MIN_PRIORITY = Long.MIN_VALUE;
@Before
public void setUpRuntimeData() {
mockQuery = setUpMockJobQuery(MockProvider.createMockJobs());
}
private JobQuery setUpMockJobQuery(List<Job> mockedJobs) {
JobQuery sampleJobQuery = mock(JobQuery.class);
when(sampleJobQuery.list()).thenReturn(mockedJobs);
when(sampleJobQuery.count()).thenReturn((long) mockedJobs.size());
when(processEngine.getManagementService().createJobQuery()).thenReturn(sampleJobQuery);
return sampleJobQuery;
}
@Test
public void testEmptyQuery() {
String queryJobId = "";
given().queryParam("id", queryJobId).then().expect()
.statusCode(Status.OK.getStatusCode())
.when().get(JOBS_RESOURCE_URL);
}
@Test
public void testNoParametersQuery() {
expect().statusCode(Status.OK.getStatusCode())
.when().get(JOBS_RESOURCE_URL);
verify(mockQuery).list();
verifyNoMoreInteractions(mockQuery);
}
@Test
public void testSortByParameterOnly() {
given().queryParam("sortBy", "jobDueDate")
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.contentType(ContentType.JSON)
.body("type",
equalTo(InvalidRequestException.class.getSimpleName()))
.body("message",
equalTo("Only a single sorting parameter specified. sortBy and sortOrder required"))
.when().get(JOBS_RESOURCE_URL);
}
@Test
public void testSortOrderParameterOnly() {
given().queryParam("sortOrder", "asc")
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.contentType(ContentType.JSON)
.body("type",
equalTo(InvalidRequestException.class.getSimpleName()))
.body("message",
equalTo("Only a single sorting parameter specified. sortBy and sortOrder required"))
.when().get(JOBS_RESOURCE_URL);
}
@Test
public void testSimpleJobQuery() {
String jobId = MockProvider.EXAMPLE_JOB_ID;
Response response = given().queryParam("jobId", jobId).then().expect()
.statusCode(Status.OK.getStatusCode()).when()
.get(JOBS_RESOURCE_URL);
InOrder inOrder = inOrder(mockQuery);
inOrder.verify(mockQuery).jobId(jobId);
inOrder.verify(mockQuery).list();
String content = response.asString();
List<String> instances = from(content).getList("");
Assert.assertEquals("There should be one job returned.", 1, instances.size());
Assert.assertNotNull("The returned job should not be null.", instances.get(0));
String returnedJobId = from(content).getString("[0].id");
String returnedProcessInstanceId = from(content).getString("[0].processInstanceId");
String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId");
String returnedProcessDefinitionKey = from(content).getString("[0].processDefinitionKey");
String returnedExecutionId = from(content).getString("[0].executionId");
String returnedExceptionMessage = from(content).getString("[0].exceptionMessage");
int returnedRetries = from(content).getInt("[0].retries");
Date returnedDueDate = DateTimeUtil.parseDate(from(content).getString("[0].dueDate"));
boolean returnedSuspended = from(content).getBoolean("[0].suspended");
long returnedPriority = from(content).getLong("[0].priority");
String returnedJobDefinitionId= from(content).getString("[0].jobDefinitionId");
String returnedTenantId = from(content).getString("[0].tenantId");
Assert.assertEquals(MockProvider.EXAMPLE_JOB_ID, returnedJobId);
Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedProcessInstanceId);
Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, returnedProcessDefinitionId);
Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, returnedProcessDefinitionKey);
Assert.assertEquals(MockProvider.EXAMPLE_EXECUTION_ID, returnedExecutionId);
Assert.assertEquals(MockProvider.EXAMPLE_JOB_NO_EXCEPTION_MESSAGE, returnedExceptionMessage);
Assert.assertEquals(MockProvider.EXAMPLE_JOB_RETRIES, returnedRetries);
Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_DUE_DATE), returnedDueDate);
Assert.assertEquals(MockProvider.EXAMPLE_JOB_IS_SUSPENDED, returnedSuspended);
Assert.assertEquals(MockProvider.EXAMPLE_JOB_PRIORITY, returnedPriority);
Assert.assertEquals(MockProvider.EXAMPLE_JOB_DEFINITION_ID, returnedJobDefinitionId);
Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId);
}
@Test
public void testInvalidDueDateComparator() {
String variableValue = "2013-05-05T00:00:00";
String invalidComparator = "bt";
String queryValue = invalidComparator + "_" + variableValue;
given().queryParam("dueDates", queryValue)
.then()
.expect()
.statusCode(Status.BAD_REQUEST.getStatusCode())
.contentType(ContentType.JSON)
.body("type",equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Invalid due date comparator specified: " + invalidComparator))
.when().get(JOBS_RESOURCE_URL);
}
@Test
public void testInvalidDueDateComperatorAsPost() {
String invalidComparator = "bt";
Map<String, Object> conditionJson = new HashMap<String, Object>();
conditionJson.put("operator", invalidComparator);
conditionJson.put("value", "2013-05-05T00:00:00");
List<Map<String, Object>> conditions = new ArrayList<Map<String, Object>>();
conditions.add(conditionJson);
Map<String, Object> json = new HashMap<String, Object>();
json.put("dueDates", conditions);
given().contentType(POST_JSON_CONTENT_TYPE).body(json)
.then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON)
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Invalid due date comparator specified: " + invalidComparator))
.when().post(JOBS_RESOURCE_URL);
}
@Test
public void testInvalidDueDate() {
String variableValue = "invalidValue";
String invalidComparator = "lt";
String queryValue = invalidComparator + "_" + variableValue;
given().queryParam("dueDates", queryValue)
.then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON)
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Invalid due date format: Cannot convert value \"invalidValue\" to java type java.util.Date"))
.when().get(JOBS_RESOURCE_URL);
}
@Test
public void testInvalidDueDateAsPost() {
Map<String, Object> conditionJson = new HashMap<String, Object>();
conditionJson.put("operator", "lt");
conditionJson.put("value", "invalidValue");
List<Map<String, Object>> conditions = new ArrayList<Map<String, Object>>();
conditions.add(conditionJson);
Map<String, Object> json = new HashMap<String, Object>();
json.put("dueDates", conditions);
given().contentType(POST_JSON_CONTENT_TYPE).body(json)
.then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON)
.body("type", equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Invalid due date format: Cannot convert value \"invalidValue\" to java type java.util.Date"))
.when().post(JOBS_RESOURCE_URL);
}
@Test
public void testAdditionalParametersExcludingDueDates() {
Map<String, Object> parameters = getCompleteParameters();
given().queryParams(parameters).then().expect()
.statusCode(Status.OK.getStatusCode()).when()
.get(JOBS_RESOURCE_URL);
verifyParameterQueryInvocations();
verify(mockQuery).list();
}
@Test
public void testMessagesParameter() {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("messages", MockProvider.EXAMPLE_MESSAGES);
given().queryParams(parameters)
.then().expect().statusCode(Status.OK.getStatusCode())
.when().get(JOBS_RESOURCE_URL);
verify(mockQuery).messages();
verify(mockQuery).list();
}
@Test
public void testMessagesTimersParameter() {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("messages", MockProvider.EXAMPLE_MESSAGES);
parameters.put("timers", MockProvider.EXAMPLE_TIMERS);
given().queryParams(parameters)
.then().expect().statusCode(Status.BAD_REQUEST.getStatusCode())
.contentType(ContentType.JSON)
.body("type",equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Parameter timers cannot be used together with parameter messages."))
.when().get(JOBS_RESOURCE_URL);
}
@Test
public void testMessagesTimersParameterAsPost() {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("messages", MockProvider.EXAMPLE_MESSAGES);
parameters.put("timers", MockProvider.EXAMPLE_TIMERS);
given().contentType(POST_JSON_CONTENT_TYPE).body(parameters)
.then().expect().statusCode(Status.BAD_REQUEST.getStatusCode())
.contentType(ContentType.JSON)
.body("type",equalTo(InvalidRequestException.class.getSimpleName()))
.body("message", equalTo("Parameter timers cannot be used together with parameter messages."))
.when().post(JOBS_RESOURCE_URL);
}
@Test
public void testMessagesParameterAsPost() {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("messages", MockProvider.EXAMPLE_MESSAGES);
given().contentType(POST_JSON_CONTENT_TYPE).body(parameters)
.then().expect().statusCode(Status.OK.getStatusCode())
.when().post(JOBS_RESOURCE_URL);
verify(mockQuery).messages();
verify(mockQuery).list();
}
private Map<String, Object> getCompleteParameters() {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("activityId", MockProvider.EXAMPLE_ACTIVITY_ID);
parameters.put("jobId", MockProvider.EXAMPLE_JOB_ID);
parameters.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
parameters.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);
parameters.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
parameters.put("executionId", MockProvider.EXAMPLE_EXECUTION_ID);
parameters.put("withRetriesLeft", MockProvider.EXAMPLE_WITH_RETRIES_LEFT);
parameters.put("executable", MockProvider.EXAMPLE_EXECUTABLE);
parameters.put("timers", MockProvider.EXAMPLE_TIMERS);
parameters.put("withException", MockProvider.EXAMPLE_WITH_EXCEPTION);
parameters.put("exceptionMessage", MockProvider.EXAMPLE_EXCEPTION_MESSAGE);
parameters.put("noRetriesLeft", MockProvider.EXAMPLE_NO_RETRIES_LEFT);
parameters.put("active", true);
parameters.put("suspended", true);
parameters.put("priorityLowerThanOrEquals", JOB_QUERY_MAX_PRIORITY);
parameters.put("priorityHigherThanOrEquals", JOB_QUERY_MIN_PRIORITY);
parameters.put("jobDefinitionId", MockProvider.EXAMPLE_JOB_DEFINITION_ID);
return parameters;
}
@Test
public void testAdditionalParametersExcludingDueDatesAsPost() {
Map<String, Object> parameters = getCompleteParameters();
given().contentType(POST_JSON_CONTENT_TYPE).body(parameters)
.then().expect().statusCode(Status.OK.getStatusCode())
.when().post(JOBS_RESOURCE_URL);
verifyParameterQueryInvocations();
verify(mockQuery).list();
}
private void verifyParameterQueryInvocations() {
Map<String, Object> parameters = getCompleteParameters();
verify(mockQuery).jobId((String) parameters.get("jobId"));
verify(mockQuery).processInstanceId((String) parameters.get("processInstanceId"));
verify(mockQuery).processDefinitionId((String) parameters.get("processDefinitionId"));
verify(mockQuery).processDefinitionKey((String) parameters.get("processDefinitionKey"));
verify(mockQuery).executionId((String) parameters.get("executionId"));
verify(mockQuery).activityId((String) parameters.get("activityId"));
verify(mockQuery).withRetriesLeft();
verify(mockQuery).executable();
verify(mockQuery).timers();
verify(mockQuery).withException();
verify(mockQuery).exceptionMessage((String) parameters.get("exceptionMessage"));
verify(mockQuery).noRetriesLeft();
verify(mockQuery).active();
verify(mockQuery).suspended();
verify(mockQuery).priorityLowerThanOrEquals(JOB_QUERY_MAX_PRIORITY);
verify(mockQuery).priorityHigherThanOrEquals(JOB_QUERY_MIN_PRIORITY);
verify(mockQuery).jobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID);
}
@Test
public void testDueDateParameters() {
String variableValue = "2013-05-05T00:00:00";
Date date = DateTimeUtil.parseDate(variableValue);
String queryValue = "lt_" + variableValue;
given().queryParam("dueDates", queryValue).then().expect()
.statusCode(Status.OK.getStatusCode()).when()
.get(JOBS_RESOURCE_URL);
InOrder inOrder = inOrder(mockQuery);
inOrder.verify(mockQuery).duedateLowerThan(date);
inOrder.verify(mockQuery).list();
queryValue = "gt_" + variableValue;
given().queryParam("dueDates", queryValue).then().expect()
.statusCode(Status.OK.getStatusCode()).when()
.get(JOBS_RESOURCE_URL);
inOrder = inOrder(mockQuery);
inOrder.verify(mockQuery).duedateHigherThan(date);
inOrder.verify(mockQuery).list();
}
@Test
public void testDueDateParametersAsPost() {
String value = "2013-05-18T00:00:00";
String anotherValue = "2013-05-05T00:00:00";
Date date = DateTimeUtil.parseDate(value);
Date anotherDate = DateTimeUtil.parseDate(anotherValue);
Map<String, Object> conditionJson = new HashMap<String, Object>();
conditionJson.put("operator", "lt");
conditionJson.put("value", value);
Map<String, Object> anotherConditionJson = new HashMap<String, Object>();
anotherConditionJson.put("operator", "gt");
anotherConditionJson.put("value", anotherValue);
List<Map<String, Object>> conditions = new ArrayList<Map<String, Object>>();
conditions.add(conditionJson);
conditions.add(anotherConditionJson);
Map<String, Object> json = new HashMap<String, Object>();
json.put("dueDates", conditions);
given().contentType(POST_JSON_CONTENT_TYPE).body(json)
.then().expect().statusCode(Status.OK.getStatusCode())
.when().post(JOBS_RESOURCE_URL);
verify(mockQuery).duedateHigherThan(anotherDate);
verify(mockQuery).duedateLowerThan(date);
}
@Test
public void testMultipleDueDateParameters() {
String variableValue1 = "2012-05-05T00:00:00";
String variableParameter1 = "gt_" + variableValue1;
String variableValue2 = "2013-02-02T00:00:00";
String variableParameter2 = "lt_" + variableValue2;
Date date = DateTimeUtil.parseDate(variableValue1);
Date anotherDate = DateTimeUtil.parseDate(variableValue2);
String queryValue = variableParameter1 + "," + variableParameter2;
given().queryParam("dueDates", queryValue).then().expect()
.statusCode(Status.OK.getStatusCode()).when()
.get(JOBS_RESOURCE_URL);
verify(mockQuery).duedateHigherThan(date);
verify(mockQuery).duedateLowerThan(anotherDate);
}
@Test
public void testSortingParameters() {
InOrder inOrder = Mockito.inOrder(mockQuery);
executeAndVerifySorting("jobId", "desc", Status.OK);
inOrder.verify(mockQuery).orderByJobId();
inOrder.verify(mockQuery).desc();
inOrder = Mockito.inOrder(mockQuery);
executeAndVerifySorting("processInstanceId", "asc", Status.OK);
inOrder.verify(mockQuery).orderByProcessInstanceId();
inOrder.verify(mockQuery).asc();
inOrder = Mockito.inOrder(mockQuery);
executeAndVerifySorting("executionId", "desc", Status.OK);
inOrder.verify(mockQuery).orderByExecutionId();
inOrder.verify(mockQuery).desc();
inOrder = Mockito.inOrder(mockQuery);
executeAndVerifySorting("jobRetries", "asc", Status.OK);
inOrder.verify(mockQuery).orderByJobRetries();
inOrder.verify(mockQuery).asc();
inOrder = Mockito.inOrder(mockQuery);
executeAndVerifySorting("jobDueDate", "desc", Status.OK);
inOrder.verify(mockQuery).orderByJobDuedate();
inOrder.verify(mockQuery).desc();
inOrder = Mockito.inOrder(mockQuery);
executeAndVerifySorting("jobPriority", "asc", Status.OK);
inOrder.verify(mockQuery).orderByJobPriority();
inOrder.verify(mockQuery).asc();
inOrder = Mockito.inOrder(mockQuery);
executeAndVerifySorting("tenantId", "asc", Status.OK);
inOrder.verify(mockQuery).orderByTenantId();
inOrder.verify(mockQuery).asc();
inOrder = Mockito.inOrder(mockQuery);
executeAndVerifySorting("tenantId", "desc", Status.OK);
inOrder.verify(mockQuery).orderByTenantId();
inOrder.verify(mockQuery).desc();
}
private void executeAndVerifySorting(String sortBy, String sortOrder,
Status expectedStatus) {
given().queryParam("sortBy", sortBy).queryParam("sortOrder", sortOrder)
.then().expect().statusCode(expectedStatus.getStatusCode())
.when().get(JOBS_RESOURCE_URL);
}
@Test
public void testSecondarySortingAsPost() {
InOrder inOrder = Mockito.inOrder(mockQuery);
Map<String, Object> json = new HashMap<String, Object>();
json.put("sorting", OrderingBuilder.create()
.orderBy("jobRetries").desc()
.orderBy("jobDueDate").asc()
.getJson());
given().contentType(POST_JSON_CONTENT_TYPE).body(json)
.header("accept", MediaType.APPLICATION_JSON)
.then().expect().statusCode(Status.OK.getStatusCode())
.when().post(JOBS_RESOURCE_URL);
inOrder.verify(mockQuery).orderByJobRetries();
inOrder.verify(mockQuery).desc();
inOrder.verify(mockQuery).orderByJobDuedate();
inOrder.verify(mockQuery).asc();
}
@Test
public void testSuccessfulPagination() {
int firstResult = FIRST_RESULTS_ZERO;
int maxResults = MAX_RESULTS_TEN;
given().queryParam("firstResult", firstResult)
.queryParam("maxResults", maxResults).then().expect()
.statusCode(Status.OK.getStatusCode()).when()
.get(JOBS_RESOURCE_URL);
verify(mockQuery).listPage(firstResult, maxResults);
}
@Test
public void testQueryCount() {
given()
.header("accept", MediaType.APPLICATION_JSON)
.expect()
.statusCode(Status.OK.getStatusCode())
.body("count", equalTo(1))
.when()
.get(JOBS_QUERY_COUNT_URL);
verify(mockQuery).count();
}
@Test
public void testQueryCountForPost() {
given().contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT)
.header("accept", MediaType.APPLICATION_JSON)
.expect().statusCode(Status.OK.getStatusCode())
.body("count", equalTo(1))
.when().post(JOBS_QUERY_COUNT_URL);
verify(mockQuery).count();
}
@Test
public void testTenantIdListParameter() {
mockQuery = setUpMockJobQuery(createMockJobsTwoTenants());
Response response = given()
.queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when()
.get(JOBS_RESOURCE_URL);
verify(mockQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID);
verify(mockQuery).list();
String content = response.asString();
List<String> jobs = from(content).getList("");
assertThat(jobs).hasSize(2);
String returnedTenantId1 = from(content).getString("[0].tenantId");
String returnedTenantId2 = from(content).getString("[1].tenantId");
assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID);
assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID);
}
@Test
public void testWithoutTenantIdParameter() {
Job mockJob = MockProvider.mockJob().tenantId(null).build();
mockQuery = setUpMockJobQuery(Arrays.asList(mockJob));
Response response = given()
.queryParam("withoutTenantId", true)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when()
.get(JOBS_RESOURCE_URL);
verify(mockQuery).withoutTenantId();
verify(mockQuery).list();
String content = response.asString();
List<String> jobs = from(content).getList("");
assertThat(jobs).hasSize(1);
String returnedTenantId = from(content).getString("[0].tenantId");
assertThat(returnedTenantId).isEqualTo(null);
}
@Test
public void testIncludeJobsWithoutTenantIdParameter() {
List<Job> jobs = Arrays.asList(
MockProvider.mockJob().tenantId(null).build(),
MockProvider.mockJob().tenantId(MockProvider.EXAMPLE_TENANT_ID).build());
mockQuery = setUpMockJobQuery(jobs);
Response response = given()
.queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID)
.queryParam("includeJobsWithoutTenantId", true)
.then().expect()
.statusCode(Status.OK.getStatusCode())
.when()
.get(JOBS_RESOURCE_URL);
verify(mockQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID);
verify(mockQuery).includeJobsWithoutTenantId();
verify(mockQuery).list();
String content = response.asString();
List<String> definitions = from(content).getList("");
assertThat(definitions).hasSize(2);
String returnedTenantId1 = from(content).getString("[0].tenantId");
String returnedTenantId2 = from(content).getString("[1].tenantId");
assertThat(returnedTenantId1).isEqualTo(null);
assertThat(returnedTenantId2).isEqualTo(MockProvider.EXAMPLE_TENANT_ID);
}
@Test
public void testTenantIdListPostParameter() {
mockQuery = setUpMockJobQuery(createMockJobsTwoTenants());
Map<String, Object> queryParameters = new HashMap<String, Object>();
queryParameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST.split(","));
Response response = given()
.contentType(POST_JSON_CONTENT_TYPE)
.body(queryParameters)
.expect()
.statusCode(Status.OK.getStatusCode())
.when()
.post(JOBS_RESOURCE_URL);
verify(mockQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID);
verify(mockQuery).list();
String content = response.asString();
List<String> jobs = from(content).getList("");
assertThat(jobs).hasSize(2);
String returnedTenantId1 = from(content).getString("[0].tenantId");
String returnedTenantId2 = from(content).getString("[1].tenantId");
assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID);
assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID);
}
@Test
public void testWithoutTenantIdPostParameter() {
Job mockJob = MockProvider.mockJob().tenantId(null).build();
mockQuery = setUpMockJobQuery(Arrays.asList(mockJob));
Map<String, Object> queryParameters = new HashMap<String, Object>();
queryParameters.put("withoutTenantId", true);
Response response = given()
.contentType(POST_JSON_CONTENT_TYPE)
.body(queryParameters)
.expect()
.statusCode(Status.OK.getStatusCode())
.when()
.post(JOBS_RESOURCE_URL);
String content = response.asString();
List<String> jobs = from(content).getList("");
assertThat(jobs).hasSize(1);
String returnedTenantId = from(content).getString("[0].tenantId");
assertThat(returnedTenantId).isEqualTo(null);
}
@Test
public void testIncludeJobsWithoutTenantIdPostParameter() {
List<Job> jobs = Arrays.asList(
MockProvider.mockJob().tenantId(null).build(),
MockProvider.mockJob().tenantId(MockProvider.EXAMPLE_TENANT_ID).build());
mockQuery = setUpMockJobQuery(jobs);
Map<String, Object> queryParameters = new HashMap<String, Object>();
queryParameters.put("tenantIdIn", new String[] { MockProvider.EXAMPLE_TENANT_ID });
queryParameters.put("includeJobsWithoutTenantId", true);
Response response = given()
.contentType(POST_JSON_CONTENT_TYPE)
.body(queryParameters)
.expect()
.statusCode(Status.OK.getStatusCode())
.when()
.post(JOBS_RESOURCE_URL);
verify(mockQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID);
verify(mockQuery).includeJobsWithoutTenantId();
verify(mockQuery).list();
String content = response.asString();
List<String> definitions = from(content).getList("");
assertThat(definitions).hasSize(2);
String returnedTenantId1 = from(content).getString("[0].tenantId");
String returnedTenantId2 = from(content).getString("[1].tenantId");
assertThat(returnedTenantId1).isEqualTo(null);
assertThat(returnedTenantId2).isEqualTo(MockProvider.EXAMPLE_TENANT_ID);
}
private List<Job> createMockJobsTwoTenants() {
return Arrays.asList(
MockProvider.mockJob().tenantId(MockProvider.EXAMPLE_TENANT_ID).build(),
MockProvider.mockJob().tenantId(MockProvider.ANOTHER_EXAMPLE_TENANT_ID).build());
}
}
| apache-2.0 |
ilganeli/incubator-apex-malhar | contrib/src/main/java/com/datatorrent/contrib/solr/ConcurrentUpdateSolrServerConnector.java | 3567 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.datatorrent.contrib.solr;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import javax.validation.constraints.NotNull;
import org.apache.http.client.HttpClient;
import org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrServer;
/**
* Initializes ConcurrentUpdateServer instance of Solr Server.<br>
* <br>
* properties:<br>
* solrServerURL - The Solr server URL<br>
* queueSize - The buffer size before the documents are sent to the server <br>
* threadCount - The number of background threads used to empty the queue<br>
* httpClient - HttpClient instance
*
* @since 2.0.0
*/
public class ConcurrentUpdateSolrServerConnector extends SolrServerConnector
{
private static final int DEFAULT_THREAD_COUNT = 5;
private static final int DEFAULT_QUEUE_SIZE = 1024;
@NotNull
private String solrServerURL;
private int queueSize = DEFAULT_QUEUE_SIZE;
private int threadCount = DEFAULT_THREAD_COUNT;
private HttpClient httpClient;
private ExecutorService executorService;
private boolean streamDeletes = false;
@Override
public void connect() throws IOException
{
if (httpClient == null && executorService == null) {
solrServer = new ConcurrentUpdateSolrServer(solrServerURL, queueSize, threadCount);
} else if (executorService == null) {
solrServer = new ConcurrentUpdateSolrServer(solrServerURL, httpClient, queueSize, threadCount);
} else {
solrServer = new ConcurrentUpdateSolrServer(solrServerURL, httpClient, queueSize, threadCount, executorService, streamDeletes);
}
}
public void setSolrServerURL(String solrServerURL)
{
this.solrServerURL = solrServerURL;
}
/*
* The Solr server URL
* Gets the solr server URL
*/
public String getSolrServerURL()
{
return solrServerURL;
}
public void setQueueSize(int queueSize)
{
this.queueSize = queueSize;
}
/*
* The buffer size before the documents are sent to the server
* Gets the queue size of documents buffer
*/
public int getQueueSize()
{
return queueSize;
}
public void setThreadCount(int threadCount)
{
this.threadCount = threadCount;
}
/*
* The number of background threads used to empty the queue
* Gets the background threads count
*/
public int getThreadCount()
{
return threadCount;
}
public void setHttpClient(HttpClient httpClient)
{
this.httpClient = httpClient;
}
/*
* HttpClient instance
* Gets the HTTP Client instance
*/
public HttpClient getHttpClient()
{
return httpClient;
}
public void setStreamDeletes(boolean streamDeletes)
{
this.streamDeletes = streamDeletes;
}
public boolean getStreamDeletes()
{
return streamDeletes;
}
}
| apache-2.0 |
jasonkuster/incubator-beam | runners/core-java/src/main/java/org/apache/beam/runners/core/SimpleDoFnRunner.java | 31465 | /*
* 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.beam.runners.core;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
import org.apache.beam.runners.core.DoFnRunners.OutputManager;
import org.apache.beam.runners.core.ExecutionContext.StepContext;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.transforms.Aggregator;
import org.apache.beam.sdk.transforms.Combine.CombineFn;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.DoFn.Context;
import org.apache.beam.sdk.transforms.DoFn.OnTimerContext;
import org.apache.beam.sdk.transforms.DoFn.ProcessContext;
import org.apache.beam.sdk.transforms.reflect.DoFnInvoker;
import org.apache.beam.sdk.transforms.reflect.DoFnInvokers;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature;
import org.apache.beam.sdk.transforms.reflect.DoFnSignatures;
import org.apache.beam.sdk.transforms.splittabledofn.RestrictionTracker;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
import org.apache.beam.sdk.transforms.windowing.GlobalWindows;
import org.apache.beam.sdk.transforms.windowing.PaneInfo;
import org.apache.beam.sdk.transforms.windowing.WindowFn;
import org.apache.beam.sdk.util.SideInputReader;
import org.apache.beam.sdk.util.SystemDoFnInternal;
import org.apache.beam.sdk.util.TimeDomain;
import org.apache.beam.sdk.util.Timer;
import org.apache.beam.sdk.util.TimerSpec;
import org.apache.beam.sdk.util.UserCodeException;
import org.apache.beam.sdk.util.WindowedValue;
import org.apache.beam.sdk.util.WindowingStrategy;
import org.apache.beam.sdk.util.state.State;
import org.apache.beam.sdk.util.state.StateSpec;
import org.apache.beam.sdk.values.PCollectionView;
import org.apache.beam.sdk.values.TupleTag;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.joda.time.format.PeriodFormat;
/**
* Runs a {@link DoFn} by constructing the appropriate contexts and passing them in.
*
* <p>Also, if the {@link DoFn} observes the window of the element, then {@link SimpleDoFnRunner}
* explodes windows of the input {@link WindowedValue} and calls {@link DoFn.ProcessElement} for
* each window individually.
*
* @param <InputT> the type of the {@link DoFn} (main) input elements
* @param <OutputT> the type of the {@link DoFn} (main) output elements
*/
public class SimpleDoFnRunner<InputT, OutputT> implements DoFnRunner<InputT, OutputT> {
/** The {@link DoFn} being run. */
private final DoFn<InputT, OutputT> fn;
/** The {@link DoFnInvoker} being run. */
private final DoFnInvoker<InputT, OutputT> invoker;
/** The context used for running the {@link DoFn}. */
private final DoFnContext<InputT, OutputT> context;
private final OutputManager outputManager;
private final TupleTag<OutputT> mainOutputTag;
private final boolean observesWindow;
private final DoFnSignature signature;
private final Coder<BoundedWindow> windowCoder;
private final Duration allowedLateness;
// Because of setKey(Object), we really must refresh stateInternals() at each access
private final StepContext stepContext;
public SimpleDoFnRunner(
PipelineOptions options,
DoFn<InputT, OutputT> fn,
SideInputReader sideInputReader,
OutputManager outputManager,
TupleTag<OutputT> mainOutputTag,
List<TupleTag<?>> sideOutputTags,
StepContext stepContext,
AggregatorFactory aggregatorFactory,
WindowingStrategy<?, ?> windowingStrategy) {
this.fn = fn;
this.signature = DoFnSignatures.getSignature(fn.getClass());
this.observesWindow = signature.processElement().observesWindow() || !sideInputReader.isEmpty();
this.invoker = DoFnInvokers.invokerFor(fn);
this.outputManager = outputManager;
this.mainOutputTag = mainOutputTag;
this.stepContext = stepContext;
// This is a cast of an _invariant_ coder. But we are assured by pipeline validation
// that it really is the coder for whatever BoundedWindow subclass is provided
@SuppressWarnings("unchecked")
Coder<BoundedWindow> untypedCoder =
(Coder<BoundedWindow>) windowingStrategy.getWindowFn().windowCoder();
this.windowCoder = untypedCoder;
this.allowedLateness = windowingStrategy.getAllowedLateness();
this.context =
new DoFnContext<>(
options,
fn,
sideInputReader,
outputManager,
mainOutputTag,
sideOutputTags,
stepContext,
aggregatorFactory,
windowingStrategy.getWindowFn());
}
@Override
public void startBundle() {
// This can contain user code. Wrap it in case it throws an exception.
try {
invoker.invokeStartBundle(context);
} catch (Throwable t) {
// Exception in user code.
throw wrapUserCodeException(t);
}
}
@Override
public void processElement(WindowedValue<InputT> compressedElem) {
if (observesWindow) {
for (WindowedValue<InputT> elem : compressedElem.explodeWindows()) {
invokeProcessElement(elem);
}
} else {
invokeProcessElement(compressedElem);
}
}
@Override
public void onTimer(
String timerId, BoundedWindow window, Instant timestamp, TimeDomain timeDomain) {
// The effective timestamp is when derived elements will have their timestamp set, if not
// otherwise specified. If this is an event time timer, then they have the timestamp of the
// timer itself. Otherwise, they are set to the input timestamp, which is by definition
// non-late.
Instant effectiveTimestamp;
switch (timeDomain) {
case EVENT_TIME:
effectiveTimestamp = timestamp;
break;
case PROCESSING_TIME:
case SYNCHRONIZED_PROCESSING_TIME:
effectiveTimestamp = context.stepContext.timerInternals().currentInputWatermarkTime();
break;
default:
throw new IllegalArgumentException(
String.format("Unknown time domain: %s", timeDomain));
}
OnTimerArgumentProvider<InputT, OutputT> argumentProvider =
new OnTimerArgumentProvider<>(
fn, context, window, allowedLateness, effectiveTimestamp, timeDomain);
invoker.invokeOnTimer(timerId, argumentProvider);
}
private void invokeProcessElement(WindowedValue<InputT> elem) {
final DoFnProcessContext<InputT, OutputT> processContext = createProcessContext(elem);
// This can contain user code. Wrap it in case it throws an exception.
try {
invoker.invokeProcessElement(processContext);
} catch (Exception ex) {
throw wrapUserCodeException(ex);
}
}
@Override
public void finishBundle() {
// This can contain user code. Wrap it in case it throws an exception.
try {
invoker.invokeFinishBundle(context);
} catch (Throwable t) {
// Exception in user code.
throw wrapUserCodeException(t);
}
}
/** Returns a new {@link DoFn.ProcessContext} for the given element. */
private DoFnProcessContext<InputT, OutputT> createProcessContext(WindowedValue<InputT> elem) {
return new DoFnProcessContext<InputT, OutputT>(fn, context, elem, allowedLateness);
}
private RuntimeException wrapUserCodeException(Throwable t) {
throw UserCodeException.wrapIf(!isSystemDoFn(), t);
}
private boolean isSystemDoFn() {
return invoker.getClass().isAnnotationPresent(SystemDoFnInternal.class);
}
/**
* A concrete implementation of {@code DoFn.Context} used for running a {@link DoFn}.
*
* @param <InputT> the type of the {@link DoFn} (main) input elements
* @param <OutputT> the type of the {@link DoFn} (main) output elements
*/
private static class DoFnContext<InputT, OutputT> extends DoFn<InputT, OutputT>.Context
implements DoFnInvoker.ArgumentProvider<InputT, OutputT> {
private static final int MAX_SIDE_OUTPUTS = 1000;
final PipelineOptions options;
final DoFn<InputT, OutputT> fn;
final SideInputReader sideInputReader;
final OutputManager outputManager;
final TupleTag<OutputT> mainOutputTag;
final StepContext stepContext;
final AggregatorFactory aggregatorFactory;
final WindowFn<?, ?> windowFn;
/**
* The set of known output tags, some of which may be undeclared, so we can throw an exception
* when it exceeds {@link #MAX_SIDE_OUTPUTS}.
*/
private Set<TupleTag<?>> outputTags;
public DoFnContext(
PipelineOptions options,
DoFn<InputT, OutputT> fn,
SideInputReader sideInputReader,
OutputManager outputManager,
TupleTag<OutputT> mainOutputTag,
List<TupleTag<?>> sideOutputTags,
StepContext stepContext,
AggregatorFactory aggregatorFactory,
WindowFn<?, ?> windowFn) {
fn.super();
this.options = options;
this.fn = fn;
this.sideInputReader = sideInputReader;
this.outputManager = outputManager;
this.mainOutputTag = mainOutputTag;
this.outputTags = Sets.newHashSet();
outputTags.add(mainOutputTag);
for (TupleTag<?> sideOutputTag : sideOutputTags) {
outputTags.add(sideOutputTag);
}
this.stepContext = stepContext;
this.aggregatorFactory = aggregatorFactory;
this.windowFn = windowFn;
super.setupDelegateAggregators();
}
//////////////////////////////////////////////////////////////////////////////
@Override
public PipelineOptions getPipelineOptions() {
return options;
}
<T, W extends BoundedWindow> WindowedValue<T> makeWindowedValue(
T output, Instant timestamp, Collection<W> windows, PaneInfo pane) {
final Instant inputTimestamp = timestamp;
if (timestamp == null) {
timestamp = BoundedWindow.TIMESTAMP_MIN_VALUE;
}
if (windows == null) {
try {
// The windowFn can never succeed at accessing the element, so its type does not
// matter here
@SuppressWarnings("unchecked")
WindowFn<Object, W> objectWindowFn = (WindowFn<Object, W>) windowFn;
windows =
objectWindowFn.assignWindows(
objectWindowFn.new AssignContext() {
@Override
public Object element() {
throw new UnsupportedOperationException(
"WindowFn attempted to access input element when none was available");
}
@Override
public Instant timestamp() {
if (inputTimestamp == null) {
throw new UnsupportedOperationException(
"WindowFn attempted to access input timestamp when none was available");
}
return inputTimestamp;
}
@Override
public W window() {
throw new UnsupportedOperationException(
"WindowFn attempted to access input windows when none were available");
}
});
} catch (Exception e) {
throw UserCodeException.wrap(e);
}
}
return WindowedValue.of(output, timestamp, windows, pane);
}
public <T> T sideInput(PCollectionView<T> view, BoundedWindow sideInputWindow) {
if (!sideInputReader.contains(view)) {
throw new IllegalArgumentException("calling sideInput() with unknown view");
}
return sideInputReader.get(view, sideInputWindow);
}
void outputWindowedValue(
OutputT output,
Instant timestamp,
Collection<? extends BoundedWindow> windows,
PaneInfo pane) {
outputWindowedValue(makeWindowedValue(output, timestamp, windows, pane));
}
void outputWindowedValue(WindowedValue<OutputT> windowedElem) {
outputManager.output(mainOutputTag, windowedElem);
if (stepContext != null) {
stepContext.noteOutput(windowedElem);
}
}
private <T> void sideOutputWindowedValue(
TupleTag<T> tag,
T output,
Instant timestamp,
Collection<? extends BoundedWindow> windows,
PaneInfo pane) {
sideOutputWindowedValue(tag, makeWindowedValue(output, timestamp, windows, pane));
}
private <T> void sideOutputWindowedValue(TupleTag<T> tag, WindowedValue<T> windowedElem) {
if (!outputTags.contains(tag)) {
// This tag wasn't declared nor was it seen before during this execution.
// Thus, this must be a new, undeclared and unconsumed output.
// To prevent likely user errors, enforce the limit on the number of side
// outputs.
if (outputTags.size() >= MAX_SIDE_OUTPUTS) {
throw new IllegalArgumentException(
"the number of side outputs has exceeded a limit of " + MAX_SIDE_OUTPUTS);
}
outputTags.add(tag);
}
outputManager.output(tag, windowedElem);
if (stepContext != null) {
stepContext.noteSideOutput(tag, windowedElem);
}
}
// Following implementations of output, outputWithTimestamp, and sideOutput
// are only accessible in DoFn.startBundle and DoFn.finishBundle, and will be shadowed by
// ProcessContext's versions in DoFn.processElement.
@Override
public void output(OutputT output) {
outputWindowedValue(output, null, null, PaneInfo.NO_FIRING);
}
@Override
public void outputWithTimestamp(OutputT output, Instant timestamp) {
outputWindowedValue(output, timestamp, null, PaneInfo.NO_FIRING);
}
@Override
public <T> void sideOutput(TupleTag<T> tag, T output) {
checkNotNull(tag, "TupleTag passed to sideOutput cannot be null");
sideOutputWindowedValue(tag, output, null, null, PaneInfo.NO_FIRING);
}
@Override
public <T> void sideOutputWithTimestamp(TupleTag<T> tag, T output, Instant timestamp) {
checkNotNull(tag, "TupleTag passed to sideOutputWithTimestamp cannot be null");
sideOutputWindowedValue(tag, output, timestamp, null, PaneInfo.NO_FIRING);
}
@Override
protected <AggInputT, AggOutputT> Aggregator<AggInputT, AggOutputT> createAggregator(
String name, CombineFn<AggInputT, ?, AggOutputT> combiner) {
checkNotNull(combiner, "Combiner passed to createAggregator cannot be null");
return aggregatorFactory.createAggregatorForDoFn(fn.getClass(), stepContext, name, combiner);
}
@Override
public BoundedWindow window() {
throw new UnsupportedOperationException(
"Cannot access window outside of @ProcessElement and @OnTimer methods.");
}
@Override
public Context context(DoFn<InputT, OutputT> doFn) {
return this;
}
@Override
public ProcessContext processContext(DoFn<InputT, OutputT> doFn) {
throw new UnsupportedOperationException(
"Cannot access ProcessContext outside of @Processelement method.");
}
@Override
public OnTimerContext onTimerContext(DoFn<InputT, OutputT> doFn) {
throw new UnsupportedOperationException(
"Cannot access OnTimerContext outside of @OnTimer methods.");
}
@Override
public RestrictionTracker<?> restrictionTracker() {
throw new UnsupportedOperationException(
"Cannot access RestrictionTracker outside of @ProcessElement method.");
}
@Override
public State state(String stateId) {
throw new UnsupportedOperationException(
"Cannot access state outside of @ProcessElement and @OnTimer methods.");
}
@Override
public Timer timer(String timerId) {
throw new UnsupportedOperationException(
"Cannot access timers outside of @ProcessElement and @OnTimer methods.");
}
}
/**
* A concrete implementation of {@link DoFn.ProcessContext} used for running a {@link DoFn} over a
* single element.
*
* @param <InputT> the type of the {@link DoFn} (main) input elements
* @param <OutputT> the type of the {@link DoFn} (main) output elements
*/
private class DoFnProcessContext<InputT, OutputT> extends DoFn<InputT, OutputT>.ProcessContext
implements DoFnInvoker.ArgumentProvider<InputT, OutputT> {
final DoFn<InputT, OutputT> fn;
final DoFnContext<InputT, OutputT> context;
final WindowedValue<InputT> windowedValue;
private final Duration allowedLateness;
/** Lazily initialized; should only be accessed via {@link #getNamespace()}. */
@Nullable private StateNamespace namespace;
/**
* The state namespace for this context.
*
* <p>Any call to {@link #getNamespace()} when more than one window is present will crash; this
* represents a bug in the runner or the {@link DoFnSignature}, since values must be in exactly
* one window when state or timers are relevant.
*/
private StateNamespace getNamespace() {
if (namespace == null) {
namespace = StateNamespaces.window(windowCoder, window());
}
return namespace;
}
private DoFnProcessContext(
DoFn<InputT, OutputT> fn,
DoFnContext<InputT, OutputT> context,
WindowedValue<InputT> windowedValue,
Duration allowedLateness) {
fn.super();
this.fn = fn;
this.context = context;
this.windowedValue = windowedValue;
this.allowedLateness = allowedLateness;
}
@Override
public PipelineOptions getPipelineOptions() {
return context.getPipelineOptions();
}
@Override
public InputT element() {
return windowedValue.getValue();
}
@Override
public <T> T sideInput(PCollectionView<T> view) {
checkNotNull(view, "View passed to sideInput cannot be null");
Iterator<? extends BoundedWindow> windowIter = windows().iterator();
BoundedWindow window;
if (!windowIter.hasNext()) {
if (context.windowFn instanceof GlobalWindows) {
// TODO: Remove this once GroupByKeyOnly no longer outputs elements
// without windows
window = GlobalWindow.INSTANCE;
} else {
throw new IllegalStateException(
"sideInput called when main input element is not in any windows");
}
} else {
window = windowIter.next();
if (windowIter.hasNext()) {
throw new IllegalStateException(
"sideInput called when main input element is in multiple windows");
}
}
return context.sideInput(
view, view.getWindowingStrategyInternal().getWindowFn().getSideInputWindow(window));
}
@Override
public PaneInfo pane() {
return windowedValue.getPane();
}
@Override
public void output(OutputT output) {
context.outputWindowedValue(windowedValue.withValue(output));
}
@Override
public void outputWithTimestamp(OutputT output, Instant timestamp) {
checkTimestamp(timestamp);
context.outputWindowedValue(
output, timestamp, windowedValue.getWindows(), windowedValue.getPane());
}
@Override
public <T> void sideOutput(TupleTag<T> tag, T output) {
checkNotNull(tag, "Tag passed to sideOutput cannot be null");
context.sideOutputWindowedValue(tag, windowedValue.withValue(output));
}
@Override
public <T> void sideOutputWithTimestamp(TupleTag<T> tag, T output, Instant timestamp) {
checkNotNull(tag, "Tag passed to sideOutputWithTimestamp cannot be null");
checkTimestamp(timestamp);
context.sideOutputWindowedValue(
tag, output, timestamp, windowedValue.getWindows(), windowedValue.getPane());
}
@Override
public Instant timestamp() {
return windowedValue.getTimestamp();
}
public Collection<? extends BoundedWindow> windows() {
return windowedValue.getWindows();
}
private void checkTimestamp(Instant timestamp) {
if (timestamp.isBefore(windowedValue.getTimestamp().minus(fn.getAllowedTimestampSkew()))) {
throw new IllegalArgumentException(
String.format(
"Cannot output with timestamp %s. Output timestamps must be no earlier than the "
+ "timestamp of the current input (%s) minus the allowed skew (%s). See the "
+ "DoFn#getAllowedTimestampSkew() Javadoc for details on changing the allowed "
+ "skew.",
timestamp,
windowedValue.getTimestamp(),
PeriodFormat.getDefault().print(fn.getAllowedTimestampSkew().toPeriod())));
}
}
@Override
protected <AggregatorInputT, AggregatorOutputT>
Aggregator<AggregatorInputT, AggregatorOutputT> createAggregator(
String name, CombineFn<AggregatorInputT, ?, AggregatorOutputT> combiner) {
return context.createAggregator(name, combiner);
}
@Override
public BoundedWindow window() {
return Iterables.getOnlyElement(windowedValue.getWindows());
}
@Override
public DoFn<InputT, OutputT>.Context context(DoFn<InputT, OutputT> doFn) {
return this;
}
@Override
public DoFn<InputT, OutputT>.ProcessContext processContext(DoFn<InputT, OutputT> doFn) {
return this;
}
@Override
public OnTimerContext onTimerContext(DoFn<InputT, OutputT> doFn) {
throw new UnsupportedOperationException(
"Cannot access OnTimerContext outside of @OnTimer methods.");
}
@Override
public RestrictionTracker<?> restrictionTracker() {
throw new UnsupportedOperationException("RestrictionTracker parameters are not supported.");
}
@Override
public State state(String stateId) {
try {
StateSpec<?, ?> spec =
(StateSpec<?, ?>) signature.stateDeclarations().get(stateId).field().get(fn);
return stepContext
.stateInternals()
.state(getNamespace(), StateTags.tagForSpec(stateId, (StateSpec) spec));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public Timer timer(String timerId) {
try {
TimerSpec spec =
(TimerSpec) signature.timerDeclarations().get(timerId).field().get(fn);
return new TimerInternalsTimer(
window(), getNamespace(), allowedLateness, timerId, spec, stepContext.timerInternals());
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
/**
* A concrete implementation of {@link DoFnInvoker.ArgumentProvider} used for running a {@link
* DoFn} on a timer.
*
* @param <InputT> the type of the {@link DoFn} (main) input elements
* @param <OutputT> the type of the {@link DoFn} (main) output elements
*/
private class OnTimerArgumentProvider<InputT, OutputT>
extends DoFn<InputT, OutputT>.OnTimerContext
implements DoFnInvoker.ArgumentProvider<InputT, OutputT> {
final DoFn<InputT, OutputT> fn;
final DoFnContext<InputT, OutputT> context;
private final BoundedWindow window;
private final Instant timestamp;
private final TimeDomain timeDomain;
private final Duration allowedLateness;
/** Lazily initialized; should only be accessed via {@link #getNamespace()}. */
private StateNamespace namespace;
/**
* The state namespace for this context.
*
* <p>Any call to {@link #getNamespace()} when more than one window is present will crash; this
* represents a bug in the runner or the {@link DoFnSignature}, since values must be in exactly
* one window when state or timers are relevant.
*/
private StateNamespace getNamespace() {
if (namespace == null) {
namespace = StateNamespaces.window(windowCoder, window);
}
return namespace;
}
private OnTimerArgumentProvider(
DoFn<InputT, OutputT> fn,
DoFnContext<InputT, OutputT> context,
BoundedWindow window,
Duration allowedLateness,
Instant timestamp,
TimeDomain timeDomain) {
fn.super();
this.fn = fn;
this.context = context;
this.window = window;
this.allowedLateness = allowedLateness;
this.timestamp = timestamp;
this.timeDomain = timeDomain;
}
@Override
public Instant timestamp() {
return timestamp;
}
@Override
public BoundedWindow window() {
return window;
}
@Override
public TimeDomain timeDomain() {
return timeDomain;
}
@Override
public Context context(DoFn<InputT, OutputT> doFn) {
throw new UnsupportedOperationException("Context parameters are not supported.");
}
@Override
public ProcessContext processContext(DoFn<InputT, OutputT> doFn) {
throw new UnsupportedOperationException("ProcessContext parameters are not supported.");
}
@Override
public OnTimerContext onTimerContext(DoFn<InputT, OutputT> doFn) {
return this;
}
@Override
public RestrictionTracker<?> restrictionTracker() {
throw new UnsupportedOperationException("RestrictionTracker parameters are not supported.");
}
@Override
public State state(String stateId) {
try {
StateSpec<?, ?> spec =
(StateSpec<?, ?>) signature.stateDeclarations().get(stateId).field().get(fn);
return stepContext
.stateInternals()
.state(getNamespace(), StateTags.tagForSpec(stateId, (StateSpec) spec));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public Timer timer(String timerId) {
try {
TimerSpec spec =
(TimerSpec) signature.timerDeclarations().get(timerId).field().get(fn);
return new TimerInternalsTimer(
window, getNamespace(), allowedLateness, timerId, spec, stepContext.timerInternals());
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public PipelineOptions getPipelineOptions() {
return context.getPipelineOptions();
}
@Override
public void output(OutputT output) {
context.outputWithTimestamp(output, timestamp);
}
@Override
public void outputWithTimestamp(OutputT output, Instant timestamp) {
context.outputWithTimestamp(output, timestamp);
}
@Override
public <T> void sideOutput(TupleTag<T> tag, T output) {
context.sideOutputWithTimestamp(tag, output, timestamp);
}
@Override
public <T> void sideOutputWithTimestamp(TupleTag<T> tag, T output, Instant timestamp) {
context.sideOutputWithTimestamp(tag, output, timestamp);
}
@Override
protected <AggInputT, AggOutputT> Aggregator<AggInputT, AggOutputT> createAggregator(
String name,
CombineFn<AggInputT, ?, AggOutputT> combiner) {
throw new UnsupportedOperationException("Cannot createAggregator in @OnTimer method");
}
}
private static class TimerInternalsTimer implements Timer {
private final TimerInternals timerInternals;
// The window and the namespace represent the same thing, but the namespace is a cached
// and specially encoded form. Since the namespace can be cached across timers, it is
// passed in whole rather than being computed here.
private final BoundedWindow window;
private final Duration allowedLateness;
private final StateNamespace namespace;
private final String timerId;
private final TimerSpec spec;
public TimerInternalsTimer(
BoundedWindow window,
StateNamespace namespace,
Duration allowedLateness,
String timerId,
TimerSpec spec,
TimerInternals timerInternals) {
this.window = window;
this.allowedLateness = allowedLateness;
this.namespace = namespace;
this.timerId = timerId;
this.spec = spec;
this.timerInternals = timerInternals;
}
@Override
public void set(Instant target) {
verifyAbsoluteTimeDomain();
verifyTargetTime(target);
setUnderlyingTimer(target);
}
@Override
public void setForNowPlus(Duration durationFromNow) {
Instant target = getCurrentTime().plus(durationFromNow);
verifyTargetTime(target);
setUnderlyingTimer(target);
}
/**
* Ensures that the target time is reasonable. For event time timers this means that the
* time should be prior to window GC time.
*/
private void verifyTargetTime(Instant target) {
if (TimeDomain.EVENT_TIME.equals(spec.getTimeDomain())) {
Instant windowExpiry = window.maxTimestamp().plus(allowedLateness);
checkArgument(!target.isAfter(windowExpiry),
"Attempted to set event time timer for %s but that is after"
+ " the expiration of window %s", target, windowExpiry);
}
}
/** Verifies that the time domain of this timer is acceptable for absolute timers. */
private void verifyAbsoluteTimeDomain() {
if (!TimeDomain.EVENT_TIME.equals(spec.getTimeDomain())) {
throw new IllegalStateException(
"Cannot only set relative timers in processing time domain."
+ " Use #setForNowPlus(Duration)");
}
}
/**
* Sets the timer for the target time without checking anything about whether it is
* a reasonable thing to do. For example, absolute processing time timers are not
* really sensible since the user has no way to compute a good choice of time.
*/
private void setUnderlyingTimer(Instant target) {
timerInternals.setTimer(namespace, timerId, target, spec.getTimeDomain());
}
@Override
public void cancel() {
timerInternals.deleteTimer(namespace, timerId);
}
private Instant getCurrentTime() {
switch(spec.getTimeDomain()) {
case EVENT_TIME:
return timerInternals.currentInputWatermarkTime();
case PROCESSING_TIME:
return timerInternals.currentProcessingTime();
case SYNCHRONIZED_PROCESSING_TIME:
return timerInternals.currentSynchronizedProcessingTime();
default:
throw new IllegalStateException(
String.format("Timer created for unknown time domain %s", spec.getTimeDomain()));
}
}
}
}
| apache-2.0 |
JingchengDu/hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/converter/FSConfigToCSConfigRuleHandler.java | 9183 | /*
* 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.yarn.server.resourcemanager.scheduler.fair.converter;
import static java.lang.String.format;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.classification.VisibleForTesting;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.placement.schema.Rule.Policy;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairSchedulerConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class that determines what should happen if the FS->CS converter
* encounters a property that is currently not supported.
*
* Acceptable values are either "abort" or "warning".
*/
public class FSConfigToCSConfigRuleHandler {
private static final Logger LOG =
LoggerFactory.getLogger(FSConfigToCSConfigRuleHandler.class);
private ConversionOptions conversionOptions;
public static final String MAX_CHILD_QUEUE_LIMIT =
"maxChildQueue.limit";
public static final String MAX_CAPACITY_PERCENTAGE =
"maxCapacityPercentage.action";
public static final String MAX_CHILD_CAPACITY =
"maxChildCapacity.action";
public static final String MAX_RESOURCES =
"maxResources.action";
public static final String MIN_RESOURCES =
"minResources.action";
public static final String DYNAMIC_MAX_ASSIGN =
"dynamicMaxAssign.action";
public static final String RESERVATION_SYSTEM =
"reservationSystem.action";
public static final String QUEUE_AUTO_CREATE =
"queueAutoCreate.action";
public static final String FAIR_AS_DRF =
"fairAsDrf.action";
public static final String QUEUE_DYNAMIC_CREATE =
"queueDynamicCreate.action";
public static final String PARENT_DYNAMIC_CREATE =
"parentDynamicCreate.action";
public static final String CHILD_STATIC_DYNAMIC_CONFLICT =
"childStaticDynamicConflict.action";
public static final String PARENT_CHILD_CREATE_DIFFERS =
"parentChildCreateDiff.action";
@VisibleForTesting
enum RuleAction {
WARNING,
ABORT
}
private Map<String, RuleAction> actions;
private Properties properties;
void loadRulesFromFile(String ruleFile) throws IOException {
if (ruleFile == null) {
throw new IllegalArgumentException("Rule file cannot be null!");
}
properties = new Properties();
try (InputStream is = new FileInputStream(new File(ruleFile))) {
properties.load(is);
}
actions = new HashMap<>();
}
public FSConfigToCSConfigRuleHandler(ConversionOptions conversionOptions) {
this.properties = new Properties();
this.actions = new HashMap<>();
this.conversionOptions = conversionOptions;
}
@VisibleForTesting
FSConfigToCSConfigRuleHandler(Properties props,
ConversionOptions conversionOptions) {
this.properties = props;
this.actions = new HashMap<>();
this.conversionOptions = conversionOptions;
initPropertyActions();
}
public void initPropertyActions() {
setActionForProperty(MAX_CAPACITY_PERCENTAGE);
setActionForProperty(MAX_CHILD_CAPACITY);
setActionForProperty(MAX_RESOURCES);
setActionForProperty(MIN_RESOURCES);
setActionForProperty(DYNAMIC_MAX_ASSIGN);
setActionForProperty(RESERVATION_SYSTEM);
setActionForProperty(QUEUE_AUTO_CREATE);
setActionForProperty(FAIR_AS_DRF);
setActionForProperty(QUEUE_DYNAMIC_CREATE);
setActionForProperty(PARENT_DYNAMIC_CREATE);
setActionForProperty(CHILD_STATIC_DYNAMIC_CONFLICT);
setActionForProperty(PARENT_CHILD_CREATE_DIFFERS);
}
public void handleMaxCapacityPercentage(String queueName) {
handle(MAX_CAPACITY_PERCENTAGE, null,
format("<maxResources> defined in percentages for queue %s",
queueName));
}
public void handleMaxChildCapacity() {
handle(MAX_CHILD_CAPACITY, "<maxChildResources>", null);
}
public void handleMaxResources() {
handle(MAX_RESOURCES, "<maxResources>", null);
}
public void handleMinResources() {
handle(MIN_RESOURCES, "<minResources>", null);
}
public void handleChildQueueCount(String queue, int count) {
String value = properties.getProperty(MAX_CHILD_QUEUE_LIMIT);
if (value != null) {
if (StringUtils.isNumeric(value)) {
int maxChildQueue = Integer.parseInt(value);
if (count > maxChildQueue) {
throw new ConversionException(
format("Queue %s has too many children: %d", queue, count));
}
} else {
throw new ConversionException(
"Rule setting: maxChildQueue.limit is not an integer");
}
}
}
public void handleDynamicMaxAssign() {
handle(DYNAMIC_MAX_ASSIGN,
FairSchedulerConfiguration.DYNAMIC_MAX_ASSIGN, null);
}
public void handleReservationSystem() {
handle(RESERVATION_SYSTEM,
null,
"Conversion of reservation system is not supported");
}
public void handleFairAsDrf(String queueName) {
handle(FAIR_AS_DRF,
null,
format(
"Queue %s will use DRF policy instead of Fair",
queueName));
}
public void handleRuleAutoCreateFlag(String queue) {
String msg = format("Placement rules: create=true is enabled for"
+ " path %s - you have to make sure that these queues are"
+ " managed queues and set auto-create-child-queues=true."
+ " Other queues cannot statically exist under this path!", queue);
handle(QUEUE_DYNAMIC_CREATE, null, msg);
}
public void handleFSParentCreateFlag(String parentPath) {
String msg = format("Placement rules: create=true is enabled for parent"
+ " path %s - this is not supported in Capacity Scheduler."
+ " The parent must exist as a static queue and cannot be"
+ " created automatically", parentPath);
handle(PARENT_DYNAMIC_CREATE, null, msg);
}
public void handleChildStaticDynamicConflict(String parentPath) {
String msg = String.format("Placement rules: rule maps to"
+ " path %s, but this queue already contains static queue definitions!"
+ " This configuration is invalid and *must* be corrected", parentPath);
handle(CHILD_STATIC_DYNAMIC_CONFLICT, null, msg);
}
public void handleFSParentAndChildCreateFlagDiff(Policy policy) {
String msg = String.format("Placement rules: the policy %s originally uses"
+ " true/false or false/true \"create\" settings on the Fair Scheduler"
+ " side. This is not supported and create flag will be set"
+ " to *true* in the generated JSON rule chain", policy.name());
handle(PARENT_CHILD_CREATE_DIFFERS, null, msg);
}
private void handle(String actionName, String fsSetting, String message) {
RuleAction action = actions.get(actionName);
if (action != null) {
switch (action) {
case ABORT:
String exceptionMessage;
if (message != null) {
exceptionMessage = message;
} else {
exceptionMessage = format("Setting %s is not supported", fsSetting);
}
conversionOptions.handleError(exceptionMessage);
break;
case WARNING:
String loggedMsg = (message != null) ? message :
format("Setting %s is not supported, ignoring conversion",
fsSetting);
conversionOptions.handleWarning(loggedMsg, LOG);
break;
default:
throw new IllegalArgumentException(
"Unknown action " + action);
}
}
}
private void setActionForProperty(String property) {
String action = properties.getProperty(property);
if (action == null) {
LOG.info("No rule set for {}, defaulting to WARNING", property);
actions.put(property, RuleAction.WARNING);
} else if (action.equalsIgnoreCase("warning")) {
actions.put(property, RuleAction.WARNING);
} else if (action.equalsIgnoreCase("abort")) {
actions.put(property, RuleAction.ABORT);
} else {
LOG.warn("Unknown action {} set for rule {}, defaulting to WARNING",
action, property);
actions.put(property, RuleAction.WARNING);
}
}
@VisibleForTesting
public Map<String, RuleAction> getActions() {
return actions;
}
}
| apache-2.0 |
goodwinnk/intellij-community | platform/util/src/com/intellij/util/io/storage/RefCountingRecordsTable.java | 1900 | /*
* Copyright 2000-2009 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.util.io.storage;
import com.intellij.util.io.PagePool;
import java.io.File;
import java.io.IOException;
class RefCountingRecordsTable extends AbstractRecordsTable {
private static final int VERSION = 1;
private static final int REF_COUNT_OFFSET = DEFAULT_RECORD_SIZE;
private static final int RECORD_SIZE = REF_COUNT_OFFSET + 4;
private static final byte[] ZEROES = new byte[RECORD_SIZE];
RefCountingRecordsTable(File recordsFile, PagePool pool) throws IOException {
super(recordsFile, pool);
}
@Override
protected int getImplVersion() {
return VERSION;
}
@Override
protected int getRecordSize() {
return RECORD_SIZE;
}
@Override
protected byte[] getZeros() {
return ZEROES;
}
public void incRefCount(int record) {
markDirty();
int offset = getOffset(record, REF_COUNT_OFFSET);
myStorage.putInt(offset, myStorage.getInt(offset) + 1);
}
public boolean decRefCount(int record) {
markDirty();
int offset = getOffset(record, REF_COUNT_OFFSET);
int count = myStorage.getInt(offset);
assert count > 0;
count--;
myStorage.putInt(offset, count);
return count == 0;
}
public int getRefCount(int record) {
return myStorage.getInt(getOffset(record, REF_COUNT_OFFSET));
}
}
| apache-2.0 |
naver/pinpoint | web/src/main/java/com/navercorp/pinpoint/web/filter/transaction/WasToQueueFilter.java | 1045 | /*
* Copyright 2020 NAVER 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.
*/
package com.navercorp.pinpoint.web.filter.transaction;
import com.navercorp.pinpoint.common.server.bo.SpanEventBo;
import com.navercorp.pinpoint.web.filter.Filter;
/**
* WAS -> Queue (virtual)
* Should be the same as {@link WasToBackendFilter}
*/
public class WasToQueueFilter extends WasToBackendFilter {
public WasToQueueFilter(Filter<SpanEventBo> spanEventResponseConditionFilter) {
super(spanEventResponseConditionFilter);
}
}
| apache-2.0 |
andreagenso/java2scala | test/J2s/java/openjdk-6-src-b27/jdk/src/share/classes/java/util/FormattableFlags.java | 3006 | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util;
/**
* FomattableFlags are passed to the {@link Formattable#formatTo
* Formattable.formatTo()} method and modify the output format for {@linkplain
* Formattable Formattables}. Implementations of {@link Formattable} are
* responsible for interpreting and validating any flags.
*
* @since 1.5
*/
public class FormattableFlags {
// Explicit instantiation of this class is prohibited.
private FormattableFlags() {}
/**
* Left-justifies the output. Spaces (<tt>'\u0020'</tt>) will be added
* at the end of the converted value as required to fill the minimum width
* of the field. If this flag is not set then the output will be
* right-justified.
*
* <p> This flag corresponds to <tt>'-'</tt> (<tt>'\u002d'</tt>) in
* the format specifier.
*/
public static final int LEFT_JUSTIFY = 1<<0; // '-'
/**
* Converts the output to upper case according to the rules of the
* {@linkplain java.util.Locale locale} given during creation of the
* <tt>formatter</tt> argument of the {@link Formattable#formatTo
* formatTo()} method. The output should be equivalent the following
* invocation of {@link String#toUpperCase(java.util.Locale)}
*
* <pre>
* out.toUpperCase() </pre>
*
* <p> This flag corresponds to <tt>'^'</tt> (<tt>'\u005e'</tt>) in
* the format specifier.
*/
public static final int UPPERCASE = 1<<1; // '^'
/**
* Requires the output to use an alternate form. The definition of the
* form is specified by the <tt>Formattable</tt>.
*
* <p> This flag corresponds to <tt>'#'</tt> (<tt>'\u0023'</tt>) in
* the format specifier.
*/
public static final int ALTERNATE = 1<<2; // '#'
}
| apache-2.0 |
oscarceballos/flink-1.3.2 | flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/operators/windowing/functions/InternalProcessAllWindowContext.java | 1874 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.runtime.operators.windowing.functions;
import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.state.KeyedStateStore;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.Window;
/**
* Internal reusable context wrapper.
*
* @param <IN> The type of the input value.
* @param <OUT> The type of the output value.
* @param <W> The type of the window.
*/
@Internal
public class InternalProcessAllWindowContext<IN, OUT, W extends Window>
extends ProcessAllWindowFunction<IN, OUT, W>.Context {
W window;
InternalWindowFunction.InternalWindowContext internalContext;
InternalProcessAllWindowContext(ProcessAllWindowFunction<IN, OUT, W> function) {
function.super();
}
@Override
public W window() {
return window;
}
@Override
public KeyedStateStore windowState() {
return internalContext.windowState();
}
@Override
public KeyedStateStore globalState() {
return internalContext.globalState();
}
}
| apache-2.0 |
asedunov/intellij-community | plugins/xpath/xpath-lang/test/org/intellij/lang/xpath/xslt/Xslt2CompletionTest.java | 1413 | /*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.lang.xpath.xslt;
import org.intellij.lang.xpath.TestBase;
public class Xslt2CompletionTest extends TestBase {
public void testCustomFunctions() throws Throwable {
doXsltCompletion();
}
public void testTypeCompletion() throws Throwable {
doXsltCompletion();
}
public void testSchemaTypeCompletion() throws Throwable {
final String name = getTestFileName();
myFixture.testCompletionTyping(name + ".xsl", "\n", name + "_after.xsl");
}
private void doXsltCompletion(String... moreFiles) throws Throwable {
final String name = getTestFileName();
myFixture.testCompletion(name + ".xsl", name + "_after.xsl", moreFiles);
}
@Override
protected String getSubPath() {
return "xslt2/completion";
}
} | apache-2.0 |
winklerm/droolsjbpm-integration | kie-camel/src/test/java/org/kie/camel/embedded/camel/component/CamelEndpointWithMarshallersTest.java | 11197 | /*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* 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.
* under the License.
*/
package org.kie.camel.embedded.camel.component;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.DataFormatDefinition;
import org.drools.core.command.runtime.BatchExecutionCommandImpl;
import org.drools.core.command.runtime.rule.InsertObjectCommand;
import org.drools.core.common.InternalFactHandle;
import org.junit.Test;
import org.kie.api.command.Command;
import org.kie.api.runtime.ExecutionResults;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;
import org.kie.camel.embedded.component.KiePolicy;
import org.kie.internal.runtime.helper.BatchExecutionHelper;
import org.kie.pipeline.camel.Person;
public class CamelEndpointWithMarshallersTest extends KieCamelTestSupport {
private String handle;
@Test
public void testSimple() {
}
@Test
public void testSessionInsert() throws Exception {
String cmd = "";
cmd += "<batch-execution lookup=\"ksession1\">\n";
cmd += " <insert out-identifier=\"salaboy\">\n";
cmd += " <org.kie.pipeline.camel.Person>\n";
cmd += " <name>salaboy</name>\n";
cmd += " </org.kie.pipeline.camel.Person>\n";
cmd += " </insert>\n";
cmd += " <fire-all-rules/>\n";
cmd += "</batch-execution>\n";
String outXml = new String((byte[])template.requestBody("direct:test-with-session", cmd));
ExecutionResults result = (ExecutionResults) BatchExecutionHelper.newXStreamMarshaller().fromXML(outXml);
Person person = (Person)result.getValue("salaboy");
assertEquals("salaboy", person.getName());
String expectedXml = "";
expectedXml += "<?xml version='1.0' encoding='UTF-8'?><execution-results>";
expectedXml += "<result identifier=\"salaboy\">";
expectedXml += "<org.kie.pipeline.camel.Person>";
expectedXml += "<name>salaboy</name>";
expectedXml += "</org.kie.pipeline.camel.Person>";
expectedXml += "</result>";
expectedXml += "<fact-handle identifier=\"salaboy\" external-form=\"" + ((InternalFactHandle)result.getFactHandle("salaboy")).toExternalForm() + "\"/>";
expectedXml += "</execution-results>";
assertXMLEqual(expectedXml, outXml);
}
@Test
public void testJSonSessionInsert() throws Exception {
String inXml = "";
inXml += "{\"batch-execution\":{\"commands\":[";
inXml += "{\"insert\":{\"lookup\":\"ksession1\", ";
inXml += " \"object\":{\"org.kie.pipeline.camel.Person\":{\"name\":\"salaboy\"}}, \"out-identifier\":\"salaboy\" } }";
inXml += ", {\"fire-all-rules\":\"\"}";
inXml += "]}}";
String outXml = new String((byte[])template.requestBody("direct:test-with-session-json", inXml));
ExecutionResults result = (ExecutionResults) BatchExecutionHelper.newJSonMarshaller().fromXML(outXml);
Person person = (Person)result.getValue("salaboy");
assertEquals("salaboy", person.getName());
}
@Test
public void testNoSessionInsert() throws Exception {
String cmd = "";
cmd += "<batch-execution lookup=\"ksession1\">\n";
cmd += "<insert out-identifier=\"salaboy\">\n";
cmd += "<org.kie.pipeline.camel.Person>\n";
cmd += "<name>salaboy</name>\n";
cmd += "</org.kie.pipeline.camel.Person>\n";
cmd += "</insert>\n";
cmd += "<fire-all-rules/>\n";
cmd += "</batch-execution>\n";
String outXml = new String((byte[])template.requestBody("direct:test-no-session", cmd));
ExecutionResults result = (ExecutionResults) BatchExecutionHelper.newXStreamMarshaller().fromXML(outXml);
Person person = (Person)result.getValue("salaboy");
assertEquals("salaboy", person.getName());
String expectedXml = "";
expectedXml += "<?xml version='1.0' encoding='UTF-8'?><execution-results>";
expectedXml += "<result identifier=\"salaboy\">";
expectedXml += "<org.kie.pipeline.camel.Person>";
expectedXml += "<name>salaboy</name>";
expectedXml += "</org.kie.pipeline.camel.Person>";
expectedXml += "</result>";
expectedXml += "<fact-handle identifier=\"salaboy\" external-form=\"" + ((InternalFactHandle)result.getFactHandle("salaboy")).toExternalForm() + "\"/>";
expectedXml += "</execution-results>";
assertXMLEqual(expectedXml, outXml);
}
@Test
public void testNoSessionInsertCustomXstream() throws Exception {
String cmd = "";
cmd += "<batch-execution lookup=\"ksession1\">\n";
cmd += "<insert out-identifier=\"salaboy\">\n";
cmd += "<org.kie.pipeline.camel.Person name=\"salaboy\">\n";
cmd += "</org.kie.pipeline.camel.Person>\n";
cmd += "</insert>\n";
cmd += "<fire-all-rules/>\n";
cmd += "</batch-execution>\n";
String outXml = new String((byte[])template.requestBody("direct:test-no-session-custom", cmd));
XStream xstream = BatchExecutionHelper.newXStreamMarshaller();
PersonConverter converter = new PersonConverter();
xstream.registerConverter(converter);
ExecutionResults result = (ExecutionResults)xstream.fromXML(outXml);
Person person = (Person)result.getValue("salaboy");
assertEquals("salaboy", person.getName());
String expectedXml = "";
expectedXml += "<?xml version='1.0' encoding='UTF-8'?><execution-results>";
expectedXml += "<result identifier=\"salaboy\">";
expectedXml += "<org.kie.pipeline.camel.Person name=\"salaboy\"/>";
expectedXml += "</result>";
expectedXml += "<fact-handle identifier=\"salaboy\" external-form=\"" + ((InternalFactHandle)result.getFactHandle("salaboy")).toExternalForm() + "\"/>";
expectedXml += "</execution-results>";
assertXMLEqual(expectedXml, outXml);
}
@Test
public void testSessionGetObject() throws Exception {
String cmd = "";
cmd += "<batch-execution lookup=\"ksession1\">\n";
cmd += "<get-object out-identifier=\"rider\" fact-handle=\"" + this.handle + "\"/>\n";
cmd += "</batch-execution>\n";
String outXml = new String((byte[])template.requestBody("direct:test-with-session", cmd));
ExecutionResults result = (ExecutionResults) BatchExecutionHelper.newXStreamMarshaller().fromXML(outXml);
Person person = (Person)result.getValue("rider");
assertEquals("Hadrian", person.getName());
String expectedXml = "";
expectedXml += "<?xml version='1.0' encoding='UTF-8'?><execution-results>";
expectedXml += "<result identifier=\"rider\">";
expectedXml += "<org.kie.pipeline.camel.Person>";
expectedXml += "<name>Hadrian</name>";
expectedXml += "</org.kie.pipeline.camel.Person>";
expectedXml += "</result>";
expectedXml += "</execution-results>";
assertXMLEqual(expectedXml, outXml);
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
org.apache.camel.model.dataformat.XStreamDataFormat xstreamDataFormat = new org.apache.camel.model.dataformat.XStreamDataFormat();
xstreamDataFormat.setConverters(Arrays.asList(new String[] {PersonConverter.class.getName()}));
Map<String, DataFormatDefinition> dataFormats = new HashMap<String, DataFormatDefinition>();
dataFormats.put("custom-xstream", xstreamDataFormat);
getContext().setDataFormats(dataFormats);
from("direct:test-with-session").policy(new KiePolicy()).unmarshal("xstream").to("kie-local:ksession1").marshal("xstream");
from("direct:test-with-session-json").policy(new KiePolicy()).unmarshal("json").to("kie-local:ksession1").marshal("json");
from("direct:test-no-session").policy(new KiePolicy()).unmarshal("xstream").to("kie-local:dynamic").marshal("xstream");
from("direct:test-no-session-custom").policy(new KiePolicy()).unmarshal("custom-xstream").to("kie-local:dynamic").marshal("custom-xstream");
}
};
}
@Override
protected void configureDroolsContext(javax.naming.Context jndiContext) {
Person me = new Person();
me.setName("Hadrian");
KieSession ksession = registerKnowledgeRuntime("ksession1", null);
InsertObjectCommand cmd = new InsertObjectCommand(me);
cmd.setOutIdentifier("camel-rider");
cmd.setReturnObject(false);
BatchExecutionCommandImpl script = new BatchExecutionCommandImpl(Arrays.asList(new Command<?>[] {cmd}));
ExecutionResults results = ksession.execute(script);
handle = ((FactHandle)results.getFactHandle("camel-rider")).toExternalForm();
}
public static class PersonConverter implements Converter {
public PersonConverter() {
}
public void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext context) {
Person p = (Person)object;
writer.addAttribute("name", p.getName());
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
Person p = new Person(reader.getAttribute("name"));
return p;
}
public boolean canConvert(Class clazz) {
return clazz.equals(Person.class);
}
}
}
| apache-2.0 |
abdullah38rcc/closure-compiler | test/com/google/javascript/jscomp/TypedScopeCreatorTest.java | 57667 | /*
* Copyright 2009 The Closure Compiler 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.javascript.jscomp;
import static com.google.javascript.jscomp.TypedScopeCreator.CTOR_INITIALIZER;
import static com.google.javascript.jscomp.TypedScopeCreator.IFACE_INITIALIZER;
import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.NodeTraversal.Callback;
import com.google.javascript.jscomp.Scope.Var;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.EnumType;
import com.google.javascript.rhino.jstype.FunctionType;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.JSTypeNative;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import com.google.javascript.rhino.jstype.ObjectType;
import com.google.javascript.rhino.testing.Asserts;
import java.util.Deque;
/**
* Tests for {@link TypedScopeCreator} and {@link TypeInference}. Admittedly,
* the name is a bit of a misnomer.
* @author nicksantos@google.com (Nick Santos)
*/
public class TypedScopeCreatorTest extends CompilerTestCase {
private JSTypeRegistry registry;
private Scope globalScope;
private Scope lastLocalScope;
@Override
public int getNumRepetitions() {
return 1;
}
private final Callback callback = new AbstractPostOrderCallback() {
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
Scope s = t.getScope();
if (s.isGlobal()) {
globalScope = s;
} else {
lastLocalScope = s;
}
}
};
@Override
public CompilerPass getProcessor(final Compiler compiler) {
registry = compiler.getTypeRegistry();
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
MemoizedScopeCreator scopeCreator =
new MemoizedScopeCreator(new TypedScopeCreator(compiler));
Scope topScope = scopeCreator.createScope(root.getParent(), null);
(new TypeInferencePass(
compiler, compiler.getReverseAbstractInterpreter(),
topScope, scopeCreator)).process(externs, root);
NodeTraversal t = new NodeTraversal(
compiler, callback, scopeCreator);
t.traverseRoots(Lists.newArrayList(externs, root));
}
};
}
public void testStubProperty() {
testSame("function Foo() {}; Foo.bar;");
ObjectType foo = (ObjectType) globalScope.getVar("Foo").getType();
assertFalse(foo.hasProperty("bar"));
Asserts.assertTypeEquals(registry.getNativeType(UNKNOWN_TYPE),
foo.getPropertyType("bar"));
Asserts.assertTypeCollectionEquals(
Lists.newArrayList(foo), registry.getTypesWithProperty("bar"));
}
public void testConstructorProperty() {
testSame("var foo = {}; /** @constructor */ foo.Bar = function() {};");
ObjectType foo = (ObjectType) findNameType("foo", globalScope);
assertTrue(foo.hasProperty("Bar"));
assertFalse(foo.isPropertyTypeInferred("Bar"));
JSType fooBar = foo.getPropertyType("Bar");
assertEquals("function (new:foo.Bar): undefined", fooBar.toString());
Asserts.assertTypeCollectionEquals(
Lists.newArrayList(foo), registry.getTypesWithProperty("Bar"));
}
public void testPrototypePropertyMethodWithoutAnnotation() {
testSame("var Foo = function Foo() {};" +
"var proto = Foo.prototype = {" +
" bar: function(a, b){}" +
"};" +
"proto.baz = function(c) {};" +
"(function() { proto.baz = function() {}; })();");
ObjectType foo = (ObjectType) findNameType("Foo", globalScope);
assertTrue(foo.hasProperty("prototype"));
ObjectType fooProto = (ObjectType) foo.getPropertyType("prototype");
assertTrue(fooProto.hasProperty("bar"));
assertEquals("function (?, ?): undefined",
fooProto.getPropertyType("bar").toString());
assertTrue(fooProto.hasProperty("baz"));
assertEquals("function (?): undefined",
fooProto.getPropertyType("baz").toString());
}
public void testEnumProperty() {
testSame("var foo = {}; /** @enum */ foo.Bar = {XXX: 'xxx'};");
ObjectType foo = (ObjectType) findNameType("foo", globalScope);
assertTrue(foo.hasProperty("Bar"));
assertFalse(foo.isPropertyTypeInferred("Bar"));
assertTrue(foo.isPropertyTypeDeclared("Bar"));
JSType fooBar = foo.getPropertyType("Bar");
assertEquals("enum{foo.Bar}", fooBar.toString());
Asserts.assertTypeCollectionEquals(
Lists.newArrayList(foo), registry.getTypesWithProperty("Bar"));
}
public void testInferredProperty1() {
testSame("var foo = {}; foo.Bar = 3;");
ObjectType foo = (ObjectType) findNameType("foo", globalScope);
assertTrue(foo.toString(), foo.hasProperty("Bar"));
assertEquals("number", foo.getPropertyType("Bar").toString());
assertTrue(foo.isPropertyTypeInferred("Bar"));
}
public void testInferredProperty1a() {
testSame("var foo = {}; /** @type {number} */ foo.Bar = 3;");
ObjectType foo = (ObjectType) findNameType("foo", globalScope);
assertTrue(foo.toString(), foo.hasProperty("Bar"));
assertEquals("number", foo.getPropertyType("Bar").toString());
assertFalse(foo.isPropertyTypeInferred("Bar"));
}
public void testInferredProperty2() {
testSame("var foo = { Bar: 3 };");
ObjectType foo = (ObjectType) findNameType("foo", globalScope);
assertTrue(foo.toString(), foo.hasProperty("Bar"));
assertEquals("number", foo.getPropertyType("Bar").toString());
assertTrue(foo.isPropertyTypeInferred("Bar"));
}
public void testInferredProperty2b() {
testSame("var foo = { /** @type {number} */ Bar: 3 };");
ObjectType foo = (ObjectType) findNameType("foo", globalScope);
assertTrue(foo.toString(), foo.hasProperty("Bar"));
assertEquals("number", foo.getPropertyType("Bar").toString());
assertFalse(foo.isPropertyTypeInferred("Bar"));
}
public void testInferredProperty2c() {
testSame("var foo = { /** @return {number} */ Bar: 3 };");
ObjectType foo = (ObjectType) findNameType("foo", globalScope);
assertTrue(foo.toString(), foo.hasProperty("Bar"));
assertEquals("function (): number", foo.getPropertyType("Bar").toString());
assertFalse(foo.isPropertyTypeInferred("Bar"));
}
public void testInferredProperty3() {
testSame("var foo = { /** @type {number} */ get Bar() { return 3 } };");
ObjectType foo = (ObjectType) findNameType("foo", globalScope);
assertTrue(foo.toString(), foo.hasProperty("Bar"));
assertEquals("?", foo.getPropertyType("Bar").toString());
assertTrue(foo.isPropertyTypeInferred("Bar"));
}
public void testInferredProperty4() {
testSame("var foo = { /** @type {number} */ set Bar(a) {} };");
ObjectType foo = (ObjectType) findNameType("foo", globalScope);
assertTrue(foo.toString(), foo.hasProperty("Bar"));
assertEquals("?", foo.getPropertyType("Bar").toString());
assertTrue(foo.isPropertyTypeInferred("Bar"));
}
public void testInferredProperty5() {
testSame("var foo = { /** @return {number} */ get Bar() { return 3 } };");
ObjectType foo = (ObjectType) findNameType("foo", globalScope);
assertTrue(foo.toString(), foo.hasProperty("Bar"));
assertEquals("number", foo.getPropertyType("Bar").toString());
assertFalse(foo.isPropertyTypeInferred("Bar"));
}
public void testInferredProperty6() {
testSame("var foo = { /** @param {number} a */ set Bar(a) {} };");
ObjectType foo = (ObjectType) findNameType("foo", globalScope);
assertTrue(foo.toString(), foo.hasProperty("Bar"));
assertEquals("number", foo.getPropertyType("Bar").toString());
assertFalse(foo.isPropertyTypeInferred("Bar"));
}
public void testPrototypeInit() {
testSame("/** @constructor */ var Foo = function() {};" +
"Foo.prototype = {bar: 1}; var foo = new Foo();");
ObjectType foo = (ObjectType) findNameType("foo", globalScope);
assertTrue(foo.hasProperty("bar"));
assertEquals("number", foo.getPropertyType("bar").toString());
assertTrue(foo.isPropertyTypeInferred("bar"));
}
public void testBogusPrototypeInit() {
// This used to cause a compiler crash.
testSame("/** @const */ var goog = {}; " +
"goog.F = {}; /** @const */ goog.F.prototype = {};" +
"/** @constructor */ goog.F = function() {};");
}
public void testInferredPrototypeProperty1() {
testSame("/** @constructor */ var Foo = function() {};" +
"Foo.prototype.bar = 1; var x = new Foo();");
ObjectType x = (ObjectType) findNameType("x", globalScope);
assertTrue(x.hasProperty("bar"));
assertEquals("number", x.getPropertyType("bar").toString());
assertTrue(x.isPropertyTypeInferred("bar"));
}
public void testInferredPrototypeProperty2() {
testSame("/** @constructor */ var Foo = function() {};" +
"Foo.prototype = {bar: 1}; var x = new Foo();");
ObjectType x = (ObjectType) findNameType("x", globalScope);
assertTrue(x.hasProperty("bar"));
assertEquals("number", x.getPropertyType("bar").toString());
assertTrue(x.isPropertyTypeInferred("bar"));
}
public void testEnum() {
testSame("/** @enum */ var Foo = {BAR: 1}; var f = Foo;");
ObjectType f = (ObjectType) findNameType("f", globalScope);
assertTrue(f.hasProperty("BAR"));
assertEquals("Foo.<number>", f.getPropertyType("BAR").toString());
assertTrue(f instanceof EnumType);
}
public void testEnumElement() {
testSame("/** @enum */ var Foo = {BAR: 1}; var f = Foo;");
Var bar = globalScope.getVar("Foo.BAR");
assertNotNull(bar);
assertEquals("Foo.<number>", bar.getType().toString());
}
public void testNamespacedEnum() {
testSame("var goog = {}; goog.ui = {};" +
"/** @constructor */goog.ui.Zippy = function() {};" +
"/** @enum{string} */goog.ui.Zippy.EventType = { TOGGLE: 'toggle' };" +
"var x = goog.ui.Zippy.EventType;" +
"var y = goog.ui.Zippy.EventType.TOGGLE;");
ObjectType x = (ObjectType) findNameType("x", globalScope);
assertTrue(x.isEnumType());
assertTrue(x.hasProperty("TOGGLE"));
assertEquals("enum{goog.ui.Zippy.EventType}", x.getReferenceName());
ObjectType y = (ObjectType) findNameType("y", globalScope);
assertTrue(y.isSubtype(getNativeType(STRING_TYPE)));
assertTrue(y.isEnumElementType());
assertEquals("goog.ui.Zippy.EventType", y.getReferenceName());
}
public void testEnumAlias() {
testSame("/** @enum */ var Foo = {BAR: 1}; " +
"/** @enum */ var FooAlias = Foo; var f = FooAlias;");
assertEquals("Foo.<number>",
registry.getType("FooAlias").toString());
Asserts.assertTypeEquals(registry.getType("FooAlias"),
registry.getType("Foo"));
ObjectType f = (ObjectType) findNameType("f", globalScope);
assertTrue(f.hasProperty("BAR"));
assertEquals("Foo.<number>", f.getPropertyType("BAR").toString());
assertTrue(f instanceof EnumType);
}
public void testNamespacesEnumAlias() {
testSame("var goog = {}; /** @enum */ goog.Foo = {BAR: 1}; " +
"/** @enum */ goog.FooAlias = goog.Foo;");
assertEquals("goog.Foo.<number>",
registry.getType("goog.FooAlias").toString());
Asserts.assertTypeEquals(registry.getType("goog.Foo"),
registry.getType("goog.FooAlias"));
}
public void testCollectedFunctionStub() {
testSame(
"/** @constructor */ function f() { " +
" /** @return {number} */ this.foo;" +
"}" +
"var x = new f();");
ObjectType x = (ObjectType) findNameType("x", globalScope);
assertEquals("f", x.toString());
assertTrue(x.hasProperty("foo"));
assertEquals("function (this:f): number",
x.getPropertyType("foo").toString());
assertFalse(x.isPropertyTypeInferred("foo"));
}
public void testCollectedFunctionStubLocal() {
testSame(
"(function() {" +
"/** @constructor */ function f() { " +
" /** @return {number} */ this.foo;" +
"}" +
"var x = new f();" +
"});");
ObjectType x = (ObjectType) findNameType("x", lastLocalScope);
assertEquals("f", x.toString());
assertTrue(x.hasProperty("foo"));
assertEquals("function (this:f): number",
x.getPropertyType("foo").toString());
assertFalse(x.isPropertyTypeInferred("foo"));
}
public void testNamespacedFunctionStub() {
testSame(
"var goog = {};" +
"/** @param {number} x */ goog.foo;");
ObjectType goog = (ObjectType) findNameType("goog", globalScope);
assertTrue(goog.hasProperty("foo"));
assertEquals("function (number): ?",
goog.getPropertyType("foo").toString());
assertTrue(goog.isPropertyTypeDeclared("foo"));
Asserts.assertTypeEquals(globalScope.getVar("goog.foo").getType(),
goog.getPropertyType("foo"));
}
public void testNamespacedFunctionStubLocal() {
testSame(
"(function() {" +
"var goog = {};" +
"/** @param {number} x */ goog.foo;" +
"});");
ObjectType goog = (ObjectType) findNameType("goog", lastLocalScope);
assertTrue(goog.hasProperty("foo"));
assertEquals("function (number): ?",
goog.getPropertyType("foo").toString());
assertTrue(goog.isPropertyTypeDeclared("foo"));
Asserts.assertTypeEquals(lastLocalScope.getVar("goog.foo").getType(),
goog.getPropertyType("foo"));
}
public void testCollectedCtorProperty() {
testSame(
"/** @constructor */ function f() { " +
" /** @type {number} */ this.foo = 3;" +
"}" +
"var x = new f();");
ObjectType x = (ObjectType) findNameType("x", globalScope);
assertEquals("f", x.toString());
assertTrue(x.hasProperty("foo"));
assertEquals("number", x.getPropertyType("foo").toString());
assertFalse(x.isPropertyTypeInferred("foo"));
}
public void testPropertyOnUnknownSuperClass1() {
testSame(
"var goog = this.foo();" +
"/** @constructor \n * @extends {goog.Unknown} */" +
"function Foo() {}" +
"Foo.prototype.bar = 1;" +
"var x = new Foo();",
RhinoErrorReporter.TYPE_PARSE_ERROR);
ObjectType x = (ObjectType) findNameType("x", globalScope);
assertEquals("Foo", x.toString());
assertTrue(x.getImplicitPrototype().hasOwnProperty("bar"));
assertEquals("?", x.getPropertyType("bar").toString());
assertTrue(x.isPropertyTypeInferred("bar"));
}
public void testPropertyOnUnknownSuperClass2() {
testSame(
"var goog = this.foo();" +
"/** @constructor \n * @extends {goog.Unknown} */" +
"function Foo() {}" +
"Foo.prototype = {bar: 1};" +
"var x = new Foo();",
RhinoErrorReporter.TYPE_PARSE_ERROR);
ObjectType x = (ObjectType) findNameType("x", globalScope);
assertEquals("Foo", x.toString());
assertEquals("Foo.prototype", x.getImplicitPrototype().toString());
assertTrue(x.getImplicitPrototype().hasOwnProperty("bar"));
assertEquals("?", x.getPropertyType("bar").toString());
assertTrue(x.isPropertyTypeInferred("bar"));
}
public void testMethodBeforeFunction1() throws Exception {
testSame(
"var y = Window.prototype;" +
"Window.prototype.alert = function(message) {};" +
"/** @constructor */ function Window() {}\n" +
"var window = new Window(); \n" +
"var x = window;");
ObjectType x = (ObjectType) findNameType("x", globalScope);
assertEquals("Window", x.toString());
assertTrue(x.getImplicitPrototype().hasOwnProperty("alert"));
assertEquals("function (this:Window, ?): undefined",
x.getPropertyType("alert").toString());
assertTrue(x.isPropertyTypeDeclared("alert"));
ObjectType y = (ObjectType) findNameType("y", globalScope);
assertEquals("function (this:Window, ?): undefined",
y.getPropertyType("alert").toString());
}
public void testMethodBeforeFunction2() throws Exception {
testSame(
"var y = Window.prototype;" +
"Window.prototype = {alert: function(message) {}};" +
"/** @constructor */ function Window() {}\n" +
"var window = new Window(); \n" +
"var x = window;");
ObjectType x = (ObjectType) findNameType("x", globalScope);
assertEquals("Window", x.toString());
assertTrue(x.getImplicitPrototype().hasOwnProperty("alert"));
assertEquals("function (this:Window, ?): undefined",
x.getPropertyType("alert").toString());
assertFalse(x.isPropertyTypeDeclared("alert"));
ObjectType y = (ObjectType) findNameType("y", globalScope);
assertEquals("?",
y.getPropertyType("alert").toString());
}
public void testAddMethodsPrototypeTwoWays() throws Exception {
testSame(
"/** @constructor */function A() {}" +
"A.prototype = {m1: 5, m2: true};" +
"A.prototype.m3 = 'third property!';" +
"var x = new A();");
ObjectType instanceType = (ObjectType) findNameType("x", globalScope);
assertEquals(
getNativeObjectType(OBJECT_TYPE).getPropertiesCount() + 3,
instanceType.getPropertiesCount());
Asserts.assertTypeEquals(getNativeType(NUMBER_TYPE),
instanceType.getPropertyType("m1"));
Asserts.assertTypeEquals(getNativeType(BOOLEAN_TYPE),
instanceType.getPropertyType("m2"));
Asserts.assertTypeEquals(getNativeType(STRING_TYPE),
instanceType.getPropertyType("m3"));
// Verify the prototype chain.
// This is a special case where we want the anonymous object to
// become a prototype.
assertFalse(instanceType.hasOwnProperty("m1"));
assertFalse(instanceType.hasOwnProperty("m2"));
assertFalse(instanceType.hasOwnProperty("m3"));
ObjectType proto1 = instanceType.getImplicitPrototype();
assertTrue(proto1.hasOwnProperty("m1"));
assertTrue(proto1.hasOwnProperty("m2"));
assertTrue(proto1.hasOwnProperty("m3"));
ObjectType proto2 = proto1.getImplicitPrototype();
assertFalse(proto2.hasProperty("m1"));
assertFalse(proto2.hasProperty("m2"));
assertFalse(proto2.hasProperty("m3"));
}
public void testInferredVar() throws Exception {
testSame("var x = 3; x = 'x'; x = true;");
Var x = globalScope.getVar("x");
assertEquals("(boolean|number|string)", x.getType().toString());
assertTrue(x.isTypeInferred());
}
public void testDeclaredVar() throws Exception {
testSame("/** @type {?number} */ var x = 3; var y = x;");
Var x = globalScope.getVar("x");
assertEquals("(null|number)", x.getType().toString());
assertFalse(x.isTypeInferred());
JSType y = findNameType("y", globalScope);
assertEquals("(null|number)", y.toString());
}
public void testPropertiesOnInterface() throws Exception {
testSame("/** @interface */ var I = function() {};" +
"/** @type {number} */ I.prototype.bar;" +
"I.prototype.baz = function(){};");
Var i = globalScope.getVar("I");
assertEquals("function (this:I): ?", i.getType().toString());
assertTrue(i.getType().isInterface());
ObjectType iPrototype = (ObjectType)
((ObjectType) i.getType()).getPropertyType("prototype");
assertEquals("I.prototype", iPrototype.toString());
assertTrue(iPrototype.isFunctionPrototypeType());
assertEquals("number", iPrototype.getPropertyType("bar").toString());
assertEquals("function (this:I): undefined",
iPrototype.getPropertyType("baz").toString());
Asserts.assertTypeEquals(iPrototype, globalScope.getVar("I.prototype").getType());
}
public void testPropertiesOnInterface2() throws Exception {
testSame("/** @interface */ var I = function() {};" +
"I.prototype = {baz: function(){}};" +
"/** @type {number} */ I.prototype.bar;");
Var i = globalScope.getVar("I");
assertEquals("function (this:I): ?", i.getType().toString());
assertTrue(i.getType().isInterface());
ObjectType iPrototype = (ObjectType)
((ObjectType) i.getType()).getPropertyType("prototype");
assertEquals("I.prototype", iPrototype.toString());
assertTrue(iPrototype.isFunctionPrototypeType());
assertEquals("number", iPrototype.getPropertyType("bar").toString());
assertEquals("function (this:I): undefined",
iPrototype.getPropertyType("baz").toString());
// should not be null
assertNull(globalScope.getVar("I.prototype"));
// assertEquals(iPrototype, globalScope.getVar("I.prototype").getType());
}
// TODO(johnlenz): A syntax for stubs using object literals?
public void testStubsInExterns() {
testSame(
"/** @constructor */ function Extern() {}" +
"Extern.prototype.bar;" +
"var e = new Extern(); e.baz;",
"/** @constructor */ function Foo() {}" +
"Foo.prototype.bar;" +
"var f = new Foo(); f.baz;", null);
ObjectType e = (ObjectType) globalScope.getVar("e").getType();
assertEquals("?", e.getPropertyType("bar").toString());
assertEquals("?", e.getPropertyType("baz").toString());
ObjectType f = (ObjectType) globalScope.getVar("f").getType();
assertEquals("?", f.getPropertyType("bar").toString());
assertFalse(f.hasProperty("baz"));
}
public void testStubsInExterns2() {
testSame(
"/** @constructor */ function Extern() {}" +
"/** @type {Extern} */ var myExtern;" +
"/** @type {number} */ myExtern.foo;",
"", null);
JSType e = globalScope.getVar("myExtern").getType();
assertEquals("(Extern|null)", e.toString());
ObjectType externType = (ObjectType) e.restrictByNotNullOrUndefined();
assertTrue(globalScope.getRootNode().toStringTree(),
externType.hasOwnProperty("foo"));
assertTrue(externType.isPropertyTypeDeclared("foo"));
assertEquals("number", externType.getPropertyType("foo").toString());
assertTrue(externType.isPropertyInExterns("foo"));
}
public void testStubsInExterns3() {
testSame(
"/** @type {number} */ myExtern.foo;" +
"/** @type {Extern} */ var myExtern;" +
"/** @constructor */ function Extern() {}",
"", null);
JSType e = globalScope.getVar("myExtern").getType();
assertEquals("(Extern|null)", e.toString());
ObjectType externType = (ObjectType) e.restrictByNotNullOrUndefined();
assertTrue(globalScope.getRootNode().toStringTree(),
externType.hasOwnProperty("foo"));
assertTrue(externType.isPropertyTypeDeclared("foo"));
assertEquals("number", externType.getPropertyType("foo").toString());
assertTrue(externType.isPropertyInExterns("foo"));
}
public void testStubsInExterns4() {
testSame(
"Extern.prototype.foo;" +
"/** @constructor */ function Extern() {}",
"", null);
JSType e = globalScope.getVar("Extern").getType();
assertEquals("function (new:Extern): ?", e.toString());
ObjectType externProto = ((FunctionType) e).getPrototype();
assertTrue(globalScope.getRootNode().toStringTree(),
externProto.hasOwnProperty("foo"));
assertTrue(externProto.isPropertyTypeInferred("foo"));
assertEquals("?", externProto.getPropertyType("foo").toString());
assertTrue(externProto.isPropertyInExterns("foo"));
}
public void testPropertyInExterns1() {
testSame(
"/** @constructor */ function Extern() {}" +
"/** @type {Extern} */ var extern;" +
"/** @return {number} */ extern.one;",
"/** @constructor */ function Normal() {}" +
"/** @type {Normal} */ var normal;" +
"/** @return {number} */ normal.one;", null);
JSType e = globalScope.getVar("Extern").getType();
ObjectType externInstance = ((FunctionType) e).getInstanceType();
assertTrue(externInstance.hasOwnProperty("one"));
assertTrue(externInstance.isPropertyTypeDeclared("one"));
assertEquals("function (): number",
externInstance.getPropertyType("one").toString());
JSType n = globalScope.getVar("Normal").getType();
ObjectType normalInstance = ((FunctionType) n).getInstanceType();
assertFalse(normalInstance.hasOwnProperty("one"));
}
public void testPropertyInExterns2() {
testSame(
"/** @type {Object} */ var extern;" +
"/** @return {number} */ extern.one;",
"/** @type {Object} */ var normal;" +
"/** @return {number} */ normal.one;", null);
JSType e = globalScope.getVar("extern").getType();
assertFalse(e.dereference().hasOwnProperty("one"));
JSType normal = globalScope.getVar("normal").getType();
assertFalse(normal.dereference().hasOwnProperty("one"));
}
public void testPropertyInExterns3() {
testSame(
"/** @constructor \n * @param {*=} x */ function Object(x) {}" +
"/** @type {number} */ Object.one;", "", null);
ObjectType obj = globalScope.getVar("Object").getType().dereference();
assertTrue(obj.hasOwnProperty("one"));
assertEquals("number", obj.getPropertyType("one").toString());
}
public void testTypedStubsInExterns() {
testSame(
"/** @constructor \n * @param {*} var_args */ " +
"function Function(var_args) {}" +
"/** @type {!Function} */ Function.prototype.apply;",
"var f = new Function();", null);
ObjectType f = (ObjectType) globalScope.getVar("f").getType();
// The type of apply() on a function instance is resolved dynamically,
// since apply varies with the type of the function it's called on.
assertEquals(
"function (?=, (Object|null)=): ?",
f.getPropertyType("apply").toString());
// The type of apply() on the function prototype just takes what it was
// declared with.
FunctionType func = (FunctionType) globalScope.getVar("Function").getType();
assertEquals("Function",
func.getPrototype().getPropertyType("apply").toString());
}
public void testTypesInExterns() throws Exception {
testSame(
CompilerTypeTestCase.DEFAULT_EXTERNS,
"", null);
Var v = globalScope.getVar("Object");
FunctionType obj = (FunctionType) v.getType();
assertEquals("function (new:Object, *=): ?", obj.toString());
assertNotNull(v.getNode());
assertNotNull(v.input);
}
public void testPropertyDeclarationOnInstanceType() {
testSame(
"/** @type {!Object} */ var a = {};" +
"/** @type {number} */ a.name = 0;");
assertEquals("number", globalScope.getVar("a.name").getType().toString());
ObjectType a = (ObjectType) (globalScope.getVar("a").getType());
assertFalse(a.hasProperty("name"));
assertFalse(getNativeObjectType(OBJECT_TYPE).hasProperty("name"));
}
public void testPropertyDeclarationOnRecordType() {
testSame(
"/** @type {{foo: number}} */ var a = {foo: 3};" +
"/** @type {number} */ a.name = 0;");
assertEquals("number", globalScope.getVar("a.name").getType().toString());
ObjectType a = (ObjectType) (globalScope.getVar("a").getType());
assertEquals("{foo: number}", a.toString());
assertFalse(a.hasProperty("name"));
}
public void testGlobalThis1() {
testSame(
"/** @constructor */ function Window() {}" +
"Window.prototype.alert = function() {};" +
"var x = this;");
ObjectType x = (ObjectType) (globalScope.getVar("x").getType());
FunctionType windowCtor =
(FunctionType) (globalScope.getVar("Window").getType());
assertEquals("global this", x.toString());
assertTrue(x.isSubtype(windowCtor.getInstanceType()));
assertFalse(x.isEquivalentTo(windowCtor.getInstanceType()));
assertTrue(x.hasProperty("alert"));
}
public void testGlobalThis2() {
testSame(
"/** @constructor */ function Window() {}" +
"Window.prototype = {alert: function() {}};" +
"var x = this;");
ObjectType x = (ObjectType) (globalScope.getVar("x").getType());
FunctionType windowCtor =
(FunctionType) (globalScope.getVar("Window").getType());
assertEquals("global this", x.toString());
assertTrue(x.isSubtype(windowCtor.getInstanceType()));
assertFalse(x.isEquivalentTo(windowCtor.getInstanceType()));
assertTrue(x.hasProperty("alert"));
}
public void testObjectLiteralCast() {
// Verify that "goog.reflect.object" does not modify the types on
// "A.B"
testSame("/** @constructor */ A.B = function() {}\n" +
"A.B.prototype.isEnabled = true;\n" +
"goog.reflect.object(A.B, {isEnabled: 3})\n" +
"var x = (new A.B()).isEnabled;");
assertEquals("A.B",
findTokenType(Token.OBJECTLIT, globalScope).toString());
assertEquals("boolean",
findNameType("x", globalScope).toString());
}
public void testBadObjectLiteralCast1() {
testSame("/** @constructor */ A.B = function() {}\n" +
"goog.reflect.object(A.B, 1)",
ClosureCodingConvention.OBJECTLIT_EXPECTED);
}
public void testBadObjectLiteralCast2() {
testSame("goog.reflect.object(A.B, {})",
TypedScopeCreator.CONSTRUCTOR_EXPECTED);
}
public void testConstructorNode() {
testSame("var goog = {}; /** @constructor */ goog.Foo = function() {};");
ObjectType ctor = (ObjectType) (findNameType("goog.Foo", globalScope));
assertNotNull(ctor);
assertTrue(ctor.isConstructor());
assertEquals("function (new:goog.Foo): undefined", ctor.toString());
}
public void testForLoopIntegration() {
testSame("var y = 3; for (var x = true; x; y = x) {}");
Var y = globalScope.getVar("y");
assertTrue(y.isTypeInferred());
assertEquals("(boolean|number)", y.getType().toString());
}
public void testConstructorAlias() {
testSame(
"/** @constructor */ var Foo = function() {};" +
"/** @constructor */ var FooAlias = Foo;");
assertEquals("Foo", registry.getType("FooAlias").toString());
Asserts.assertTypeEquals(registry.getType("Foo"), registry.getType("FooAlias"));
}
public void testNamespacedConstructorAlias() {
testSame(
"var goog = {};" +
"/** @constructor */ goog.Foo = function() {};" +
"/** @constructor */ goog.FooAlias = goog.Foo;");
assertEquals("goog.Foo", registry.getType("goog.FooAlias").toString());
Asserts.assertTypeEquals(registry.getType("goog.Foo"),
registry.getType("goog.FooAlias"));
}
public void testTemplateType1() {
testSame(
"/**\n" +
" * @param {function(this:T, ...)} fn\n" +
" * @param {T} thisObj\n" +
" * @template T\n" +
" */\n" +
"function bind(fn, thisObj) {}" +
"/** @constructor */\n" +
"function Foo() {}\n" +
"/** @return {number} */\n" +
"Foo.prototype.baz = function() {};\n" +
"bind(function() { var g = this; var f = this.baz(); }, new Foo());");
assertEquals("Foo", findNameType("g", lastLocalScope).toString());
assertEquals("number", findNameType("f", lastLocalScope).toString());
}
public void testTemplateType2() {
testSame(
"/**\n" +
" * @param {T} x\n" +
" * @return {T}\n" +
" * @template T\n" +
" */\n" +
"function f(x) {\n" +
" return x;\n" +
"}" +
"/** @type {string} */\n" +
"var val = 'hi';\n" +
"var result = f(val);");
assertEquals("string", findNameType("result", globalScope).toString());
}
public void testTemplateType2a() {
testSame(
"/**\n" +
" * @param {T} x\n" +
" * @return {T|undefined}\n" +
" * @template T\n" +
" */\n" +
"function f(x) {\n" +
" return x;\n" +
"}" +
"/** @type {string} */\n" +
"var val = 'hi';\n" +
"var result = f(val);");
assertEquals("(string|undefined)",
findNameType("result", globalScope).toString());
}
public void testTemplateType2b() {
testSame(
"/**\n" +
" * @param {T} x\n" +
" * @return {T}\n" +
" * @template T\n" +
" */\n" +
"function f(x) {\n" +
" return x;\n" +
"}" +
"/** @type {string|undefined} */\n" +
"var val = 'hi';\n" +
"var result = f(val);");
assertEquals("(string|undefined)",
findNameType("result", globalScope).toString());
}
public void testTemplateType3() {
testSame(
"/**\n" +
" * @param {T} x\n" +
" * @return {T}\n" +
" * @template T\n" +
" */\n" +
"function f(x) {\n" +
" return x;\n" +
"}" +
"/** @type {string} */\n" +
"var val1 = 'hi';\n" +
"var result1 = f(val1);" +
"/** @type {number} */\n" +
"var val2 = 0;\n" +
"var result2 = f(val2);");
assertEquals("string", findNameType("result1", globalScope).toString());
assertEquals("number", findNameType("result2", globalScope).toString());
}
public void testTemplateType4() {
testSame(
"/**\n" +
" * @param {T} x\n" +
" * @return {T}\n" +
" * @template T\n" +
" */\n" +
"function f(x) {\n" +
" return x;\n" +
"}" +
"/** @type {!Array.<string>} */\n" +
"var arr = [];\n" +
"(function () {var result = f(arr);})();");
JSType resultType = findNameType("result", lastLocalScope);
assertEquals("Array.<string>", resultType.toString());
}
public void testTemplateType4a() {
testSame(
"/**\n" +
" * @param {function():T} x\n" +
" * @return {T}\n" +
" * @template T\n" +
" */\n" +
"function f(x) {\n" +
" return x;\n" +
"}" +
"/** @return {string} */\n" +
"var g = function(){return 'hi'};\n" +
"(function () {var result = f(g);})();");
JSType resultType = findNameType("result", lastLocalScope);
assertEquals("string", resultType.toString());
}
public void testTemplateType4b() {
testSame(
"/**\n" +
" * @param {function(T):void} x\n" +
" * @return {T}\n" +
" * @template T\n" +
" */\n" +
"function f(x) {\n" +
" return x;\n" +
"}" +
"/** @param {string} x */\n" +
"var g = function(x){};\n" +
"(function () {var result = f(g);})();");
JSType resultType = findNameType("result", lastLocalScope);
assertEquals("string", resultType.toString());
}
public void testTemplateType5() {
testSame(
"/**\n" +
" * @param {Array.<T>} arr\n" +
" * @return {!Array.<T>}\n" +
" * @template T\n" +
" */\n" +
"function f(arr) {\n" +
" return arr;\n" +
"}" +
"/** @type {Array.<string>} */\n" +
"var arr = [];\n" +
"var result = f(arr);");
assertEquals("Array.<string>", findNameTypeStr("result", globalScope));
}
public void testTemplateType6() {
testSame(
"/**\n" +
" * @param {Array.<T>|string|undefined} arr\n" +
" * @return {!Array.<T>}\n" +
" * @template T\n" +
" */\n" +
"function f(arr) {\n" +
" return arr;\n" +
"}" +
"/** @type {Array.<string>} */\n" +
"var arr = [];\n" +
"var result = f(arr);");
assertEquals("Array.<string>", findNameTypeStr("result", globalScope));
}
public void testTemplateType7() {
testSame(
"var goog = {};\n" +
"goog.array = {};\n" +
"/**\n" +
" * @param {Array.<T>} arr\n" +
" * @param {function(this:S, !T, number, !Array.<!T>):boolean} f\n" +
" * @param {!S=} opt_obj\n" +
" * @return {!Array.<T>}\n" +
" * @template T,S\n" +
" */\n" +
"goog.array.filter = function(arr, f, opt_obj) {\n" +
" var res = [];\n" +
" for (var i = 0; i < arr.length; i++) {\n" +
" if (f.call(opt_obj, arr[i], i, arr)) {\n" +
" res.push(val);\n" +
" }\n" +
" }\n" +
" return res;\n" +
"}" +
"/** @constructor */\n" +
"function Foo() {}\n" +
"/** @type {Array.<string>} */\n" +
"var arr = [];\n" +
"var result = goog.array.filter(arr," +
" function(a,b,c) {var self=this;}, new Foo());");
assertEquals("Foo", findNameType("self", lastLocalScope).toString());
assertEquals("string", findNameType("a", lastLocalScope).toString());
assertEquals("number", findNameType("b", lastLocalScope).toString());
assertEquals("Array.<string>",
findNameType("c", lastLocalScope).toString());
assertEquals("Array.<string>",
findNameType("result", globalScope).toString());
}
public void testTemplateType7b() {
testSame(
"var goog = {};\n" +
"goog.array = {};\n" +
"/**\n" +
" * @param {Array.<T>} arr\n" +
" * @param {function(this:S, !T, number, !Array.<T>):boolean} f\n" +
" * @param {!S=} opt_obj\n" +
" * @return {!Array.<T>}\n" +
" * @template T,S\n" +
" */\n" +
"goog.array.filter = function(arr, f, opt_obj) {\n" +
" var res = [];\n" +
" for (var i = 0; i < arr.length; i++) {\n" +
" if (f.call(opt_obj, arr[i], i, arr)) {\n" +
" res.push(val);\n" +
" }\n" +
" }\n" +
" return res;\n" +
"}" +
"/** @constructor */\n" +
"function Foo() {}\n" +
"/** @type {Array.<string>} */\n" +
"var arr = [];\n" +
"var result = goog.array.filter(arr," +
" function(a,b,c) {var self=this;}, new Foo());");
assertEquals("Foo", findNameType("self", lastLocalScope).toString());
assertEquals("string", findNameType("a", lastLocalScope).toString());
assertEquals("number", findNameType("b", lastLocalScope).toString());
assertEquals("Array.<string>",
findNameType("c", lastLocalScope).toString());
assertEquals("Array.<string>",
findNameType("result", globalScope).toString());
}
public void testTemplateType7c() {
testSame(
"var goog = {};\n" +
"goog.array = {};\n" +
"/**\n" +
" * @param {Array.<T>} arr\n" +
" * @param {function(this:S, T, number, Array.<T>):boolean} f\n" +
" * @param {!S=} opt_obj\n" +
" * @return {!Array.<T>}\n" +
" * @template T,S\n" +
" */\n" +
"goog.array.filter = function(arr, f, opt_obj) {\n" +
" var res = [];\n" +
" for (var i = 0; i < arr.length; i++) {\n" +
" if (f.call(opt_obj, arr[i], i, arr)) {\n" +
" res.push(val);\n" +
" }\n" +
" }\n" +
" return res;\n" +
"}" +
"/** @constructor */\n" +
"function Foo() {}\n" +
"/** @type {Array.<string>} */\n" +
"var arr = [];\n" +
"var result = goog.array.filter(arr," +
" function(a,b,c) {var self=this;}, new Foo());");
assertEquals("Foo", findNameType("self", lastLocalScope).toString());
assertEquals("string", findNameType("a", lastLocalScope).toString());
assertEquals("number", findNameType("b", lastLocalScope).toString());
assertEquals("(Array.<string>|null)",
findNameType("c", lastLocalScope).toString());
assertEquals("Array.<string>",
findNameType("result", globalScope).toString());
}
public void disable_testTemplateType8() {
// TODO(johnlenz): somehow allow templated typedefs
testSame(
"/** @constructor */ NodeList = function() {};" +
"/** @constructor */ Arguments = function() {};" +
"var goog = {};" +
"goog.array = {};" +
"/**\n" +
" * @typedef {Array.<T>|NodeList|Arguments|{length: number}}\n" +
" * @template T\n" +
" */\n" +
"goog.array.ArrayLike;" +
"/**\n" +
" * @param {function(this:T, ...)} fn\n" +
" * @param {T} thisObj\n" +
" * @template T\n" +
" */\n" +
"function bind(fn, thisObj) {}" +
"/** @constructor */\n" +
"function Foo() {}\n" +
"/** @return {number} */\n" +
"Foo.prototype.baz = function() {};\n" +
"bind(function() { var g = this; var f = this.baz(); }, new Foo());");
assertEquals("T", findNameType("g", lastLocalScope).toString());
assertTrue(findNameType("g", lastLocalScope).isEquivalentTo(
registry.getType("Foo")));
assertEquals("number", findNameType("f", lastLocalScope).toString());
}
public void testTemplateType9() {
testSame(
"/** @constructor */\n" +
"function Foo() {}\n" +
"/**\n" +
" * @this {T}\n" +
" * @return {T}\n" +
" * @template T\n" +
" */\n" +
"Foo.prototype.method = function() {};\n" +
"/**\n" +
" * @constructor\n" +
" * @extends {Foo}\n" +
" */\n" +
"function Bar() {}\n" +
"\n" +
"var g = new Bar().method();\n");
assertEquals("Bar", findNameType("g", globalScope).toString());
}
public void testTemplateType10() {
// NOTE: we would like the type within the function to remain "Foo"
// we can handle this by support template type like "T extends Foo"
// to provide a "minimum" type for "Foo" within the function body.
testSame(
"/** @constructor */\n" +
"function Foo() {}\n" +
"\n" +
"/**\n" +
" * @this {T}\n" +
" * @return {T} fn\n" +
" * @template T\n" +
" */\n" +
"Foo.prototype.method = function() {var g = this;};\n");
assertEquals("T", findNameType("g", lastLocalScope).toString());
}
public void testTemplateType11() {
testSame(
"/**\n" +
" * @this {T}\n" +
" * @return {T} fn\n" +
" * @template T\n" +
" */\n" +
"var method = function() {};\n" +
"/**\n" +
" * @constructor\n" +
" */\n" +
"function Bar() {}\n" +
"\n" +
"var g = method().call(new Bar());\n");
// NOTE: we would like this to be "Bar"
assertEquals("?", findNameType("g", globalScope).toString());
}
public void testTemplateType12() {
testSame(
"/** @constructor */\n" +
"function Foo() {}\n" +
"\n" +
"/**\n" +
" * @this {Array.<T>|{length:number}}\n" +
" * @return {T} fn\n" +
" * @template T\n" +
" */\n" +
"Foo.prototype.method = function() {var g = this;};\n");
assertEquals("(Array.<T>|{length: number})",
findNameType("g", lastLocalScope).toString());
}
public void testClosureParameterTypesWithoutJSDoc() {
testSame(
"/**\n" +
" * @param {function(!Object)} bar\n" +
" */\n" +
"function foo(bar) {}\n" +
"foo(function(baz) { var f = baz; })\n");
assertEquals("Object", findNameType("f", lastLocalScope).toString());
}
public void testClosureParameterTypesWithJSDoc() {
testSame(
"/**\n" +
" * @param {function(!Object)} bar\n" +
" */\n" +
"function foo(bar) {}\n" +
"foo((/** @type {function(string)} */" +
"function(baz) { var f = baz; }))\n");
assertEquals("string", findNameType("f", lastLocalScope).toString());
}
public void testDuplicateExternProperty1() {
testSame(
"/** @constructor */ function Foo() {}" +
"Foo.prototype.bar;" +
"/** @type {number} */ Foo.prototype.bar; var x = (new Foo).bar;",
null);
assertEquals("number", findNameType("x", globalScope).toString());
}
public void testDuplicateExternProperty2() {
testSame(
"/** @constructor */ function Foo() {}" +
"/** @type {number} */ Foo.prototype.bar;" +
"Foo.prototype.bar; var x = (new Foo).bar;", null);
assertEquals("number", findNameType("x", globalScope).toString());
}
public void testAbstractMethod() {
testSame(
"/** @type {!Function} */ var abstractMethod;" +
"/** @constructor */ function Foo() {}" +
"/** @param {number} x */ Foo.prototype.bar = abstractMethod;");
assertEquals(
"Function", findNameType("abstractMethod", globalScope).toString());
FunctionType ctor = (FunctionType) findNameType("Foo", globalScope);
ObjectType instance = ctor.getInstanceType();
assertEquals("Foo", instance.toString());
ObjectType proto = instance.getImplicitPrototype();
assertEquals("Foo.prototype", proto.toString());
assertEquals(
"function (this:Foo, number): ?",
proto.getPropertyType("bar").toString());
}
public void testAbstractMethod2() {
testSame(
"/** @type {!Function} */ var abstractMethod;" +
"/** @param {number} x */ var y = abstractMethod;");
assertEquals(
"Function",
findNameType("y", globalScope).toString());
assertEquals(
"function (number): ?",
globalScope.getVar("y").getType().toString());
}
public void testAbstractMethod3() {
testSame(
"/** @type {!Function} */ var abstractMethod;" +
"/** @param {number} x */ var y = abstractMethod; y;");
assertEquals(
"function (number): ?",
findNameType("y", globalScope).toString());
}
public void testAbstractMethod4() {
testSame(
"/** @type {!Function} */ var abstractMethod;" +
"/** @constructor */ function Foo() {}" +
"Foo.prototype = {/** @param {number} x */ bar: abstractMethod};");
assertEquals(
"Function", findNameType("abstractMethod", globalScope).toString());
FunctionType ctor = (FunctionType) findNameType("Foo", globalScope);
ObjectType instance = ctor.getInstanceType();
assertEquals("Foo", instance.toString());
ObjectType proto = instance.getImplicitPrototype();
assertEquals("Foo.prototype", proto.toString());
assertEquals(
// should be: "function (this:Foo, number): ?"
"function (this:Foo, number): ?",
proto.getPropertyType("bar").toString());
}
public void testActiveXObject() {
testSame(
CompilerTypeTestCase.ACTIVE_X_OBJECT_DEF,
"var x = new ActiveXObject();", null);
assertEquals(
"?",
findNameType("x", globalScope).toString());
}
public void testReturnTypeInference1() {
testSame("function f() {}");
assertEquals(
"function (): undefined",
findNameType("f", globalScope).toString());
}
public void testReturnTypeInference2() {
testSame("/** @return {?} */ function f() {}");
assertEquals(
"function (): ?",
findNameType("f", globalScope).toString());
}
public void testReturnTypeInference3() {
testSame("function f() {x: return 3;}");
assertEquals(
"function (): ?",
findNameType("f", globalScope).toString());
}
public void testReturnTypeInference4() {
testSame("function f() { throw Error(); }");
assertEquals(
"function (): ?",
findNameType("f", globalScope).toString());
}
public void testReturnTypeInference5() {
testSame("function f() { if (true) { return 1; } }");
assertEquals(
"function (): ?",
findNameType("f", globalScope).toString());
}
public void testLiteralTypesInferred() {
testSame("null + true + false + 0 + '' + {}");
assertEquals(
"null", findTokenType(Token.NULL, globalScope).toString());
assertEquals(
"boolean", findTokenType(Token.TRUE, globalScope).toString());
assertEquals(
"boolean", findTokenType(Token.FALSE, globalScope).toString());
assertEquals(
"number", findTokenType(Token.NUMBER, globalScope).toString());
assertEquals(
"string", findTokenType(Token.STRING, globalScope).toString());
assertEquals(
"{}", findTokenType(Token.OBJECTLIT, globalScope).toString());
}
public void testGlobalQualifiedNameInLocalScope() {
testSame(
"var ns = {}; " +
"(function() { " +
" /** @param {number} x */ ns.foo = function(x) {}; })();" +
"(function() { ns.foo(3); })();");
assertNotNull(globalScope.getVar("ns.foo"));
assertEquals(
"function (number): undefined",
globalScope.getVar("ns.foo").getType().toString());
}
public void testDeclaredObjectLitProperty1() throws Exception {
testSame("var x = {/** @type {number} */ y: 3};");
ObjectType xType = ObjectType.cast(globalScope.getVar("x").getType());
assertEquals(
"number",
xType.getPropertyType("y").toString());
assertEquals(
"{y: number}",
xType.toString());
}
public void testDeclaredObjectLitProperty2() throws Exception {
testSame("var x = {/** @param {number} z */ y: function(z){}};");
ObjectType xType = ObjectType.cast(globalScope.getVar("x").getType());
assertEquals(
"function (number): undefined",
xType.getPropertyType("y").toString());
assertEquals(
"{y: function (number): undefined}",
xType.toString());
}
public void testDeclaredObjectLitProperty3() throws Exception {
testSame("function f() {" +
" var x = {/** @return {number} */ y: function(z){ return 3; }};" +
"}");
ObjectType xType = ObjectType.cast(lastLocalScope.getVar("x").getType());
assertEquals(
"function (?): number",
xType.getPropertyType("y").toString());
assertEquals(
"{y: function (?): number}",
xType.toString());
}
public void testDeclaredObjectLitProperty4() throws Exception {
testSame("var x = {y: 5, /** @type {number} */ z: 3};");
ObjectType xType = ObjectType.cast(globalScope.getVar("x").getType());
assertEquals(
"number", xType.getPropertyType("y").toString());
assertFalse(xType.isPropertyTypeDeclared("y"));
assertTrue(xType.isPropertyTypeDeclared("z"));
assertEquals(
"{y: number, z: number}",
xType.toString());
}
public void testDeclaredObjectLitProperty5() throws Exception {
testSame("var x = {/** @type {number} */ prop: 3};" +
"function f() { var y = x.prop; }");
JSType yType = lastLocalScope.getVar("y").getType();
assertEquals("number", yType.toString());
}
public void testDeclaredObjectLitProperty6() throws Exception {
testSame("var x = {/** This is JsDoc */ prop: function(){}};");
Var prop = globalScope.getVar("x.prop");
JSType propType = prop.getType();
assertEquals("function (): undefined", propType.toString());
assertFalse(prop.isTypeInferred());
assertFalse(
ObjectType.cast(globalScope.getVar("x").getType())
.isPropertyTypeInferred("prop"));
}
public void testInferredObjectLitProperty1() throws Exception {
testSame("var x = {prop: 3};");
Var prop = globalScope.getVar("x.prop");
JSType propType = prop.getType();
assertEquals("number", propType.toString());
assertTrue(prop.isTypeInferred());
assertTrue(
ObjectType.cast(globalScope.getVar("x").getType())
.isPropertyTypeInferred("prop"));
}
public void testInferredObjectLitProperty2() throws Exception {
testSame("var x = {prop: function(){}};");
Var prop = globalScope.getVar("x.prop");
JSType propType = prop.getType();
assertEquals("function (): undefined", propType.toString());
assertTrue(prop.isTypeInferred());
assertTrue(
ObjectType.cast(globalScope.getVar("x").getType())
.isPropertyTypeInferred("prop"));
}
public void testDeclaredConstType1() throws Exception {
testSame(
"/** @const */ var x = 3;" +
"function f() { var y = x; }");
JSType yType = lastLocalScope.getVar("y").getType();
assertEquals("number", yType.toString());
}
public void testDeclaredConstType2() throws Exception {
testSame(
"/** @const */ var x = {};" +
"function f() { var y = x; }");
JSType yType = lastLocalScope.getVar("y").getType();
assertEquals("{}", yType.toString());
}
public void testDeclaredConstType3() throws Exception {
testSame(
"/** @const */ var x = {};" +
"/** @const */ x.z = 'hi';" +
"function f() { var y = x.z; }");
JSType yType = lastLocalScope.getVar("y").getType();
assertEquals("string", yType.toString());
}
public void testDeclaredConstType4() throws Exception {
testSame(
"/** @constructor */ function Foo() {}" +
"/** @const */ Foo.prototype.z = 'hi';" +
"function f() { var y = (new Foo()).z; }");
JSType yType = lastLocalScope.getVar("y").getType();
assertEquals("string", yType.toString());
ObjectType fooType =
((FunctionType) globalScope.getVar("Foo").getType()).getInstanceType();
assertTrue(fooType.isPropertyTypeDeclared("z"));
}
public void testDeclaredConstType5() throws Exception {
testSame(
"/** @const */ var goog = goog || {};" +
"/** @const */ var foo = goog || {};" +
"function f() { var y = goog; var z = foo; }");
JSType yType = lastLocalScope.getVar("y").getType();
assertEquals("{}", yType.toString());
JSType zType = lastLocalScope.getVar("z").getType();
assertEquals("?", zType.toString());
}
public void testBadCtorInit1() throws Exception {
testSame("/** @constructor */ var f;", CTOR_INITIALIZER);
}
public void testBadCtorInit2() throws Exception {
testSame("var x = {}; /** @constructor */ x.f;", CTOR_INITIALIZER);
}
public void testBadIfaceInit1() throws Exception {
testSame("/** @interface */ var f;", IFACE_INITIALIZER);
}
public void testBadIfaceInit2() throws Exception {
testSame("var x = {}; /** @interface */ x.f;", IFACE_INITIALIZER);
}
public void testFunctionInHook() throws Exception {
testSame("/** @param {number} x */ var f = Math.random() ? " +
"function(x) {} : function(x) {};");
assertEquals("number", lastLocalScope.getVar("x").getType().toString());
}
public void testFunctionInAnd() throws Exception {
testSame("/** @param {number} x */ var f = Math.random() && " +
"function(x) {};");
assertEquals("number", lastLocalScope.getVar("x").getType().toString());
}
public void testFunctionInOr() throws Exception {
testSame("/** @param {number} x */ var f = Math.random() || " +
"function(x) {};");
assertEquals("number", lastLocalScope.getVar("x").getType().toString());
}
public void testFunctionInComma() throws Exception {
testSame("/** @param {number} x */ var f = (Math.random(), " +
"function(x) {});");
assertEquals("number", lastLocalScope.getVar("x").getType().toString());
}
public void testDeclaredCatchExpression1() {
testSame(
"try {} catch (e) {}");
// Note: "e" actually belongs to a inner scope but we don't
// model catches as separate scopes currently.
assertEquals(null, globalScope.getVar("e").getType());
}
public void testDeclaredCatchExpression2() {
testSame(
"try {} catch (/** @type {string} */ e) {}");
// Note: "e" actually belongs to a inner scope but we don't
// model catches as separate scopes currently.
assertEquals("string", globalScope.getVar("e").getType().toString());
}
private JSType findNameType(final String name, Scope scope) {
return findTypeOnMatchedNode(new Predicate<Node>() {
@Override public boolean apply(Node n) {
return name.equals(n.getQualifiedName());
}
}, scope);
}
private String findNameTypeStr(final String name, Scope scope) {
return findNameType(name, scope).toString();
}
private JSType findTokenType(final int type, Scope scope) {
return findTypeOnMatchedNode(new Predicate<Node>() {
@Override public boolean apply(Node n) {
return type == n.getType();
}
}, scope);
}
private JSType findTypeOnMatchedNode(Predicate<Node> matcher, Scope scope) {
Node root = scope.getRootNode();
Deque<Node> queue = Lists.newLinkedList();
queue.push(root);
while (!queue.isEmpty()) {
Node current = queue.pop();
if (matcher.apply(current) &&
current.getJSType() != null) {
return current.getJSType();
}
for (Node child : current.children()) {
queue.push(child);
}
}
return null;
}
private JSType getNativeType(JSTypeNative type) {
return registry.getNativeType(type);
}
private ObjectType getNativeObjectType(JSTypeNative type) {
return (ObjectType) registry.getNativeType(type);
}
}
| apache-2.0 |
leleuj/cas | support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/support/oauth/web/response/accesstoken/OAuth20AccessTokenAtHashGenerator.java | 3145 | package org.apereo.cas.support.oauth.web.response.accesstoken;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.util.DigestUtils;
import org.apereo.cas.util.EncodingUtils;
import lombok.Builder;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.codec.digest.MessageDigestAlgorithms;
import org.jose4j.jws.AlgorithmIdentifiers;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* This is {@link OAuth20AccessTokenAtHashGenerator}.
*
* @author Misagh Moayyed
* @since 6.1.0
*/
@Builder
@Getter
@Slf4j
public class OAuth20AccessTokenAtHashGenerator {
private final String encodedAccessToken;
private final String algorithm;
private final RegisteredService registeredService;
/**
* Generate string.
*
* @return the string
*/
public String generate() {
val tokenBytes = encodedAccessToken.getBytes(StandardCharsets.UTF_8);
if (AlgorithmIdentifiers.NONE.equalsIgnoreCase(this.algorithm)) {
LOGGER.debug("Signing algorithm specified by service [{}] is unspecified/none", registeredService.getServiceId());
return EncodingUtils.encodeUrlSafeBase64(tokenBytes);
}
val alg = determineSigningHashAlgorithm();
LOGGER.debug("Digesting access token hash via algorithm [{}]", alg);
val digested = DigestUtils.rawDigest(alg, tokenBytes);
val hashBytesLeftHalf = Arrays.copyOf(digested, digested.length / 2);
return EncodingUtils.encodeUrlSafeBase64(hashBytesLeftHalf);
}
/**
* Gets signing hash algorithm.
*
* @return the signing hash algorithm
*/
protected String determineSigningHashAlgorithm() {
LOGGER.debug("Signing algorithm specified is [{}]", this.algorithm);
if (AlgorithmIdentifiers.HMAC_SHA512.equalsIgnoreCase(algorithm)
|| AlgorithmIdentifiers.RSA_USING_SHA512.equalsIgnoreCase(algorithm)
|| AlgorithmIdentifiers.RSA_PSS_USING_SHA512.equalsIgnoreCase(algorithm)
|| AlgorithmIdentifiers.ECDSA_USING_P521_CURVE_AND_SHA512.equalsIgnoreCase(algorithm)) {
return MessageDigestAlgorithms.SHA_512;
}
if (AlgorithmIdentifiers.HMAC_SHA384.equalsIgnoreCase(algorithm)
|| AlgorithmIdentifiers.RSA_USING_SHA384.equalsIgnoreCase(algorithm)
|| AlgorithmIdentifiers.RSA_PSS_USING_SHA384.equalsIgnoreCase(algorithm)
|| AlgorithmIdentifiers.ECDSA_USING_P384_CURVE_AND_SHA384.equalsIgnoreCase(algorithm)) {
return MessageDigestAlgorithms.SHA_384;
}
if (AlgorithmIdentifiers.HMAC_SHA256.equalsIgnoreCase(algorithm)
|| AlgorithmIdentifiers.RSA_USING_SHA256.equalsIgnoreCase(algorithm)
|| AlgorithmIdentifiers.RSA_PSS_USING_SHA256.equalsIgnoreCase(algorithm)
|| AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256.equalsIgnoreCase(algorithm)) {
return MessageDigestAlgorithms.SHA_256;
}
throw new IllegalArgumentException("Could not determine the hash algorithm for the id token");
}
}
| apache-2.0 |
VinodKumarS-Huawei/ietf96yang | apps/pce/app/src/main/java/org/onosproject/pce/pceservice/BasicPceccHandler.java | 17236 | /*
* Copyright 2016-present Open Networking Laboratory
*
* 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.onosproject.pce.pceservice;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.LinkedList;
import org.onlab.packet.MplsLabel;
import org.onosproject.core.ApplicationId;
import org.onosproject.incubator.net.resource.label.DefaultLabelResource;
import org.onosproject.incubator.net.resource.label.LabelResource;
import org.onosproject.incubator.net.resource.label.LabelResourceId;
import org.onosproject.incubator.net.resource.label.LabelResourceService;
import org.onosproject.incubator.net.tunnel.Tunnel;
import org.onosproject.incubator.net.tunnel.TunnelId;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.flowobjective.DefaultForwardingObjective;
import org.onosproject.net.flowobjective.FlowObjectiveService;
import org.onosproject.net.flowobjective.ForwardingObjective;
import org.onosproject.net.flowobjective.Objective;
import org.onosproject.pce.pcestore.api.PceStore;
import org.onosproject.pce.pcestore.api.LspLocalLabelInfo;
import org.onosproject.pce.pcestore.PceccTunnelInfo;
import org.onosproject.pce.pcestore.DefaultLspLocalLabelInfo;
import org.onosproject.net.Link;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
/**
* Basic PCECC handler.
* In Basic PCECC, after path computation will configure IN and OUT label to nodes.
* [X]OUT---link----IN[Y]OUT---link-----IN[Z] where X, Y and Z are nodes.
* For generating labels, will go thorough links in the path from Egress to Ingress.
* In each link, will take label from destination node local pool as IN label,
* and assign this label as OUT label to source node.
*/
public final class BasicPceccHandler {
private static final Logger log = LoggerFactory.getLogger(BasicPceccHandler.class);
private static final String LABEL_RESOURCE_SERVICE_NULL = "Label Resource Service cannot be null";
private static final String PCE_STORE_NULL = "PCE Store cannot be null";
private static BasicPceccHandler crHandlerInstance = null;
private LabelResourceService labelRsrcService;
private PceStore pceStore;
private FlowObjectiveService flowObjectiveService;
private ApplicationId appId;
/**
* Initializes default values.
*/
private BasicPceccHandler() {
}
/**
* Returns single instance of this class.
*
* @return this class single instance
*/
public static BasicPceccHandler getInstance() {
if (crHandlerInstance == null) {
crHandlerInstance = new BasicPceccHandler();
}
return crHandlerInstance;
}
/**
* Initialization of label manager and pce store.
*
* @param labelRsrcService label resource service
* @param flowObjectiveService flow objective service to push device label information
* @param appId applicaton id
* @param pceStore pce label store
*/
public void initialize(LabelResourceService labelRsrcService, FlowObjectiveService flowObjectiveService,
ApplicationId appId, PceStore pceStore) {
this.labelRsrcService = labelRsrcService;
this.flowObjectiveService = flowObjectiveService;
this.appId = appId;
this.pceStore = pceStore;
}
/**
* Allocates labels from local resource pool and configure these (IN and OUT) labels into devices.
*
* @param tunnel tunnel between ingress to egress
* @return success or failure
*/
public boolean allocateLabel(Tunnel tunnel) {
long applyNum = 1;
boolean isLastLabelToPush = false;
Collection<LabelResource> labelRscList;
checkNotNull(labelRsrcService, LABEL_RESOURCE_SERVICE_NULL);
checkNotNull(pceStore, PCE_STORE_NULL);
List<Link> linkList = tunnel.path().links();
if ((linkList != null) && (linkList.size() > 0)) {
// Sequence through reverse order to push local labels into devices
// Generation of labels from egress to ingress
for (ListIterator<Link> iterator = linkList.listIterator(linkList.size()); iterator.hasPrevious();) {
Link link = iterator.previous();
DeviceId dstDeviceId = link.dst().deviceId();
DeviceId srcDeviceId = link.src().deviceId();
labelRscList = labelRsrcService.applyFromDevicePool(dstDeviceId, applyNum);
if ((labelRscList != null) && (labelRscList.size() > 0)) {
// Link label value is taken from destination device local pool.
// [X]OUT---link----IN[Y]OUT---link-----IN[Z] where X, Y and Z are nodes.
// Link label value is used as OUT and IN for both ends
// (source and destination devices) of the link.
// Currently only one label is allocated to a device (destination device).
// So, no need to iterate through list
Iterator<LabelResource> labelIterator = labelRscList.iterator();
DefaultLabelResource defaultLabelResource = (DefaultLabelResource) labelIterator.next();
LabelResourceId labelId = defaultLabelResource.labelResourceId();
log.debug("Allocated local label: " + labelId.toString()
+ "to device: " + defaultLabelResource.deviceId().toString());
PortNumber dstPort = link.dst().port();
// Check whether this is last link label to push
if (!iterator.hasPrevious()) {
isLastLabelToPush = true;
}
// Push into destination device
// Destination device IN port is link.dst().port()
installLocalLabelRule(dstDeviceId, labelId, dstPort, tunnel.tunnelId(), false,
Long.valueOf(LabelType.IN_LABEL.value), Objective.Operation.ADD);
// Push into source device
// Source device OUT port will be link.dst().port(). Means its remote port used to send packet.
installLocalLabelRule(srcDeviceId, labelId, dstPort, tunnel.tunnelId(), isLastLabelToPush,
Long.valueOf(LabelType.OUT_LABEL.value), Objective.Operation.ADD);
// Add or update pcecc tunnel info in pce store.
updatePceccTunnelInfoInStore(srcDeviceId, dstDeviceId, labelId, dstPort,
tunnel, isLastLabelToPush);
} else {
log.error("Unable to allocate label to device id {}.", dstDeviceId.toString());
releaseLabel(tunnel);
return false;
}
}
} else {
log.error("Tunnel {} is having empty links.", tunnel.toString());
return false;
}
return true;
}
/**
* Updates list of local labels of PCECC tunnel info in pce store.
*
* @param srcDeviceId source device in a link
* @param dstDeviceId destination device in a link
* @param labelId label id of a link
* @param dstPort destination device port number of a link
* @param tunnel tunnel
* @param isLastLabelToPush indicates this is the last label to push in Basic PCECC case
*/
public void updatePceccTunnelInfoInStore(DeviceId srcDeviceId, DeviceId dstDeviceId, LabelResourceId labelId,
PortNumber dstPort, Tunnel tunnel, boolean isLastLabelToPush) {
// First try to retrieve device from store and update its label id if it is exists,
// otherwise add it
boolean dstDeviceUpdated = false;
boolean srcDeviceUpdated = false;
PceccTunnelInfo pceccTunnelInfo = pceStore.getTunnelInfo(tunnel.tunnelId());
List<LspLocalLabelInfo> lspLabelInfoList;
if (pceccTunnelInfo != null) {
lspLabelInfoList = pceccTunnelInfo.lspLocalLabelInfoList();
if ((lspLabelInfoList != null) && (lspLabelInfoList.size() > 0)) {
for (int i = 0; i < lspLabelInfoList.size(); ++i) {
LspLocalLabelInfo lspLocalLabelInfo =
lspLabelInfoList.get(i);
LspLocalLabelInfo.Builder lspLocalLabelInfoBuilder = null;
if (dstDeviceId.equals(lspLocalLabelInfo.deviceId())) {
lspLocalLabelInfoBuilder = DefaultLspLocalLabelInfo.builder(lspLocalLabelInfo);
lspLocalLabelInfoBuilder.inLabelId(labelId);
// Destination device IN port will be link destination port
lspLocalLabelInfoBuilder.inPort(dstPort);
dstDeviceUpdated = true;
} else if (srcDeviceId.equals(lspLocalLabelInfo.deviceId())) {
lspLocalLabelInfoBuilder = DefaultLspLocalLabelInfo.builder(lspLocalLabelInfo);
lspLocalLabelInfoBuilder.outLabelId(labelId);
// Source device OUT port will be link destination (remote) port
lspLocalLabelInfoBuilder.outPort(dstPort);
srcDeviceUpdated = true;
}
// Update
if ((lspLocalLabelInfoBuilder != null) && (dstDeviceUpdated || srcDeviceUpdated)) {
lspLabelInfoList.set(i, lspLocalLabelInfoBuilder.build());
}
}
}
}
// If it is not found in store then add it to store
if (!dstDeviceUpdated || !srcDeviceUpdated) {
// If tunnel info itself not available then create new one, otherwise add node to list.
if (pceccTunnelInfo == null) {
pceccTunnelInfo = new PceccTunnelInfo();
lspLabelInfoList = new LinkedList<>();
} else {
lspLabelInfoList = pceccTunnelInfo.lspLocalLabelInfoList();
if (lspLabelInfoList == null) {
lspLabelInfoList = new LinkedList<>();
}
}
if (!dstDeviceUpdated) {
LspLocalLabelInfo lspLocalLabelInfo = DefaultLspLocalLabelInfo.builder()
.deviceId(dstDeviceId)
.inLabelId(labelId)
.outLabelId(null)
.inPort(dstPort) // Destination device IN port will be link destination port
.outPort(null)
.build();
lspLabelInfoList.add(lspLocalLabelInfo);
}
if (!srcDeviceUpdated) {
LspLocalLabelInfo lspLocalLabelInfo = DefaultLspLocalLabelInfo.builder()
.deviceId(srcDeviceId)
.inLabelId(null)
.outLabelId(labelId)
.inPort(null)
.outPort(dstPort) // Source device OUT port will be link destination (remote) port
.build();
lspLabelInfoList.add(lspLocalLabelInfo);
}
pceccTunnelInfo.lspLocalLabelInfoList(lspLabelInfoList);
pceStore.addTunnelInfo(tunnel.tunnelId(), pceccTunnelInfo);
}
}
/**
* Deallocates unused labels to device pools.
*
* @param tunnel tunnel between ingress to egress
*/
public void releaseLabel(Tunnel tunnel) {
boolean isLastLabelToPush = false;
checkNotNull(labelRsrcService, LABEL_RESOURCE_SERVICE_NULL);
checkNotNull(pceStore, PCE_STORE_NULL);
Multimap<DeviceId, LabelResource> release = ArrayListMultimap.create();
PceccTunnelInfo pceccTunnelInfo = pceStore.getTunnelInfo(tunnel.tunnelId());
if (pceccTunnelInfo != null) {
List<LspLocalLabelInfo> lspLocalLabelInfoList = pceccTunnelInfo.lspLocalLabelInfoList();
if ((lspLocalLabelInfoList != null) && (lspLocalLabelInfoList.size() > 0)) {
for (Iterator<LspLocalLabelInfo> iterator = lspLocalLabelInfoList.iterator(); iterator.hasNext();) {
LspLocalLabelInfo lspLocalLabelInfo = iterator.next();
DeviceId deviceId = lspLocalLabelInfo.deviceId();
LabelResourceId inLabelId = lspLocalLabelInfo.inLabelId();
LabelResourceId outLabelId = lspLocalLabelInfo.outLabelId();
PortNumber inPort = lspLocalLabelInfo.inPort();
PortNumber outPort = lspLocalLabelInfo.outPort();
// Check whether this is last link label to push
if (!iterator.hasNext()) {
isLastLabelToPush = true;
}
// Push into device
if ((inLabelId != null) && (inPort != null)) {
installLocalLabelRule(deviceId, inLabelId, inPort, tunnel.tunnelId(), isLastLabelToPush,
Long.valueOf(LabelType.IN_LABEL.value), Objective.Operation.REMOVE);
}
if ((outLabelId != null) && (outPort != null)) {
installLocalLabelRule(deviceId, outLabelId, outPort, tunnel.tunnelId(), isLastLabelToPush,
Long.valueOf(LabelType.OUT_LABEL.value), Objective.Operation.REMOVE);
}
// List is stored from egress to ingress. So, using IN label id to release.
// Only one local label is assigned to device (destination node)
// and that is used as OUT label for source node.
// No need to release label for last node in the list from pool because label was not allocated to
// ingress node (source node).
if ((iterator.hasNext()) && (inLabelId != null)) {
LabelResource labelRsc = new DefaultLabelResource(deviceId, inLabelId);
release.put(deviceId, labelRsc);
}
}
}
// Release from label pool
if (!release.isEmpty()) {
labelRsrcService.releaseToDevicePool(release);
}
// Remove tunnel info only if tunnel consumer id is not saved.
// If tunnel consumer id is saved, this tunnel info will be removed during releasing bandwidth.
if (pceccTunnelInfo.tunnelConsumerId() == null) {
pceStore.removeTunnelInfo(tunnel.tunnelId());
}
} else {
log.error("Unable to find PCECC tunnel info in store for a tunnel {}.", tunnel.toString());
}
}
// Install a rule for pushing local labels to the device which is specific to path.
private void installLocalLabelRule(DeviceId deviceId, LabelResourceId labelId,
PortNumber portNum, TunnelId tunnelId,
Boolean isBos, Long labelType,
Objective.Operation type) {
checkNotNull(flowObjectiveService);
checkNotNull(appId);
TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
selectorBuilder.matchMplsLabel(MplsLabel.mplsLabel(labelId.id().intValue()));
selectorBuilder.matchInPort(portNum);
selectorBuilder.matchTunnelId(Long.parseLong(tunnelId.id()));
selectorBuilder.matchMplsBos(isBos);
selectorBuilder.matchMetadata(labelType);
TrafficTreatment treatment = DefaultTrafficTreatment.builder().build();
ForwardingObjective.Builder forwardingObjective = DefaultForwardingObjective.builder()
.withSelector(selectorBuilder.build())
.withTreatment(treatment)
.withFlag(ForwardingObjective.Flag.VERSATILE)
.fromApp(appId)
.makePermanent();
if (type.equals(Objective.Operation.ADD)) {
flowObjectiveService.forward(deviceId, forwardingObjective.add());
} else {
flowObjectiveService.forward(deviceId, forwardingObjective.remove());
}
}
}
| apache-2.0 |
shs96c/buck | test/com/facebook/buck/cli/SingleStringSetOptionHandlerTest.java | 3006 | /*
* Copyright 2018-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cli;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
public class SingleStringSetOptionHandlerTest {
private class TestBean {
@Option(name = "--set", handler = SingleStringSetOptionHandler.class)
Supplier<ImmutableSet<String>> someSet;
@Option(name = "--other")
String otherString = null;
@Argument() List<String> nargs = new ArrayList<>();
}
@Rule public ExpectedException expected = ExpectedException.none();
@Test
public void createsSetWithoutConsumingOtherArgs() throws CmdLineException {
TestBean bean = new TestBean();
CmdLineParser parser = new CmdLineParser(bean);
parser.parseArgument("--set", "a", "b", "c");
assertEquals(ImmutableSet.of("a"), bean.someSet.get());
assertEquals(ImmutableList.of("b", "c"), bean.nargs);
assertNull(bean.otherString);
}
@Test
public void handlesMultipleSpecificationsOfSet() throws CmdLineException {
TestBean bean = new TestBean();
CmdLineParser parser = new CmdLineParser(bean);
parser.parseArgument("--set", "a", "--set", "b", "c", "d", "--set", "e", "f");
assertEquals(ImmutableSet.of("a", "b", "e"), bean.someSet.get());
assertEquals(ImmutableList.of("c", "d", "f"), bean.nargs);
assertNull(bean.otherString);
}
@Test
public void failsIfNoValueGiven() throws CmdLineException {
expected.expect(CmdLineException.class);
expected.expectMessage("Option \"--set\" takes an operand");
TestBean bean = new TestBean();
CmdLineParser parser = new CmdLineParser(bean);
parser.parseArgument("--set");
}
@Test
public void failsIfNoValueBeforeNextOption() throws CmdLineException {
expected.expect(CmdLineException.class);
expected.expectMessage("Option \"--set\" takes one operand");
TestBean bean = new TestBean();
CmdLineParser parser = new CmdLineParser(bean);
parser.parseArgument("--set", "--other", "a", "b", "c");
}
}
| apache-2.0 |
tadayosi/switchyard | release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BeanServiceQuickstartTest.java | 3039 | /*
* Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors.
*
* 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.switchyard.karaf.test.quickstarts;
import java.io.InputStreamReader;
import java.io.StringReader;
import org.custommonkey.xmlunit.XMLAssert;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.BeforeClass;
import org.junit.Test;
import org.switchyard.common.type.Classes;
import org.switchyard.component.test.mixins.http.HTTPMixIn;
public class BeanServiceQuickstartTest extends AbstractQuickstartTest {
private static String bundleName = "org.switchyard.quickstarts.switchyard.bean.service";
private static String featureName = "switchyard-quickstart-bean-service";
@BeforeClass
public static void before() throws Exception {
startTestContainer(featureName, bundleName);
}
@Test
public void testOrders() throws Exception {
HTTPMixIn httpMixIn = new HTTPMixIn();
httpMixIn.initialize();
try {
XMLUnit.setIgnoreWhitespace(true);
String port = getSoapClientPort();
String wsdl = httpMixIn.sendString("http://localhost:" + port + "/quickstart-bean/OrderService?wsdl", "", HTTPMixIn.HTTP_GET);
XMLAssert.assertXMLEqual(new InputStreamReader(Classes.getResourceAsStream("quickstarts/bean-service/OrderService.wsdl")), new StringReader(wsdl));
String response = httpMixIn.postString("http://localhost:" + port + "/quickstart-bean/OrderService", SOAP_REQUEST);
XMLAssert.assertXpathEvaluatesTo("PO-19838-XYZ", "//orderAck/orderId", response);
XMLAssert.assertXpathEvaluatesTo("true", "//orderAck/accepted", response);
XMLAssert.assertXpathEvaluatesTo("Order Accepted [intercepted]", "//orderAck/status", response);
} finally {
httpMixIn.uninitialize();
}
}
private static final String SOAP_REQUEST = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\">\n" +
" <soap:Body>\n" +
" <orders:submitOrder xmlns:orders=\"urn:switchyard-quickstart:bean-service:1.0\">\n" +
" <order>\n" +
" <orderId>PO-19838-XYZ</orderId>\n" +
" <itemId>BUTTER</itemId>\n" +
" <quantity>200</quantity>\n" +
" </order>\n" +
" </orders:submitOrder>\n" +
" </soap:Body>\n" +
"</soap:Envelope>";
}
| apache-2.0 |
minudika/carbon-analytics | components/org.wso2.carbon.siddhi.editor.core/src/main/java/org/wso2/carbon/siddhi/editor/core/util/designview/beans/configs/siddhielements/attributesselection/AttributesSelectionConfig.java | 1195 | /*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.siddhi.editor.core.util.designview.beans.configs.siddhielements.attributesselection;
import org.wso2.carbon.siddhi.editor.core.util.designview.beans.configs.siddhielements.SiddhiElementConfig;
/**
* Represents selection of Siddhi attributes
*/
public abstract class AttributesSelectionConfig extends SiddhiElementConfig {
private String type;
public AttributesSelectionConfig(String type) {
this.type = type;
}
public String getType() {
return type;
}
}
| apache-2.0 |
emre-aydin/hazelcast | hazelcast/src/test/java/com/hazelcast/test/jitter/Slot.java | 2044 | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.test.jitter;
import java.text.DateFormat;
import java.util.Date;
import static com.hazelcast.test.jitter.JitterRule.LONG_HICCUP_THRESHOLD;
import static java.lang.Math.max;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
class Slot {
private final long startInterval;
private volatile long accumulatedHiccupsNanos;
private volatile long maxPauseNanos;
private volatile int pausesOverThreshold;
Slot(long startInterval) {
this.startInterval = startInterval;
}
long getStartIntervalMillis() {
return startInterval;
}
long getMaxPauseNanos() {
return maxPauseNanos;
}
long getAccumulatedHiccupsNanos() {
return accumulatedHiccupsNanos;
}
void recordHiccup(long hiccupNanos) {
accumulatedHiccupsNanos += hiccupNanos;
maxPauseNanos = max(maxPauseNanos, hiccupNanos);
if (hiccupNanos > LONG_HICCUP_THRESHOLD) {
pausesOverThreshold++;
}
}
String toHumanFriendly(DateFormat dateFormat) {
return dateFormat.format(new Date(startInterval))
+ ", accumulated pauses: " + NANOSECONDS.toMillis(accumulatedHiccupsNanos) + " ms"
+ ", max pause: " + NANOSECONDS.toMillis(maxPauseNanos) + " ms"
+ ", pauses over " + NANOSECONDS.toMillis(LONG_HICCUP_THRESHOLD) + " ms: " + pausesOverThreshold;
}
}
| apache-2.0 |
YOLOSPAGHETTI/final-project | retrofit-adapters/rxjava/src/test/java/retrofit2/adapter/rxjava/RxJavaCallAdapterFactoryTest.java | 6925 | /*
* Copyright (C) 2015 Square, 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 retrofit2.adapter.rxjava;
import com.google.common.reflect.TypeToken;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import retrofit2.CallAdapter;
import retrofit2.Response;
import retrofit2.Retrofit;
import rx.Observable;
import rx.Single;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class RxJavaCallAdapterFactoryTest {
private static final Annotation[] NO_ANNOTATIONS = new Annotation[0];
private final CallAdapter.Factory factory = RxJavaCallAdapterFactory.create();
private Retrofit retrofit;
@Before public void setUp() {
retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:1")
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(factory)
.build();
}
@Test public void nullSchedulerThrows() {
try {
RxJavaCallAdapterFactory.createWithScheduler(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("scheduler == null");
}
}
@Test public void nonRxJavaTypeReturnsNull() {
CallAdapter<?> adapter = factory.get(String.class, NO_ANNOTATIONS, retrofit);
assertThat(adapter).isNull();
}
@Test public void responseTypes() {
Type oBodyClass = new TypeToken<Observable<String>>() {}.getType();
assertThat(factory.get(oBodyClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type sBodyClass = new TypeToken<Single<String>>() {}.getType();
assertThat(factory.get(sBodyClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type oBodyWildcard = new TypeToken<Observable<? extends String>>() {}.getType();
assertThat(factory.get(oBodyWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type sBodyWildcard = new TypeToken<Single<? extends String>>() {}.getType();
assertThat(factory.get(sBodyWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type oBodyGeneric = new TypeToken<Observable<List<String>>>() {}.getType();
assertThat(factory.get(oBodyGeneric, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(new TypeToken<List<String>>() {}.getType());
Type sBodyGeneric = new TypeToken<Single<List<String>>>() {}.getType();
assertThat(factory.get(sBodyGeneric, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(new TypeToken<List<String>>() {}.getType());
Type oResponseClass = new TypeToken<Observable<Response<String>>>() {}.getType();
assertThat(factory.get(oResponseClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type sResponseClass = new TypeToken<Single<Response<String>>>() {}.getType();
assertThat(factory.get(sResponseClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type oResponseWildcard = new TypeToken<Observable<Response<? extends String>>>() {}.getType();
assertThat(factory.get(oResponseWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type sResponseWildcard = new TypeToken<Single<Response<? extends String>>>() {}.getType();
assertThat(factory.get(sResponseWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type oResultClass = new TypeToken<Observable<Result<String>>>() {}.getType();
assertThat(factory.get(oResultClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type sResultClass = new TypeToken<Single<Result<String>>>() {}.getType();
assertThat(factory.get(sResultClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type oResultWildcard = new TypeToken<Observable<Result<? extends String>>>() {}.getType();
assertThat(factory.get(oResultWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type sResultWildcard = new TypeToken<Single<Result<? extends String>>>() {}.getType();
assertThat(factory.get(sResultWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
}
@Test public void rawBodyTypeThrows() {
Type observableType = new TypeToken<Observable>() {}.getType();
try {
factory.get(observableType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage(
"Observable return type must be parameterized as Observable<Foo> or Observable<? extends Foo>");
}
Type singleType = new TypeToken<Single>() {}.getType();
try {
factory.get(singleType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage(
"Single return type must be parameterized as Single<Foo> or Single<? extends Foo>");
}
}
@Test public void rawResponseTypeThrows() {
Type observableType = new TypeToken<Observable<Response>>() {}.getType();
try {
factory.get(observableType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage(
"Response must be parameterized as Response<Foo> or Response<? extends Foo>");
}
Type singleType = new TypeToken<Single<Response>>() {}.getType();
try {
factory.get(singleType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage(
"Response must be parameterized as Response<Foo> or Response<? extends Foo>");
}
}
@Test public void rawResultTypeThrows() {
Type observableType = new TypeToken<Observable<Result>>() {}.getType();
try {
factory.get(observableType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage(
"Result must be parameterized as Result<Foo> or Result<? extends Foo>");
}
Type singleType = new TypeToken<Single<Result>>() {}.getType();
try {
factory.get(singleType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage(
"Result must be parameterized as Result<Foo> or Result<? extends Foo>");
}
}
}
| apache-2.0 |
davidwebster48/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/taglib/el/ELJavascriptBundleTagBeanInfo.java | 2116 | /**
* Copyright 2008-2016 Ibrahim Chaehoi
*
* 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 net.jawr.web.taglib.el;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.beans.SimpleBeanInfo;
import java.util.ArrayList;
import java.util.List;
/**
* This class defines the bean information for the ELCSSBundleTag class.
*
* @author Ibrahim Chaehoi
*/
public class ELJavascriptBundleTagBeanInfo extends SimpleBeanInfo {
/*
* (non-Javadoc)
*
* @see java.beans.SimpleBeanInfo#getPropertyDescriptors()
*/
@Override
public PropertyDescriptor[] getPropertyDescriptors() {
List<PropertyDescriptor> proplist = new ArrayList<>();
try {
proplist.add(new PropertyDescriptor("type", ELJavascriptBundleTag.class, null, "setTypeExpr"));
} catch (IntrospectionException ex) {
}
try {
proplist.add(new PropertyDescriptor("async", ELJavascriptBundleTag.class, null, "setAsync"));
} catch (IntrospectionException ex) {
}
try {
proplist.add(new PropertyDescriptor("defer", ELJavascriptBundleTag.class, null, "setDefer"));
} catch (IntrospectionException ex) {
}
try {
proplist.add(new PropertyDescriptor("src", ELJavascriptBundleTag.class, null, "setSrcExpr"));
} catch (IntrospectionException ex) {
}
try {
proplist.add(new PropertyDescriptor("useRandomParam", ELJavascriptBundleTag.class, null,
"setUseRandomParamExpr"));
} catch (IntrospectionException ex) {
}
PropertyDescriptor[] result = new PropertyDescriptor[proplist.size()];
return ((PropertyDescriptor[]) proplist.toArray(result));
}
}
| apache-2.0 |
speddy93/nifi | nifi-mock/src/main/java/org/apache/nifi/util/TestRunner.java | 37135 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.util;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import org.apache.nifi.components.AllowableValue;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.components.ValidationResult;
import org.apache.nifi.controller.ControllerService;
import org.apache.nifi.controller.queue.QueueSize;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSessionFactory;
import org.apache.nifi.processor.Processor;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.provenance.ProvenanceEventRecord;
import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.state.MockStateManager;
public interface TestRunner {
/**
* @return the {@link Processor} for which this <code>TestRunner</code> is
* configured
*/
Processor getProcessor();
/**
* @return the {@link ProcessSessionFactory} that this
* <code>TestRunner</code> will use to invoke the
* {@link Processor#onTrigger(ProcessContext, ProcessSessionFactory)} method
*/
ProcessSessionFactory getProcessSessionFactory();
/**
* @return the {@Link ProcessContext} that this <code>TestRunner</code> will
* use to invoke the
* {@link Processor#onTrigger(ProcessContext, ProcessSessionFactory) onTrigger}
* method
*/
ProcessContext getProcessContext();
/**
* Performs exactly the same operation as calling {@link #run(int)} with a
* value of 1.
*/
void run();
/**
* Performs the same operation as calling {@link #run(int, boolean)} with a
* value of <code>true</code>
*
* @param iterations number of iterations
*/
void run(int iterations);
/**
* performs the same operation as calling {@link #run(int, boolean, boolean)}
* with a value of {@code iterations}, {@code stopOnFinish}, {@code true}
*
* @param iterations number of iterations
* @param stopOnFinish flag to stop when finished
*/
void run(int iterations, boolean stopOnFinish);
/**
* This method runs the {@link Processor} <code>iterations</code> times,
* using the sequence of steps below:
* <ul>
* <li>
* If {@code initialize} is true, run all methods on the Processor that are
* annotated with the
* {@link org.apache.nifi.processor.annotation.OnScheduled @OnScheduled} annotation. If
* any of these methods throws an Exception, the Unit Test will fail.
* </li>
* <li>
* Schedule the
* {@link Processor#onTrigger(ProcessContext, ProcessSessionFactory) onTrigger}
* method to be invoked <code>iterations</code> times. The number of threads
* used to run these iterations is determined by the ThreadCount of this
* <code>TestRunner</code>. By default, the value is set to 1, but it can be
* modified by calling the {@link #setThreadCount(int)} method.
* </li>
* <li>
* As soon as the first thread finishes its execution of
* {@link Processor#onTrigger(ProcessContext, ProcessSessionFactory) onTrigger},
* all methods on the Processor that are annotated with the
* {@link org.apache.nifi.processor.annotation.OnUnscheduled @OnUnscheduled} annotation
* are invoked. If any of these methods throws an Exception, the Unit Test
* will fail.
* </li>
* <li>
* Waits for all threads to finish execution.
* </li>
* <li>
* If and only if the value of <code>shutdown</code> is true: Call all
* methods on the Processor that is annotated with the
* {@link org.apache.nifi.processor.annotation.OnStopped @OnStopped} annotation.
* </li>
* </ul>
*
* @param iterations number of iterations
* @param stopOnFinish whether or not to run the Processor methods that are
* annotated with {@link org.apache.nifi.processor.annotation.OnStopped @OnStopped}
* @param initialize true if must initialize
*/
void run(int iterations, boolean stopOnFinish, final boolean initialize);
/**
* This method runs the {@link Processor} <code>iterations</code> times,
* using the sequence of steps below:
* <ul>
* <li>
* If {@code initialize} is true, run all methods on the Processor that are
* annotated with the
* {@link org.apache.nifi.processor.annotation.OnScheduled @OnScheduled} annotation. If
* any of these methods throws an Exception, the Unit Test will fail.
* </li>
* <li>
* Schedule the
* {@link Processor#onTrigger(ProcessContext, ProcessSessionFactory) onTrigger}
* method to be invoked <code>iterations</code> times. The number of threads
* used to run these iterations is determined by the ThreadCount of this
* <code>TestRunner</code>. By default, the value is set to 1, but it can be
* modified by calling the {@link #setThreadCount(int)} method.
* </li>
* <li>
* As soon as the first thread finishes its execution of
* {@link Processor#onTrigger(ProcessContext, ProcessSessionFactory) onTrigger},
* all methods on the Processor that are annotated with the
* {@link org.apache.nifi.processor.annotation.OnUnscheduled @OnUnscheduled} annotation
* are invoked. If any of these methods throws an Exception, the Unit Test
* will fail.
* </li>
* <li>
* Waits for all threads to finish execution.
* </li>
* <li>
* If and only if the value of <code>shutdown</code> is true: Call all
* methods on the Processor that is annotated with the
* {@link org.apache.nifi.processor.annotation.OnStopped @OnStopped} annotation.
* </li>
* </ul>
*
* @param iterations number of iterations
* @param stopOnFinish whether or not to run the Processor methods that are
* annotated with {@link org.apache.nifi.processor.annotation.OnStopped @OnStopped}
* @param initialize true if must initialize
* @param runWait indicates the amount of time in milliseconds that the framework should wait for
* processors to stop running before calling the {@link org.apache.nifi.processor.annotation.OnUnscheduled @OnUnscheduled} annotation
*/
void run(int iterations, boolean stopOnFinish, final boolean initialize, final long runWait);
/**
* Invokes all methods on the Processor that are annotated with the
* {@link org.apache.nifi.processor.annotation.OnShutdown @OnShutdown} annotation. If
* any of these methods throws an Exception, the Unit Test will fail
*/
void shutdown();
/**
* Updates the number of threads that will be used to run the Processor when
* calling the {@link #run()} or {@link #run(int)} methods.
*
* @param threadCount num threads
*/
void setThreadCount(int threadCount);
/**
* @return the currently configured number of threads that will be used to
* runt he Processor when calling the {@link #run()} or {@link #run(int)}
* methods
*/
int getThreadCount();
/**
* Updates the value of the property with the given PropertyDescriptor to
* the specified value IF and ONLY IF the value is valid according to the
* descriptor's validator. Otherwise, Assert.fail() is called, causing the
* unit test to fail
*
* @param propertyName name
* @param propertyValue value
* @return result
*/
ValidationResult setProperty(String propertyName, String propertyValue);
/**
* Updates the value of the property with the given PropertyDescriptor to
* the specified value IF and ONLY IF the value is valid according to the
* descriptor's validator. Otherwise, Assert.fail() is called, causing the
* unit test to fail
*
* @param descriptor descriptor
* @param value value
* @return result
*/
ValidationResult setProperty(PropertyDescriptor descriptor, String value);
/**
* Updates the value of the property with the given PropertyDescriptor to
* the specified value IF and ONLY IF the value is valid according to the
* descriptor's validator. Otherwise, Assert.fail() is called, causing the
* unit test to fail
*
* @param descriptor descriptor
* @param value allowable valu
* @return result
*/
ValidationResult setProperty(PropertyDescriptor descriptor, AllowableValue value);
/**
* Sets the annotation data.
*
* @param annotationData data
*/
void setAnnotationData(String annotationData);
/**
* Asserts that all FlowFiles that were transferred were transferred to the
* given relationship
*
* @param relationship to verify
*/
void assertAllFlowFilesTransferred(String relationship);
/**
* Asserts that all FlowFiles that were transferred were transferred to the
* given relationship
*
* @param relationship to verify
*/
void assertAllFlowFilesTransferred(Relationship relationship);
/**
* Asserts that all FlowFiles that were transferred were transferred to the
* given relationship and that the number of FlowFiles transferred is equal
* to <code>count</code>
*
* @param relationship to verify
* @param count number of expected transfers
*/
void assertAllFlowFilesTransferred(String relationship, int count);
/**
* Asserts that all FlowFiles that were transferred were transferred to the
* given relationship and that the number of FlowFiles transferred is equal
* to <code>count</code>
*
* @param relationship to verify
* @param count number of expected transfers
*/
void assertAllFlowFilesTransferred(Relationship relationship, int count);
/**
* Asserts that all FlowFiles that were transferred contain the given
* attribute.
*
* @param attributeName attribute to look for
*/
void assertAllFlowFilesContainAttribute(String attributeName);
/**
* Asserts that all FlowFiles that were transferred to the given
* relationship contain the given attribute.
*
* @param relationship relationship to check
* @param attributeName attribute to look for
*/
void assertAllFlowFilesContainAttribute(Relationship relationship, String attributeName);
/**
* Asserts that all FlowFiles that were transferred are compliant with the
* given validator.
*
* @param validator validator to use
*/
void assertAllFlowFiles(FlowFileValidator validator);
/**
* Asserts that all FlowFiles that were transferred in the given relationship
* are compliant with the given validator.
*
* @param validator validator to use
*/
void assertAllFlowFiles(Relationship relationship, FlowFileValidator validator);
/**
* Assert that the number of FlowFiles transferred to the given relationship
* is equal to the given count
*
* @param relationship to verify
* @param count number of expected transfers
*/
void assertTransferCount(Relationship relationship, int count);
/**
* Assert that the number of FlowFiles transferred to the given relationship
* is equal to the given count
*
* @param relationship to verify
* @param count number of expected transfers
*/
void assertTransferCount(String relationship, int count);
/**
* Assert that the number of FlowFiles that were penalized is equal to the given count
*
* @param count
* number of expected penalized
*/
void assertPenalizeCount(int count);
/**
* Assert that there are no FlowFiles left on the input queue.
*/
void assertQueueEmpty();
/**
* @return <code>true</code> if the Input Queue to the Processor is empty,
* <code>false</code> otherwise
*/
boolean isQueueEmpty();
/**
* Assert that there is at least one FlowFile left on the input queue.
*/
void assertQueueNotEmpty();
/**
* Assert that the currently configured set of properties/annotation data
* are valid
*/
void assertValid();
/**
* Assert that the currently configured set of properties/annotation data
* are NOT valid
*/
void assertNotValid();
/**
* Resets the Transfer Counts that indicate how many FlowFiles have been
* transferred to each Relationship and removes from memory any FlowFiles
* that have been transferred to this Relationships. This method should be
* called between successive calls to {@link #run(int) run} if the output is
* to be examined after each run.
*/
void clearTransferState();
/**
* Enqueues the given FlowFiles into the Processor's input queue
*
* @param flowFiles to enqueue
*/
void enqueue(FlowFile... flowFiles);
/**
* Reads the content from the given {@link Path} into memory and creates a
* FlowFile from this content with no attributes and adds this FlowFile to
* the Processor's Input Queue
*
* @param path to read content from
* @throws IOException if unable to read content
*/
MockFlowFile enqueue(Path path) throws IOException;
/**
* Reads the content from the given {@link Path} into memory and creates a
* FlowFile from this content with the given attributes and adds this
* FlowFile to the Processor's Input Queue
*
* @param path to read content from
* @param attributes attributes to use for new flow file
* @throws IOException if unable to read content
*/
MockFlowFile enqueue(Path path, Map<String, String> attributes) throws IOException;
/**
* Copies the content from the given byte array into memory and creates a
* FlowFile from this content with no attributes and adds this FlowFile to
* the Processor's Input Queue
*
* @param data to enqueue
*/
MockFlowFile enqueue(byte[] data);
/**
* Creates a FlowFile with the content set to the given string (in UTF-8 format), with no attributes,
* and adds this FlowFile to the Processor's Input Queue
*
* @param data to enqueue
*/
MockFlowFile enqueue(String data);
/**
* Copies the content from the given byte array into memory and creates a
* FlowFile from this content with the given attributes and adds this
* FlowFile to the Processor's Input Queue
*
* @param data to enqueue
* @param attributes to use for enqueued item
*/
MockFlowFile enqueue(byte[] data, Map<String, String> attributes);
/**
* Creates a FlowFile with the content set to the given string (in UTF-8 format), with the given attributes,
* and adds this FlowFile to the Processor's Input Queue
*
* @param data to enqueue
* @param attributes to use for enqueued item
*/
MockFlowFile enqueue(String data, Map<String, String> attributes);
/**
* Reads the content from the given {@link InputStream} into memory and
* creates a FlowFile from this content with no attributes and adds this
* FlowFile to the Processor's Input Queue
*
* @param data to source data from
*/
MockFlowFile enqueue(InputStream data);
/**
* Reads the content from the given {@link InputStream} into memory and
* creates a FlowFile from this content with the given attributes and adds
* this FlowFile to the Processor's Input Queue
*
* @param data source of data
* @param attributes to use for flow files
*/
MockFlowFile enqueue(InputStream data, Map<String, String> attributes);
/**
* Copies the contents of the given {@link MockFlowFile} into a byte array
* and returns that byte array.
*
* @param flowFile to get content for
* @return byte array of flowfile content
*/
byte[] getContentAsByteArray(MockFlowFile flowFile);
/**
* Returns a List of FlowFiles in the order in which they were transferred
* to the given relationship
*
* @param relationship to get flowfiles for
* @return flowfiles transferred to given relationship
*/
List<MockFlowFile> getFlowFilesForRelationship(String relationship);
/**
* Returns a List of FlowFiles in the order in which they were transferred
* to the given relationship
*
* @param relationship to get flowfiles for
* @return flowfiles transferred to given relationship
*/
List<MockFlowFile> getFlowFilesForRelationship(Relationship relationship);
/**
* Returns a List of FlowFiles in the order in which they were transferred that were penalized
*
* @return flowfiles that were penalized
*/
List<MockFlowFile> getPenalizedFlowFiles();
/**
* @return the current size of the Processor's Input Queue
*/
QueueSize getQueueSize();
/**
* @param name of counter
* @return the current value of the counter with the specified name, or null
* if no counter exists with the specified name
*/
Long getCounterValue(String name);
/**
* @return the number of FlowFiles that have been removed from the system
*/
int getRemovedCount();
/**
* Indicates to the Framework that the given Relationship should be
* considered "available", meaning that the queues of all Connections that
* contain this Relationship are not full. This is generally used only when
* dealing with Processors that use the
* {@link org.apache.nifi.processor.annotation.TriggerWhenAnyDestinationAvailable}
* annotation.
*
* @param relationship to mark as available
*/
void setRelationshipAvailable(Relationship relationship);
/**
* Indicates to the Framework that the given Relationship with the given
* name should be considered "available", meaning that the queues of all
* Connections that contain this Relationship are not full. This is
* generally used only when dealing with Processors that use the
* {@link org.apache.nifi.processor.annotation.TriggerWhenAnyDestinationAvailable}
*
* @param relationshipName relationship name
*/
void setRelationshipAvailable(String relationshipName);
/**
* Indicates to the Framework that the given Relationship should NOT be
* considered "available", meaning that the queue of at least one Connection
* that contain this Relationship is full. This is generally used only when
* dealing with Processors that use the
* {@link org.apache.nifi.processor.annotation.TriggerWhenAnyDestinationAvailable}
* annotation.
*
* @param relationship to mark as unavailable
*/
void setRelationshipUnavailable(Relationship relationship);
/**
* Indicates to the Framework that the Relationship with the given name
* should NOT be considered "available", meaning that the queue of at least
* one Connection that contain this Relationship is full. This is generally
* used only when dealing with Processors that use the
* {@link org.apache.nifi.processor.annotation.TriggerWhenAnyDestinationAvailable}
*
* @param relationshipName name of relationship.
*/
void setRelationshipUnavailable(String relationshipName);
/**
* Indicates to the framework that the configured processor has one or more
* incoming connections.
*
* @param hasIncomingConnection whether or not the configured processor should behave as though it has an incoming connection
*/
void setIncomingConnection(boolean hasIncomingConnection);
/**
* Indicates to the framework that the configured processor has one or more incoming
* connections for which the processor is not also the source.
*
* @param hasNonLoopConnection whether or not the configured processor should behave as though it has a non-looping incoming connection
*/
void setNonLoopConnection(boolean hasNonLoopConnection);
/**
* Indicates to the Framework that the configured processor has a connection for the given Relationship.
*
* @param relationship that has a connection
*/
void addConnection(Relationship relationship);
/**
* Indicates to the Framework that the configured processor has a connection for the
* Relationship with the given name.
*
* @param relationshipName name of relationship that has a connection
*/
void addConnection(String relationshipName);
/**
* Removes the connection for the given Relationship from the configured processor.
*
* @param relationship to remove
*/
void removeConnection(Relationship relationship);
/**
* Removes the connection for the relationship with the given name from the configured processor.
*
* @param relationshipName name of the relationship to remove
*/
void removeConnection(String relationshipName);
/**
* Adds the given {@link ControllerService} to this TestRunner so that the
* configured Processor can access it using the given
* <code>identifier</code>. The ControllerService is not expected to be
* initialized, as the framework will create the appropriate
* {@link org.apache.nifi.controller.ControllerServiceInitializationContext ControllerServiceInitializationContext}
* and initialize the ControllerService with no specified properties.
*
* This will call any method on the given Controller Service that is
* annotated with the
* {@link org.apache.nifi.annotation.lifecycle.OnAdded @OnAdded} annotation.
*
* @param identifier of service
* @param service the service
* @throws InitializationException ie
*/
void addControllerService(String identifier, ControllerService service) throws InitializationException;
/**
* Adds the given {@link ControllerService} to this TestRunner so that the
* configured Processor can access it using the given
* <code>identifier</code>. The ControllerService is not expected to be
* initialized, as the framework will create the appropriate
* {@link org.apache.nifi.controller.ControllerServiceInitializationContext ControllerServiceInitializationContext}
* and initialize the ControllerService with the given properties.
*
* This will call any method on the given Controller Service that is
* annotated with the
* {@link org.apache.nifi.annotation.lifecycle.OnAdded @OnAdded} annotation.
*
* @param identifier of service
* @param service the service
* @param properties service properties
* @throws InitializationException ie
*/
void addControllerService(String identifier, ControllerService service, Map<String, String> properties) throws InitializationException;
/**
* <p>
* Marks the Controller Service as enabled so that it can be used by other
* components.
* </p>
*
* <p>
* This method will result in calling any method in the Controller Service
* that is annotated with the
* {@link org.apache.nifi.annotation.lifecycle.OnEnabled @OnEnabled}
* annotation.
* </p>
*
* @param service the service to enable
*/
void enableControllerService(ControllerService service);
/**
* <p>
* Marks the Controller Service as disabled so that it cannot be used by
* other components.
* </p>
*
* <p>
* This method will result in calling any method in the Controller Service
* that is annotated with the
* {@link org.apache.nifi.annotation.lifecycle.OnDisabled @OnDisabled}
* annotation.
* </p>
*
* @param service the service to disable
*/
void disableControllerService(ControllerService service);
/**
* @param service the service
* @return {@code true} if the given Controller Service is enabled,
* {@code false} if it is disabled
*
* @throws IllegalArgumentException if the given ControllerService is not
* known by this TestRunner (i.e., it has not been added via the
* {@link #addControllerService(String, ControllerService)} or
* {@link #addControllerService(String, ControllerService, Map)} method or
* if the Controller Service has been removed via the
* {@link #removeControllerService(ControllerService)} method.
*/
boolean isControllerServiceEnabled(ControllerService service);
/**
* <p>
* Removes the Controller Service from the TestRunner. This will call any
* method on the ControllerService that is annotated with the
* {@link org.apache.nifi.annotation.lifecycle.OnRemoved @OnRemoved}
* annotation.
* </p>
*
* @param service the service
*
* @throws IllegalStateException if the ControllerService is not disabled
* @throws IllegalArgumentException if the given ControllerService is not
* known by this TestRunner (i.e., it has not been added via the
* {@link #addControllerService(String, ControllerService)} or
* {@link #addControllerService(String, ControllerService, Map)} method or
* if the Controller Service has been removed via the
* {@link #removeControllerService(ControllerService)} method.
*
*/
void removeControllerService(ControllerService service);
/**
* Sets the given property on the given ControllerService
*
* @param service to modify
* @param property to modify
* @param value value to use
* @return result
*
* @throws IllegalStateException if the ControllerService is not disabled
* @throws IllegalArgumentException if the given ControllerService is not
* known by this TestRunner (i.e., it has not been added via the
* {@link #addControllerService(String, ControllerService)} or
* {@link #addControllerService(String, ControllerService, Map)} method or
* if the Controller Service has been removed via the
* {@link #removeControllerService(ControllerService)} method.
*
*/
ValidationResult setProperty(ControllerService service, PropertyDescriptor property, String value);
/**
* Sets the given property on the given ControllerService
*
* @param service to modify
* @param property to modify
* @param value value to use
* @return result
*
* @throws IllegalStateException if the ControllerService is not disabled
* @throws IllegalArgumentException if the given ControllerService is not
* known by this TestRunner (i.e., it has not been added via the
* {@link #addControllerService(String, ControllerService)} or
* {@link #addControllerService(String, ControllerService, Map)} method or
* if the Controller Service has been removed via the
* {@link #removeControllerService(ControllerService)} method.
*
*/
ValidationResult setProperty(ControllerService service, PropertyDescriptor property, AllowableValue value);
/**
* Sets the property with the given name on the given ControllerService
*
* @param service to modify
* @param propertyName to modify
* @param value value to use
* @return result
*
* @throws IllegalStateException if the ControllerService is not disabled
* @throws IllegalArgumentException if the given ControllerService is not
* known by this TestRunner (i.e., it has not been added via the
* {@link #addControllerService(String, ControllerService)} or
* {@link #addControllerService(String, ControllerService, Map)} method or
* if the Controller Service has been removed via the
* {@link #removeControllerService(ControllerService)} method.
*
*/
ValidationResult setProperty(ControllerService service, String propertyName, String value);
/**
* Sets the annotation data of the given service to the provided annotation
* data.
*
* @param service to modify
* @param annotationData the data
*
* @throws IllegalStateException if the Controller Service is not disabled
*
* @throws IllegalArgumentException if the given ControllerService is not
* known by this TestRunner (i.e., it has not been added via the
* {@link #addControllerService(String, ControllerService)} or
* {@link #addControllerService(String, ControllerService, Map)} method or
* if the Controller Service has been removed via the
* {@link #removeControllerService(ControllerService)} method.
*/
void setAnnotationData(ControllerService service, String annotationData);
/**
* @param identifier of controller service
* @return the {@link ControllerService} that is registered with the given
* identifier, or <code>null</code> if no Controller Service exists with the
* given identifier
*/
ControllerService getControllerService(String identifier);
/**
* Assert that the currently configured set of properties/annotation data
* are valid for the given Controller Service.
*
* @param service the service to validate
* @throws IllegalArgumentException if the given ControllerService is not
* known by this TestRunner (i.e., it has not been added via the
* {@link #addControllerService(String, ControllerService)} or
* {@link #addControllerService(String, ControllerService, Map)} method or
* if the Controller Service has been removed via the
* {@link #removeControllerService(ControllerService)} method.
*/
void assertValid(ControllerService service);
/**
* Assert that the currently configured set of properties/annotation data
* are NOT valid for the given Controller Service.
*
* @param service the service to validate
* @throws IllegalArgumentException if the given ControllerService is not
* known by this TestRunner (i.e., it has not been added via the
* {@link #addControllerService(String, ControllerService)} or
* {@link #addControllerService(String, ControllerService, Map)} method or
* if the Controller Service has been removed via the
* {@link #removeControllerService(ControllerService)} method.
*
*/
void assertNotValid(ControllerService service);
/**
* @param <T> type of service
* @param identifier identifier of service
* @param serviceType type of service
* @return the {@link ControllerService} that is registered with the given
* identifier, cast as the provided service type, or <code>null</code> if no
* Controller Service exists with the given identifier
*
* @throws ClassCastException if the identifier given is registered for a
* Controller Service but that Controller Service is not of the type
* specified
*/
<T extends ControllerService> T getControllerService(String identifier, Class<T> serviceType);
/**
* Specifies whether or not the TestRunner will validate the use of
* Expression Language. By default, the value is <code>true</code>, which
* means that an Exception will be thrown if the Processor attempts to
* obtain the configured value of a Property without calling
* {@link org.apache.nifi.components.PropertyValue#evaluateAttributeExpressions evaluateAttributeExpressions}
* on the Property Value or if
* {@link org.apache.nifi.components.PropertyValue#evaluateAttributeExpressions evaluateAttributeExpressions}
* is called but the PropertyDescriptor indicates that the Expression
* Language is not supported.
*
* <p>
* <b>See Also:
* </b>{@link PropertyDescriptor.Builder#expressionLanguageSupported(boolean)}
* </p>
*
* @param validate whether there is any need to validate the EL was used
*/
void setValidateExpressionUsage(boolean validate);
/**
* Removes the {@link PropertyDescriptor} from the {@link ProcessContext},
* effectively setting its value to null, or the property's default value, if it has one.
*
* @param descriptor of property to remove
* @return <code>true</code> if removed, <code>false</code> if the property was not set
*/
boolean removeProperty(PropertyDescriptor descriptor);
/**
* Returns a {@link List} of all {@link ProvenanceEventRecord}s that were
* emitted by the Processor
*
* @return a List of all Provenance Events that were emitted by the
* Processor
*/
List<ProvenanceEventRecord> getProvenanceEvents();
/**
* Clears the Provenance Events that have been emitted by the Processor
*/
void clearProvenanceEvents();
/**
* Returns the {@link MockComponentLog} that is used by the Processor under test.
* @return the logger
*/
public MockComponentLog getLogger();
/**
* Returns the {@link MockComponentLog} that is used by the specified controller service.
*
* @param identifier a controller service identifier
* @return the logger
*/
public MockComponentLog getControllerServiceLogger(final String identifier);
/**
* @return the State Manager that is used to stored and retrieve state
*/
MockStateManager getStateManager();
/**
* @param service the controller service of interest
* @return the State Manager that is used to store and retrieve state for the given controller service
*/
MockStateManager getStateManager(ControllerService service);
/**
* @param clustered Specify if this test emulates running in a clustered environment
*/
void setClustered(boolean clustered);
/**
* @param primaryNode Specify if this test emulates running as a primary node
*/
void setPrimaryNode(boolean primaryNode);
/**
* Sets the value of the variable with the given name to be the given value. This exposes the variable
* for use by the Expression Language.
*
* @param name the name of the variable to set
* @param value the value of the variable
*
* @throws NullPointerException if either the name or the value is null
*/
void setVariable(String name, String value);
/**
* Returns the current value of the variable with the given name
*
* @param name the name of the variable whose value should be returned.
* @return the current value of the variable with the given name or <code>null</code> if no value is currently set
*
* @throws NullPointerException if the name is null
*/
String getVariableValue(String name);
/**
* Removes the variable with the given name from this Test Runner, if it is set.
*
* @param name the name of the variable to remove
* @return the value that was set for the variable, or <code>null</code> if the variable was not set
*
* @throws NullPointerException if the name is null
*/
String removeVariable(String name);
/**
* Asserts that all FlowFiles meet all conditions.
*
* @param relationshipName relationship name
* @param predicate conditions
*/
void assertAllConditionsMet(final String relationshipName, Predicate<MockFlowFile> predicate);
/**
* Asserts that all FlowFiles meet all conditions.
*
* @param relationship relationship
* @param predicate conditions
*/
void assertAllConditionsMet(final Relationship relationship, Predicate<MockFlowFile> predicate);
}
| apache-2.0 |
pascalrobert/aribaweb | src/widgets/src/main/java/ariba/ui/widgets/BrandingComponent.java | 2359 | /*
Copyright 1996-2008 Ariba, 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.
$Id: //ariba/platform/ui/widgets/ariba/ui/widgets/BrandingComponent.java#12 $
*/
package ariba.ui.widgets;
import ariba.ui.aribaweb.core.AWBinding;
import ariba.ui.aribaweb.core.AWComponent;
import ariba.ui.aribaweb.core.AWTemplate;
import ariba.ui.aribaweb.core.AWElement;
abstract public class BrandingComponent extends AWComponent
{
public Object findValueForBinding (String bindingName)
{
AWComponent parent;
for (parent = parent(); parent != null; parent = parent.parent()) {
AWBinding binding = parent.bindingForName(bindingName);
if (binding != null) {
return parent.valueForBinding(binding);
}
}
return null;
}
public String resolveTemplateOrComponentBasedInclude (String bindingName)
{
String bindingValue = (String)findValueForBinding(bindingName);
if (bindingValue == null &&
BrandingComponent.componentWithTemplateNamed(bindingName, this) != null)
{
return bindingName;
}
return bindingValue;
}
public static AWComponent componentWithTemplateNamed (String templateName,
AWComponent component)
{
AWComponent context = component;
for (; context != null; context = context.parent()) {
AWElement contentElement = context.componentReference().contentElement();
if (contentElement instanceof AWTemplate) {
AWTemplate template = (AWTemplate)contentElement;
if (template.indexOfNamedSubtemplate(templateName, component) != -1) {
return context;
}
}
}
return null;
}
}
| apache-2.0 |
WSO2Telco/component-dep | components/mediator/src/main/java/com/wso2telco/dep/mediator/entity/provision/ServiceInfo.java | 1477 | /*******************************************************************************
* Copyright (c) 2015-2016, WSO2.Telco Inc. (http://www.wso2telco.com) All Rights Reserved.
*
* WSO2.Telco Inc. licences this file to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.wso2telco.dep.mediator.entity.provision;
public class ServiceInfo {
private String serviceCode;
private String description;
private String serviceCharge;
public String getServiceCode() {
return serviceCode;
}
public void setServiceCode(String serviceCode) {
this.serviceCode = serviceCode;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getServiceCharge() {
return serviceCharge;
}
public void setServiceCharge(String serviceCharge) {
this.serviceCharge = serviceCharge;
}
}
| apache-2.0 |
smmribeiro/intellij-community | platform/platform-api/src/com/intellij/util/net/IdeaWideProxySelector.java | 4869 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. 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.net;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.SystemProperties;
import com.intellij.util.proxy.CommonProxy;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.net.*;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
public final class IdeaWideProxySelector extends ProxySelector {
private final static Logger LOG = Logger.getInstance(IdeaWideProxySelector.class);
private static final String DOCUMENT_BUILDER_FACTORY_KEY = "javax.xml.parsers.DocumentBuilderFactory";
private final HttpConfigurable myHttpConfigurable;
private final AtomicReference<Pair<ProxySelector, String>> myPacProxySelector = new AtomicReference<>();
public IdeaWideProxySelector(@NotNull HttpConfigurable configurable) {
myHttpConfigurable = configurable;
}
@Override
public List<Proxy> select(@NotNull URI uri) {
LOG.debug("IDEA-wide proxy selector asked for " + uri.toString());
String scheme = uri.getScheme();
if (!("http".equals(scheme) || "https".equals(scheme))) {
LOG.debug("No proxy: not http/https scheme: " + scheme);
return CommonProxy.NO_PROXY_LIST;
}
if (myHttpConfigurable.USE_HTTP_PROXY) {
if (myHttpConfigurable.isProxyException(uri)) {
LOG.debug("No proxy: URI '", uri, "' matches proxy exceptions [", myHttpConfigurable.PROXY_EXCEPTIONS, "]");
return CommonProxy.NO_PROXY_LIST;
}
if (myHttpConfigurable.PROXY_PORT < 0 || myHttpConfigurable.PROXY_PORT > 65535) {
LOG.debug("No proxy: invalid port: " + myHttpConfigurable.PROXY_PORT);
return CommonProxy.NO_PROXY_LIST;
}
Proxy.Type type = myHttpConfigurable.PROXY_TYPE_IS_SOCKS ? Proxy.Type.SOCKS : Proxy.Type.HTTP;
Proxy proxy = new Proxy(type, new InetSocketAddress(myHttpConfigurable.PROXY_HOST, myHttpConfigurable.PROXY_PORT));
LOG.debug("Defined proxy: ", proxy);
myHttpConfigurable.LAST_ERROR = null;
return Collections.singletonList(proxy);
}
if (myHttpConfigurable.USE_PROXY_PAC) {
// https://youtrack.jetbrains.com/issue/IDEA-262173
String oldDocumentBuilderFactory =
System.setProperty(DOCUMENT_BUILDER_FACTORY_KEY, "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
try {
return selectUsingPac(uri);
}
catch (Throwable e) {
LOG.error("Cannot select using PAC", e);
}
finally {
SystemProperties.setProperty(DOCUMENT_BUILDER_FACTORY_KEY, oldDocumentBuilderFactory);
}
}
return CommonProxy.NO_PROXY_LIST;
}
@NotNull
private List<Proxy> selectUsingPac(@NotNull URI uri) {
// It is important to avoid resetting Pac based ProxySelector unless option was changed
// New instance will download configuration file and interpret it before making the connection
String pacUrlForUse = myHttpConfigurable.USE_PAC_URL && !StringUtil.isEmpty(myHttpConfigurable.PAC_URL) ? myHttpConfigurable.PAC_URL : null;
Pair<ProxySelector, String> pair = myPacProxySelector.get();
if (pair != null && !Objects.equals(pair.second, pacUrlForUse)) {
pair = null;
}
if (pair == null) {
ProxySelector newProxySelector = NetUtils.getProxySelector(pacUrlForUse);
pair = Pair.create(newProxySelector, pacUrlForUse);
myPacProxySelector.lazySet(pair);
}
ProxySelector pacProxySelector = pair.first;
if (pacProxySelector == null) {
LOG.debug("No proxies detected");
}
else {
try {
List<Proxy> select = pacProxySelector.select(uri);
LOG.debug("Autodetected proxies: ", select);
return select;
}
catch (StackOverflowError ignore) {
LOG.warn("Too large PAC script (JRE-247)");
}
}
return CommonProxy.NO_PROXY_LIST;
}
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
if (myHttpConfigurable.USE_PROXY_PAC) {
myHttpConfigurable.removeGeneric(new CommonProxy.HostInfo(uri.getScheme(), uri.getHost(), uri.getPort()));
LOG.debug("generic proxy credentials (if were saved) removed");
return;
}
final InetSocketAddress isa = sa instanceof InetSocketAddress ? (InetSocketAddress) sa : null;
if (myHttpConfigurable.USE_HTTP_PROXY && isa != null && Objects.equals(myHttpConfigurable.PROXY_HOST, isa.getHostString())) {
LOG.debug("connection failed message passed to http configurable");
myHttpConfigurable.LAST_ERROR = ioe.getMessage();
}
}
}
| apache-2.0 |
nvoron23/incubator-drill | exec/java-exec/src/main/java/org/apache/drill/exec/expr/fn/impl/IsNotFalse.java | 2139 | /**
* 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.expr.fn.impl;
import org.apache.drill.exec.expr.DrillSimpleFunc;
import org.apache.drill.exec.expr.annotations.FunctionTemplate;
import org.apache.drill.exec.expr.annotations.Output;
import org.apache.drill.exec.expr.annotations.Param;
import org.apache.drill.exec.expr.holders.BitHolder;
import org.apache.drill.exec.expr.holders.NullableBitHolder;
import org.apache.drill.exec.record.RecordBatch;
public class IsNotFalse {
@FunctionTemplate(names = {"isNotFalse", "isnotfalse", "is not false"}, scope = FunctionTemplate.FunctionScope.SIMPLE, nulls = FunctionTemplate.NullHandling.INTERNAL)
public static class Optional implements DrillSimpleFunc {
@Param NullableBitHolder in;
@Output BitHolder out;
public void setup(RecordBatch incoming) { }
public void eval() {
if (in.isSet == 0) {
out.value = 1;
} else {
out.value = in.value;
}
}
}
@FunctionTemplate(names = {"isNotFalse", "isnotfalse", "is not false"}, scope = FunctionTemplate.FunctionScope.SIMPLE, nulls = FunctionTemplate.NullHandling.INTERNAL)
public static class Required implements DrillSimpleFunc {
@Param BitHolder in;
@Output BitHolder out;
public void setup(RecordBatch incoming) { }
public void eval() {
out.value = in.value;
}
}
}
| apache-2.0 |
Spokeo/dynamodb-titan-storage-backend | src/test/java/com/amazon/titan/graphdb/dynamodb/AbstractDynamoDBGraphConcurrentTest.java | 1624 | /*
* Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazon.titan.graphdb.dynamodb;
import java.util.Collections;
import org.junit.AfterClass;
import com.amazon.titan.diskstorage.dynamodb.BackendDataModel;
import com.amazon.titan.diskstorage.dynamodb.test.TestGraphUtil;
import com.thinkaurelius.titan.diskstorage.BackendException;
import com.thinkaurelius.titan.diskstorage.configuration.WriteConfiguration;
import com.thinkaurelius.titan.graphdb.TitanGraphConcurrentTest;
/**
*
* @author Alexander Patrikalakis
*
*/
public abstract class AbstractDynamoDBGraphConcurrentTest extends TitanGraphConcurrentTest
{
protected final BackendDataModel model;
protected AbstractDynamoDBGraphConcurrentTest(BackendDataModel model) {
this.model = model;
}
@Override
public WriteConfiguration getConfiguration()
{
return TestGraphUtil.instance().getWriteConfiguration(model, Collections.<String>emptyList());
}
@AfterClass
public static void deleteTables() throws BackendException {
TestGraphUtil.cleanUpTables();
}
}
| apache-2.0 |
emre-aydin/hazelcast | hazelcast/src/main/java/com/hazelcast/replicatedmap/impl/operation/KeySetOperation.java | 2711 | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.replicatedmap.impl.operation;
import com.hazelcast.internal.serialization.SerializationService;
import com.hazelcast.map.impl.DataCollection;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.internal.serialization.Data;
import com.hazelcast.replicatedmap.impl.ReplicatedMapService;
import com.hazelcast.replicatedmap.impl.record.ReplicatedRecordStore;
import com.hazelcast.spi.impl.operationservice.ReadonlyOperation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class KeySetOperation extends AbstractNamedSerializableOperation implements ReadonlyOperation {
private String name;
private transient Object response;
public KeySetOperation() {
}
public KeySetOperation(String name) {
this.name = name;
}
@Override
public void run() throws Exception {
ReplicatedMapService service = getService();
Collection<ReplicatedRecordStore> stores = service.getAllReplicatedRecordStores(name);
List<Object> keys = new ArrayList<>();
for (ReplicatedRecordStore store : stores) {
keys.addAll(store.keySet(false));
}
ArrayList<Data> dataKeys = new ArrayList<>(keys.size());
SerializationService serializationService = getNodeEngine().getSerializationService();
for (Object key : keys) {
dataKeys.add(serializationService.toData(key));
}
response = new DataCollection(dataKeys);
}
@Override
public Object getResponse() {
return response;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
out.writeString(name);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
name = in.readString();
}
@Override
public int getClassId() {
return ReplicatedMapDataSerializerHook.KEY_SET;
}
@Override
public String getName() {
return name;
}
}
| apache-2.0 |
javaslang/javaslang-circuitbreaker | resilience4j-reactor/src/main/java/io/github/resilience4j/reactor/circuitbreaker/operator/CircuitBreakerOperator.java | 2373 | /*
* Copyright 2018 Julien Hoarau, Robert Winkler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.resilience4j.reactor.circuitbreaker.operator;
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.reactor.IllegalPublisherException;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.function.UnaryOperator;
/**
* A CircuitBreaker operator which checks if a downstream subscriber/observer can acquire a
* permission to subscribe to an upstream Publisher. Otherwise emits a {@link
* CallNotPermittedException} if the CircuitBreaker is OPEN.
*
* @param <T> the value type
*/
public class CircuitBreakerOperator<T> implements UnaryOperator<Publisher<T>> {
private final CircuitBreaker circuitBreaker;
private CircuitBreakerOperator(CircuitBreaker circuitBreaker) {
this.circuitBreaker = circuitBreaker;
}
/**
* Creates a CircuitBreakerOperator.
*
* @param <T> the value type of the upstream and downstream
* @param circuitBreaker the circuit breaker
* @return a CircuitBreakerOperator
*/
public static <T> CircuitBreakerOperator<T> of(CircuitBreaker circuitBreaker) {
return new CircuitBreakerOperator<>(circuitBreaker);
}
@Override
public Publisher<T> apply(Publisher<T> publisher) {
if (publisher instanceof Mono) {
return new MonoCircuitBreaker<>((Mono<? extends T>) publisher, circuitBreaker);
} else if (publisher instanceof Flux) {
return new FluxCircuitBreaker<>((Flux<? extends T>) publisher, circuitBreaker);
} else {
throw new IllegalPublisherException(publisher);
}
}
}
| apache-2.0 |
smmribeiro/intellij-community | platform/ide-core/src/com/intellij/openapi/vfs/SafeWriteRequestor.java | 720 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. 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.vfs;
import com.intellij.ide.ui.IdeUiService;
/**
* A marker interface for {@link VirtualFile#getOutputStream(Object)} to take extra caution w.r.t. an existing content.
* Specifically, if the operation fails for whatever reason (like not enough disk space left), the prior content shall not be overwritten.
*
* @author max
*/
public interface SafeWriteRequestor {
static boolean shouldUseSafeWrite(Object requestor) {
return requestor instanceof SafeWriteRequestor && IdeUiService.getInstance().isUseSafeWrite();
}
}
| apache-2.0 |
andreagenso/java2scala | test/J2s/java/openjdk-6-src-b27/jdk/src/share/classes/javax/management/MBeanPermission.java | 43036 | /*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.security.Permission;
/**
* <p>Permission controlling access to MBeanServer operations. If a
* security manager has been set using {@link
* System#setSecurityManager}, most operations on the MBean Server
* require that the caller's permissions imply an MBeanPermission
* appropriate for the operation. This is described in detail in the
* documentation for the {@link MBeanServer} interface.</p>
*
* <p>As with other {@link Permission} objects, an MBeanPermission can
* represent either a permission that you <em>have</em> or a
* permission that you <em>need</em>. When a sensitive operation is
* being checked for permission, an MBeanPermission is constructed
* representing the permission you need. The operation is only
* allowed if the permissions you have {@link #implies imply} the
* permission you need.</p>
*
* <p>An MBeanPermission contains four items of information:</p>
*
* <ul>
*
* <li><p>The <em>action</em>. For a permission you need,
* this is one of the actions in the list <a
* href="#action-list">below</a>. For a permission you have, this is
* a comma-separated list of those actions, or <code>*</code>,
* representing all actions.</p>
*
* <p>The action is returned by {@link #getActions()}.</p>
*
* <li><p>The <em>class name</em>.</p>
*
* <p>For a permission you need, this is the class name of an MBean
* you are accessing, as returned by {@link
* MBeanServer#getMBeanInfo(ObjectName)
* MBeanServer.getMBeanInfo(name)}.{@link MBeanInfo#getClassName()
* getClassName()}. Certain operations do not reference a class name,
* in which case the class name is null.</p>
*
* <p>For a permission you have, this is either empty or a <em>class
* name pattern</em>. A class name pattern is a string following the
* Java conventions for dot-separated class names. It may end with
* "<code>.*</code>" meaning that the permission grants access to any
* class that begins with the string preceding "<code>.*</code>". For
* instance, "<code>javax.management.*</code>" grants access to
* <code>javax.management.MBeanServerDelegate</code> and
* <code>javax.management.timer.Timer</code>, among other classes.</p>
*
* <p>A class name pattern can also be empty or the single character
* "<code>*</code>", both of which grant access to any class.</p>
*
* <li><p>The <em>member</em>.</p>
*
* <p>For a permission you need, this is the name of the attribute or
* operation you are accessing. For operations that do not reference
* an attribute or operation, the member is null.</p>
*
* <p>For a permission you have, this is either the name of an attribute
* or operation you can access, or it is empty or the single character
* "<code>*</code>", both of which grant access to any member.</p>
*
* <li><p>The <em>object name</em>.</p>
*
* <p>For a permission you need, this is the {@link ObjectName} of the
* MBean you are accessing. For operations that do not reference a
* single MBean, it is null. It is never an object name pattern.</p>
*
* <p>For a permission you have, this is the {@link ObjectName} of the
* MBean or MBeans you can access. It may be an object name pattern
* to grant access to all MBeans whose names match the pattern. It
* may also be empty, which grants access to all MBeans whatever their
* name.</p>
*
* </ul>
*
* <p>If you have an MBeanPermission, it allows operations only if all
* four of the items match.</p>
*
* <p>The class name, member, and object name can be written together
* as a single string, which is the <em>name</em> of this permission.
* The name of the permission is the string returned by {@link
* Permission#getName() getName()}. The format of the string is:</p>
*
* <blockquote>
* <code>className#member[objectName]</code>
* </blockquote>
*
* <p>The object name is written using the usual syntax for {@link
* ObjectName}. It may contain any legal characters, including
* <code>]</code>. It is terminated by a <code>]</code> character
* that is the last character in the string.</p>
*
* <p>One or more of the <code>className</code>, <code>member</code>,
* or <code>objectName</code> may be omitted. If the
* <code>member</code> is omitted, the <code>#</code> may be too (but
* does not have to be). If the <code>objectName</code> is omitted,
* the <code>[]</code> may be too (but does not have to be). It is
* not legal to omit all three items, that is to have a <em>name</em>
* that is the empty string.</p>
*
* <p>One or more of the <code>className</code>, <code>member</code>,
* or <code>objectName</code> may be the character "<code>-</code>",
* which is equivalent to a null value. A null value is implied by
* any value (including another null value) but does not imply any
* other value.</p>
*
* <p><a name="action-list">The possible actions are these:</a></p>
*
* <ul>
* <li>addNotificationListener</li>
* <li>getAttribute</li>
* <li>getClassLoader</li>
* <li>getClassLoaderFor</li>
* <li>getClassLoaderRepository</li>
* <li>getDomains</li>
* <li>getMBeanInfo</li>
* <li>getObjectInstance</li>
* <li>instantiate</li>
* <li>invoke</li>
* <li>isInstanceOf</li>
* <li>queryMBeans</li>
* <li>queryNames</li>
* <li>registerMBean</li>
* <li>removeNotificationListener</li>
* <li>setAttribute</li>
* <li>unregisterMBean</li>
* </ul>
*
* <p>In a comma-separated list of actions, spaces are allowed before
* and after each action.</p>
*
* @since 1.5
*/
public class MBeanPermission extends Permission {
private static final long serialVersionUID = -2416928705275160661L;
/**
* Actions list.
*/
private static final int AddNotificationListener = 0x00001;
private static final int GetAttribute = 0x00002;
private static final int GetClassLoader = 0x00004;
private static final int GetClassLoaderFor = 0x00008;
private static final int GetClassLoaderRepository = 0x00010;
private static final int GetDomains = 0x00020;
private static final int GetMBeanInfo = 0x00040;
private static final int GetObjectInstance = 0x00080;
private static final int Instantiate = 0x00100;
private static final int Invoke = 0x00200;
private static final int IsInstanceOf = 0x00400;
private static final int QueryMBeans = 0x00800;
private static final int QueryNames = 0x01000;
private static final int RegisterMBean = 0x02000;
private static final int RemoveNotificationListener = 0x04000;
private static final int SetAttribute = 0x08000;
private static final int UnregisterMBean = 0x10000;
/**
* No actions.
*/
private static final int NONE = 0x00000;
/**
* All actions.
*/
private static final int ALL =
AddNotificationListener |
GetAttribute |
GetClassLoader |
GetClassLoaderFor |
GetClassLoaderRepository |
GetDomains |
GetMBeanInfo |
GetObjectInstance |
Instantiate |
Invoke |
IsInstanceOf |
QueryMBeans |
QueryNames |
RegisterMBean |
RemoveNotificationListener |
SetAttribute |
UnregisterMBean;
/**
* The actions string.
*/
private String actions;
/**
* The actions mask.
*/
private transient int mask;
/**
* The classname prefix that must match. If null, is implied by any
* classNamePrefix but does not imply any non-null classNamePrefix.
*/
private transient String classNamePrefix;
/**
* True if classNamePrefix must match exactly. Otherwise, the
* className being matched must start with classNamePrefix.
*/
private transient boolean classNameExactMatch;
/**
* The member that must match. If null, is implied by any member
* but does not imply any non-null member.
*/
private transient String member;
/**
* The objectName that must match. If null, is implied by any
* objectName but does not imply any non-null objectName.
*/
private transient ObjectName objectName;
/**
* Parse <code>actions</code> parameter.
*/
private void parseActions() {
int mask;
if (actions == null)
throw new IllegalArgumentException("MBeanPermission: " +
"actions can't be null");
if (actions.equals(""))
throw new IllegalArgumentException("MBeanPermission: " +
"actions can't be empty");
mask = getMask(actions);
if ((mask & ALL) != mask)
throw new IllegalArgumentException("Invalid actions mask");
if (mask == NONE)
throw new IllegalArgumentException("Invalid actions mask");
this.mask = mask;
}
/**
* Parse <code>name</code> parameter.
*/
private void parseName() {
String name = getName();
if (name == null)
throw new IllegalArgumentException("MBeanPermission name " +
"cannot be null");
if (name.equals(""))
throw new IllegalArgumentException("MBeanPermission name " +
"cannot be empty");
/* The name looks like "class#member[objectname]". We subtract
elements from the right as we parse, so after parsing the
objectname we have "class#member" and after parsing the
member we have "class". Each element is optional. */
// Parse ObjectName
int openingBracket = name.indexOf("[");
if (openingBracket == -1) {
// If "[on]" missing then ObjectName("*:*")
//
objectName = ObjectName.WILDCARD;
} else {
if (!name.endsWith("]")) {
throw new IllegalArgumentException("MBeanPermission: " +
"The ObjectName in the " +
"target name must be " +
"included in square " +
"brackets");
} else {
// Create ObjectName
//
try {
// If "[]" then ObjectName("*:*")
//
String on = name.substring(openingBracket + 1,
name.length() - 1);
if (on.equals(""))
objectName = ObjectName.WILDCARD;
else if (on.equals("-"))
objectName = null;
else
objectName = new ObjectName(on);
} catch (MalformedObjectNameException e) {
throw new IllegalArgumentException("MBeanPermission: " +
"The target name does " +
"not specify a valid " +
"ObjectName");
}
}
name = name.substring(0, openingBracket);
}
// Parse member
int poundSign = name.indexOf("#");
if (poundSign == -1)
setMember("*");
else {
String memberName = name.substring(poundSign + 1);
setMember(memberName);
name = name.substring(0, poundSign);
}
// Parse className
setClassName(name);
}
/**
* Assign fields based on className, member, and objectName
* parameters.
*/
private void initName(String className, String member,
ObjectName objectName) {
setClassName(className);
setMember(member);
this.objectName = objectName;
}
private void setClassName(String className) {
if (className == null || className.equals("-")) {
classNamePrefix = null;
classNameExactMatch = false;
} else if (className.equals("") || className.equals("*")) {
classNamePrefix = "";
classNameExactMatch = false;
} else if (className.endsWith(".*")) {
// Note that we include the "." in the required prefix
classNamePrefix = className.substring(0, className.length() - 1);
classNameExactMatch = false;
} else {
classNamePrefix = className;
classNameExactMatch = true;
}
}
private void setMember(String member) {
if (member == null || member.equals("-"))
this.member = null;
else if (member.equals(""))
this.member = "*";
else
this.member = member;
}
/**
* <p>Create a new MBeanPermission object with the specified target name
* and actions.</p>
*
* <p>The target name is of the form
* "<code>className#member[objectName]</code>" where each part is
* optional. It must not be empty or null.</p>
*
* <p>The actions parameter contains a comma-separated list of the
* desired actions granted on the target name. It must not be
* empty or null.</p>
*
* @param name the triplet "className#member[objectName]".
* @param actions the action string.
*
* @exception IllegalArgumentException if the <code>name</code> or
* <code>actions</code> is invalid.
*/
public MBeanPermission(String name, String actions) {
super(name);
parseName();
this.actions = actions;
parseActions();
}
/**
* <p>Create a new MBeanPermission object with the specified target name
* (class name, member, object name) and actions.</p>
*
* <p>The class name, member and object name parameters define a
* target name of the form
* "<code>className#member[objectName]</code>" where each part is
* optional. This will be the result of {@link #getName()} on the
* resultant MBeanPermission.</p>
*
* <p>The actions parameter contains a comma-separated list of the
* desired actions granted on the target name. It must not be
* empty or null.</p>
*
* @param className the class name to which this permission applies.
* May be null or <code>"-"</code>, which represents a class name
* that is implied by any class name but does not imply any other
* class name.
* @param member the member to which this permission applies. May
* be null or <code>"-"</code>, which represents a member that is
* implied by any member but does not imply any other member.
* @param objectName the object name to which this permission
* applies. May be null, which represents an object name that is
* implied by any object name but does not imply any other object
* name.
* @param actions the action string.
*/
public MBeanPermission(String className,
String member,
ObjectName objectName,
String actions) {
super(makeName(className, member, objectName));
initName(className, member, objectName);
this.actions = actions;
parseActions();
}
private static String makeName(String className, String member,
ObjectName objectName) {
final StringBuilder name = new StringBuilder();
if (className == null)
className = "-";
name.append(className);
if (member == null)
member = "-";
name.append("#" + member);
if (objectName == null)
name.append("[-]");
else
name.append("[").append(objectName.getCanonicalName()).append("]");
/* In the interests of legibility for Permission.toString(), we
transform the empty string into "*". */
if (name.length() == 0)
return "*";
else
return name.toString();
}
/**
* Returns the "canonical string representation" of the actions. That is,
* this method always returns present actions in alphabetical order.
*
* @return the canonical string representation of the actions.
*/
public String getActions() {
if (actions == null)
actions = getActions(this.mask);
return actions;
}
/**
* Returns the "canonical string representation"
* of the actions from the mask.
*/
private static String getActions(int mask) {
final StringBuilder sb = new StringBuilder();
boolean comma = false;
if ((mask & AddNotificationListener) == AddNotificationListener) {
comma = true;
sb.append("addNotificationListener");
}
if ((mask & GetAttribute) == GetAttribute) {
if (comma) sb.append(',');
else comma = true;
sb.append("getAttribute");
}
if ((mask & GetClassLoader) == GetClassLoader) {
if (comma) sb.append(',');
else comma = true;
sb.append("getClassLoader");
}
if ((mask & GetClassLoaderFor) == GetClassLoaderFor) {
if (comma) sb.append(',');
else comma = true;
sb.append("getClassLoaderFor");
}
if ((mask & GetClassLoaderRepository) == GetClassLoaderRepository) {
if (comma) sb.append(',');
else comma = true;
sb.append("getClassLoaderRepository");
}
if ((mask & GetDomains) == GetDomains) {
if (comma) sb.append(',');
else comma = true;
sb.append("getDomains");
}
if ((mask & GetMBeanInfo) == GetMBeanInfo) {
if (comma) sb.append(',');
else comma = true;
sb.append("getMBeanInfo");
}
if ((mask & GetObjectInstance) == GetObjectInstance) {
if (comma) sb.append(',');
else comma = true;
sb.append("getObjectInstance");
}
if ((mask & Instantiate) == Instantiate) {
if (comma) sb.append(',');
else comma = true;
sb.append("instantiate");
}
if ((mask & Invoke) == Invoke) {
if (comma) sb.append(',');
else comma = true;
sb.append("invoke");
}
if ((mask & IsInstanceOf) == IsInstanceOf) {
if (comma) sb.append(',');
else comma = true;
sb.append("isInstanceOf");
}
if ((mask & QueryMBeans) == QueryMBeans) {
if (comma) sb.append(',');
else comma = true;
sb.append("queryMBeans");
}
if ((mask & QueryNames) == QueryNames) {
if (comma) sb.append(',');
else comma = true;
sb.append("queryNames");
}
if ((mask & RegisterMBean) == RegisterMBean) {
if (comma) sb.append(',');
else comma = true;
sb.append("registerMBean");
}
if ((mask & RemoveNotificationListener) == RemoveNotificationListener) {
if (comma) sb.append(',');
else comma = true;
sb.append("removeNotificationListener");
}
if ((mask & SetAttribute) == SetAttribute) {
if (comma) sb.append(',');
else comma = true;
sb.append("setAttribute");
}
if ((mask & UnregisterMBean) == UnregisterMBean) {
if (comma) sb.append(',');
else comma = true;
sb.append("unregisterMBean");
}
return sb.toString();
}
/**
* Returns the hash code value for this object.
*
* @return a hash code value for this object.
*/
public int hashCode() {
return this.getName().hashCode() + this.getActions().hashCode();
}
/**
* Converts an action String to an integer action mask.
*
* @param action the action string.
* @return the action mask.
*/
private static int getMask(String action) {
/*
* BE CAREFUL HERE! PARSING ORDER IS IMPORTANT IN THIS ALGORITHM.
*
* The 'string length' test must be performed for the lengthiest
* strings first.
*
* In this permission if the "unregisterMBean" string length test is
* performed after the "registerMBean" string length test the algorithm
* considers the 'unregisterMBean' action as being the 'registerMBean'
* action and a parsing error is returned.
*/
int mask = NONE;
if (action == null) {
return mask;
}
if (action.equals("*")) {
return ALL;
}
char[] a = action.toCharArray();
int i = a.length - 1;
if (i < 0)
return mask;
while (i != -1) {
char c;
// skip whitespace
while ((i!=-1) && ((c = a[i]) == ' ' ||
c == '\r' ||
c == '\n' ||
c == '\f' ||
c == '\t'))
i--;
// check for the known strings
int matchlen;
if (i >= 25 && /* removeNotificationListener */
(a[i-25] == 'r') &&
(a[i-24] == 'e') &&
(a[i-23] == 'm') &&
(a[i-22] == 'o') &&
(a[i-21] == 'v') &&
(a[i-20] == 'e') &&
(a[i-19] == 'N') &&
(a[i-18] == 'o') &&
(a[i-17] == 't') &&
(a[i-16] == 'i') &&
(a[i-15] == 'f') &&
(a[i-14] == 'i') &&
(a[i-13] == 'c') &&
(a[i-12] == 'a') &&
(a[i-11] == 't') &&
(a[i-10] == 'i') &&
(a[i-9] == 'o') &&
(a[i-8] == 'n') &&
(a[i-7] == 'L') &&
(a[i-6] == 'i') &&
(a[i-5] == 's') &&
(a[i-4] == 't') &&
(a[i-3] == 'e') &&
(a[i-2] == 'n') &&
(a[i-1] == 'e') &&
(a[i] == 'r')) {
matchlen = 26;
mask |= RemoveNotificationListener;
} else if (i >= 23 && /* getClassLoaderRepository */
(a[i-23] == 'g') &&
(a[i-22] == 'e') &&
(a[i-21] == 't') &&
(a[i-20] == 'C') &&
(a[i-19] == 'l') &&
(a[i-18] == 'a') &&
(a[i-17] == 's') &&
(a[i-16] == 's') &&
(a[i-15] == 'L') &&
(a[i-14] == 'o') &&
(a[i-13] == 'a') &&
(a[i-12] == 'd') &&
(a[i-11] == 'e') &&
(a[i-10] == 'r') &&
(a[i-9] == 'R') &&
(a[i-8] == 'e') &&
(a[i-7] == 'p') &&
(a[i-6] == 'o') &&
(a[i-5] == 's') &&
(a[i-4] == 'i') &&
(a[i-3] == 't') &&
(a[i-2] == 'o') &&
(a[i-1] == 'r') &&
(a[i] == 'y')) {
matchlen = 24;
mask |= GetClassLoaderRepository;
} else if (i >= 22 && /* addNotificationListener */
(a[i-22] == 'a') &&
(a[i-21] == 'd') &&
(a[i-20] == 'd') &&
(a[i-19] == 'N') &&
(a[i-18] == 'o') &&
(a[i-17] == 't') &&
(a[i-16] == 'i') &&
(a[i-15] == 'f') &&
(a[i-14] == 'i') &&
(a[i-13] == 'c') &&
(a[i-12] == 'a') &&
(a[i-11] == 't') &&
(a[i-10] == 'i') &&
(a[i-9] == 'o') &&
(a[i-8] == 'n') &&
(a[i-7] == 'L') &&
(a[i-6] == 'i') &&
(a[i-5] == 's') &&
(a[i-4] == 't') &&
(a[i-3] == 'e') &&
(a[i-2] == 'n') &&
(a[i-1] == 'e') &&
(a[i] == 'r')) {
matchlen = 23;
mask |= AddNotificationListener;
} else if (i >= 16 && /* getClassLoaderFor */
(a[i-16] == 'g') &&
(a[i-15] == 'e') &&
(a[i-14] == 't') &&
(a[i-13] == 'C') &&
(a[i-12] == 'l') &&
(a[i-11] == 'a') &&
(a[i-10] == 's') &&
(a[i-9] == 's') &&
(a[i-8] == 'L') &&
(a[i-7] == 'o') &&
(a[i-6] == 'a') &&
(a[i-5] == 'd') &&
(a[i-4] == 'e') &&
(a[i-3] == 'r') &&
(a[i-2] == 'F') &&
(a[i-1] == 'o') &&
(a[i] == 'r')) {
matchlen = 17;
mask |= GetClassLoaderFor;
} else if (i >= 16 && /* getObjectInstance */
(a[i-16] == 'g') &&
(a[i-15] == 'e') &&
(a[i-14] == 't') &&
(a[i-13] == 'O') &&
(a[i-12] == 'b') &&
(a[i-11] == 'j') &&
(a[i-10] == 'e') &&
(a[i-9] == 'c') &&
(a[i-8] == 't') &&
(a[i-7] == 'I') &&
(a[i-6] == 'n') &&
(a[i-5] == 's') &&
(a[i-4] == 't') &&
(a[i-3] == 'a') &&
(a[i-2] == 'n') &&
(a[i-1] == 'c') &&
(a[i] == 'e')) {
matchlen = 17;
mask |= GetObjectInstance;
} else if (i >= 14 && /* unregisterMBean */
(a[i-14] == 'u') &&
(a[i-13] == 'n') &&
(a[i-12] == 'r') &&
(a[i-11] == 'e') &&
(a[i-10] == 'g') &&
(a[i-9] == 'i') &&
(a[i-8] == 's') &&
(a[i-7] == 't') &&
(a[i-6] == 'e') &&
(a[i-5] == 'r') &&
(a[i-4] == 'M') &&
(a[i-3] == 'B') &&
(a[i-2] == 'e') &&
(a[i-1] == 'a') &&
(a[i] == 'n')) {
matchlen = 15;
mask |= UnregisterMBean;
} else if (i >= 13 && /* getClassLoader */
(a[i-13] == 'g') &&
(a[i-12] == 'e') &&
(a[i-11] == 't') &&
(a[i-10] == 'C') &&
(a[i-9] == 'l') &&
(a[i-8] == 'a') &&
(a[i-7] == 's') &&
(a[i-6] == 's') &&
(a[i-5] == 'L') &&
(a[i-4] == 'o') &&
(a[i-3] == 'a') &&
(a[i-2] == 'd') &&
(a[i-1] == 'e') &&
(a[i] == 'r')) {
matchlen = 14;
mask |= GetClassLoader;
} else if (i >= 12 && /* registerMBean */
(a[i-12] == 'r') &&
(a[i-11] == 'e') &&
(a[i-10] == 'g') &&
(a[i-9] == 'i') &&
(a[i-8] == 's') &&
(a[i-7] == 't') &&
(a[i-6] == 'e') &&
(a[i-5] == 'r') &&
(a[i-4] == 'M') &&
(a[i-3] == 'B') &&
(a[i-2] == 'e') &&
(a[i-1] == 'a') &&
(a[i] == 'n')) {
matchlen = 13;
mask |= RegisterMBean;
} else if (i >= 11 && /* getAttribute */
(a[i-11] == 'g') &&
(a[i-10] == 'e') &&
(a[i-9] == 't') &&
(a[i-8] == 'A') &&
(a[i-7] == 't') &&
(a[i-6] == 't') &&
(a[i-5] == 'r') &&
(a[i-4] == 'i') &&
(a[i-3] == 'b') &&
(a[i-2] == 'u') &&
(a[i-1] == 't') &&
(a[i] == 'e')) {
matchlen = 12;
mask |= GetAttribute;
} else if (i >= 11 && /* getMBeanInfo */
(a[i-11] == 'g') &&
(a[i-10] == 'e') &&
(a[i-9] == 't') &&
(a[i-8] == 'M') &&
(a[i-7] == 'B') &&
(a[i-6] == 'e') &&
(a[i-5] == 'a') &&
(a[i-4] == 'n') &&
(a[i-3] == 'I') &&
(a[i-2] == 'n') &&
(a[i-1] == 'f') &&
(a[i] == 'o')) {
matchlen = 12;
mask |= GetMBeanInfo;
} else if (i >= 11 && /* isInstanceOf */
(a[i-11] == 'i') &&
(a[i-10] == 's') &&
(a[i-9] == 'I') &&
(a[i-8] == 'n') &&
(a[i-7] == 's') &&
(a[i-6] == 't') &&
(a[i-5] == 'a') &&
(a[i-4] == 'n') &&
(a[i-3] == 'c') &&
(a[i-2] == 'e') &&
(a[i-1] == 'O') &&
(a[i] == 'f')) {
matchlen = 12;
mask |= IsInstanceOf;
} else if (i >= 11 && /* setAttribute */
(a[i-11] == 's') &&
(a[i-10] == 'e') &&
(a[i-9] == 't') &&
(a[i-8] == 'A') &&
(a[i-7] == 't') &&
(a[i-6] == 't') &&
(a[i-5] == 'r') &&
(a[i-4] == 'i') &&
(a[i-3] == 'b') &&
(a[i-2] == 'u') &&
(a[i-1] == 't') &&
(a[i] == 'e')) {
matchlen = 12;
mask |= SetAttribute;
} else if (i >= 10 && /* instantiate */
(a[i-10] == 'i') &&
(a[i-9] == 'n') &&
(a[i-8] == 's') &&
(a[i-7] == 't') &&
(a[i-6] == 'a') &&
(a[i-5] == 'n') &&
(a[i-4] == 't') &&
(a[i-3] == 'i') &&
(a[i-2] == 'a') &&
(a[i-1] == 't') &&
(a[i] == 'e')) {
matchlen = 11;
mask |= Instantiate;
} else if (i >= 10 && /* queryMBeans */
(a[i-10] == 'q') &&
(a[i-9] == 'u') &&
(a[i-8] == 'e') &&
(a[i-7] == 'r') &&
(a[i-6] == 'y') &&
(a[i-5] == 'M') &&
(a[i-4] == 'B') &&
(a[i-3] == 'e') &&
(a[i-2] == 'a') &&
(a[i-1] == 'n') &&
(a[i] == 's')) {
matchlen = 11;
mask |= QueryMBeans;
} else if (i >= 9 && /* getDomains */
(a[i-9] == 'g') &&
(a[i-8] == 'e') &&
(a[i-7] == 't') &&
(a[i-6] == 'D') &&
(a[i-5] == 'o') &&
(a[i-4] == 'm') &&
(a[i-3] == 'a') &&
(a[i-2] == 'i') &&
(a[i-1] == 'n') &&
(a[i] == 's')) {
matchlen = 10;
mask |= GetDomains;
} else if (i >= 9 && /* queryNames */
(a[i-9] == 'q') &&
(a[i-8] == 'u') &&
(a[i-7] == 'e') &&
(a[i-6] == 'r') &&
(a[i-5] == 'y') &&
(a[i-4] == 'N') &&
(a[i-3] == 'a') &&
(a[i-2] == 'm') &&
(a[i-1] == 'e') &&
(a[i] == 's')) {
matchlen = 10;
mask |= QueryNames;
} else if (i >= 5 && /* invoke */
(a[i-5] == 'i') &&
(a[i-4] == 'n') &&
(a[i-3] == 'v') &&
(a[i-2] == 'o') &&
(a[i-1] == 'k') &&
(a[i] == 'e')) {
matchlen = 6;
mask |= Invoke;
} else {
// parse error
throw new IllegalArgumentException("Invalid permission: " +
action);
}
// make sure we didn't just match the tail of a word
// like "ackbarfaccept". Also, skip to the comma.
boolean seencomma = false;
while (i >= matchlen && !seencomma) {
switch(a[i-matchlen]) {
case ',':
seencomma = true;
break;
case ' ': case '\r': case '\n':
case '\f': case '\t':
break;
default:
throw new IllegalArgumentException("Invalid permission: " +
action);
}
i--;
}
// point i at the location of the comma minus one (or -1).
i -= matchlen;
}
return mask;
}
/**
* <p>Checks if this MBeanPermission object "implies" the
* specified permission.</p>
*
* <p>More specifically, this method returns true if:</p>
*
* <ul>
*
* <li> <i>p</i> is an instance of MBeanPermission; and</li>
*
* <li> <i>p</i> has a null className or <i>p</i>'s className
* matches this object's className; and</li>
*
* <li> <i>p</i> has a null member or <i>p</i>'s member matches this
* object's member; and</li>
*
* <li> <i>p</i> has a null object name or <i>p</i>'s
* object name matches this object's object name; and</li>
*
* <li> <i>p</i>'s actions are a subset of this object's actions</li>
*
* </ul>
*
* <p>If this object's className is "<code>*</code>", <i>p</i>'s
* className always matches it. If it is "<code>a.*</code>", <i>p</i>'s
* className matches it if it begins with "<code>a.</code>".</p>
*
* <p>If this object's member is "<code>*</code>", <i>p</i>'s
* member always matches it.</p>
*
* <p>If this object's objectName <i>n1</i> is an object name pattern,
* <i>p</i>'s objectName <i>n2</i> matches it if
* {@link ObjectName#equals <i>n1</i>.equals(<i>n2</i>)} or if
* {@link ObjectName#apply <i>n1</i>.apply(<i>n2</i>)}.</p>
*
* <p>A permission that includes the <code>queryMBeans</code> action
* is considered to include <code>queryNames</code> as well.</p>
*
* @param p the permission to check against.
* @return true if the specified permission is implied by this object,
* false if not.
*/
public boolean implies(Permission p) {
if (!(p instanceof MBeanPermission))
return false;
MBeanPermission that = (MBeanPermission) p;
// Actions
//
// The actions in 'this' permission must be a
// superset of the actions in 'that' permission
//
/* "queryMBeans" implies "queryNames" */
if ((this.mask & QueryMBeans) == QueryMBeans) {
if (((this.mask | QueryNames) & that.mask) != that.mask) {
//System.out.println("action [with QueryNames] does not imply");
return false;
}
} else {
if ((this.mask & that.mask) != that.mask) {
//System.out.println("action does not imply");
return false;
}
}
// Target name
//
// The 'className' check is true iff:
// 1) the className in 'this' permission is omitted or "*", or
// 2) the className in 'that' permission is omitted or "*", or
// 3) the className in 'this' permission does pattern
// matching with the className in 'that' permission.
//
// The 'member' check is true iff:
// 1) the member in 'this' permission is omitted or "*", or
// 2) the member in 'that' permission is omitted or "*", or
// 3) the member in 'this' permission equals the member in
// 'that' permission.
//
// The 'object name' check is true iff:
// 1) the object name in 'this' permission is omitted or "*:*", or
// 2) the object name in 'that' permission is omitted or "*:*", or
// 3) the object name in 'this' permission does pattern
// matching with the object name in 'that' permission.
//
/* Check if this.className implies that.className.
If that.classNamePrefix is empty that means the className is
irrelevant for this permission check. Otherwise, we do not
expect that "that" contains a wildcard, since it is a
needed permission. So we assume that.classNameExactMatch. */
if (that.classNamePrefix == null) {
// bottom is implied
} else if (this.classNamePrefix == null) {
// bottom implies nothing but itself
return false;
} else if (this.classNameExactMatch) {
if (!that.classNameExactMatch)
return false; // exact never implies wildcard
if (!that.classNamePrefix.equals(this.classNamePrefix))
return false; // exact match fails
} else {
// prefix match, works even if "that" is also a wildcard
// e.g. a.* implies a.* and a.b.*
if (!that.classNamePrefix.startsWith(this.classNamePrefix))
return false;
}
/* Check if this.member implies that.member */
if (that.member == null) {
// bottom is implied
} else if (this.member == null) {
// bottom implies nothing but itself
return false;
} else if (this.member.equals("*")) {
// wildcard implies everything (including itself)
} else if (!this.member.equals(that.member)) {
return false;
}
/* Check if this.objectName implies that.objectName */
if (that.objectName == null) {
// bottom is implied
} else if (this.objectName == null) {
// bottom implies nothing but itself
return false;
} else if (!this.objectName.apply(that.objectName)) {
/* ObjectName.apply returns false if that.objectName is a
wildcard so we also allow equals for that case. This
never happens during real permission checks, but means
the implies relation is reflexive. */
if (!this.objectName.equals(that.objectName))
return false;
}
return true;
}
/**
* Checks two MBeanPermission objects for equality. Checks
* that <i>obj</i> is an MBeanPermission, and has the same
* name and actions as this object.
* <P>
* @param obj the object we are testing for equality with this object.
* @return true if obj is an MBeanPermission, and has the
* same name and actions as this MBeanPermission object.
*/
public boolean equals(Object obj) {
if (obj == this)
return true;
if (! (obj instanceof MBeanPermission))
return false;
MBeanPermission that = (MBeanPermission) obj;
return (this.mask == that.mask) &&
(this.getName().equals(that.getName()));
}
/**
* Deserialize this object based on its name and actions.
*/
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
parseName();
parseActions();
}
}
| apache-2.0 |
hhclam/bazel | src/test/java/com/google/devtools/build/skyframe/SkyKeyTest.java | 3062 | // Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.skyframe;
import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.testutil.TestUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.io.Serializable;
/**
* Unit test for the SkyKey class, checking hash code transience logic.
*/
@RunWith(JUnit4.class)
public class SkyKeyTest {
@Test
public void testHashCodeTransience() throws Exception {
// Given a freshly constructed HashCodeSpy object,
HashCodeSpy hashCodeSpy = new HashCodeSpy();
assertThat(hashCodeSpy.getNumberOfTimesHashCodeCalled()).isEqualTo(0);
// When a SkyKey is constructed with that HashCodeSpy as its argument,
SkyKey originalKey = new SkyKey(SkyFunctionName.create("TEMP"), hashCodeSpy);
// Then the HashCodeSpy reports that its hashcode method was called once.
assertThat(hashCodeSpy.getNumberOfTimesHashCodeCalled()).isEqualTo(1);
// When the SkyKey's hashCode method is called,
originalKey.hashCode();
// Then the spy's hashCode method isn't called, because the SkyKey's hashCode was cached.
assertThat(hashCodeSpy.getNumberOfTimesHashCodeCalled()).isEqualTo(1);
// When that SkyKey is serialized and then deserialized,
SkyKey newKey = (SkyKey) TestUtils.deserializeObject(TestUtils.serializeObject(originalKey));
// Then the new SkyKey's HashCodeSpy has not had its hashCode method called.
HashCodeSpy spyInNewKey = (HashCodeSpy) newKey.argument();
assertThat(spyInNewKey.getNumberOfTimesHashCodeCalled()).isEqualTo(0);
// When the new SkyKey's hashCode method is called once,
newKey.hashCode();
// Then the new SkyKey's spy's hashCode method gets called.
assertThat(spyInNewKey.getNumberOfTimesHashCodeCalled()).isEqualTo(1);
// When the new SkyKey's hashCode method is called a second time,
newKey.hashCode();
// Then the new SkyKey's spy's hashCOde isn't called a second time, because the SkyKey's
// hashCode was cached.
assertThat(spyInNewKey.getNumberOfTimesHashCodeCalled()).isEqualTo(1);
}
private static class HashCodeSpy implements Serializable {
private transient int numberOfTimesHashCodeCalled;
public int getNumberOfTimesHashCodeCalled() {
return numberOfTimesHashCodeCalled;
}
@Override
public int hashCode() {
numberOfTimesHashCodeCalled++;
return 42;
}
}
}
| apache-2.0 |
Guavus/hbase | hbase-server/src/main/java/org/apache/hadoop/hbase/master/procedure/MasterDDLOperationHelper.java | 6437 | /**
* 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.hbase.master.procedure;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.NavigableMap;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.MetaTableAccessor;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.TableNotDisabledException;
import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.RegionLocator;
import org.apache.hadoop.hbase.client.TableState;
import org.apache.hadoop.hbase.master.AssignmentManager;
import org.apache.hadoop.hbase.master.BulkReOpen;
import org.apache.hadoop.hbase.master.MasterFileSystem;
import org.apache.hadoop.hbase.util.Bytes;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* Helper class for schema change procedures
*/
@InterfaceAudience.Private
public final class MasterDDLOperationHelper {
private static final Log LOG = LogFactory.getLog(MasterDDLOperationHelper.class);
private MasterDDLOperationHelper() {}
/**
* Check whether online schema change is allowed from config
**/
public static boolean isOnlineSchemaChangeAllowed(final MasterProcedureEnv env) {
return env.getMasterServices().getConfiguration()
.getBoolean("hbase.online.schema.update.enable", false);
}
/**
* Check whether a table is modifiable - exists and either offline or online with config set
* @param env MasterProcedureEnv
* @param tableName name of the table
* @throws IOException
*/
public static void checkTableModifiable(final MasterProcedureEnv env, final TableName tableName)
throws IOException {
// Checks whether the table exists
if (!MetaTableAccessor.tableExists(env.getMasterServices().getConnection(), tableName)) {
throw new TableNotFoundException(tableName);
}
// We only execute this procedure with table online if online schema change config is set.
if (!env.getMasterServices().getAssignmentManager().getTableStateManager()
.isTableState(tableName, TableState.State.DISABLED)
&& !MasterDDLOperationHelper.isOnlineSchemaChangeAllowed(env)) {
throw new TableNotDisabledException(tableName);
}
}
/**
* Remove the column family from the file system
**/
public static void deleteColumnFamilyFromFileSystem(
final MasterProcedureEnv env,
final TableName tableName,
List<HRegionInfo> regionInfoList,
final byte[] familyName) throws IOException {
final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem();
if (LOG.isDebugEnabled()) {
LOG.debug("Removing family=" + Bytes.toString(familyName) + " from table=" + tableName);
}
if (regionInfoList == null) {
regionInfoList = ProcedureSyncWait.getRegionsFromMeta(env, tableName);
}
for (HRegionInfo hri : regionInfoList) {
// Delete the family directory in FS for all the regions one by one
mfs.deleteFamilyFromFS(hri, familyName);
}
}
/**
* Reopen all regions from a table after a schema change operation.
**/
public static boolean reOpenAllRegions(
final MasterProcedureEnv env,
final TableName tableName,
final List<HRegionInfo> regionInfoList) throws IOException {
boolean done = false;
LOG.info("Bucketing regions by region server...");
List<HRegionLocation> regionLocations = null;
Connection connection = env.getMasterServices().getConnection();
try (RegionLocator locator = connection.getRegionLocator(tableName)) {
regionLocations = locator.getAllRegionLocations();
}
// Convert List<HRegionLocation> to Map<HRegionInfo, ServerName>.
NavigableMap<HRegionInfo, ServerName> hri2Sn = new TreeMap<HRegionInfo, ServerName>();
for (HRegionLocation location : regionLocations) {
hri2Sn.put(location.getRegionInfo(), location.getServerName());
}
TreeMap<ServerName, List<HRegionInfo>> serverToRegions = Maps.newTreeMap();
List<HRegionInfo> reRegions = new ArrayList<HRegionInfo>();
for (HRegionInfo hri : regionInfoList) {
ServerName sn = hri2Sn.get(hri);
// Skip the offlined split parent region
// See HBASE-4578 for more information.
if (null == sn) {
LOG.info("Skip " + hri);
continue;
}
if (!serverToRegions.containsKey(sn)) {
LinkedList<HRegionInfo> hriList = Lists.newLinkedList();
serverToRegions.put(sn, hriList);
}
reRegions.add(hri);
serverToRegions.get(sn).add(hri);
}
LOG.info("Reopening " + reRegions.size() + " regions on " + serverToRegions.size()
+ " region servers.");
AssignmentManager am = env.getMasterServices().getAssignmentManager();
am.setRegionsToReopen(reRegions);
BulkReOpen bulkReopen = new BulkReOpen(env.getMasterServices(), serverToRegions, am);
while (true) {
try {
if (bulkReopen.bulkReOpen()) {
done = true;
break;
} else {
LOG.warn("Timeout before reopening all regions");
}
} catch (InterruptedException e) {
LOG.warn("Reopen was interrupted");
// Preserve the interrupt.
Thread.currentThread().interrupt();
break;
}
}
return done;
}
}
| apache-2.0 |
coding0011/elasticsearch | x-pack/plugin/ml/qa/native-multi-node-tests/src/test/java/org/elasticsearch/xpack/ml/integration/SetUpgradeModeIT.java | 8553 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.ml.integration;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.persistent.PersistentTasksCustomMetaData;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.xpack.core.ml.MlMetadata;
import org.elasticsearch.xpack.core.ml.MlTasks;
import org.elasticsearch.xpack.core.ml.action.GetDatafeedsStatsAction;
import org.elasticsearch.xpack.core.ml.action.GetJobsStatsAction;
import org.elasticsearch.xpack.core.ml.action.SetUpgradeModeAction;
import org.elasticsearch.xpack.core.ml.datafeed.DatafeedConfig;
import org.elasticsearch.xpack.core.ml.datafeed.DatafeedState;
import org.elasticsearch.xpack.core.ml.job.config.Job;
import org.elasticsearch.xpack.core.ml.job.config.JobState;
import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.DataCounts;
import org.junit.After;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import static org.elasticsearch.xpack.core.ml.MlTasks.AWAITING_UPGRADE;
import static org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase.createDatafeed;
import static org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase.createScheduledJob;
import static org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase.getDataCounts;
import static org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase.getDatafeedStats;
import static org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase.indexDocs;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
public class SetUpgradeModeIT extends MlNativeAutodetectIntegTestCase {
@After
public void cleanup() throws Exception {
cleanUp();
}
public void testEnableUpgradeMode() throws Exception {
String jobId = "realtime-job-test-enable-upgrade-mode";
String datafeedId = jobId + "-datafeed";
startRealtime(jobId);
// Assert appropriate task state and assignment numbers
assertThat(client().admin()
.cluster()
.prepareListTasks()
.setActions(MlTasks.JOB_TASK_NAME + "[c]", MlTasks.DATAFEED_TASK_NAME + "[c]")
.get()
.getTasks()
.size(), equalTo(2));
ClusterState masterClusterState = client().admin().cluster().prepareState().all().get().getState();
PersistentTasksCustomMetaData persistentTasks = masterClusterState.getMetaData().custom(PersistentTasksCustomMetaData.TYPE);
assertThat(persistentTasks.findTasks(MlTasks.DATAFEED_TASK_NAME, task -> true).size(), equalTo(1));
assertThat(persistentTasks.findTasks(MlTasks.JOB_TASK_NAME, task -> true).size(), equalTo(1));
assertThat(MlMetadata.getMlMetadata(masterClusterState).isUpgradeMode(), equalTo(false));
// Set the upgrade mode setting
AcknowledgedResponse response = client().execute(SetUpgradeModeAction.INSTANCE, new SetUpgradeModeAction.Request(true))
.actionGet();
assertThat(response.isAcknowledged(), equalTo(true));
masterClusterState = client().admin().cluster().prepareState().all().get().getState();
// Assert state for tasks still exists and that the upgrade setting is set
persistentTasks = masterClusterState.getMetaData().custom(PersistentTasksCustomMetaData.TYPE);
assertThat(persistentTasks.findTasks(MlTasks.DATAFEED_TASK_NAME, task -> true).size(), equalTo(1));
assertThat(persistentTasks.findTasks(MlTasks.JOB_TASK_NAME, task -> true).size(), equalTo(1));
assertThat(MlMetadata.getMlMetadata(masterClusterState).isUpgradeMode(), equalTo(true));
assertThat(client().admin()
.cluster()
.prepareListTasks()
.setActions(MlTasks.JOB_TASK_NAME + "[c]", MlTasks.DATAFEED_TASK_NAME + "[c]")
.get()
.getTasks(), is(empty()));
GetJobsStatsAction.Response.JobStats jobStats = getJobStats(jobId).get(0);
assertThat(jobStats.getState(), equalTo(JobState.OPENED));
assertThat(jobStats.getAssignmentExplanation(), equalTo(AWAITING_UPGRADE.getExplanation()));
assertThat(jobStats.getNode(), is(nullValue()));
GetDatafeedsStatsAction.Response.DatafeedStats datafeedStats = getDatafeedStats(datafeedId);
assertThat(datafeedStats.getDatafeedState(), equalTo(DatafeedState.STARTED));
assertThat(datafeedStats.getAssignmentExplanation(), equalTo(AWAITING_UPGRADE.getExplanation()));
assertThat(datafeedStats.getNode(), is(nullValue()));
Job.Builder job = createScheduledJob("job-should-not-open");
registerJob(job);
putJob(job);
ElasticsearchStatusException statusException = expectThrows(ElasticsearchStatusException.class, () -> openJob(job.getId()));
assertThat(statusException.status(), equalTo(RestStatus.TOO_MANY_REQUESTS));
assertThat(statusException.getMessage(), equalTo("Cannot open jobs when upgrade mode is enabled"));
//Disable the setting
response = client().execute(SetUpgradeModeAction.INSTANCE, new SetUpgradeModeAction.Request(false))
.actionGet();
assertThat(response.isAcknowledged(), equalTo(true));
masterClusterState = client().admin().cluster().prepareState().all().get().getState();
persistentTasks = masterClusterState.getMetaData().custom(PersistentTasksCustomMetaData.TYPE);
assertThat(persistentTasks.findTasks(MlTasks.DATAFEED_TASK_NAME, task -> true).size(), equalTo(1));
assertThat(persistentTasks.findTasks(MlTasks.JOB_TASK_NAME, task -> true).size(), equalTo(1));
assertThat(MlMetadata.getMlMetadata(masterClusterState).isUpgradeMode(), equalTo(false));
assertBusy(() -> assertThat(client().admin()
.cluster()
.prepareListTasks()
.setActions(MlTasks.JOB_TASK_NAME + "[c]", MlTasks.DATAFEED_TASK_NAME + "[c]")
.get()
.getTasks()
.size(), equalTo(2)));
jobStats = getJobStats(jobId).get(0);
assertThat(jobStats.getState(), equalTo(JobState.OPENED));
assertThat(jobStats.getAssignmentExplanation(), not(equalTo(AWAITING_UPGRADE.getExplanation())));
datafeedStats = getDatafeedStats(datafeedId);
assertThat(datafeedStats.getDatafeedState(), equalTo(DatafeedState.STARTED));
assertThat(datafeedStats.getAssignmentExplanation(), not(equalTo(AWAITING_UPGRADE.getExplanation())));
}
private void startRealtime(String jobId) throws Exception {
client().admin().indices().prepareCreate("data")
.addMapping("type", "time", "type=date")
.get();
long numDocs1 = randomIntBetween(32, 2048);
long now = System.currentTimeMillis();
long lastWeek = now - 604800000;
indexDocs(logger, "data", numDocs1, lastWeek, now);
Job.Builder job = createScheduledJob(jobId);
registerJob(job);
putJob(job);
openJob(job.getId());
assertBusy(() -> assertEquals(getJobStats(job.getId()).get(0).getState(), JobState.OPENED));
DatafeedConfig datafeedConfig = createDatafeed(job.getId() + "-datafeed", job.getId(), Collections.singletonList("data"));
registerDatafeed(datafeedConfig);
putDatafeed(datafeedConfig);
startDatafeed(datafeedConfig.getId(), 0L, null);
assertBusy(() -> {
DataCounts dataCounts = getDataCounts(job.getId());
assertThat(dataCounts.getProcessedRecordCount(), equalTo(numDocs1));
assertThat(dataCounts.getOutOfOrderTimeStampCount(), equalTo(0L));
});
long numDocs2 = randomIntBetween(2, 64);
now = System.currentTimeMillis();
indexDocs(logger, "data", numDocs2, now + 5000, now + 6000);
assertBusy(() -> {
DataCounts dataCounts = getDataCounts(job.getId());
assertThat(dataCounts.getProcessedRecordCount(), equalTo(numDocs1 + numDocs2));
assertThat(dataCounts.getOutOfOrderTimeStampCount(), equalTo(0L));
}, 30, TimeUnit.SECONDS);
}
}
| apache-2.0 |
apache/jmeter | src/core/src/main/java/org/apache/jmeter/gui/util/JMeterToolBar.java | 13290 | /*
* 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.jmeter.gui.util;
import java.awt.Component;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JToolBar;
import org.apache.commons.lang3.StringUtils;
import org.apache.jmeter.gui.UndoHistory;
import org.apache.jmeter.gui.action.ActionNames;
import org.apache.jmeter.gui.action.ActionRouter;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jmeter.util.LocaleChangeEvent;
import org.apache.jmeter.util.LocaleChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.weisj.darklaf.icons.ThemedSVGIcon;
import com.github.weisj.darklaf.ui.button.DarkButtonUI;
/**
* The JMeter main toolbar class
*
*/
public class JMeterToolBar extends JToolBar implements LocaleChangeListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(JMeterToolBar.class);
private static final String TOOLBAR_ENTRY_SEP = ","; //$NON-NLS-1$
private static final String TOOLBAR_PROP_NAME = "toolbar"; //$NON-NLS-1$
// protected fields: JMeterToolBar class can be use to create another toolbar (plugin, etc.)
protected static final String DEFAULT_TOOLBAR_PROPERTY_FILE = "org/apache/jmeter/images/toolbar/icons-toolbar.properties"; //$NON-NLS-1$
protected static final String USER_DEFINED_TOOLBAR_PROPERTY_FILE = "jmeter.toolbar.icons"; //$NON-NLS-1$
public static final String TOOLBAR_ICON_SIZE = "jmeter.toolbar.icons.size"; //$NON-NLS-1$
public static final String DEFAULT_TOOLBAR_ICON_SIZE = "22x22"; //$NON-NLS-1$
protected static final String TOOLBAR_LIST = "jmeter.toolbar";
/**
* Create the default JMeter toolbar
*
* @param visible
* Flag whether toolbar should be visible
* @return the newly created {@link JMeterToolBar}
*/
public static JMeterToolBar createToolbar(boolean visible) {
JMeterToolBar toolBar = new JMeterToolBar();
toolBar.setFloatable(false);
toolBar.setVisible(visible);
setupToolbarContent(toolBar);
JMeterUtils.addLocaleChangeListener(toolBar);
// implicit return empty toolbar if icons == null
return toolBar;
}
@Override
protected void addImpl(Component comp, Object constraints, int index) {
super.addImpl(comp, constraints, index);
if (comp instanceof JButton) {
// Ensure buttons added to the toolbar have the same style.
JButton b = (JButton) comp;
b.setFocusable(false);
if (b.isBorderPainted() && (b.getText() == null || b.getText().isEmpty())) {
b.setRolloverEnabled(true);
b.putClientProperty(DarkButtonUI.KEY_VARIANT, DarkButtonUI.VARIANT_BORDERLESS);
b.putClientProperty(DarkButtonUI.KEY_THIN, true);
b.putClientProperty(DarkButtonUI.KEY_SQUARE, true);
}
}
}
/**
* Setup toolbar content
* @param toolBar {@link JMeterToolBar}
*/
private static void setupToolbarContent(JMeterToolBar toolBar) {
List<IconToolbarBean> icons = getIconMappings();
if (icons != null) {
for (IconToolbarBean iconToolbarBean : icons) {
if (iconToolbarBean == null) {
toolBar.addSeparator();
} else {
try {
if(ActionNames.UNDO.equalsIgnoreCase(iconToolbarBean.getActionName())
|| ActionNames.REDO.equalsIgnoreCase(iconToolbarBean.getActionName())) {
if(UndoHistory.isEnabled()) {
toolBar.add(makeButtonItemRes(iconToolbarBean));
}
} else {
toolBar.add(makeButtonItemRes(iconToolbarBean));
}
} catch (Exception e) {
if (log.isWarnEnabled()) {
log.warn("Exception while adding button item to toolbar. {}", e.getMessage());
}
}
}
}
toolBar.initButtonsState();
}
}
/**
* Generate a button component from icon bean
* @param iconBean contains I18N key, ActionNames, icon path, optional icon path pressed
* @return a button for toolbar
*/
private static JButton makeButtonItemRes(IconToolbarBean iconBean) throws Exception {
JButton button = new JButton(loadIcon(iconBean, iconBean.getIconPath()));
button.setToolTipText(JMeterUtils.getResString(iconBean.getI18nKey()));
if (!iconBean.getIconPathPressed().equals(iconBean.getIconPath())) {
button.setPressedIcon(loadIcon(iconBean, iconBean.getIconPathPressed()));
}
button.addActionListener(ActionRouter.getInstance());
button.setActionCommand(iconBean.getActionNameResolve());
return button;
}
private static Icon loadIcon(IconToolbarBean iconBean, String iconPath) throws URISyntaxException {
final URL imageURL = JMeterUtils.class.getClassLoader().getResource(iconPath);
if (imageURL == null) {
throw new IllegalArgumentException("No icon for: " + iconBean.getActionName());
}
if (StringUtils.endsWithIgnoreCase(iconBean.getIconPath(), ".svg")) {
return new ThemedSVGIcon(imageURL.toURI(), iconBean.getWidth(), iconBean.getHeight());
}
return new ImageIcon(imageURL);
}
/**
* Parse icon set file.
* @return List of icons/action definition
*/
private static List<IconToolbarBean> getIconMappings() {
// Get the standard toolbar properties
Properties defaultProps = JMeterUtils.loadProperties(DEFAULT_TOOLBAR_PROPERTY_FILE);
if (defaultProps == null) {
JOptionPane.showMessageDialog(null,
JMeterUtils.getResString("toolbar_icon_set_not_found"), // $NON-NLS-1$
JMeterUtils.getResString("toolbar_icon_set_not_found"), // $NON-NLS-1$
JOptionPane.WARNING_MESSAGE);
return null;
}
Properties p;
String userProp = JMeterUtils.getProperty(USER_DEFINED_TOOLBAR_PROPERTY_FILE);
if (userProp != null){
p = JMeterUtils.loadProperties(userProp, defaultProps);
} else {
p = defaultProps;
}
String order = JMeterUtils.getPropDefault(TOOLBAR_LIST, p.getProperty(TOOLBAR_PROP_NAME));
if (order == null) {
log.warn("Could not find toolbar definition list");
JOptionPane.showMessageDialog(null,
JMeterUtils.getResString("toolbar_icon_set_not_found"), // $NON-NLS-1$
JMeterUtils.getResString("toolbar_icon_set_not_found"), // $NON-NLS-1$
JOptionPane.WARNING_MESSAGE);
return null;
}
String[] oList = order.split(TOOLBAR_ENTRY_SEP);
String iconSize = JMeterUtils.getPropDefault(TOOLBAR_ICON_SIZE, DEFAULT_TOOLBAR_ICON_SIZE);
List<IconToolbarBean> listIcons = new ArrayList<>();
for (String key : oList) {
log.debug("Toolbar icon key: {}", key); //$NON-NLS-1$
String trimmed = key.trim();
if (trimmed.equals("|")) { //$NON-NLS-1$
listIcons.add(null);
} else {
String property = p.getProperty(trimmed);
if (property == null) {
log.warn("No definition for toolbar entry: {}", key);
} else {
try {
IconToolbarBean itb = new IconToolbarBean(property, iconSize);
listIcons.add(itb);
} catch (IllegalArgumentException e) {
// already reported by IconToolbarBean
}
}
}
}
return listIcons;
}
/**
* {@inheritDoc}
*/
@Override
public void localeChanged(LocaleChangeEvent event) {
Map<String, Boolean> currentButtonStates = getCurrentButtonsStates();
this.removeAll();
setupToolbarContent(this);
updateButtons(currentButtonStates);
}
/**
*
* @return Current state (enabled/disabled) of Toolbar button
*/
private Map<String, Boolean> getCurrentButtonsStates() {
Component[] components = getComponents();
Map<String, Boolean> buttonStates = new HashMap<>(components.length);
for (Component component : components) {
if (component instanceof JButton) {
JButton button = (JButton) component;
buttonStates.put(button.getActionCommand(), button.isEnabled());
}
}
return buttonStates;
}
/**
* Init the state of buttons
*/
public void initButtonsState() {
Map<String, Boolean> buttonStates = new HashMap<>();
buttonStates.put(ActionNames.ACTION_START, Boolean.TRUE);
buttonStates.put(ActionNames.ACTION_START_NO_TIMERS, Boolean.TRUE);
buttonStates.put(ActionNames.ACTION_STOP, Boolean.FALSE);
buttonStates.put(ActionNames.ACTION_SHUTDOWN, Boolean.FALSE);
buttonStates.put(ActionNames.UNDO, Boolean.FALSE);
buttonStates.put(ActionNames.REDO, Boolean.FALSE);
buttonStates.put(ActionNames.REMOTE_START_ALL, Boolean.TRUE);
buttonStates.put(ActionNames.REMOTE_STOP_ALL, Boolean.FALSE);
buttonStates.put(ActionNames.REMOTE_SHUT_ALL, Boolean.FALSE);
updateButtons(buttonStates);
}
/**
* Change state of buttons on local test
*
* @param started
* Flag whether local test is started
*/
public void setLocalTestStarted(boolean started) {
Map<String, Boolean> buttonStates = new HashMap<>(3);
buttonStates.put(ActionNames.ACTION_START, !started);
buttonStates.put(ActionNames.ACTION_START_NO_TIMERS, !started);
buttonStates.put(ActionNames.ACTION_STOP, started);
buttonStates.put(ActionNames.ACTION_SHUTDOWN, started);
updateButtons(buttonStates);
}
/**
* Change state of buttons on remote test
*
* @param started
* Flag whether the test is started
*/
public void setRemoteTestStarted(boolean started) {
Map<String, Boolean> buttonStates = new HashMap<>(3);
buttonStates.put(ActionNames.REMOTE_START_ALL, !started);
buttonStates.put(ActionNames.REMOTE_STOP_ALL, started);
buttonStates.put(ActionNames.REMOTE_SHUT_ALL, started);
updateButtons(buttonStates);
}
/**
* Change state of buttons after undo or redo
*
* @param canUndo
* Flag whether the button corresponding to
* {@link ActionNames#UNDO} should be enabled
* @param canRedo
* Flag whether the button corresponding to
* {@link ActionNames#REDO} should be enabled
*/
public void updateUndoRedoIcons(boolean canUndo, boolean canRedo) {
Map<String, Boolean> buttonStates = new HashMap<>(2);
buttonStates.put(ActionNames.UNDO, canUndo);
buttonStates.put(ActionNames.REDO, canRedo);
updateButtons(buttonStates);
}
/**
* Set buttons to a given state
*
* @param buttonStates
* {@link Map} of button names and their states
*/
private void updateButtons(Map<String, Boolean> buttonStates) {
// Swing APIs (e.g. Button.setEnabled) must be called on a Swing dispatch thread
boolean synchronous = false;
JMeterUtils.runSafe(synchronous, () -> {
for (Component component : getComponents()) {
if (component instanceof JButton) {
JButton button = (JButton) component;
Boolean enabled = buttonStates.get(button.getActionCommand());
if (enabled != null) {
button.setEnabled(enabled);
}
}
}
});
}
}
| apache-2.0 |
haoyanjun21/jstorm | jstorm-core/src/main/java/backtype/storm/transactional/TransactionalTopologyBuilder.java | 19907 | /**
* 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 backtype.storm.transactional;
import backtype.storm.coordination.IBatchBolt;
import backtype.storm.coordination.BatchBoltExecutor;
import backtype.storm.Config;
import backtype.storm.Constants;
import backtype.storm.coordination.CoordinatedBolt;
import backtype.storm.coordination.CoordinatedBolt.IdStreamSpec;
import backtype.storm.coordination.CoordinatedBolt.SourceArgs;
import backtype.storm.generated.GlobalStreamId;
import backtype.storm.generated.Grouping;
import backtype.storm.generated.StormTopology;
import backtype.storm.grouping.CustomStreamGrouping;
import backtype.storm.grouping.PartialKeyGrouping;
import backtype.storm.topology.BaseConfigurationDeclarer;
import backtype.storm.topology.BasicBoltExecutor;
import backtype.storm.topology.BoltDeclarer;
import backtype.storm.topology.IBasicBolt;
import backtype.storm.topology.IRichBolt;
import backtype.storm.topology.InputDeclarer;
import backtype.storm.topology.SpoutDeclarer;
import backtype.storm.topology.TopologyBuilder;
import backtype.storm.transactional.partitioned.IOpaquePartitionedTransactionalSpout;
import backtype.storm.transactional.partitioned.IPartitionedTransactionalSpout;
import backtype.storm.transactional.partitioned.OpaquePartitionedTransactionalSpoutExecutor;
import backtype.storm.transactional.partitioned.PartitionedTransactionalSpoutExecutor;
import backtype.storm.tuple.Fields;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.alibaba.jstorm.client.ConfigExtension;
/**
* Trident subsumes the functionality provided by transactional topologies, so this class is deprecated.
*
*/
@Deprecated
public class TransactionalTopologyBuilder {
String _id;
String _spoutId;
ITransactionalSpout _spout;
Map<String, Component> _bolts = new HashMap<String, Component>();
Integer _spoutParallelism;
List<Map> _spoutConfs = new ArrayList();
// id is used to store the state of this transactionalspout in zookeeper
// it would be very dangerous to have 2 topologies active with the same id in the same cluster
public TransactionalTopologyBuilder(String id, String spoutId, ITransactionalSpout spout, Number spoutParallelism) {
_id = id;
_spoutId = spoutId;
_spout = spout;
_spoutParallelism = (spoutParallelism == null) ? null : spoutParallelism.intValue();
}
public TransactionalTopologyBuilder(String id, String spoutId, ITransactionalSpout spout) {
this(id, spoutId, spout, null);
}
public TransactionalTopologyBuilder(String id, String spoutId, IPartitionedTransactionalSpout spout, Number spoutParallelism) {
this(id, spoutId, new PartitionedTransactionalSpoutExecutor(spout), spoutParallelism);
}
public TransactionalTopologyBuilder(String id, String spoutId, IPartitionedTransactionalSpout spout) {
this(id, spoutId, spout, null);
}
public TransactionalTopologyBuilder(String id, String spoutId, IOpaquePartitionedTransactionalSpout spout, Number spoutParallelism) {
this(id, spoutId, new OpaquePartitionedTransactionalSpoutExecutor(spout), spoutParallelism);
}
public TransactionalTopologyBuilder(String id, String spoutId, IOpaquePartitionedTransactionalSpout spout) {
this(id, spoutId, spout, null);
}
public SpoutDeclarer getSpoutDeclarer() {
return new SpoutDeclarerImpl();
}
public BoltDeclarer setBolt(String id, IBatchBolt bolt) {
return setBolt(id, bolt, null);
}
public BoltDeclarer setBolt(String id, IBatchBolt bolt, Number parallelism) {
return setBolt(id, new BatchBoltExecutor(bolt), parallelism, bolt instanceof ICommitter);
}
public BoltDeclarer setCommitterBolt(String id, IBatchBolt bolt) {
return setCommitterBolt(id, bolt, null);
}
public BoltDeclarer setCommitterBolt(String id, IBatchBolt bolt, Number parallelism) {
return setBolt(id, new BatchBoltExecutor(bolt), parallelism, true);
}
public BoltDeclarer setBolt(String id, IBasicBolt bolt) {
return setBolt(id, bolt, null);
}
public BoltDeclarer setBolt(String id, IBasicBolt bolt, Number parallelism) {
return setBolt(id, new BasicBoltExecutor(bolt), parallelism, false);
}
private BoltDeclarer setBolt(String id, IRichBolt bolt, Number parallelism, boolean committer) {
Integer p = null;
if (parallelism != null)
p = parallelism.intValue();
Component component = new Component(bolt, p, committer);
_bolts.put(id, component);
return new BoltDeclarerImpl(component);
}
public TopologyBuilder buildTopologyBuilder() {
// Transaction is not compatible with jstorm batch mode(task.batch.tuple)
// so we close batch mode via system property
System.setProperty(ConfigExtension.TASK_BATCH_TUPLE, "false");
String coordinator = _spoutId + "/coordinator";
TopologyBuilder builder = new TopologyBuilder();
SpoutDeclarer declarer = builder.setSpout(coordinator, new TransactionalSpoutCoordinator(_spout));
for (Map conf : _spoutConfs) {
declarer.addConfigurations(conf);
}
declarer.addConfiguration(Config.TOPOLOGY_TRANSACTIONAL_ID, _id);
BoltDeclarer emitterDeclarer =
builder.setBolt(_spoutId, new CoordinatedBolt(new TransactionalSpoutBatchExecutor(_spout), null, null), _spoutParallelism)
.allGrouping(coordinator, TransactionalSpoutCoordinator.TRANSACTION_BATCH_STREAM_ID)
.addConfiguration(Config.TOPOLOGY_TRANSACTIONAL_ID, _id);
if (_spout instanceof ICommitterTransactionalSpout) {
emitterDeclarer.allGrouping(coordinator, TransactionalSpoutCoordinator.TRANSACTION_COMMIT_STREAM_ID);
}
for (String id : _bolts.keySet()) {
Component component = _bolts.get(id);
Map<String, SourceArgs> coordinatedArgs = new HashMap<String, SourceArgs>();
for (String c : componentBoltSubscriptions(component)) {
coordinatedArgs.put(c, SourceArgs.all());
}
IdStreamSpec idSpec = null;
if (component.committer) {
idSpec = IdStreamSpec.makeDetectSpec(coordinator, TransactionalSpoutCoordinator.TRANSACTION_COMMIT_STREAM_ID);
}
BoltDeclarer input = builder.setBolt(id, new CoordinatedBolt(component.bolt, coordinatedArgs, idSpec), component.parallelism);
for (Map conf : component.componentConfs) {
input.addConfigurations(conf);
}
for (String c : componentBoltSubscriptions(component)) {
input.directGrouping(c, Constants.COORDINATED_STREAM_ID);
}
for (InputDeclaration d : component.declarations) {
d.declare(input);
}
if (component.committer) {
input.allGrouping(coordinator, TransactionalSpoutCoordinator.TRANSACTION_COMMIT_STREAM_ID);
}
}
return builder;
}
public StormTopology buildTopology() {
return buildTopologyBuilder().createTopology();
}
private Set<String> componentBoltSubscriptions(Component component) {
Set<String> ret = new HashSet<String>();
for (InputDeclaration d : component.declarations) {
ret.add(d.getComponent());
}
return ret;
}
private static class Component {
public IRichBolt bolt;
public Integer parallelism;
public List<InputDeclaration> declarations = new ArrayList<InputDeclaration>();
public List<Map> componentConfs = new ArrayList<Map>();
public boolean committer;
public Component(IRichBolt bolt, Integer parallelism, boolean committer) {
this.bolt = bolt;
this.parallelism = parallelism;
this.committer = committer;
}
}
private static interface InputDeclaration {
void declare(InputDeclarer declarer);
String getComponent();
}
private class SpoutDeclarerImpl extends BaseConfigurationDeclarer<SpoutDeclarer> implements SpoutDeclarer {
@Override
public SpoutDeclarer addConfigurations(Map conf) {
_spoutConfs.add(conf);
return this;
}
}
private class BoltDeclarerImpl extends BaseConfigurationDeclarer<BoltDeclarer> implements BoltDeclarer {
Component _component;
public BoltDeclarerImpl(Component component) {
_component = component;
}
@Override
public BoltDeclarer fieldsGrouping(final String component, final Fields fields) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.fieldsGrouping(component, fields);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer fieldsGrouping(final String component, final String streamId, final Fields fields) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.fieldsGrouping(component, streamId, fields);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer globalGrouping(final String component) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.globalGrouping(component);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer globalGrouping(final String component, final String streamId) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.globalGrouping(component, streamId);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer shuffleGrouping(final String component) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.shuffleGrouping(component);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer shuffleGrouping(final String component, final String streamId) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.shuffleGrouping(component, streamId);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer localOrShuffleGrouping(final String component) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.localOrShuffleGrouping(component);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer localOrShuffleGrouping(final String component, final String streamId) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.localOrShuffleGrouping(component, streamId);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer localFirstGrouping(final String component) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.localFirstGrouping(component);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer localFirstGrouping(final String component, final String streamId) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.localFirstGrouping(component, streamId);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer noneGrouping(final String component) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.noneGrouping(component);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer noneGrouping(final String component, final String streamId) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.noneGrouping(component, streamId);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer allGrouping(final String component) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.allGrouping(component);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer allGrouping(final String component, final String streamId) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.allGrouping(component, streamId);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer directGrouping(final String component) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.directGrouping(component);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer directGrouping(final String component, final String streamId) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.directGrouping(component, streamId);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer partialKeyGrouping(String componentId, Fields fields) {
return customGrouping(componentId, new PartialKeyGrouping(fields));
}
@Override
public BoltDeclarer partialKeyGrouping(String componentId, String streamId, Fields fields) {
return customGrouping(componentId, streamId, new PartialKeyGrouping(fields));
}
@Override
public BoltDeclarer customGrouping(final String component, final CustomStreamGrouping grouping) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.customGrouping(component, grouping);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer customGrouping(final String component, final String streamId, final CustomStreamGrouping grouping) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.customGrouping(component, streamId, grouping);
}
@Override
public String getComponent() {
return component;
}
});
return this;
}
@Override
public BoltDeclarer grouping(final GlobalStreamId stream, final Grouping grouping) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(InputDeclarer declarer) {
declarer.grouping(stream, grouping);
}
@Override
public String getComponent() {
return stream.get_componentId();
}
});
return this;
}
private void addDeclaration(InputDeclaration declaration) {
_component.declarations.add(declaration);
}
@Override
public BoltDeclarer addConfigurations(Map conf) {
_component.componentConfs.add(conf);
return this;
}
}
}
| apache-2.0 |
zstackio/zstack | sdk/src/main/java/org/zstack/sdk/CreateL2VlanNetworkResult.java | 356 | package org.zstack.sdk;
import org.zstack.sdk.L2VlanNetworkInventory;
public class CreateL2VlanNetworkResult {
public L2VlanNetworkInventory inventory;
public void setInventory(L2VlanNetworkInventory inventory) {
this.inventory = inventory;
}
public L2VlanNetworkInventory getInventory() {
return this.inventory;
}
}
| apache-2.0 |
davidwebster48/jawr-main-repo | jawr-spring/jawr-spring-integration-test/src/test/java/net/jawr/web/test/PageOnlyJsCssJawrServletTest.java | 2699 | /**
*
*/
package net.jawr.web.test;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import com.gargoylesoftware.htmlunit.JavaScriptPage;
import com.gargoylesoftware.htmlunit.TextPage;
import com.gargoylesoftware.htmlunit.html.HtmlLink;
import com.gargoylesoftware.htmlunit.html.HtmlScript;
/**
* Test case for page with only JS and Css servlet in production mode.
*
* @author ibrahim Chaehoi
*/
@JawrSpringTestConfigFiles(webXml = "net/jawr/web/standard/config/web-without-img-servlet.xml", jawrConfig = "net/jawr/web/standard/config/jawr-without-img-servlet.properties",
dispatcherServletConfig = "net/jawr/web/standard/config/dispatcherWithOutImgServlet-servlet.xml")
public class PageOnlyJsCssJawrServletTest extends AbstractSpringPageTest {
/**
* Returns the page URL to test
* @return the page URL to test
*/
protected String getPageUrl() {
return getServerUrlPrefix() + getUrlPrefix()+"/page-without-img-tags.jsp";
}
@Test
public void testPageLoad() throws Exception {
final List<String> expectedAlerts = Collections
.singletonList("A little message retrieved from the message bundle : Hello $ world!");
assertEquals(expectedAlerts, collectedAlerts);
assertContentEquals("/net/jawr/web/standard/resources/without_img_servlet/page-without-img-tags-result-expected.txt", page);
}
@Test
public void checkGeneratedJsLinks() {
// Test generated Script link
final List<?> scripts = getJsScriptTags();
assertEquals(1, scripts.size());
final HtmlScript script = (HtmlScript) scripts.get(0);
assertEquals(
getUrlPrefix()+"/spring/jawr/690372103.en_US/js/bundle/msg.js",
script.getSrcAttribute());
}
@Test
public void testJsBundleContent() throws Exception {
final List<?> scripts = getJsScriptTags();
final HtmlScript script = (HtmlScript) scripts.get(0);
final JavaScriptPage page = getJavascriptPage(script);
assertContentEquals("/net/jawr/web/standard/resources/msg-bundle.js", page);
}
@Test
public void checkGeneratedCssLinks() {
// Test generated Css link
final List<?> styleSheets = getHtmlLinkTags();
assertEquals(1, styleSheets.size());
final HtmlLink css = (HtmlLink) styleSheets.get(0);
assertEquals(
getUrlPrefix()+"/spring/jawr/N1529412158/fwk/core/component.css",
css.getHrefAttribute());
}
@Test
public void testCssBundleContent() throws Exception {
final List<?> styleSheets = getHtmlLinkTags();
final HtmlLink css = (HtmlLink) styleSheets.get(0);
final TextPage page = getCssPage(css);
assertContentEquals("/net/jawr/web/standard/resources/without_img_servlet/component-expected.css", page);
}
}
| apache-2.0 |
thinkernel/buck | test/com/facebook/buck/model/ImmediateDirectoryBuildTargetPatternTest.java | 2481 | /*
* Copyright 2012-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ImmediateDirectoryBuildTargetPatternTest {
@Test
public void testApply() {
ImmediateDirectoryBuildTargetPattern pattern =
new ImmediateDirectoryBuildTargetPattern("src/com/facebook/buck/");
assertFalse(pattern.apply(null));
assertTrue(pattern.apply(new BuildTarget("//src/com/facebook/buck", "buck")));
assertFalse(pattern.apply(new BuildTarget("//src/com/facebook/foo/", "foo")));
assertFalse(pattern.apply(new BuildTarget("//src/com/facebook/buck/bar", "bar")));
}
@Test
public void testEquals() {
ImmediateDirectoryBuildTargetPattern pattern =
new ImmediateDirectoryBuildTargetPattern("src/com/facebook/buck/");
ImmediateDirectoryBuildTargetPattern samePattern =
new ImmediateDirectoryBuildTargetPattern("src/com/facebook/buck/");
ImmediateDirectoryBuildTargetPattern cliPattern =
new ImmediateDirectoryBuildTargetPattern("src/com/facebook/buck/cli/");
assertEquals(pattern, samePattern);
assertFalse(pattern.equals(null));
assertFalse(pattern.equals(cliPattern));
}
@Test
public void testHashCode() {
ImmediateDirectoryBuildTargetPattern pattern =
new ImmediateDirectoryBuildTargetPattern("src/com/facebook/buck/");
ImmediateDirectoryBuildTargetPattern samePattern =
new ImmediateDirectoryBuildTargetPattern("src/com/facebook/buck/");
ImmediateDirectoryBuildTargetPattern cliPattern =
new ImmediateDirectoryBuildTargetPattern("src/com/facebook/buck/cli/");
assertEquals(pattern.hashCode(), samePattern.hashCode());
assertNotSame(pattern.hashCode(), cliPattern.hashCode());
}
}
| apache-2.0 |
zouzhberk/ambaridemo | demo-server/src/main/java/org/apache/ambari/server/api/predicate/operators/OrOperator.java | 1760 | /**
* 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.ambari.server.api.predicate.operators;
import org.apache.ambari.server.controller.predicate.OrPredicate;
import org.apache.ambari.server.controller.spi.Predicate;
/**
* Or operator implementation.
*/
public class OrOperator extends AbstractOperator implements LogicalOperator {
/**
* Constructor.
*
* @param ctxPrecedence precedence value for the current context
*/
public OrOperator(int ctxPrecedence) {
super(ctxPrecedence);
}
@Override
public TYPE getType() {
return TYPE.OR;
}
@Override
public String getName() {
return "OrOperator";
}
@Override
public int getBasePrecedence() {
return 1;
}
@Override
public Predicate toPredicate(Predicate left, Predicate right) {
//todo: refactor to remove down casts
return new OrPredicate(left, right);
}
@Override
public String toString() {
return getName() + "[precedence=" + getPrecedence() + "]";
}
}
| apache-2.0 |
lindzh/mybatis-spring-1.2.2 | src/main/java/org/mybatis/spring/transaction/package-info.java | 788 | /*
* Copyright 2010-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Contains core classes to manage MyBatis transactions in Spring3.X.
*
* @version $Id$
*/
package org.mybatis.spring.transaction;
| apache-2.0 |
mbittmann/opensoc-streaming | OpenSOC-MessageParsers/src/main/java/com/opensoc/parsing/TelemetryParserBolt.java | 6479 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.opensoc.parsing;
import java.io.IOException;
import java.util.Map;
import org.apache.commons.configuration.Configuration;
import org.json.simple.JSONObject;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;
import com.opensoc.helpers.topology.ErrorGenerator;
import com.opensoc.json.serialization.JSONEncoderHelper;
import com.opensoc.metrics.MetricReporter;
import com.opensoc.parser.interfaces.MessageFilter;
import com.opensoc.parser.interfaces.MessageParser;
/**
* Uses an adapter to parse a telemetry message from its native format into a
* standard JSON. For a list of available adapter please check
* com.opensoc.parser.parsers. The input is a raw byte array and the output is a
* JSONObject
* <p>
* The parsing conventions are as follows:
* <p>
* <ul>
*
* <li>ip_src_addr = source ip of a message
* <li>ip_dst_addr = destination ip of a message
* <li>ip_src_port = source port of a message
* <li>ip_dst_port = destination port of a message
* <li>protocol = protocol of a message
* <ul>
* <p>
* <p>
* If a message does not contain at least one of these variables it will be
* failed
**/
@SuppressWarnings("rawtypes")
public class TelemetryParserBolt extends AbstractParserBolt {
private static final long serialVersionUID = -2647123143398352020L;
private JSONObject metricConfiguration;
/**
* @param parser
* The parser class for parsing the incoming raw message byte
* stream
* @return Instance of this class
*/
public TelemetryParserBolt withMessageParser(MessageParser parser) {
_parser = parser;
return this;
}
/**
* @param OutputFieldName
* Field name of the output tuple
* @return Instance of this class
*/
public TelemetryParserBolt withOutputFieldName(String OutputFieldName) {
this.OutputFieldName = OutputFieldName;
return this;
}
/**
* @param filter
* A class for filtering/dropping incomming telemetry messages
* @return Instance of this class
*/
public TelemetryParserBolt withMessageFilter(MessageFilter filter) {
this._filter = filter;
return this;
}
/**
* @param config
* A class for generating custom metrics into graphite
* @return Instance of this class
*/
public TelemetryParserBolt withMetricConfig(Configuration config) {
this.metricConfiguration = JSONEncoderHelper.getJSON(config
.subset("com.opensoc.metrics"));
return this;
}
@Override
void doPrepare(Map conf, TopologyContext topologyContext,
OutputCollector collector) throws IOException {
LOG.info("[OpenSOC] Preparing TelemetryParser Bolt...");
if (metricConfiguration != null) {
_reporter = new MetricReporter();
_reporter
.initialize(metricConfiguration, TelemetryParserBolt.class);
LOG.info("[OpenSOC] Metric reporter is initialized");
} else {
LOG.info("[OpenSOC] Metric reporter is not initialized");
}
this.registerCounters();
if(_parser != null)
_parser.init();
}
@SuppressWarnings("unchecked")
public void execute(Tuple tuple) {
LOG.trace("[OpenSOC] Starting to process a new incoming tuple");
byte[] original_message = null;
try {
original_message = tuple.getBinary(0);
LOG.trace("[OpenSOC] Starting the parsing process");
if (original_message == null || original_message.length == 0) {
LOG.error("Incomming tuple is null");
throw new Exception("Invalid message length");
}
LOG.trace("[OpenSOC] Attempting to transofrm binary message to JSON");
JSONObject transformed_message = _parser.parse(original_message);
LOG.debug("[OpenSOC] Transformed Telemetry message: "
+ transformed_message);
if (transformed_message == null || transformed_message.isEmpty())
throw new Exception("Unable to turn binary message into a JSON");
LOG.trace("[OpenSOC] Checking if the transformed JSON conforms to the right schema");
if (!checkForSchemaCorrectness(transformed_message)) {
throw new Exception("Incorrect formatting on message: "
+ transformed_message);
}
else {
LOG.trace("[OpenSOC] JSON message has the right schema");
boolean filtered = false;
if (_filter != null) {
if (!_filter.emitTuple(transformed_message)) {
filtered = true;
}
}
if (!filtered) {
String ip1 = null;
if (transformed_message.containsKey("ip_src_addr"))
ip1 = transformed_message.get("ip_src_addr").toString();
String ip2 = null;
if (transformed_message.containsKey("ip_dst_addr"))
ip2 = transformed_message.get("ip_dst_addr").toString();
String key = generateTopologyKey(ip1, ip2);
JSONObject new_message = new JSONObject();
new_message.put("message", transformed_message);
_collector.emit("message", new Values(key, new_message));
}
_collector.ack(tuple);
if (metricConfiguration != null)
ackCounter.inc();
}
} catch (Exception e) {
e.printStackTrace();
LOG.error("Failed to parse telemetry message :" + original_message);
_collector.fail(tuple);
if (metricConfiguration != null)
failCounter.inc();
JSONObject error = ErrorGenerator.generateErrorMessage(
"Parsing problem: " + new String(original_message),
e);
_collector.emit("error", new Values(error));
}
}
public void declareOutputFields(OutputFieldsDeclarer declearer) {
declearer.declareStream("message", new Fields("key", "message"));
declearer.declareStream("error", new Fields("message"));
}
} | apache-2.0 |
ksen007/janala2 | src/main/java/database/table/select/Select.java | 258 | package database.table.select;
import database.table.operations.Operations;
/**
* Author: Koushik Sen (ksen@cs.berkeley.edu)
* Date: 8/20/12
* Time: 12:44 PM
*/
public interface Select {
public String[] selectAs();
public Operations[] select();
}
| bsd-2-clause |
valum-framework/FrameworkBenchmarks | frameworks/Java/vertx/src/main/java/vertx/App.java | 11736 | package vertx;
import com.julienviet.pgclient.*;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import vertx.model.Fortune;
import vertx.model.Message;
import vertx.model.World;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class App extends AbstractVerticle implements Handler<HttpServerRequest> {
/**
* Returns the value of the "queries" getRequest parameter, which is an integer
* bound between 1 and 500 with a default value of 1.
*
* @param request the current HTTP request
* @return the value of the "queries" parameter
*/
static int getQueries(HttpServerRequest request) {
String param = request.getParam("queries");
if (param == null) {
return 1;
}
try {
int parsedValue = Integer.parseInt(param);
return Math.min(500, Math.max(1, parsedValue));
} catch (NumberFormatException e) {
return 1;
}
}
static Logger logger = LoggerFactory.getLogger(App.class.getName());
private static final String PATH_PLAINTEXT = "/plaintext";
private static final String PATH_JSON = "/json";
private static final String PATH_DB = "/db";
private static final String PATH_QUERIES = "/queries";
private static final String PATH_UPDATES = "/updates";
private static final String PATH_FORTUNES = "/fortunes";
private static final CharSequence RESPONSE_TYPE_PLAIN = HttpHeaders.createOptimized("text/plain");
private static final CharSequence RESPONSE_TYPE_HTML = HttpHeaders.createOptimized("text/html; charset=UTF-8");
private static final CharSequence RESPONSE_TYPE_JSON = HttpHeaders.createOptimized("application/json");
private static final String HELLO_WORLD = "Hello, world!";
private static final Buffer HELLO_WORLD_BUFFER = Buffer.buffer(HELLO_WORLD);
private static final CharSequence HEADER_SERVER = HttpHeaders.createOptimized("server");
private static final CharSequence HEADER_DATE = HttpHeaders.createOptimized("date");
private static final CharSequence HEADER_CONTENT_TYPE = HttpHeaders.createOptimized("content-type");
private static final CharSequence HEADER_CONTENT_LENGTH = HttpHeaders.createOptimized("content-length");
private static final CharSequence HELLO_WORLD_LENGTH = HttpHeaders.createOptimized("" + HELLO_WORLD.length());
private static final CharSequence SERVER = HttpHeaders.createOptimized("vert.x");
private static final String UPDATE_WORLD = "UPDATE world SET randomnumber=$1 WHERE id=$2";
private static final String SELECT_WORLD = "SELECT id, randomnumber from WORLD where id=$1";
private static final String SELECT_FORTUNE = "SELECT id, message from FORTUNE";
private CharSequence dateString;
private HttpServer server;
private PgClient client;
@Override
public void start() throws Exception {
int port = 8080;
server = vertx.createHttpServer(new HttpServerOptions());
server.requestHandler(App.this).listen(port);
dateString = HttpHeaders.createOptimized(java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME.format(java.time.ZonedDateTime.now()));
JsonObject config = config();
vertx.setPeriodic(1000, handler -> {
dateString = HttpHeaders.createOptimized(java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME.format(java.time.ZonedDateTime.now()));
});
PgPoolOptions options = new PgPoolOptions();
options.setDatabase(config.getString("database"));
options.setHost(config.getString("host"));
options.setPort(config.getInteger("port", 5432));
options.setUsername(config.getString("username"));
options.setPassword(config.getString("password"));
options.setCachePreparedStatements(true);
options.setMaxSize(1);
client = PgClient.pool(vertx, options);
}
@Override
public void handle(HttpServerRequest request) {
switch (request.path()) {
case PATH_PLAINTEXT:
handlePlainText(request);
break;
case PATH_JSON:
handleJson(request);
break;
case PATH_DB:
handleDb(request);
break;
case PATH_QUERIES:
new Queries().handle(request);
break;
case PATH_UPDATES:
new Update(request).handle();
break;
case PATH_FORTUNES:
handleFortunes(request);
break;
default:
request.response().setStatusCode(404);
request.response().end();
break;
}
}
@Override
public void stop() {
if (server != null) server.close();
}
private void handlePlainText(HttpServerRequest request) {
HttpServerResponse response = request.response();
MultiMap headers = response.headers();
headers
.add(HEADER_CONTENT_TYPE, RESPONSE_TYPE_PLAIN)
.add(HEADER_SERVER, SERVER)
.add(HEADER_DATE, dateString)
.add(HEADER_CONTENT_LENGTH, HELLO_WORLD_LENGTH);
response.end(HELLO_WORLD_BUFFER);
}
private void handleJson(HttpServerRequest request) {
HttpServerResponse response = request.response();
MultiMap headers = response.headers();
headers
.add(HEADER_CONTENT_TYPE, RESPONSE_TYPE_JSON)
.add(HEADER_SERVER, SERVER)
.add(HEADER_DATE, dateString);
response.end(new Message("Hello, World!").toBuffer());
}
/**
* Returns a random integer that is a suitable value for both the {@code id}
* and {@code randomNumber} properties of a world object.
*
* @return a random world number
*/
private static int randomWorld() {
return 1 + ThreadLocalRandom.current().nextInt(10000);
}
private void handleDb(HttpServerRequest req) {
HttpServerResponse resp = req.response();
client.preparedQuery(SELECT_WORLD, Tuple.of(randomWorld()), res -> {
if (res.succeeded()) {
PgIterator<Row> resultSet = res.result().iterator();
if (!resultSet.hasNext()) {
resp.setStatusCode(404).end();
return;
}
Tuple row = resultSet.next();
resp
.putHeader(HttpHeaders.SERVER, SERVER)
.putHeader(HttpHeaders.DATE, dateString)
.putHeader(HttpHeaders.CONTENT_TYPE, RESPONSE_TYPE_JSON)
.end(Json.encode(new World(row.getInteger(0), row.getInteger(1))));
} else {
logger.error(res.cause());
resp.setStatusCode(500).end(res.cause().getMessage());
}
});
}
class Queries {
boolean failed;
JsonArray worlds = new JsonArray();
private void handle(HttpServerRequest req) {
HttpServerResponse resp = req.response();
final int queries = getQueries(req);
for (int i = 0; i < queries; i++) {
client.preparedQuery(SELECT_WORLD, Tuple.of(randomWorld()), ar -> {
if (!failed) {
if (ar.failed()) {
failed = true;
resp.setStatusCode(500).end(ar.cause().getMessage());
return;
}
// we need a final reference
final Tuple row = ar.result().iterator().next();
worlds.add(new JsonObject().put("id", "" + row.getInteger(0)).put("randomNumber", "" + row.getInteger(1)));
// stop condition
if (worlds.size() == queries) {
resp
.putHeader(HttpHeaders.SERVER, SERVER)
.putHeader(HttpHeaders.DATE, dateString)
.putHeader(HttpHeaders.CONTENT_TYPE, RESPONSE_TYPE_JSON)
.end(worlds.encode());
}
}
});
}
}
}
class Update {
final HttpServerRequest req;
boolean failed;
int queryCount;
final World[] worlds;
public Update(HttpServerRequest req) {
final int queries = getQueries(req);
this.req = req;
this.worlds = new World[queries];
}
private void handle() {
for (int i = 0; i < worlds.length; i++) {
int id = randomWorld();
int index = i;
client.preparedQuery(SELECT_WORLD, Tuple.of(id), ar -> {
if (!failed) {
if (ar.failed()) {
failed = true;
sendError(ar.cause());
return;
}
worlds[index] = new World(ar.result().iterator().next().getInteger(0), randomWorld());
if (++queryCount == worlds.length) {
handleUpdates();
}
}
});
}
}
void handleUpdates() {
Arrays.sort(worlds);
List<Tuple> batch = new ArrayList<>();
for (World world : worlds) {
batch.add(Tuple.of(world.getRandomNumber(), world.getId()));
}
client.preparedBatch(UPDATE_WORLD, batch, ar -> {
if (ar.failed()) {
sendError(ar.cause());
return;
}
JsonArray json = new JsonArray();
for (World world : worlds) {
json.add(new JsonObject().put("id", "" + world.getId()).put("randomNumber", "" + world.getRandomNumber()));
}
req.response()
.putHeader(HttpHeaders.SERVER, SERVER)
.putHeader(HttpHeaders.DATE, dateString)
.putHeader(HttpHeaders.CONTENT_TYPE, RESPONSE_TYPE_JSON)
.end(json.toBuffer());
});
}
void sendError(Throwable err) {
logger.error("", err);
req.response().setStatusCode(500).end(err.getMessage());
}
}
private void handleFortunes(HttpServerRequest req) {
client.preparedQuery(SELECT_FORTUNE, ar -> {
HttpServerResponse response = req.response();
if (ar.succeeded()) {
List<Fortune> fortunes = new ArrayList<>();
PgIterator<Row> resultSet = ar.result().iterator();
if (!resultSet.hasNext()) {
response.setStatusCode(404).end("No results");
return;
}
while (resultSet.hasNext()) {
Tuple row = resultSet.next();
fortunes.add(new Fortune(row.getInteger(0), row.getString(1)));
}
fortunes.add(new Fortune(0, "Additional fortune added at request time."));
Collections.sort(fortunes);
response
.putHeader(HttpHeaders.SERVER, SERVER)
.putHeader(HttpHeaders.DATE, dateString)
.putHeader(HttpHeaders.CONTENT_TYPE, RESPONSE_TYPE_HTML)
.end(FortunesTemplate.template(fortunes).render().toString());
} else {
Throwable err = ar.cause();
logger.error("", err);
response.setStatusCode(500).end(err.getMessage());
}
});
}
public static void main(String[] args) throws Exception {
JsonObject config = new JsonObject(new String(Files.readAllBytes(new File(args[0]).toPath())));
int procs = Runtime.getRuntime().availableProcessors();
Vertx vertx = Vertx.vertx();
vertx.exceptionHandler(err -> {
err.printStackTrace();
});
vertx.deployVerticle(App.class.getName(),
new DeploymentOptions().setInstances(procs * 2).setConfig(config), event -> {
if (event.succeeded()) {
logger.debug("Your Vert.x application is started!");
} else {
logger.error("Unable to start your application", event.cause());
}
});
}
}
| bsd-3-clause |
armersong/luaj | src/main/java/org/luaj/vm2/lib/jse/CoerceLuaToJava.java | 12992 | /*******************************************************************************
* Copyright (c) 2009-2011 Luaj.org. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
package org.luaj.vm2.lib.jse;
import java.lang.reflect.Array;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.luaj.vm2.LuaString;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
/**
* Helper class to coerce values from lua to Java within the luajava library.
* <p>
* This class is primarily used by the {@link org.luaj.vm2.lib.jse.LuajavaLib},
* but can also be used directly when working with Java/lua bindings.
* <p>
* To coerce to specific Java values, generally the {@code toType()} methods
* on {@link LuaValue} may be used:
* <ul>
* <li>{@link LuaValue#toboolean()}</li>
* <li>{@link LuaValue#tobyte()}</li>
* <li>{@link LuaValue#tochar()}</li>
* <li>{@link LuaValue#toshort()}</li>
* <li>{@link LuaValue#toint()}</li>
* <li>{@link LuaValue#tofloat()}</li>
* <li>{@link LuaValue#todouble()}</li>
* <li>{@link LuaValue#tojstring()}</li>
* <li>{@link LuaValue#touserdata()}</li>
* <li>{@link LuaValue#touserdata(Class)}</li>
* </ul>
* <p>
* For data in lua tables, the various methods on {@link LuaTable} can be used directly
* to convert data to something more useful.
*
* @see org.luaj.vm2.lib.jse.LuajavaLib
* @see CoerceJavaToLua
*/
public class CoerceLuaToJava {
static int SCORE_NULL_VALUE = 0x10;
static int SCORE_WRONG_TYPE = 0x100;
static int SCORE_UNCOERCIBLE = 0x10000;
static interface Coercion {
public int score( LuaValue value );
public Object coerce( LuaValue value );
};
/**
* Coerce a LuaValue value to a specified java class
* @param value LuaValue to coerce
* @param clazz Class to coerce into
* @return Object of type clazz (or a subclass) with the corresponding value.
*/
public static Object coerce(LuaValue value, Class clazz) {
return getCoercion(clazz).coerce(value);
}
static final Map COERCIONS = Collections.synchronizedMap(new HashMap());
static final class BoolCoercion implements Coercion {
public String toString() {
return "BoolCoercion()";
}
public int score( LuaValue value ) {
switch ( value.type() ) {
case LuaValue.TBOOLEAN:
return 0;
}
return 1;
}
public Object coerce(LuaValue value) {
return value.toboolean()? Boolean.TRUE: Boolean.FALSE;
}
}
static final class NumericCoercion implements Coercion {
static final int TARGET_TYPE_BYTE = 0;
static final int TARGET_TYPE_CHAR = 1;
static final int TARGET_TYPE_SHORT = 2;
static final int TARGET_TYPE_INT = 3;
static final int TARGET_TYPE_LONG = 4;
static final int TARGET_TYPE_FLOAT = 5;
static final int TARGET_TYPE_DOUBLE = 6;
static final String[] TYPE_NAMES = { "byte", "char", "short", "int", "long", "float", "double" };
final int targetType;
public String toString() {
return "NumericCoercion("+TYPE_NAMES[targetType]+")";
}
NumericCoercion(int targetType) {
this.targetType = targetType;
}
public int score( LuaValue value ) {
int fromStringPenalty = 0;
if ( value.type() == LuaValue.TSTRING ) {
value = value.tonumber();
if ( value.isnil() ) {
return SCORE_UNCOERCIBLE;
}
fromStringPenalty = 4;
}
if ( value.isint() ) {
switch ( targetType ) {
case TARGET_TYPE_BYTE: {
int i = value.toint();
return fromStringPenalty + ((i==(byte)i)? 0: SCORE_WRONG_TYPE);
}
case TARGET_TYPE_CHAR: {
int i = value.toint();
return fromStringPenalty + ((i==(byte)i)? 1: (i==(char)i)? 0: SCORE_WRONG_TYPE);
}
case TARGET_TYPE_SHORT: {
int i = value.toint();
return fromStringPenalty +
((i==(byte)i)? 1: (i==(short)i)? 0: SCORE_WRONG_TYPE);
}
case TARGET_TYPE_INT: {
int i = value.toint();
return fromStringPenalty +
((i==(byte)i)? 2: ((i==(char)i) || (i==(short)i))? 1: 0);
}
case TARGET_TYPE_FLOAT: return fromStringPenalty + 1;
case TARGET_TYPE_LONG: return fromStringPenalty + 1;
case TARGET_TYPE_DOUBLE: return fromStringPenalty + 2;
default: return SCORE_WRONG_TYPE;
}
} else if ( value.isnumber() ) {
switch ( targetType ) {
case TARGET_TYPE_BYTE: return SCORE_WRONG_TYPE;
case TARGET_TYPE_CHAR: return SCORE_WRONG_TYPE;
case TARGET_TYPE_SHORT: return SCORE_WRONG_TYPE;
case TARGET_TYPE_INT: return SCORE_WRONG_TYPE;
case TARGET_TYPE_LONG: {
double d = value.todouble();
return fromStringPenalty + ((d==(long)d)? 0: SCORE_WRONG_TYPE);
}
case TARGET_TYPE_FLOAT: {
double d = value.todouble();
return fromStringPenalty + ((d==(float)d)? 0: SCORE_WRONG_TYPE);
}
case TARGET_TYPE_DOUBLE: {
double d = value.todouble();
return fromStringPenalty + (((d==(long)d) || (d==(float)d))? 1: 0);
}
default: return SCORE_WRONG_TYPE;
}
} else {
return SCORE_UNCOERCIBLE;
}
}
public Object coerce(LuaValue value) {
switch ( targetType ) {
case TARGET_TYPE_BYTE: return new Byte( (byte) value.toint() );
case TARGET_TYPE_CHAR: return new Character( (char) value.toint() );
case TARGET_TYPE_SHORT: return new Short( (short) value.toint() );
case TARGET_TYPE_INT: return new Integer( (int) value.toint() );
case TARGET_TYPE_LONG: return new Long( (long) value.todouble() );
case TARGET_TYPE_FLOAT: return new Float( (float) value.todouble() );
case TARGET_TYPE_DOUBLE: return new Double( (double) value.todouble() );
default: return null;
}
}
}
static final class StringCoercion implements Coercion {
public static final int TARGET_TYPE_STRING = 0;
public static final int TARGET_TYPE_BYTES = 1;
final int targetType;
public StringCoercion(int targetType) {
this.targetType = targetType;
}
public String toString() {
return "StringCoercion("+(targetType==TARGET_TYPE_STRING? "String": "byte[]")+")";
}
public int score(LuaValue value) {
switch ( value.type() ) {
case LuaValue.TSTRING:
return value.checkstring().isValidUtf8()?
(targetType==TARGET_TYPE_STRING? 0: 1):
(targetType==TARGET_TYPE_BYTES? 0: SCORE_WRONG_TYPE);
case LuaValue.TNIL:
return SCORE_NULL_VALUE;
default:
return targetType == TARGET_TYPE_STRING? SCORE_WRONG_TYPE: SCORE_UNCOERCIBLE;
}
}
public Object coerce(LuaValue value) {
if ( value.isnil() )
return null;
if ( targetType == TARGET_TYPE_STRING )
return value.tojstring();
LuaString s = value.checkstring();
byte[] b = new byte[s.m_length];
s.copyInto(0, b, 0, b.length);
return b;
}
}
static final class ArrayCoercion implements Coercion {
final Class componentType;
final Coercion componentCoercion;
public ArrayCoercion(Class componentType) {
this.componentType = componentType;
this.componentCoercion = getCoercion(componentType);
}
public String toString() {
return "ArrayCoercion("+componentType.getName()+")";
}
public int score(LuaValue value) {
switch ( value.type() ) {
case LuaValue.TTABLE:
return value.length()==0? 0: componentCoercion.score( value.get(1) );
case LuaValue.TUSERDATA:
return inheritanceLevels( componentType, value.touserdata().getClass().getComponentType() );
case LuaValue.TNIL:
return SCORE_NULL_VALUE;
default:
return SCORE_UNCOERCIBLE;
}
}
public Object coerce(LuaValue value) {
switch ( value.type() ) {
case LuaValue.TTABLE: {
int n = value.length();
Object a = Array.newInstance(componentType, n);
for ( int i=0; i<n; i++ )
Array.set(a, i, componentCoercion.coerce(value.get(i+1)));
return a;
}
case LuaValue.TUSERDATA:
return value.touserdata();
case LuaValue.TNIL:
return null;
default:
return null;
}
}
}
/**
* Determine levels of inheritance between a base class and a subclass
* @param baseclass base class to look for
* @param subclass class from which to start looking
* @return number of inheritance levels between subclass and baseclass,
* or SCORE_UNCOERCIBLE if not a subclass
*/
static final int inheritanceLevels( Class baseclass, Class subclass ) {
if ( subclass == null )
return SCORE_UNCOERCIBLE;
if ( baseclass == subclass )
return 0;
int min = Math.min( SCORE_UNCOERCIBLE, inheritanceLevels( baseclass, subclass.getSuperclass() ) + 1 );
Class[] ifaces = subclass.getInterfaces();
for ( int i=0; i<ifaces.length; i++ )
min = Math.min(min, inheritanceLevels(baseclass, ifaces[i]) + 1 );
return min;
}
static final class ObjectCoercion implements Coercion {
final Class targetType;
ObjectCoercion(Class targetType) {
this.targetType = targetType;
}
public String toString() {
return "ObjectCoercion("+targetType.getName()+")";
}
public int score(LuaValue value) {
switch ( value.type() ) {
case LuaValue.TNUMBER:
return inheritanceLevels( targetType, value.isint()? Integer.class: Double.class );
case LuaValue.TBOOLEAN:
return inheritanceLevels( targetType, Boolean.class );
case LuaValue.TSTRING:
return inheritanceLevels( targetType, String.class );
case LuaValue.TUSERDATA:
return inheritanceLevels( targetType, value.touserdata().getClass() );
case LuaValue.TNIL:
return SCORE_NULL_VALUE;
default:
return inheritanceLevels( targetType, value.getClass() );
}
}
public Object coerce(LuaValue value) {
switch ( value.type() ) {
case LuaValue.TNUMBER:
return value.isint()? (Object)new Integer(value.toint()): (Object)new Double(value.todouble());
case LuaValue.TBOOLEAN:
return value.toboolean()? Boolean.TRUE: Boolean.FALSE;
case LuaValue.TSTRING:
return value.tojstring();
case LuaValue.TUSERDATA:
return value.optuserdata(targetType, null);
case LuaValue.TNIL:
return null;
default:
return value;
}
}
}
static {
Coercion boolCoercion = new BoolCoercion();
Coercion byteCoercion = new NumericCoercion(NumericCoercion.TARGET_TYPE_BYTE);
Coercion charCoercion = new NumericCoercion(NumericCoercion.TARGET_TYPE_CHAR);
Coercion shortCoercion = new NumericCoercion(NumericCoercion.TARGET_TYPE_SHORT);
Coercion intCoercion = new NumericCoercion(NumericCoercion.TARGET_TYPE_INT);
Coercion longCoercion = new NumericCoercion(NumericCoercion.TARGET_TYPE_LONG);
Coercion floatCoercion = new NumericCoercion(NumericCoercion.TARGET_TYPE_FLOAT);
Coercion doubleCoercion = new NumericCoercion(NumericCoercion.TARGET_TYPE_DOUBLE);
Coercion stringCoercion = new StringCoercion(StringCoercion.TARGET_TYPE_STRING);
Coercion bytesCoercion = new StringCoercion(StringCoercion.TARGET_TYPE_BYTES);
COERCIONS.put( Boolean.TYPE, boolCoercion );
COERCIONS.put( Boolean.class, boolCoercion );
COERCIONS.put( Byte.TYPE, byteCoercion );
COERCIONS.put( Byte.class, byteCoercion );
COERCIONS.put( Character.TYPE, charCoercion );
COERCIONS.put( Character.class, charCoercion );
COERCIONS.put( Short.TYPE, shortCoercion );
COERCIONS.put( Short.class, shortCoercion );
COERCIONS.put( Integer.TYPE, intCoercion );
COERCIONS.put( Integer.class, intCoercion );
COERCIONS.put( Long.TYPE, longCoercion );
COERCIONS.put( Long.class, longCoercion );
COERCIONS.put( Float.TYPE, floatCoercion );
COERCIONS.put( Float.class, floatCoercion );
COERCIONS.put( Double.TYPE, doubleCoercion );
COERCIONS.put( Double.class, doubleCoercion );
COERCIONS.put( String.class, stringCoercion );
COERCIONS.put( byte[].class, bytesCoercion );
}
static Coercion getCoercion(Class c) {
Coercion co = (Coercion) COERCIONS.get( c );
if ( co != null ) {
return co;
}
if ( c.isArray() ) {
Class typ = c.getComponentType();
co = new ArrayCoercion(c.getComponentType());
} else {
co = new ObjectCoercion(c);
}
COERCIONS.put( c, co );
return co;
}
}
| mit |
jonathan-major/Rapture | Libs/RaptureCommon/src/main/java/rapture/parser/StandardCallback.java | 1726 | /**
* The MIT License (MIT)
*
* Copyright (c) 2011-2016 Incapture Technologies LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package rapture.parser;
import java.util.ArrayList;
import java.util.List;
public class StandardCallback implements CSVCallback {
private List<List<String>> parsedOutput = new ArrayList<List<String>>();
private List<String> currentLine;
public List<List<String>> getOutput() {
return parsedOutput;
}
@Override
public void startNewLine() {
currentLine = new ArrayList<String>();
parsedOutput.add(currentLine);
}
@Override
public void addCell(String cell) {
currentLine.add(cell);
}
}
| mit |
madhavanks26/com.vliesaputra.deviceinformation | src/com/vliesaputra/cordova/plugins/android/support/v4/src/api23/android/support/v4/graphics/drawable/DrawableCompatApi23.java | 1075 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v4.graphics.drawable;
import android.graphics.drawable.Drawable;
/**
* Implementation of drawable compatibility that can call M APIs.
*/
class DrawableCompatApi23 {
public static void setLayoutDirection(Drawable drawable, int layoutDirection) {
drawable.setLayoutDirection(layoutDirection);
}
public static int getLayoutDirection(Drawable drawable) {
return drawable.getLayoutDirection();
}
}
| mit |
amkimian/Rapture | Apps/RestServer/src/integrationTest/java/rapture/server/rest/RestServerIntTest.java | 15111 | /**
* The MIT License (MIT)
*
* Copyright (c) 2011-2016 Incapture Technologies LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package rapture.server.rest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import org.junit.Before;
import org.junit.Test;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import rapture.server.rest.util.TestUtils;
public class RestServerIntTest {
private String apiKey = "18d84e26-e04c-4a5d-bcc9-637785922aab";
@Before
public void setup() throws UnirestException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
TestUtils.setupHttpsUnirest();
// HttpResponse<String> result =
// Unirest.post("https://localhost:4567/login")
// .header("x-api-key", "18d84e26-e04c-4a5d-bcc9-637785922aab")
// .body("{\"username\":\"rapture\",
// \"password\":\"rapture\"}").asString();
// printResponse(result);
// if (result.getStatus() != 200) {
// fail("Failed to login");
// }
}
@Test
public void testDocCreateRepo() throws UnirestException {
HttpResponse<String> result = Unirest.post("https://localhost:4567/doc/config").header("x-api-key", apiKey)
.body("{\"config\":\"NREP {} USING MONGODB {prefix=\\\"config\\\"}\"}").asString();
printResponse(result);
assertEquals(200, result.getStatus());
result = Unirest.post("https://localhost:4567/doc/config").header("x-api-key", apiKey)
.body("{\"config\":\"NREP {} USING MONGODB {prefix=\\\"config\\\"}\"}").asString();
printResponse(result);
assertEquals(409, result.getStatus());
}
@Test
public void testDocGet() throws UnirestException {
HttpResponse<String> result = Unirest.get("https://localhost:4567/doc/config/mqSeriesConfig").header("x-api-key", apiKey).asString();
printResponse(result);
assertTrue(result.getBody().indexOf("connectionFactory") != -1);
}
@Test
public void testDocGetWithVersion() throws UnirestException {
HttpResponse<String> result = Unirest.get("https://localhost:4567/doc/config/mqSeriesConfig@2").header("x-api-key", apiKey).asString();
printResponse(result);
assertTrue(result.getBody().indexOf("connectionFactory") != -1);
}
@Test
public void testDocGetMeta() throws UnirestException {
HttpResponse<String> result = Unirest.get("https://localhost:4567/doc/config/mqSeriesConfig?meta=true").header("x-api-key", apiKey).asString();
printResponse(result);
assertTrue(result.getBody().indexOf("connectionFactory") != -1);
}
@Test
public void testDocPut() throws UnirestException {
int status = Unirest.put("https://localhost:4567/doc/config/mqSeriesConfig").header("x-api-key", apiKey)
.body("{ \"environment\" : \"test\", \"connectionFactory\" : \"CF\", \"outputQueue\" : \"RAP_TO_TB\", \"writeEnabled\" : false }").asString()
.getStatus();
assertEquals(200, status);
}
@Test
public void testDocDeleteRepo() throws UnirestException {
HttpResponse<String> result = Unirest.delete("https://localhost:4567/doc/config").header("x-api-key", apiKey).asString();
printResponse(result);
}
@Test
public void testDocDelete() throws UnirestException {
HttpResponse<String> result = Unirest.delete("https://localhost:4567/doc/config/mqSeriesConfig").header("x-api-key", apiKey).asString();
printResponse(result);
int status = Unirest.get("https://localhost:4567/doc/config/mqSeriesConfig").header("x-api-key", apiKey).asString().getStatus();
assertEquals(404, status);
}
@Test
public void testBlobCreateRepo() throws UnirestException {
HttpResponse<String> result = Unirest.post("https://localhost:4567/blob/archive").header("x-api-key", apiKey)
.body("{\"config\":\"BLOB {} USING MONGODB {prefix=\\\"archive\\\"}\"," + "\"metaConfig\":\"REP {} USING MONGODB {prefix=\\\"archive\\\"}\"}")
.asString();
printResponse(result);
assertEquals(200, result.getStatus());
result = Unirest.post("https://localhost:4567/blob/archive").header("x-api-key", apiKey)
.body("{\"config\":\"BLOB {} USING MONGODB {prefix=\\\"archive\\\"}\"," + "\"metaConfig\":\"REP {} USING MONGODB {prefix=\\\"archive\\\"}\"}")
.asString();
printResponse(result);
assertEquals(409, result.getStatus());
}
@Test
public void testBlobGet() throws UnirestException {
HttpResponse<String> result = Unirest.get("https://localhost:4567/blob/archive/FIX/2016/05/18/8668_input").header("x-api-key", apiKey).asString();
printResponse(result);
}
@Test
public void testBlobPut() throws UnirestException {
int status = Unirest.put("https://localhost:4567/blob/archive/FIX/2016/05/18/8668_input").header("x-api-key", apiKey)
.header("Content-Type", "text/plain").body("a string value").asString().getStatus();
assertEquals(200, status);
}
@Test
public void testBlobDeleteRepo() throws UnirestException {
HttpResponse<String> result = Unirest.delete("https://localhost:4567/blob/archive").header("x-api-key", apiKey).asString();
printResponse(result);
}
@Test
public void testBlobDelete() throws UnirestException {
HttpResponse<String> result = Unirest.delete("https://localhost:4567/blob/archive/FIX/2016/05/18/8668_input").header("x-api-key", apiKey).asString();
printResponse(result);
int status = Unirest.get("https://localhost:4567/blob/archive/FIX/2016/05/18/8668_input").header("x-api-key", apiKey).asString().getStatus();
assertEquals(404, status);
}
@Test
public void testSeriesCreateRepo() throws UnirestException {
HttpResponse<String> result = Unirest.post("https://localhost:4567/series/srepo").header("x-api-key", apiKey)
.body("{\"config\":\"SREP {} USING MONGODB {prefix=\\\"srepo\\\"}\"}").asString();
printResponse(result);
assertEquals(200, result.getStatus());
result = Unirest.post("https://localhost:4567/series/srepo").header("x-api-key", apiKey)
.body("{\"config\":\"SREP {} USING MONGODB {prefix=\\\"srepo\\\"}\"}").asString();
printResponse(result);
assertEquals(409, result.getStatus());
}
@Test
public void testSeriesGet() throws UnirestException {
HttpResponse<String> result = Unirest.get("https://localhost:4567/series/srepo/x").header("x-api-key", apiKey).asString();
printResponse(result);
}
@Test
public void testSeriesPut() throws UnirestException {
int status = Unirest.put("https://localhost:4567/series/srepo/x").header("x-api-key", apiKey)
.body("{ \"keys\":[\"k1\",\"k2\"], \"values\":[\"x\",\"y\"]}").asString().getStatus();
assertEquals(200, status);
}
@Test
public void testSeriesDeleteRepo() throws UnirestException {
HttpResponse<String> result = Unirest.delete("https://localhost:4567/series/srepo").header("x-api-key", apiKey).asString();
printResponse(result);
}
@Test
public void testSeriesDelete() throws UnirestException {
HttpResponse<String> result = Unirest.delete("https://localhost:4567/series/srepo/x").header("x-api-key", apiKey).asString();
printResponse(result);
result = Unirest.get("https://localhost:4567/series/srepo/x").asString();
printResponse(result);
}
@Test
public void testWorkorderCreate() throws UnirestException {
HttpResponse<String> result = Unirest.post("https://localhost:4567/workorder/workflows/recon").header("x-api-key", apiKey).asString();
printResponse(result);
}
/**
* Create a structured store repository
*
* @throws UnirestException
*/
@Test
public void testSStoreRepoCreate() throws UnirestException {
String repoName = "mysstore" + System.currentTimeMillis();
HttpResponse<String> result = Unirest.post("https://localhost:4567/sstore/" + repoName).header("x-api-key", apiKey)
.body("{\"config\":\"STRUCTURED {} USING POSTGRES {}\"}").asString();
printResponse(result);
assertEquals(200, result.getStatus());
}
/**
* Create a structured store repository and the delete it
*
* @throws UnirestException
*/
@Test
public void testSStoreRepoDelete() throws UnirestException {
String repoName = "mysstore" + System.currentTimeMillis();
// create repo
HttpResponse<String> result = Unirest.post("https://localhost:4567/sstore/" + repoName).header("x-api-key", apiKey)
.body("{\"config\":\"STRUCTURED {} USING POSTGRES {}\"}").asString();
printResponse(result);
// delete it
HttpResponse<String> delresult = Unirest.delete("https://localhost:4567/sstore/" + repoName).header("x-api-key", apiKey).asString();
printResponse(delresult);
// assert that repo isnt there post-delete; if the repo wasn't deleted
// the post would fail with 409
HttpResponse<String> createresult = Unirest.post("https://localhost:4567/sstore/" + repoName).header("x-api-key", apiKey)
.body("{\"config\":\"STRUCTURED {} USING POSTGRES {}\"}").asString();
printResponse(createresult);
assertEquals(200, result.getStatus());
}
/**
* Create a structured store repository, add a table, add a row and get data
* using SQL statement
*
* @throws UnirestException
*/
@Test
public void testSStoreGetDataUsingSql() throws UnirestException {
}
/**
* Create a structured store repository, add a table, add a row and get data
*
* @throws UnirestException
*/
@Test
public void testSStoreGetData() throws UnirestException {
String repoName = "mysstore" + System.currentTimeMillis();
// create repo
HttpResponse<String> result = Unirest.post("https://localhost:4567/sstore/" + repoName).header("x-api-key", apiKey)
.body("{\"config\":\"STRUCTURED {} USING POSTGRES {}\"}").asString();
printResponse(result);
// add table
String tableName = "mytable" + System.currentTimeMillis();
HttpResponse<String> addtableresult = Unirest.post("https://localhost:4567/sstore/" + repoName + "/" + tableName).header("x-api-key", apiKey)
.body("{\"id\":\"int\",\"firstname\":\"varchar(30)\",\"lastname\":\"varchar(30)\",\"age\":\"int\"}").asString();
printResponse(addtableresult);
// add data
HttpResponse<String> adddataresult = Unirest.put("https://localhost:4567/sstore/" + repoName + "/" + tableName).header("x-api-key", apiKey)
.body("{\"id\":3,\"firstname\":\"jim\",\"lastname\":\"brown\",\"age\":41}").asString();
printResponse(adddataresult);
// get data
HttpResponse<String> getdataresult = Unirest.get("https://localhost:4567/sstore/" + repoName + "/" + tableName + "?where=age=41")
.header("x-api-key", apiKey).asString();
printResponse(getdataresult);
assertEquals("[{age=41, firstname=jim, id=3, lastname=brown}]", getdataresult.getBody());
}
/**
* Create a structured store repository, add a table, add a row and get data
* with raw sql
*
* @throws UnirestException
* @throws UnsupportedEncodingException
*/
@Test
public void testSStoreGetDataRawSql() throws UnirestException, UnsupportedEncodingException {
String repoName = "mysstore" + System.currentTimeMillis();
// create repo
HttpResponse<String> result = Unirest.post("https://localhost:4567/sstore/" + repoName).header("x-api-key", apiKey)
.body("{\"config\":\"STRUCTURED {} USING POSTGRES {}\"}").asString();
printResponse(result);
// add table
String tableName = "mytable" + System.currentTimeMillis();
HttpResponse<String> addtableresult = Unirest.post("https://localhost:4567/sstore/" + repoName + "/" + tableName).header("x-api-key", apiKey)
.body("{\"id\":\"int\",\"firstname\":\"varchar(30)\",\"lastname\":\"varchar(30)\",\"age\":\"int\"}").asString();
printResponse(addtableresult);
// add data
HttpResponse<String> adddataresult = Unirest.put("https://localhost:4567/sstore/" + repoName + "/" + tableName).header("x-api-key", apiKey)
.body("{\"id\":1,\"firstname\":\"jim\",\"lastname\":\"brown\",\"age\":41}").asString();
printResponse(adddataresult);
HttpResponse<String> adddataresult2 = Unirest.put("https://localhost:4567/sstore/" + repoName + "/" + tableName).header("x-api-key", apiKey)
.body("{\"id\":2,\"firstname\":\"bob\",\"lastname\":\"green\",\"age\":40}").asString();
// get data
String rawSql = URLEncoder.encode("select * from " + repoName + "." + tableName + " where age > 40", "UTF-8");
HttpResponse<String> getdataresult = Unirest.get("https://localhost:4567/sstore/" + repoName + "/" + tableName + "?sql=" + rawSql)
.header("x-api-key", apiKey).asString();
printResponse(getdataresult);
assertEquals("[{age=41, firstname=jim, id=1, lastname=brown}]", getdataresult.getBody());
}
private void printResponse(HttpResponse<String> result) {
System.out.println(result.getBody());
System.out.println(result.getStatus() + ": " + result.getStatusText());
}
} | mit |
RallySoftware/eclipselink.runtime | foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/sessions/factories/model/transport/SunCORBATransportManagerConfig.java | 956 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.internal.sessions.factories.model.transport;
/**
* INTERNAL:
*/
public class SunCORBATransportManagerConfig extends TransportManagerConfig {
public SunCORBATransportManagerConfig() {
}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | utils/eclipselink.utils.workbench.test/utility/source/org/eclipse/persistence/tools/workbench/test/utility/RangeTests.java | 3015 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.tools.workbench.test.utility;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.persistence.tools.workbench.utility.Range;
public class RangeTests extends TestCase {
public static Test suite() {
return new TestSuite(RangeTests.class);
}
public RangeTests(String name) {
super(name);
}
public void testIncludes() {
Range range = new Range(5, 17);
assertFalse(range.includes(-55));
assertFalse(range.includes(0));
assertFalse(range.includes(4));
assertTrue(range.includes(5));
assertTrue(range.includes(6));
assertTrue(range.includes(16));
assertTrue(range.includes(17));
assertFalse(range.includes(18));
assertFalse(range.includes(200));
}
public void testEquals() {
Range range1 = new Range(5, 17);
Range range2 = new Range(5, 17);
assertNotSame(range1, range2);
assertEquals(range1, range1);
assertEquals(range1, range2);
assertEquals(range2, range1);
assertEquals(range1.hashCode(), range2.hashCode());
range2 = new Range(17, 5);
assertFalse(range1.equals(range2));
assertFalse(range2.equals(range1));
// although they are unequal, they can have the same hash code
assertEquals(range1.hashCode(), range2.hashCode());
range2 = new Range(5, 15);
assertFalse(range1.equals(range2));
assertFalse(range2.equals(range1));
}
public void testClone() {
Range range1 = new Range(5, 17);
Range range2 = (Range) range1.clone();
assertNotSame(range1, range2);
assertEquals(range1, range1);
assertEquals(range1, range2);
assertEquals(range2, range1);
assertEquals(range1.hashCode(), range2.hashCode());
}
public void testSerialization() throws Exception {
Range range1 = new Range(5, 17);
Range range2 = (Range) TestTools.serialize(range1);
assertNotSame(range1, range2);
assertEquals(range1, range1);
assertEquals(range1, range2);
assertEquals(range2, range1);
assertEquals(range1.hashCode(), range2.hashCode());
}
}
| epl-1.0 |
SpoonLabs/astor | examples/evo_suite_test/math_70_spooned/src/default/org/apache/commons/math/random/RandomGenerator.java | 344 | package org.apache.commons.math.random;
public interface RandomGenerator {
void setSeed(int seed);
void setSeed(int[] seed);
void setSeed(long seed);
void nextBytes(byte[] bytes);
int nextInt();
int nextInt(int n);
long nextLong();
boolean nextBoolean();
float nextFloat();
double nextDouble();
double nextGaussian();
}
| gpl-2.0 |
traff/intellij-ocaml | OCamlSources/src/manuylov/maxim/ocaml/lang/feature/refactoring/surround/surrounder/OCamlWithParenthesesExpressionSurrounder.java | 1270 | /*
* OCaml Support For IntelliJ Platform.
* Copyright (C) 2010 Maxim Manuylov
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>.
*/
package manuylov.maxim.ocaml.lang.feature.refactoring.surround.surrounder;
import org.jetbrains.annotations.NotNull;
/**
* @author Maxim.Manuylov
* Date: 08.05.2010
*/
public class OCamlWithParenthesesExpressionSurrounder extends BaseOCamlSurrounder {
public OCamlWithParenthesesExpressionSurrounder() {
super("(...)");
}
@NotNull
@Override
protected String doSurround(@NotNull final CharSequence text) {
return "(" + text + ")";
}
}
| gpl-2.0 |
dwango/quercus | src/main/java/com/caucho/env/service/RootDirectorySystem.java | 3650 | /*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.env.service;
import java.io.IOException;
import com.caucho.java.WorkDir;
import com.caucho.util.L10N;
import com.caucho.vfs.*;
/**
* Root service for the root and data directories.
*
*/
public class RootDirectorySystem extends AbstractResinSubSystem
{
public static final int START_PRIORITY_ROOT_DIRECTORY = 20;
private static final L10N L = new L10N(RootDirectorySystem.class);
private final Path _rootDirectory;
private final Path _dataDirectory;
public RootDirectorySystem(Path rootDirectory, Path dataDirectory)
throws IOException
{
if (rootDirectory == null)
throw new NullPointerException();
if (dataDirectory == null)
throw new NullPointerException();
if (dataDirectory instanceof MemoryPath) { // QA
dataDirectory =
WorkDir.getTmpWorkDir().lookup("qa/" + dataDirectory.getFullPath());
}
_rootDirectory = rootDirectory;
_dataDirectory = dataDirectory;
rootDirectory.mkdirs();
dataDirectory.mkdirs();
}
public static RootDirectorySystem createAndAddService(Path rootDirectory)
throws IOException
{
return createAndAddService(rootDirectory,
rootDirectory.lookup("resin-data"));
}
public static RootDirectorySystem createAndAddService(Path rootDirectory,
Path dataDirectory)
throws IOException
{
ResinSystem system = preCreate(RootDirectorySystem.class);
RootDirectorySystem service =
new RootDirectorySystem(rootDirectory, dataDirectory);
system.addService(RootDirectorySystem.class, service);
return service;
}
public static RootDirectorySystem getCurrent()
{
return ResinSystem.getCurrentService(RootDirectorySystem.class);
}
/**
* Returns the data directory for current active directory service.
*/
public static Path getCurrentDataDirectory()
{
RootDirectorySystem rootService = getCurrent();
if (rootService == null)
throw new IllegalStateException(L.l("{0} must be active for getCurrentDataDirectory().",
RootDirectorySystem.class.getSimpleName()));
return rootService.getDataDirectory();
}
/**
* Returns the root directory.
*/
public Path getRootDirectory()
{
return _rootDirectory;
}
/**
* Returns the internal data directory.
*/
public Path getDataDirectory()
{
return _dataDirectory;
}
@Override
public int getStartPriority()
{
return START_PRIORITY_ROOT_DIRECTORY;
}
}
| gpl-2.0 |
jtux270/translate | ovirt/3.6_source/backend/manager/modules/restapi/jaxrs/src/test/java/org/ovirt/engine/api/restapi/resource/AbstractBackendDisksResourceTest.java | 6669 | package org.ovirt.engine.api.restapi.resource;
import static org.easymock.EasyMock.expect;
import java.util.ArrayList;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
import org.ovirt.engine.api.model.Disk;
import org.ovirt.engine.api.model.DiskFormat;
import org.ovirt.engine.api.model.Disks;
import org.ovirt.engine.api.model.StorageDomain;
import org.ovirt.engine.api.model.StorageDomains;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.DiskInterface;
import org.ovirt.engine.core.common.businessentities.storage.DiskStorageType;
import org.ovirt.engine.core.common.businessentities.storage.ImageStatus;
import org.ovirt.engine.core.common.businessentities.storage.PropagateErrors;
import org.ovirt.engine.core.common.businessentities.storage.VolumeFormat;
import org.ovirt.engine.core.common.businessentities.storage.VolumeType;
import org.ovirt.engine.core.common.queries.VdcQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Guid;
@Ignore
public class AbstractBackendDisksResourceTest<T extends AbstractBackendReadOnlyDevicesResource<Disk, Disks, org.ovirt.engine.core.common.businessentities.storage.Disk>>
extends AbstractBackendCollectionResourceTest<Disk, org.ovirt.engine.core.common.businessentities.storage.Disk, T> {
protected final static Guid PARENT_ID = GUIDS[1];
protected VdcQueryType queryType;
protected VdcQueryParametersBase queryParams;
protected String queryIdName;
public AbstractBackendDisksResourceTest(T collection,
VdcQueryType queryType,
VdcQueryParametersBase queryParams,
String queryIdName) {
super(collection, null, "");
this.queryType = queryType;
this.queryParams = queryParams;
this.queryIdName = queryIdName;
}
@Override
@Test
@Ignore
public void testQuery() throws Exception {
// skip test inherited from base class as searching
// over DiskImages is unsupported by the backend
}
@Override
protected void setUpQueryExpectations(String query) throws Exception {
setUpEntityQueryExpectations(1);
control.replay();
}
@Override
protected void setUpQueryExpectations(String query, Object failure) throws Exception {
setUpEntityQueryExpectations(1, failure);
control.replay();
}
protected void setUpEntityQueryExpectations(int times) throws Exception {
setUpEntityQueryExpectations(times, null);
}
protected void setUpEntityQueryExpectations(int times, Object failure) throws Exception {
while (times-- > 0) {
setUpEntityQueryExpectations(queryType,
queryParams.getClass(),
new String[] { queryIdName },
new Object[] { PARENT_ID },
getEntityList(),
failure);
}
}
protected List<org.ovirt.engine.core.common.businessentities.storage.Disk> getEntityList() {
List<org.ovirt.engine.core.common.businessentities.storage.Disk> entities = new ArrayList<org.ovirt.engine.core.common.businessentities.storage.Disk>();
for (int i = 0; i < NAMES.length; i++) {
entities.add(getEntity(i));
}
return entities;
}
@Override
protected org.ovirt.engine.core.common.businessentities.storage.Disk getEntity(int index) {
return setUpEntityExpectations(control.createMock(DiskImage.class), index);
}
static org.ovirt.engine.core.common.businessentities.storage.Disk setUpEntityExpectations(DiskImage entity, int index) {
expect(entity.getId()).andReturn(GUIDS[index]).anyTimes();
expect(entity.getVmSnapshotId()).andReturn(GUIDS[2]).anyTimes();
expect(entity.getVolumeFormat()).andReturn(VolumeFormat.RAW).anyTimes();
expect(entity.getDiskInterface()).andReturn(DiskInterface.VirtIO).anyTimes();
expect(entity.getImageStatus()).andReturn(ImageStatus.OK).anyTimes();
expect(entity.getVolumeType()).andReturn(VolumeType.Sparse).anyTimes();
expect(entity.isBoot()).andReturn(false).anyTimes();
expect(entity.isShareable()).andReturn(false).anyTimes();
expect(entity.getPropagateErrors()).andReturn(PropagateErrors.On).anyTimes();
expect(entity.getDiskStorageType()).andReturn(DiskStorageType.IMAGE).anyTimes();
expect(entity.getImageId()).andReturn(GUIDS[1]).anyTimes();
expect(entity.getReadOnly()).andReturn(true).anyTimes();
ArrayList<Guid> sdIds = new ArrayList<>();
sdIds.add(Guid.Empty);
expect(entity.getStorageIds()).andReturn(sdIds).anyTimes();
return setUpStatisticalEntityExpectations(entity);
}
static org.ovirt.engine.core.common.businessentities.storage.Disk setUpStatisticalEntityExpectations(DiskImage entity) {
expect(entity.getReadRate()).andReturn(1).anyTimes();
expect(entity.getWriteRate()).andReturn(2).anyTimes();
expect(entity.getReadLatency()).andReturn(3.0).anyTimes();
expect(entity.getWriteLatency()).andReturn(4.0).anyTimes();
expect(entity.getFlushLatency()).andReturn(5.0).anyTimes();
return entity;
}
@Override
protected List<Disk> getCollection() {
return collection.list().getDisks();
}
static Disk getModel(int index) {
Disk model = new Disk();
model.setFormat(DiskFormat.COW.toString());
model.setInterface(DiskInterface.VirtIO.toString());
model.setSparse(true);
model.setBootable(false);
model.setShareable(false);
model.setPropagateErrors(true);
model.setStorageDomains(new StorageDomains());
model.getStorageDomains().getStorageDomains().add(new StorageDomain());
model.getStorageDomains().getStorageDomains().get(0).setId(GUIDS[2].toString());
model.setSize(1000000000L);
return model;
}
@Override
protected void verifyModel(Disk model, int index) {
verifyModelSpecific(model, index);
verifyLinks(model);
}
static void verifyModelSpecific(Disk model, int index) {
assertEquals(GUIDS[index].toString(), model.getId());
assertTrue(model.isSparse());
assertTrue(!model.isBootable());
assertTrue(model.isPropagateErrors());
}
}
| gpl-3.0 |
eethomas/eucalyptus | clc/modules/msgs/src/main/java/com/eucalyptus/component/id/ClusterController.java | 6519 | /*************************************************************************
* Copyright 2009-2012 Eucalyptus Systems, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
* Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta
* CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need
* additional information or have any questions.
*
* This file may incorporate work covered under the following copyright
* and permission notice:
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Regents of the University of California
* All rights reserved.
*
* Redistribution and use of this software 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE. USERS OF THIS SOFTWARE ACKNOWLEDGE
* THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE LICENSED MATERIAL,
* COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS SOFTWARE,
* AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING
* IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA,
* SANTA BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY,
* WHICH IN THE REGENTS' DISCRETION MAY INCLUDE, WITHOUT LIMITATION,
* REPLACEMENT OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO
* IDENTIFIED, OR WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT
* NEEDED TO COMPLY WITH ANY SUCH LICENSES OR RIGHTS.
************************************************************************/
package com.eucalyptus.component.id;
import java.util.ArrayList;
import java.util.List;
import com.eucalyptus.component.annotation.Description;
import org.jboss.netty.channel.ChannelPipelineFactory;
import com.eucalyptus.component.ComponentId;
import com.eucalyptus.component.annotation.FaultLogPrefix;
import com.eucalyptus.component.annotation.InternalService;
import com.eucalyptus.component.annotation.Partition;
import com.eucalyptus.component.ServiceUris;
import com.eucalyptus.util.Internets;
@Partition( value = { Eucalyptus.class } )
@FaultLogPrefix( "cloud" ) // stub for cc, but in clc
@Description( "The Cluster Controller service" )
public class ClusterController extends ComponentId {
private static final long serialVersionUID = 1L;
public static final ComponentId INSTANCE = new ClusterController( );
public ClusterController( ) {
super( "cluster" );
}
@Override
public Integer getPort( ) {
return 8774;
}
@Override
public String getLocalEndpointName( ) {
return ServiceUris.remote( this, Internets.localHostInetAddress( ), this.getPort( ) ).toASCIIString( );
}
private static ChannelPipelineFactory clusterPipeline;
@Override
public ChannelPipelineFactory getClientPipeline( ) {//TODO:GRZE:fixme to use discovery
ChannelPipelineFactory factory = null;
if ( ( factory = super.getClientPipeline( ) ) == null ) {
factory = ( clusterPipeline = ( clusterPipeline != null
? clusterPipeline
: helpGetClientPipeline( "com.eucalyptus.ws.client.pipeline.ClusterClientPipelineFactory" ) ) );
}
return factory;
}
@Override
public String getServicePath( final String... pathParts ) {
return "/axis2/services/EucalyptusCC";
}
@Override
public String getInternalServicePath( final String... pathParts ) {
return this.getServicePath( pathParts );
}
@Partition( ClusterController.class )
@InternalService
@FaultLogPrefix( "cloud" )
public static class GatherLogService extends ComponentId {
private static final long serialVersionUID = 1L;
public GatherLogService( ) {
super( "gatherlog" );
}
@Override
public Integer getPort( ) {
return 8774;
}
@Override
public String getLocalEndpointName( ) {
return ServiceUris.remote( this, Internets.localHostInetAddress( ), this.getPort( ) ).toASCIIString( );
}
@Override
public String getServicePath( final String... pathParts ) {
return "/axis2/services/EucalyptusGL";
}
@Override
public String getInternalServicePath( final String... pathParts ) {
return this.getServicePath( pathParts );
}
private static ChannelPipelineFactory logPipeline;
/**
* This was born under a bad sign. No touching.
*
* @return
*/
@Override
public ChannelPipelineFactory getClientPipeline( ) {
ChannelPipelineFactory factory = null;
if ( ( factory = super.getClientPipeline( ) ) == null ) {
factory = ( logPipeline = ( logPipeline != null
? logPipeline
: helpGetClientPipeline( "com.eucalyptus.ws.client.pipeline.GatherLogClientPipeline" ) ) );
}
return factory;
}
}
}
| gpl-3.0 |