code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (C) Alkacon Software (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * 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 org.opencms.acacia.shared; import org.opencms.acacia.shared.CmsEntityChangeEvent.ChangeType; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.google.common.collect.Lists; import com.google.gwt.event.logical.shared.HasValueChangeHandlers; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.event.shared.SimpleEventBus; /** * Serializable entity implementation.<p> */ public class CmsEntity implements HasValueChangeHandlers<CmsEntity>, Serializable { /** * Handles child entity changes.<p> */ protected class EntityChangeHandler implements ValueChangeHandler<CmsEntity> { /** * @see com.google.gwt.event.logical.shared.ValueChangeHandler#onValueChange(com.google.gwt.event.logical.shared.ValueChangeEvent) */ public void onValueChange(ValueChangeEvent<CmsEntity> event) { ChangeType type = ((CmsEntityChangeEvent)event).getChangeType(); fireChange(type); } } /** The serial version id. */ private static final long serialVersionUID = -6933931178070025267L; /** The entity attribute values. */ private Map<String, List<CmsEntity>> m_entityAttributes; /** The entity id. */ private String m_id; /** The simple attribute values. */ private Map<String, List<String>> m_simpleAttributes; /** The type name. */ private String m_typeName; /** The event bus. */ private transient SimpleEventBus m_eventBus; /** The child entites change handler. */ private transient EntityChangeHandler m_childChangeHandler = new EntityChangeHandler(); /** The handler registrations. */ private transient Map<String, HandlerRegistration> m_changeHandlerRegistry; /** * Constructor.<p> * * @param id the entity id/URI * @param typeName the entity type name */ public CmsEntity(String id, String typeName) { this(); m_id = id; m_typeName = typeName; } /** * Constructor. For serialization only.<p> */ protected CmsEntity() { m_simpleAttributes = new HashMap<String, List<String>>(); m_entityAttributes = new HashMap<String, List<CmsEntity>>(); m_changeHandlerRegistry = new HashMap<String, HandlerRegistration>(); } /** * Returns the value of a simple attribute for the given path or <code>null</code>, if the value does not exist.<p> * * @param entity the entity to get the value from * @param pathElements the path elements * * @return the value */ public static String getValueForPath(CmsEntity entity, String[] pathElements) { String result = null; if ((pathElements != null) && (pathElements.length >= 1)) { String attributeName = pathElements[0]; int index = CmsContentDefinition.extractIndex(attributeName); if (index > 0) { index--; } attributeName = entity.getTypeName() + "/" + CmsContentDefinition.removeIndex(attributeName); CmsEntityAttribute attribute = entity.getAttribute(attributeName); if (!((attribute == null) || (attribute.isComplexValue() && (pathElements.length == 1)))) { if (attribute.isSimpleValue()) { if ((pathElements.length == 1) && (attribute.getValueCount() > 0)) { List<String> values = attribute.getSimpleValues(); result = values.get(index); } } else if (attribute.getValueCount() > (index)) { String[] childPathElements = new String[pathElements.length - 1]; for (int i = 1; i < pathElements.length; i++) { childPathElements[i - 1] = pathElements[i]; } List<CmsEntity> values = attribute.getComplexValues(); result = getValueForPath(values.get(index), childPathElements); } } } return result; } /** * Gets the list of values reachable from the given base object with the given path.<p> * * @param baseObject the base object (a CmsEntity or a string) * @param pathComponents the path components * @return the list of values for the given path (either of type String or CmsEntity) */ public static List<Object> getValuesForPath(Object baseObject, String[] pathComponents) { List<Object> currentList = Lists.newArrayList(); currentList.add(baseObject); for (String pathComponent : pathComponents) { List<Object> newList = Lists.newArrayList(); for (Object element : currentList) { newList.addAll(getValuesForPathComponent(element, pathComponent)); } currentList = newList; } return currentList; } /** * Gets the values reachable from a given object (an entity or a string) with a single XPath component.<p> * * If entityOrString is a string, and pathComponent is "VALUE", a list containing only entityOrString is returned. * Otherwise, entityOrString is assumed to be an entity, and the pathComponent is interpreted as a field of the entity * (possibly with an index). * * @param entityOrString the entity or string from which to get the values for the given path component * @param pathComponent the path component * @return the list of reachable values */ public static List<Object> getValuesForPathComponent(Object entityOrString, String pathComponent) { List<Object> result = Lists.newArrayList(); if (pathComponent.equals("VALUE")) { result.add(entityOrString); } else { if (entityOrString instanceof CmsEntity) { CmsEntity entity = (CmsEntity)entityOrString; boolean hasIndex = CmsContentDefinition.hasIndex(pathComponent); int index = CmsContentDefinition.extractIndex(pathComponent); if (index > 0) { index--; } String attributeName = entity.getTypeName() + "/" + CmsContentDefinition.removeIndex(pathComponent); CmsEntityAttribute attribute = entity.getAttribute(attributeName); if (attribute != null) { if (hasIndex) { if (index < attribute.getValueCount()) { if (attribute.isSimpleValue()) { result.add(attribute.getSimpleValues().get(index)); } else { result.add(attribute.getComplexValues().get(index)); } } } else { if (attribute.isSimpleValue()) { result.addAll(attribute.getSimpleValues()); } else { result.addAll(attribute.getComplexValues()); } } } } } return result; } /** * Adds the given attribute value.<p> * * @param attributeName the attribute name * @param value the attribute value */ public void addAttributeValue(String attributeName, CmsEntity value) { if (m_simpleAttributes.containsKey(attributeName)) { throw new RuntimeException("Attribute already exists with a simple type value."); } if (m_entityAttributes.containsKey(attributeName)) { m_entityAttributes.get(attributeName).add(value); } else { List<CmsEntity> values = new ArrayList<CmsEntity>(); values.add(value); m_entityAttributes.put(attributeName, values); } registerChangeHandler(value); fireChange(ChangeType.add); } /** * Adds the given attribute value.<p> * * @param attributeName the attribute name * @param value the attribute value */ public void addAttributeValue(String attributeName, String value) { if (m_entityAttributes.containsKey(attributeName)) { throw new RuntimeException("Attribute already exists with a entity type value."); } if (m_simpleAttributes.containsKey(attributeName)) { m_simpleAttributes.get(attributeName).add(value); } else { List<String> values = new ArrayList<String>(); values.add(value); m_simpleAttributes.put(attributeName, values); } fireChange(ChangeType.add); } /** * @see com.google.gwt.event.logical.shared.HasValueChangeHandlers#addValueChangeHandler(com.google.gwt.event.logical.shared.ValueChangeHandler) */ public HandlerRegistration addValueChangeHandler(ValueChangeHandler<CmsEntity> handler) { return addHandler(handler, ValueChangeEvent.getType()); } /** * Clones the given entity keeping all entity ids.<p> * * @return returns the cloned instance */ public CmsEntity cloneEntity() { CmsEntity clone = new CmsEntity(getId(), getTypeName()); for (CmsEntityAttribute attribute : getAttributes()) { if (attribute.isSimpleValue()) { List<String> values = attribute.getSimpleValues(); for (String value : values) { clone.addAttributeValue(attribute.getAttributeName(), value); } } else { List<CmsEntity> values = attribute.getComplexValues(); for (CmsEntity value : values) { clone.addAttributeValue(attribute.getAttributeName(), value.cloneEntity()); } } } return clone; } /** * Creates a deep copy of this entity.<p> * * @param entityId the id of the new entity, if <code>null</code> a generic id will be used * * @return the entity copy */ public CmsEntity createDeepCopy(String entityId) { CmsEntity result = new CmsEntity(entityId, getTypeName()); for (CmsEntityAttribute attribute : getAttributes()) { if (attribute.isSimpleValue()) { List<String> values = attribute.getSimpleValues(); for (String value : values) { result.addAttributeValue(attribute.getAttributeName(), value); } } else { List<CmsEntity> values = attribute.getComplexValues(); for (CmsEntity value : values) { result.addAttributeValue(attribute.getAttributeName(), value.createDeepCopy(null)); } } } return result; } /** * Ensures that the change event is also fired on child entity change.<p> */ public void ensureChangeHandlers() { if (!m_changeHandlerRegistry.isEmpty()) { for (HandlerRegistration reg : m_changeHandlerRegistry.values()) { reg.removeHandler(); } m_changeHandlerRegistry.clear(); } for (List<CmsEntity> attr : m_entityAttributes.values()) { for (CmsEntity child : attr) { registerChangeHandler(child); child.ensureChangeHandlers(); } } } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { boolean result = false; if (obj instanceof CmsEntity) { CmsEntity test = (CmsEntity)obj; if (m_simpleAttributes.keySet().equals(test.m_simpleAttributes.keySet()) && m_entityAttributes.keySet().equals(test.m_entityAttributes.keySet())) { result = true; for (String attributeName : m_simpleAttributes.keySet()) { if (!m_simpleAttributes.get(attributeName).equals(test.m_simpleAttributes.get(attributeName))) { result = false; break; } } if (result) { for (String attributeName : m_entityAttributes.keySet()) { if (!m_entityAttributes.get(attributeName).equals(test.m_entityAttributes.get(attributeName))) { result = false; break; } } } } } return result; } /** * @see com.google.gwt.event.shared.HasHandlers#fireEvent(com.google.gwt.event.shared.GwtEvent) */ public void fireEvent(GwtEvent<?> event) { ensureHandlers().fireEventFromSource(event, this); } /** * Returns an attribute.<p> * * @param attributeName the attribute name * * @return the attribute value */ public CmsEntityAttribute getAttribute(String attributeName) { if (m_simpleAttributes.containsKey(attributeName)) { return CmsEntityAttribute.createSimpleAttribute(attributeName, m_simpleAttributes.get(attributeName)); } if (m_entityAttributes.containsKey(attributeName)) { return CmsEntityAttribute.createEntityAttribute(attributeName, m_entityAttributes.get(attributeName)); } return null; } /** * Returns all entity attributes.<p> * * @return the entity attributes */ public List<CmsEntityAttribute> getAttributes() { List<CmsEntityAttribute> result = new ArrayList<CmsEntityAttribute>(); for (String name : m_simpleAttributes.keySet()) { result.add(getAttribute(name)); } for (String name : m_entityAttributes.keySet()) { result.add(getAttribute(name)); } return result; } /** * Returns this or a child entity with the given id.<p> * Will return <code>null</code> if no entity with the given id is present.<p> * * @param entityId the entity id * * @return the entity */ public CmsEntity getEntityById(String entityId) { CmsEntity result = null; if (m_id.equals(entityId)) { result = this; } else { for (List<CmsEntity> children : m_entityAttributes.values()) { for (CmsEntity child : children) { result = child.getEntityById(entityId); if (result != null) { break; } } if (result != null) { break; } } } return result; } /** * Returns the entity id.<p> * * @return the id */ public String getId() { return m_id; } /** * Returns the entity type name.<p> * * @return the entity type name */ public String getTypeName() { return m_typeName; } /** * Returns if the entity has the given attribute.<p> * * @param attributeName the attribute name * * @return <code>true</code> if the entity has the given attribute */ public boolean hasAttribute(String attributeName) { return m_simpleAttributes.containsKey(attributeName) || m_entityAttributes.containsKey(attributeName); } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return super.hashCode(); } /** * Inserts a new attribute value at the given index.<p> * * @param attributeName the attribute name * @param value the attribute value * @param index the value index */ public void insertAttributeValue(String attributeName, CmsEntity value, int index) { if (m_entityAttributes.containsKey(attributeName)) { m_entityAttributes.get(attributeName).add(index, value); } else { setAttributeValue(attributeName, value); } registerChangeHandler(value); fireChange(ChangeType.add); } /** * Inserts a new attribute value at the given index.<p> * * @param attributeName the attribute name * @param value the attribute value * @param index the value index */ public void insertAttributeValue(String attributeName, String value, int index) { if (m_simpleAttributes.containsKey(attributeName)) { m_simpleAttributes.get(attributeName).add(index, value); } else { setAttributeValue(attributeName, value); } fireChange(ChangeType.add); } /** * Removes the given attribute.<p> * * @param attributeName the attribute name */ public void removeAttribute(String attributeName) { removeAttributeSilent(attributeName); fireChange(ChangeType.remove); } /** * Removes the attribute without triggering any change events.<p> * * @param attributeName the attribute name */ public void removeAttributeSilent(String attributeName) { CmsEntityAttribute attr = getAttribute(attributeName); if (attr != null) { if (attr.isSimpleValue()) { m_simpleAttributes.remove(attributeName); } else { for (CmsEntity child : attr.getComplexValues()) { removeChildChangeHandler(child); } m_entityAttributes.remove(attributeName); } } } /** * Removes a specific attribute value.<p> * * @param attributeName the attribute name * @param index the value index */ public void removeAttributeValue(String attributeName, int index) { if (m_simpleAttributes.containsKey(attributeName)) { List<String> values = m_simpleAttributes.get(attributeName); if ((values.size() == 1) && (index == 0)) { removeAttributeSilent(attributeName); } else { values.remove(index); } } else if (m_entityAttributes.containsKey(attributeName)) { List<CmsEntity> values = m_entityAttributes.get(attributeName); if ((values.size() == 1) && (index == 0)) { removeAttributeSilent(attributeName); } else { CmsEntity child = values.remove(index); removeChildChangeHandler(child); } } fireChange(ChangeType.remove); } /** * Sets the given attribute value. Will remove all previous attribute values.<p> * * @param attributeName the attribute name * @param value the attribute value */ public void setAttributeValue(String attributeName, CmsEntity value) { // make sure there is no attribute value set removeAttributeSilent(attributeName); addAttributeValue(attributeName, value); } /** * Sets the given attribute value at the given index.<p> * * @param attributeName the attribute name * @param value the attribute value * @param index the value index */ public void setAttributeValue(String attributeName, CmsEntity value, int index) { if (m_simpleAttributes.containsKey(attributeName)) { throw new RuntimeException("Attribute already exists with a simple type value."); } if (!m_entityAttributes.containsKey(attributeName)) { if (index != 0) { throw new IndexOutOfBoundsException(); } else { addAttributeValue(attributeName, value); } } else { if (m_entityAttributes.get(attributeName).size() > index) { CmsEntity child = m_entityAttributes.get(attributeName).remove(index); removeChildChangeHandler(child); } m_entityAttributes.get(attributeName).add(index, value); fireChange(ChangeType.change); } } /** * Sets the given attribute value. Will remove all previous attribute values.<p> * * @param attributeName the attribute name * @param value the attribute value */ public void setAttributeValue(String attributeName, String value) { m_entityAttributes.remove(attributeName); List<String> values = new ArrayList<String>(); values.add(value); m_simpleAttributes.put(attributeName, values); fireChange(ChangeType.change); } /** * Sets the given attribute value at the given index.<p> * * @param attributeName the attribute name * @param value the attribute value * @param index the value index */ public void setAttributeValue(String attributeName, String value, int index) { if (m_entityAttributes.containsKey(attributeName)) { throw new RuntimeException("Attribute already exists with a simple type value."); } if (!m_simpleAttributes.containsKey(attributeName)) { if (index != 0) { throw new IndexOutOfBoundsException(); } else { addAttributeValue(attributeName, value); } } else { if (m_simpleAttributes.get(attributeName).size() > index) { m_simpleAttributes.get(attributeName).remove(index); } m_simpleAttributes.get(attributeName).add(index, value); fireChange(ChangeType.change); } } /** * Returns the JSON string representation of this entity.<p> * * @return the JSON string representation of this entity */ public String toJSON() { StringBuffer result = new StringBuffer(); result.append("{\n"); for (Entry<String, List<String>> simpleEntry : m_simpleAttributes.entrySet()) { result.append("\"").append(simpleEntry.getKey()).append("\"").append(": [\n"); boolean firstValue = true; for (String value : simpleEntry.getValue()) { if (firstValue) { firstValue = false; } else { result.append(",\n"); } result.append("\"").append(value).append("\""); } result.append("],\n"); } for (Entry<String, List<CmsEntity>> entityEntry : m_entityAttributes.entrySet()) { result.append("\"").append(entityEntry.getKey()).append("\"").append(": [\n"); boolean firstValue = true; for (CmsEntity value : entityEntry.getValue()) { if (firstValue) { firstValue = false; } else { result.append(",\n"); } result.append(value.toJSON()); } result.append("],\n"); } result.append("\"id\": \"").append(m_id).append("\""); result.append("}"); return result.toString(); } /** * @see java.lang.Object#toString() */ @Override public String toString() { return toJSON(); } /** * Adds this handler to the widget. * * @param <H> the type of handler to add * @param type the event type * @param handler the handler * @return {@link HandlerRegistration} used to remove the handler */ protected final <H extends EventHandler> HandlerRegistration addHandler(final H handler, GwtEvent.Type<H> type) { return ensureHandlers().addHandlerToSource(type, this, handler); } /** * Fires the change event for this entity.<p> * * @param type the change type */ void fireChange(ChangeType type) { CmsEntityChangeEvent event = new CmsEntityChangeEvent(this, type); fireEvent(event); } /** * Lazy initializing the handler manager.<p> * * @return the handler manager */ private SimpleEventBus ensureHandlers() { if (m_eventBus == null) { m_eventBus = new SimpleEventBus(); } return m_eventBus; } /** * Adds the value change handler to the given entity.<p> * * @param child the child entity */ private void registerChangeHandler(CmsEntity child) { HandlerRegistration reg = child.addValueChangeHandler(m_childChangeHandler); m_changeHandlerRegistry.put(child.getId(), reg); } /** * Removes the child entity change handler.<p> * * @param child the child entity */ private void removeChildChangeHandler(CmsEntity child) { HandlerRegistration reg = m_changeHandlerRegistry.remove(child.getId()); if (reg != null) { reg.removeHandler(); } } }
alkacon/opencms-core
src/org/opencms/acacia/shared/CmsEntity.java
Java
lgpl-2.1
27,138
package org.needle4j.postconstruct.injection; import javax.annotation.PostConstruct; import javax.inject.Inject; public class ComponentWithPrivatePostConstruct { @Inject private DependentComponent component; @PostConstruct @SuppressWarnings("unused") private void postconstruct() { component.count(); } }
needle4j/needle4j
src/test/java/org/needle4j/postconstruct/injection/ComponentWithPrivatePostConstruct.java
Java
lgpl-2.1
326
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtDBus module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdbusconnectioninterface.h" #include <QtCore/QByteArray> #include <QtCore/QList> #include <QtCore/QMap> #include <QtCore/QString> #include <QtCore/QStringList> #include <QtCore/QVariant> #include <QtCore/QDebug> #include "qdbus_symbols_p.h" // for the DBUS_* constants #ifndef QT_NO_DBUS QT_BEGIN_NAMESPACE /* * Implementation of interface class QDBusConnectionInterface */ /*! \class QDBusConnectionInterface \inmodule QtDBus \since 4.2 \brief The QDBusConnectionInterface class provides access to the D-Bus bus daemon service. The D-Bus bus server daemon provides one special interface \c org.freedesktop.DBus that allows clients to access certain properties of the bus, such as the current list of clients connected. The QDBusConnectionInterface class provides access to that interface. The most common uses of this class are to register and unregister service names on the bus using the registerService() and unregisterService() functions, query about existing names using the isServiceRegistered(), registeredServiceNames() and serviceOwner() functions, and to receive notification that a client has registered or de-registered through the serviceRegistered(), serviceUnregistered() and serviceOwnerChanged() signals. */ /*! \enum QDBusConnectionInterface::ServiceQueueOptions Flags for determining how a service registration should behave, in case the service name is already registered. \value DontQueueService If an application requests a name that is already owned, no queueing will be performed. The registeredService() call will simply fail. This is the default. \value QueueService Attempts to register the requested service, but do not try to replace it if another application already has it registered. Instead, simply put this application in queue, until it is given up. The serviceRegistered() signal will be emitted when that happens. \value ReplaceExistingService If another application already has the service name registered, attempt to replace it. \sa ServiceReplacementOptions */ /*! \enum QDBusConnectionInterface::ServiceReplacementOptions Flags for determining if the D-Bus server should allow another application to replace a name that this application has registered with the ReplaceExistingService option. The possible values are: \value DontAllowReplacement Do not allow another application to replace us. The service must be explicitly unregistered with unregisterService() for another application to acquire it. This is the default. \value AllowReplacement Allow other applications to replace us with the ReplaceExistingService option to registerService() without intervention. If that happens, the serviceUnregistered() signal will be emitted. \sa ServiceQueueOptions */ /*! \enum QDBusConnectionInterface::RegisterServiceReply The possible return values from registerService(): \value ServiceNotRegistered The call failed and the service name was not registered. \value ServiceRegistered The caller is now the owner of the service name. \value ServiceQueued The caller specified the QueueService flag and the service was already registered, so we are in queue. The serviceRegistered() signal will be emitted when the service is acquired by this application. */ /*! \internal */ const char *QDBusConnectionInterface::staticInterfaceName() { return "org.freedesktop.DBus"; } /*! \internal */ QDBusConnectionInterface::QDBusConnectionInterface(const QDBusConnection &connection, QObject *parent) : QDBusAbstractInterface(QLatin1String(DBUS_SERVICE_DBUS), QLatin1String(DBUS_PATH_DBUS), DBUS_INTERFACE_DBUS, connection, parent) { connect(this, SIGNAL(NameAcquired(QString)), this, SIGNAL(serviceRegistered(QString))); connect(this, SIGNAL(NameLost(QString)), this, SIGNAL(serviceUnregistered(QString))); connect(this, SIGNAL(NameOwnerChanged(QString,QString,QString)), this, SIGNAL(serviceOwnerChanged(QString,QString,QString))); } /*! \internal */ QDBusConnectionInterface::~QDBusConnectionInterface() { } /*! Returns the unique connection name of the primary owner of the name \a name. If the requested name doesn't have an owner, returns a \c org.freedesktop.DBus.Error.NameHasNoOwner error. */ QDBusReply<QString> QDBusConnectionInterface::serviceOwner(const QString &name) const { return internalConstCall(QDBus::AutoDetect, QLatin1String("GetNameOwner"), QList<QVariant>() << name); } /*! \property QDBusConnectionInterface::registeredServiceNames \brief holds the registered service names Lists all names currently registered on the bus. */ QDBusReply<QStringList> QDBusConnectionInterface::registeredServiceNames() const { return internalConstCall(QDBus::AutoDetect, QLatin1String("ListNames")); } /*! Returns true if the service name \a serviceName has is currently registered. */ QDBusReply<bool> QDBusConnectionInterface::isServiceRegistered(const QString &serviceName) const { return internalConstCall(QDBus::AutoDetect, QLatin1String("NameHasOwner"), QList<QVariant>() << serviceName); } /*! Returns the Unix Process ID (PID) for the process currently holding the bus service \a serviceName. */ QDBusReply<uint> QDBusConnectionInterface::servicePid(const QString &serviceName) const { return internalConstCall(QDBus::AutoDetect, QLatin1String("GetConnectionUnixProcessID"), QList<QVariant>() << serviceName); } /*! Returns the Unix User ID (UID) for the process currently holding the bus service \a serviceName. */ QDBusReply<uint> QDBusConnectionInterface::serviceUid(const QString &serviceName) const { return internalConstCall(QDBus::AutoDetect, QLatin1String("GetConnectionUnixUser"), QList<QVariant>() << serviceName); } /*! Requests that the bus start the service given by the name \a name. */ QDBusReply<void> QDBusConnectionInterface::startService(const QString &name) { return call(QLatin1String("StartServiceByName"), name, uint(0)); } /*! Requests to register the service name \a serviceName on the bus. The \a qoption flag specifies how the D-Bus server should behave if \a serviceName is already registered. The \a roption flag specifies if the server should allow another application to replace our registered name. If the service registration succeeds, the serviceRegistered() signal will be emitted. If we are placed in queue, the signal will be emitted when we obtain the name. If \a roption is AllowReplacement, the serviceUnregistered() signal will be emitted if another application replaces this one. \sa unregisterService() */ QDBusReply<QDBusConnectionInterface::RegisterServiceReply> QDBusConnectionInterface::registerService(const QString &serviceName, ServiceQueueOptions qoption, ServiceReplacementOptions roption) { // reconstruct the low-level flags uint flags = 0; switch (qoption) { case DontQueueService: flags = DBUS_NAME_FLAG_DO_NOT_QUEUE; break; case QueueService: flags = 0; break; case ReplaceExistingService: flags = DBUS_NAME_FLAG_DO_NOT_QUEUE | DBUS_NAME_FLAG_REPLACE_EXISTING; break; } switch (roption) { case DontAllowReplacement: break; case AllowReplacement: flags |= DBUS_NAME_FLAG_ALLOW_REPLACEMENT; break; } QDBusMessage reply = call(QLatin1String("RequestName"), serviceName, flags); // qDebug() << "QDBusConnectionInterface::registerService" << serviceName << "Reply:" << reply; // convert the low-level flags to something that we can use if (reply.type() == QDBusMessage::ReplyMessage) { uint code = 0; switch (reply.arguments().at(0).toUInt()) { case DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER: case DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER: code = uint(ServiceRegistered); break; case DBUS_REQUEST_NAME_REPLY_EXISTS: code = uint(ServiceNotRegistered); break; case DBUS_REQUEST_NAME_REPLY_IN_QUEUE: code = uint(ServiceQueued); break; } reply.setArguments(QVariantList() << code); } return reply; } /*! Releases the claim on the bus service name \a serviceName, that had been previously registered with registerService(). If this application had ownership of the name, it will be released for other applications to claim. If it only had the name queued, it gives up its position in the queue. */ QDBusReply<bool> QDBusConnectionInterface::unregisterService(const QString &serviceName) { QDBusMessage reply = call(QLatin1String("ReleaseName"), serviceName); if (reply.type() == QDBusMessage::ReplyMessage) { bool success = reply.arguments().at(0).toUInt() == DBUS_RELEASE_NAME_REPLY_RELEASED; reply.setArguments(QVariantList() << success); } return reply; } /*! \internal */ void QDBusConnectionInterface::connectNotify(const char *signalName) { // translate the signal names to what we really want // this avoids setting hooks for signals that don't exist on the bus if (qstrcmp(signalName, SIGNAL(serviceRegistered(QString))) == 0) QDBusAbstractInterface::connectNotify(SIGNAL(NameAcquired(QString))); else if (qstrcmp(signalName, SIGNAL(serviceUnregistered(QString))) == 0) QDBusAbstractInterface::connectNotify(SIGNAL(NameLost(QString))); else if (qstrcmp(signalName, SIGNAL(serviceOwnerChanged(QString,QString,QString))) == 0) { static bool warningPrinted = false; if (!warningPrinted) { qWarning("Connecting to deprecated signal QDBusConnectionInterface::serviceOwnerChanged(QString,QString,QString)"); warningPrinted = true; } QDBusAbstractInterface::connectNotify(SIGNAL(NameOwnerChanged(QString,QString,QString))); } } /*! \internal */ void QDBusConnectionInterface::disconnectNotify(const char *signalName) { // translate the signal names to what we really want // this avoids setting hooks for signals that don't exist on the bus if (qstrcmp(signalName, SIGNAL(serviceRegistered(QString))) == 0) QDBusAbstractInterface::disconnectNotify(SIGNAL(NameAcquired(QString))); else if (qstrcmp(signalName, SIGNAL(serviceUnregistered(QString))) == 0) QDBusAbstractInterface::disconnectNotify(SIGNAL(NameLost(QString))); else if (qstrcmp(signalName, SIGNAL(serviceOwnerChanged(QString,QString,QString))) == 0) QDBusAbstractInterface::disconnectNotify(SIGNAL(NameOwnerChanged(QString,QString,QString))); } // signals /*! \fn QDBusConnectionInterface::serviceRegistered(const QString &serviceName) This signal is emitted by the D-Bus server when the bus service name (unique connection name or well-known service name) given by \a serviceName is acquired by this application. Acquisition happens after this application has requested a name using registerService(). */ /*! \fn QDBusConnectionInterface::serviceUnregistered(const QString &serviceName) This signal is emitted by the D-Bus server when this application loses ownership of the bus service name given by \a serviceName. */ /*! \fn QDBusConnectionInterface::serviceOwnerChanged(const QString &name, const QString &oldOwner, const QString &newOwner) This signal is emitted by the D-Bus server whenever a service ownership change happens in the bus, including apparition and disparition of names. This signal means the application \a oldOwner lost ownership of bus name \a name to application \a newOwner. If \a oldOwner is an empty string, it means the name \a name has just been created; if \a newOwner is empty, the name \a name has no current owner and is no longer available. \note connecting to this signal will make the application listen for and receive every single service ownership change on the bus. Depending on how many services are running, this make the application be activated to receive more signals than it needs. To avoid this problem, use the QDBusServiceWatcher class, which can listen for specific changes. */ /*! \fn void QDBusConnectionInterface::callWithCallbackFailed(const QDBusError &error, const QDBusMessage &call) This signal is emitted when there is an error during a QDBusConnection::callWithCallback(). \a error specifies the error. \a call is the message that couldn't be delivered. \sa QDBusConnection::callWithCallback() */ QT_END_NAMESPACE #endif // QT_NO_DBUS
sunblithe/qt-everywhere-opensource-src-4.7.1
src/dbus/qdbusconnectioninterface.cpp
C++
lgpl-2.1
15,733
/////////////////////////////////////////////////6//////////////////////// // $Id: sse.cc 11984 2013-12-01 22:21:55Z sshwarts $ ///////////////////////////////////////////////////////////////////////// // // Copyright (c) 2003-2013 Stanislav Shwartsman // Written by Stanislav Shwartsman [sshwarts at sourceforge net] // // 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 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA B 02110-1301 USA // ///////////////////////////////////////////////////////////////////////// #define NEED_CPU_REG_SHORTCUTS 1 #include "bochs.h" #include "cpu.h" #define LOG_THIS BX_CPU_THIS_PTR /* ********************************************** */ /* SSE Integer Operations (128bit MMX extensions) */ /* ********************************************** */ #if BX_CPU_LEVEL >= 6 #include "simd_int.h" #include "simd_compare.h" #define SSE_2OP(HANDLER, func) \ /* SSE instruction with two src operands */ \ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C :: HANDLER (bxInstruction_c *i) \ { \ BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); \ (func)(&op1, &op2); \ BX_WRITE_XMM_REG(i->dst(), op1); \ \ BX_NEXT_INSTR(i); \ } SSE_2OP(PHADDW_VdqWdqR, xmm_phaddw) SSE_2OP(PHADDSW_VdqWdqR, xmm_phaddsw) SSE_2OP(PHADDD_VdqWdqR, xmm_phaddd) SSE_2OP(PHSUBW_VdqWdqR, xmm_phsubw) SSE_2OP(PHSUBSW_VdqWdqR, xmm_phsubsw) SSE_2OP(PHSUBD_VdqWdqR, xmm_phsubd) SSE_2OP(PSIGNB_VdqWdqR, xmm_psignb) SSE_2OP(PSIGNW_VdqWdqR, xmm_psignw) SSE_2OP(PSIGND_VdqWdqR, xmm_psignd) SSE_2OP(PCMPEQQ_VdqWdqR, xmm_pcmpeqq) SSE_2OP(PCMPGTQ_VdqWdqR, xmm_pcmpgtq) SSE_2OP(PMINSB_VdqWdqR, xmm_pminsb) SSE_2OP(PMINSD_VdqWdqR, xmm_pminsd) SSE_2OP(PMINUW_VdqWdqR, xmm_pminuw) SSE_2OP(PMINUD_VdqWdqR, xmm_pminud) SSE_2OP(PMAXSB_VdqWdqR, xmm_pmaxsb) SSE_2OP(PMAXSD_VdqWdqR, xmm_pmaxsd) SSE_2OP(PMAXUW_VdqWdqR, xmm_pmaxuw) SSE_2OP(PMAXUD_VdqWdqR, xmm_pmaxud) SSE_2OP(PACKUSDW_VdqWdqR, xmm_packusdw) SSE_2OP(PMULLD_VdqWdqR, xmm_pmulld) SSE_2OP(PMULDQ_VdqWdqR, xmm_pmuldq) SSE_2OP(PMULHRSW_VdqWdqR, xmm_pmulhrsw) SSE_2OP(PMADDUBSW_VdqWdqR, xmm_pmaddubsw) #endif // BX_CPU_LEVEL >= 6 #if BX_CPU_LEVEL >= 6 #define SSE_2OP_CPU_LEVEL6(HANDLER, func) \ SSE_2OP(HANDLER, func) #else #define SSE_2OP_CPU_LEVEL6(HANDLER, func) \ /* SSE instruction with two src operands */ \ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C :: HANDLER (bxInstruction_c *i) \ { \ BX_NEXT_INSTR(i); \ } #endif SSE_2OP_CPU_LEVEL6(PMINUB_VdqWdqR, xmm_pminub) SSE_2OP_CPU_LEVEL6(PMINSW_VdqWdqR, xmm_pminsw) SSE_2OP_CPU_LEVEL6(PMAXUB_VdqWdqR, xmm_pmaxub) SSE_2OP_CPU_LEVEL6(PMAXSW_VdqWdqR, xmm_pmaxsw) SSE_2OP_CPU_LEVEL6(PAVGB_VdqWdqR, xmm_pavgb) SSE_2OP_CPU_LEVEL6(PAVGW_VdqWdqR, xmm_pavgw) SSE_2OP_CPU_LEVEL6(PCMPEQB_VdqWdqR, xmm_pcmpeqb) SSE_2OP_CPU_LEVEL6(PCMPEQW_VdqWdqR, xmm_pcmpeqw) SSE_2OP_CPU_LEVEL6(PCMPEQD_VdqWdqR, xmm_pcmpeqd) SSE_2OP_CPU_LEVEL6(PCMPGTB_VdqWdqR, xmm_pcmpgtb) SSE_2OP_CPU_LEVEL6(PCMPGTW_VdqWdqR, xmm_pcmpgtw) SSE_2OP_CPU_LEVEL6(PCMPGTD_VdqWdqR, xmm_pcmpgtd) SSE_2OP_CPU_LEVEL6(ANDPS_VpsWpsR, xmm_andps) SSE_2OP_CPU_LEVEL6(ANDNPS_VpsWpsR, xmm_andnps) SSE_2OP_CPU_LEVEL6(ORPS_VpsWpsR, xmm_orps) SSE_2OP_CPU_LEVEL6(XORPS_VpsWpsR, xmm_xorps) SSE_2OP_CPU_LEVEL6(PSUBB_VdqWdqR, xmm_psubb) SSE_2OP_CPU_LEVEL6(PSUBW_VdqWdqR, xmm_psubw) SSE_2OP_CPU_LEVEL6(PSUBD_VdqWdqR, xmm_psubd) SSE_2OP_CPU_LEVEL6(PSUBQ_VdqWdqR, xmm_psubq) SSE_2OP_CPU_LEVEL6(PADDB_VdqWdqR, xmm_paddb) SSE_2OP_CPU_LEVEL6(PADDW_VdqWdqR, xmm_paddw) SSE_2OP_CPU_LEVEL6(PADDD_VdqWdqR, xmm_paddd) SSE_2OP_CPU_LEVEL6(PADDQ_VdqWdqR, xmm_paddq) SSE_2OP_CPU_LEVEL6(PSUBSB_VdqWdqR, xmm_psubsb) SSE_2OP_CPU_LEVEL6(PSUBUSB_VdqWdqR, xmm_psubusb) SSE_2OP_CPU_LEVEL6(PSUBSW_VdqWdqR, xmm_psubsw) SSE_2OP_CPU_LEVEL6(PSUBUSW_VdqWdqR, xmm_psubusw) SSE_2OP_CPU_LEVEL6(PADDSB_VdqWdqR, xmm_paddsb) SSE_2OP_CPU_LEVEL6(PADDUSB_VdqWdqR, xmm_paddusb) SSE_2OP_CPU_LEVEL6(PADDSW_VdqWdqR, xmm_paddsw) SSE_2OP_CPU_LEVEL6(PADDUSW_VdqWdqR, xmm_paddusw) SSE_2OP_CPU_LEVEL6(PACKUSWB_VdqWdqR, xmm_packuswb) SSE_2OP_CPU_LEVEL6(PACKSSWB_VdqWdqR, xmm_packsswb) SSE_2OP_CPU_LEVEL6(PACKSSDW_VdqWdqR, xmm_packssdw) SSE_2OP_CPU_LEVEL6(UNPCKLPS_VpsWpsR, xmm_unpcklps) SSE_2OP_CPU_LEVEL6(UNPCKHPS_VpsWpsR, xmm_unpckhps) SSE_2OP_CPU_LEVEL6(PUNPCKLQDQ_VdqWdqR, xmm_unpcklpd) SSE_2OP_CPU_LEVEL6(PUNPCKHQDQ_VdqWdqR, xmm_unpckhpd) SSE_2OP_CPU_LEVEL6(PUNPCKLBW_VdqWdqR, xmm_punpcklbw) SSE_2OP_CPU_LEVEL6(PUNPCKLWD_VdqWdqR, xmm_punpcklwd) SSE_2OP_CPU_LEVEL6(PUNPCKHBW_VdqWdqR, xmm_punpckhbw) SSE_2OP_CPU_LEVEL6(PUNPCKHWD_VdqWdqR, xmm_punpckhwd) SSE_2OP_CPU_LEVEL6(PMULLW_VdqWdqR, xmm_pmullw) SSE_2OP_CPU_LEVEL6(PMULHW_VdqWdqR, xmm_pmulhw) SSE_2OP_CPU_LEVEL6(PMULHUW_VdqWdqR, xmm_pmulhuw) SSE_2OP_CPU_LEVEL6(PMULUDQ_VdqWdqR, xmm_pmuludq) SSE_2OP_CPU_LEVEL6(PMADDWD_VdqWdqR, xmm_pmaddwd) SSE_2OP_CPU_LEVEL6(PSADBW_VdqWdqR, xmm_psadbw) #if BX_CPU_LEVEL >= 6 #define SSE_1OP(HANDLER, func) \ /* SSE instruction with single src operand */ \ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C :: HANDLER (bxInstruction_c *i) \ { \ BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); \ (func)(&op); \ BX_WRITE_XMM_REG(i->dst(), op); \ \ BX_NEXT_INSTR(i); \ } SSE_1OP(PABSB_VdqWdqR, xmm_pabsb) SSE_1OP(PABSW_VdqWdqR, xmm_pabsw) SSE_1OP(PABSD_VdqWdqR, xmm_pabsd) BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PSHUFB_VdqWdqR(bxInstruction_c *i) { BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()); BxPackedXmmRegister op2 = BX_READ_XMM_REG(i->src()), result; xmm_pshufb(&result, &op1, &op2); BX_WRITE_XMM_REG(i->dst(), result); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PBLENDVB_VdqWdqR(bxInstruction_c *i) { xmm_pblendvb(&BX_XMM_REG(i->dst()), &BX_XMM_REG(i->src()), &BX_XMM_REG(0)); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::BLENDVPS_VpsWpsR(bxInstruction_c *i) { xmm_blendvps(&BX_XMM_REG(i->dst()), &BX_XMM_REG(i->src()), &BX_XMM_REG(0)); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::BLENDVPD_VpdWpdR(bxInstruction_c *i) { xmm_blendvpd(&BX_XMM_REG(i->dst()), &BX_XMM_REG(i->src()), &BX_XMM_REG(0)); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PTEST_VdqWdqR(bxInstruction_c *i) { BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()), op2 = BX_READ_XMM_REG(i->src()); unsigned result = 0; if ((op2.xmm64u(0) & op1.xmm64u(0)) == 0 && (op2.xmm64u(1) & op1.xmm64u(1)) == 0) result |= EFlagsZFMask; if ((op2.xmm64u(0) & ~op1.xmm64u(0)) == 0 && (op2.xmm64u(1) & ~op1.xmm64u(1)) == 0) result |= EFlagsCFMask; setEFlagsOSZAPC(result); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PHMINPOSUW_VdqWdqR(bxInstruction_c *i) { BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); unsigned min = 0; for (unsigned j=1; j < 8; j++) { if (op.xmm16u(j) < op.xmm16u(min)) min = j; } op.xmm16u(0) = op.xmm16u(min); op.xmm16u(1) = min; op.xmm32u(1) = 0; op.xmm64u(1) = 0; BX_WRITE_XMM_REGZ(i->dst(), op, i->getVL()); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::BLENDPS_VpsWpsIbR(bxInstruction_c *i) { xmm_blendps(&BX_XMM_REG(i->dst()), &BX_XMM_REG(i->src()), i->Ib()); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::BLENDPD_VpdWpdIbR(bxInstruction_c *i) { xmm_blendpd(&BX_XMM_REG(i->dst()), &BX_XMM_REG(i->src()), i->Ib()); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PBLENDW_VdqWdqIbR(bxInstruction_c *i) { xmm_pblendw(&BX_XMM_REG(i->dst()), &BX_XMM_REG(i->src()), i->Ib()); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PEXTRB_EbdVdqIbR(bxInstruction_c *i) { BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); Bit8u result = op.xmmubyte(i->Ib() & 0xF); BX_WRITE_32BIT_REGZ(i->dst(), (Bit32u) result); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PEXTRB_EbdVdqIbM(bxInstruction_c *i) { BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); Bit8u result = op.xmmubyte(i->Ib() & 0xF); bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); write_virtual_byte(i->seg(), eaddr, result); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PEXTRW_EwdVdqIbR(bxInstruction_c *i) { BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); Bit16u result = op.xmm16u(i->Ib() & 7); BX_WRITE_32BIT_REGZ(i->dst(), (Bit32u) result); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PEXTRW_EwdVdqIbM(bxInstruction_c *i) { BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); Bit16u result = op.xmm16u(i->Ib() & 7); bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); write_virtual_word(i->seg(), eaddr, result); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PEXTRD_EdVdqIbR(bxInstruction_c *i) { BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); #if BX_SUPPORT_X86_64 if (i->os64L()) /* 64 bit operand size mode */ { Bit64u result = op.xmm64u(i->Ib() & 1); BX_WRITE_64BIT_REG(i->dst(), result); } else #endif { Bit32u result = op.xmm32u(i->Ib() & 3); BX_WRITE_32BIT_REGZ(i->dst(), result); } BX_NEXT_INSTR(i); } #if BX_SUPPORT_X86_64 BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PEXTRQ_EqVdqIbR(bxInstruction_c *i) { BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); Bit64u result = op.xmm64u(i->Ib() & 1); BX_WRITE_64BIT_REG(i->dst(), result); BX_NEXT_INSTR(i); } #endif BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PEXTRD_EdVdqIbM(bxInstruction_c *i) { BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); #if BX_SUPPORT_X86_64 if (i->os64L()) /* 64 bit operand size mode */ { Bit64u result = op.xmm64u(i->Ib() & 1); write_virtual_qword_64(i->seg(), eaddr, result); } else #endif { Bit32u result = op.xmm32u(i->Ib() & 3); write_virtual_dword(i->seg(), eaddr, result); } BX_NEXT_INSTR(i); } #if BX_SUPPORT_X86_64 BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PEXTRQ_EqVdqIbM(bxInstruction_c *i) { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); Bit64u result = op.xmm64u(i->Ib() & 1); write_virtual_qword_64(i->seg(), eaddr, result); BX_NEXT_INSTR(i); } #endif BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::EXTRACTPS_EdVpsIbR(bxInstruction_c *i) { BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); Bit32u result = op.xmm32u(i->Ib() & 3); BX_WRITE_32BIT_REGZ(i->dst(), result); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::EXTRACTPS_EdVpsIbM(bxInstruction_c *i) { BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); Bit32u result = op.xmm32u(i->Ib() & 3); bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); write_virtual_dword(i->seg(), eaddr, result); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PINSRB_VdqHdqEbIbR(bxInstruction_c *i) { BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->src1()); op1.xmmubyte(i->Ib() & 0xF) = BX_READ_8BIT_REGL(i->src2()); // won't allow reading of AH/CH/BH/DH BX_WRITE_XMM_REGZ(i->dst(), op1, i->getVL()); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PINSRB_VdqHdqEbIbM(bxInstruction_c *i) { BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->src1()); bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); op1.xmmubyte(i->Ib() & 0xF) = read_virtual_byte(i->seg(), eaddr); BX_WRITE_XMM_REGZ(i->dst(), op1, i->getVL()); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::INSERTPS_VpsHpsWssIb(bxInstruction_c *i) { BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->src1()); Bit8u control = i->Ib(); Bit32u op2; /* op2 is a register or memory reference */ if (i->modC0()) { BxPackedXmmRegister temp = BX_READ_XMM_REG(i->src2()); op2 = temp.xmm32u((control >> 6) & 3); } else { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); op2 = read_virtual_dword(i->seg(), eaddr); } op1.xmm32u((control >> 4) & 3) = op2; if (control & 1) op1.xmm32u(0) = 0; if (control & 2) op1.xmm32u(1) = 0; if (control & 4) op1.xmm32u(2) = 0; if (control & 8) op1.xmm32u(3) = 0; BX_WRITE_XMM_REGZ(i->dst(), op1, i->getVL()); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PINSRD_VdqHdqEdIbR(bxInstruction_c *i) { BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->src1()); #if BX_SUPPORT_X86_64 if (i->os64L()) { /* 64 bit operand size mode */ op1.xmm64u(i->Ib() & 1) = BX_READ_64BIT_REG(i->src2()); } else #endif { op1.xmm32u(i->Ib() & 3) = BX_READ_32BIT_REG(i->src2()); } BX_WRITE_XMM_REGZ(i->dst(), op1, i->getVL()); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PINSRD_VdqHdqEdIbM(bxInstruction_c *i) { BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->src1()); bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); #if BX_SUPPORT_X86_64 if (i->os64L()) { /* 64 bit operand size mode */ Bit64u op2 = read_virtual_qword_64(i->seg(), eaddr); op1.xmm64u(i->Ib() & 1) = op2; } else #endif { Bit32u op2 = read_virtual_dword(i->seg(), eaddr); op1.xmm32u(i->Ib() & 3) = op2; } BX_WRITE_XMM_REGZ(i->dst(), op1, i->getVL()); BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::MPSADBW_VdqWdqIbR(bxInstruction_c *i) { BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()); BxPackedXmmRegister op2 = BX_READ_XMM_REG(i->src()), result; xmm_mpsadbw(&result, &op1, &op2, i->Ib() & 0x7); BX_WRITE_XMM_REG(i->dst(), result); BX_NEXT_INSTR(i); } #endif // BX_CPU_LEVEL >= 6 BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PSHUFD_VdqWdqIbR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()), result; xmm_shufps(&result, &op, &op, i->Ib()); BX_WRITE_XMM_REG(i->dst(), result); #endif BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PSHUFHW_VdqWdqIbR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()), result; xmm_pshufhw(&result, &op, i->Ib()); BX_WRITE_XMM_REG(i->dst(), result); #endif BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PSHUFLW_VdqWdqIbR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()), result; xmm_pshuflw(&result, &op, i->Ib()); BX_WRITE_XMM_REG(i->dst(), result); #endif BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PINSRW_VdqHdqEwIbR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->src1()); Bit8u count = i->Ib() & 0x7; op1.xmm16u(count) = BX_READ_16BIT_REG(i->src2()); BX_WRITE_XMM_REGZ(i->dst(), op1, i->getVL()); #endif BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::PEXTRW_GdUdqIb(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op = BX_READ_XMM_REG(i->src()); Bit8u count = i->Ib() & 0x7; Bit32u result = (Bit32u) op.xmm16u(count); BX_WRITE_32BIT_REGZ(i->dst(), result); #endif BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::SHUFPS_VpsWpsIbR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()); BxPackedXmmRegister op2 = BX_READ_XMM_REG(i->src()), result; xmm_shufps(&result, &op1, &op2, i->Ib()); BX_WRITE_XMM_REG(i->dst(), result); #endif BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::SHUFPD_VpdWpdIbR(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister op1 = BX_READ_XMM_REG(i->dst()); BxPackedXmmRegister op2 = BX_READ_XMM_REG(i->src()), result; xmm_shufpd(&result, &op1, &op2, i->Ib()); BX_WRITE_XMM_REG(i->dst(), result); #endif BX_NEXT_INSTR(i); } #if BX_CPU_LEVEL >= 6 #define SSE_PSHIFT_CPU_LEVEL6(HANDLER, func) \ /* SSE packed shift instruction */ \ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C:: HANDLER (bxInstruction_c *i) \ { \ BxPackedXmmRegister op = BX_READ_XMM_REG(i->dst()); \ \ (func)(&op, BX_READ_XMM_REG_LO_QWORD(i->src())); \ \ BX_WRITE_XMM_REG(i->dst(), op); \ \ BX_NEXT_INSTR(i); \ } #else #define SSE_PSHIFT_CPU_LEVEL6(HANDLER, func) \ /* SSE instruction with two src operands */ \ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C :: HANDLER (bxInstruction_c *i) \ { \ BX_NEXT_INSTR(i); \ } #endif SSE_PSHIFT_CPU_LEVEL6(PSRLW_VdqWdqR, xmm_psrlw); SSE_PSHIFT_CPU_LEVEL6(PSRLD_VdqWdqR, xmm_psrld); SSE_PSHIFT_CPU_LEVEL6(PSRLQ_VdqWdqR, xmm_psrlq); SSE_PSHIFT_CPU_LEVEL6(PSRAW_VdqWdqR, xmm_psraw); SSE_PSHIFT_CPU_LEVEL6(PSRAD_VdqWdqR, xmm_psrad); SSE_PSHIFT_CPU_LEVEL6(PSLLW_VdqWdqR, xmm_psllw); SSE_PSHIFT_CPU_LEVEL6(PSLLD_VdqWdqR, xmm_pslld); SSE_PSHIFT_CPU_LEVEL6(PSLLQ_VdqWdqR, xmm_psllq); #if BX_CPU_LEVEL >= 6 #define SSE_PSHIFT_IMM_CPU_LEVEL6(HANDLER, func) \ /* SSE packed shift with imm8 instruction */ \ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C:: HANDLER (bxInstruction_c *i) \ { \ (func)(&BX_XMM_REG(i->dst()), i->Ib()); \ \ BX_NEXT_INSTR(i); \ } #else #define SSE_PSHIFT_IMM_CPU_LEVEL6(HANDLER, func) \ /* SSE packed shift with imm8 instruction */ \ BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C :: HANDLER (bxInstruction_c *i) \ { \ BX_NEXT_INSTR(i); \ } #endif SSE_PSHIFT_IMM_CPU_LEVEL6(PSRLW_UdqIb, xmm_psrlw); SSE_PSHIFT_IMM_CPU_LEVEL6(PSRLD_UdqIb, xmm_psrld); SSE_PSHIFT_IMM_CPU_LEVEL6(PSRLQ_UdqIb, xmm_psrlq); SSE_PSHIFT_IMM_CPU_LEVEL6(PSRAW_UdqIb, xmm_psraw); SSE_PSHIFT_IMM_CPU_LEVEL6(PSRAD_UdqIb, xmm_psrad); SSE_PSHIFT_IMM_CPU_LEVEL6(PSLLW_UdqIb, xmm_psllw); SSE_PSHIFT_IMM_CPU_LEVEL6(PSLLD_UdqIb, xmm_pslld); SSE_PSHIFT_IMM_CPU_LEVEL6(PSLLQ_UdqIb, xmm_psllq); SSE_PSHIFT_IMM_CPU_LEVEL6(PSRLDQ_UdqIb, xmm_psrldq); SSE_PSHIFT_IMM_CPU_LEVEL6(PSLLDQ_UdqIb, xmm_pslldq); /* ************************ */ /* SSE4A (AMD) INSTRUCTIONS */ /* ************************ */ #if BX_CPU_LEVEL >= 6 BX_CPP_INLINE Bit64u xmm_extrq(Bit64u src, unsigned shift, unsigned len) { len &= 0x3f; shift &= 0x3f; src >>= shift; if (len) { Bit64u mask = (BX_CONST64(1) << len) - 1; return src & mask; } return src; } BX_CPP_INLINE Bit64u xmm_insertq(Bit64u dest, Bit64u src, unsigned shift, unsigned len) { Bit64u mask; len &= 0x3f; shift &= 0x3f; if (len == 0) { mask = BX_CONST64(0xffffffffffffffff); } else { mask = (BX_CONST64(1) << len) - 1; } return (dest & ~(mask << shift)) | ((src & mask) << shift); } #endif BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::EXTRQ_UdqIbIb(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BX_WRITE_XMM_REG_LO_QWORD(i->dst(), xmm_extrq(BX_READ_XMM_REG_LO_QWORD(i->dst()), i->Ib2(), i->Ib())); #endif BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::EXTRQ_VdqUq(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 Bit16u ctrl = BX_READ_XMM_REG_LO_WORD(i->src()); BX_WRITE_XMM_REG_LO_QWORD(i->dst(), xmm_extrq(BX_READ_XMM_REG_LO_QWORD(i->dst()), ctrl >> 8, ctrl)); #endif BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::INSERTQ_VdqUqIbIb(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 Bit64u dst = BX_READ_XMM_REG_LO_QWORD(i->dst()), src = BX_READ_XMM_REG_LO_QWORD(i->src()); BX_WRITE_XMM_REG_LO_QWORD(i->dst(), xmm_insertq(dst, src, i->Ib2(), i->Ib())); #endif BX_NEXT_INSTR(i); } BX_INSF_TYPE BX_CPP_AttrRegparmN(1) BX_CPU_C::INSERTQ_VdqUdq(bxInstruction_c *i) { #if BX_CPU_LEVEL >= 6 BxPackedXmmRegister src = BX_READ_XMM_REG(i->src()); Bit64u dst = BX_READ_XMM_REG_LO_QWORD(i->dst()); BX_WRITE_XMM_REG_LO_QWORD(i->dst(), xmm_insertq(dst, src.xmm64u(0), src.xmmubyte(9), src.xmmubyte(8))); #endif BX_NEXT_INSTR(i); }
matildah/bochsdoor
cpu/sse.cc
C++
lgpl-2.1
23,130
# -*- coding: utf-8 -*- from __future__ import absolute_import from math import isinf, isnan from warnings import warn NOT_MASS_BALANCED_TERMS = {"SBO:0000627", # EXCHANGE "SBO:0000628", # DEMAND "SBO:0000629", # BIOMASS "SBO:0000631", # PSEUDOREACTION "SBO:0000632", # SINK } def check_mass_balance(model): unbalanced = {} for reaction in model.reactions: if reaction.annotation.get("SBO") not in NOT_MASS_BALANCED_TERMS: balance = reaction.check_mass_balance() if balance: unbalanced[reaction] = balance return unbalanced # no longer strictly necessary, done by optlang solver interfaces def check_reaction_bounds(model): warn("no longer necessary, done by optlang solver interfaces", DeprecationWarning) errors = [] for reaction in model.reactions: if reaction.lower_bound > reaction.upper_bound: errors.append("Reaction '%s' has lower bound > upper bound" % reaction.id) if isinf(reaction.lower_bound): errors.append("Reaction '%s' has infinite lower_bound" % reaction.id) elif isnan(reaction.lower_bound): errors.append("Reaction '%s' has NaN for lower_bound" % reaction.id) if isinf(reaction.upper_bound): errors.append("Reaction '%s' has infinite upper_bound" % reaction.id) elif isnan(reaction.upper_bound): errors.append("Reaction '%s' has NaN for upper_bound" % reaction.id) return errors def check_metabolite_compartment_formula(model): errors = [] for met in model.metabolites: if met.formula is not None and len(met.formula) > 0: if not met.formula.isalnum(): errors.append("Metabolite '%s' formula '%s' not alphanumeric" % (met.id, met.formula)) return errors
zakandrewking/cobrapy
cobra/manipulation/validate.py
Python
lgpl-2.1
2,116
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="1.1" language="nl" sourcelanguage="en"> <context> <name>AddonInstaller</name> <message> <location filename="addonmanager_workers.py" line="535"/> <source>Installed location</source> <translation>Geïnstalleerde locatie</translation> </message> </context> <context> <name>AddonsInstaller</name> <message> <location filename="addonmanager_macro.py" line="157"/> <source>Unable to fetch the code of this macro.</source> <translation>De code van de macro kan niet worden opgehaald.</translation> </message> <message> <location filename="addonmanager_macro.py" line="164"/> <source>Unable to retrieve a description for this macro.</source> <translation>De beschrijving van deze macro kan niet worden opgehaald.</translation> </message> <message> <location filename="AddonManager.py" line="86"/> <source>The addons that can be installed here are not officially part of FreeCAD, and are not reviewed by the FreeCAD team. Make sure you know what you are installing!</source> <translation>De addons die geïnstalleerd kunnen worden maken niet officiëel onderdeel uit van FreeCAD en zijn niet gereviewed door het FreeCad team. Zorg ervoor dat je weet wat je installeert!</translation> </message> <message> <location filename="AddonManager.py" line="199"/> <source>Addon manager</source> <translation>Uitbreidingsmanager</translation> </message> <message> <location filename="AddonManager.py" line="204"/> <source>You must restart FreeCAD for changes to take effect. Press Ok to restart FreeCAD now, or Cancel to restart later.</source> <translation>Je moet FreeCAD opnieuw starten om de wijzigingen door te voeren. Klik Ok om FreeCAD nu opnieuw te starten, of Cancel om dit later te doen.</translation> </message> <message> <location filename="AddonManager.py" line="243"/> <source>Checking for updates...</source> <translation>Zoeken naar updates...</translation> </message> <message> <location filename="AddonManager.py" line="262"/> <source>Apply</source> <translation>Toepassen</translation> </message> <message> <location filename="AddonManager.py" line="263"/> <source>update(s)</source> <translation>update(s)</translation> </message> <message> <location filename="AddonManager.py" line="266"/> <source>No update available</source> <translation>Geen update beschikbaar</translation> </message> <message> <location filename="AddonManager.py" line="433"/> <source>Macro successfully installed. The macro is now available from the Macros dialog.</source> <translation>Macro succesvol geïnstalleerd. De macro is nu beschikbaar via het Macros-venster.</translation> </message> <message> <location filename="AddonManager.py" line="435"/> <source>Unable to install</source> <translation>Installeren niet mogelijk</translation> </message> <message> <location filename="AddonManager.py" line="494"/> <source>Addon successfully removed. Please restart FreeCAD</source> <translation>Addon succesvol verwijderd. Herstart aub FreeCAD</translation> </message> <message> <location filename="AddonManager.py" line="496"/> <source>Unable to remove this addon</source> <translation>Deze addon kan niet worden verwijderd</translation> </message> <message> <location filename="AddonManager.py" line="502"/> <source>Macro successfully removed.</source> <translation>Macro succesvol verwijderd.</translation> </message> <message> <location filename="AddonManager.py" line="504"/> <source>Macro could not be removed.</source> <translation>Macro kon niet worden verwijderd.</translation> </message> <message> <location filename="addonmanager_workers.py" line="167"/> <source>Unable to download addon list.</source> <translation>Addon lijst kan niet worden opgehaald.</translation> </message> <message> <location filename="addonmanager_workers.py" line="172"/> <source>Workbenches list was updated.</source> <translation>Werkbankenlijst is bijgewerkt.</translation> </message> <message> <location filename="addonmanager_workers.py" line="738"/> <source>Outdated GitPython detected, consider upgrading with pip.</source> <translation>Verouderde GitPython gevonden, overweeg een upgrade met pip.</translation> </message> <message> <location filename="addonmanager_workers.py" line="296"/> <source>List of macros successfully retrieved.</source> <translation>Lijst van macro's succesvol opgehaald.</translation> </message> <message> <location filename="addonmanager_workers.py" line="651"/> <source>Retrieving description...</source> <translation>Omschrijving ophalen...</translation> </message> <message> <location filename="addonmanager_workers.py" line="391"/> <source>Retrieving info from</source> <translation>Informatie ophalen vanaf</translation> </message> <message> <location filename="addonmanager_workers.py" line="533"/> <source>An update is available for this addon.</source> <translation>Er is een update beschikbaar voor deze addon.</translation> </message> <message> <location filename="addonmanager_workers.py" line="521"/> <source>This addon is already installed.</source> <translation>Deze addon is al geïnstalleerd.</translation> </message> <message> <location filename="addonmanager_workers.py" line="653"/> <source>Retrieving info from git</source> <translation>Informatie ophalen van git</translation> </message> <message> <location filename="addonmanager_workers.py" line="656"/> <source>Retrieving info from wiki</source> <translation>Informatie ophalen van wiki</translation> </message> <message> <location filename="addonmanager_workers.py" line="700"/> <source>GitPython not found. Using standard download instead.</source> <translation>GitPython niet gevonden. Standaard download wordt nu gebruikt.</translation> </message> <message> <location filename="addonmanager_workers.py" line="705"/> <source>Your version of python doesn&apos;t appear to support ZIP files. Unable to proceed.</source> <translation>Je versie van Python lijkt geen ZIP-bestanden te ondersteunen. Verder gaan niet mogelijk.</translation> </message> <message> <location filename="addonmanager_workers.py" line="786"/> <source>Workbench successfully installed. Please restart FreeCAD to apply the changes.</source> <translation>Werkbank succesvol geïnstalleerd. Herstart FreeCAD om de wijzigingen toe te passen.</translation> </message> <message> <location filename="addonmanager_workers.py" line="835"/> <source>Missing workbench</source> <translation>Werkbank ontbreekt</translation> </message> <message> <location filename="addonmanager_workers.py" line="844"/> <source>Missing python module</source> <translation>Ontbrekende python module</translation> </message> <message> <location filename="addonmanager_workers.py" line="854"/> <source>Missing optional python module (doesn&apos;t prevent installing)</source> <translation>Ontbrekende optionele python module (voorkomt niet het installeren)</translation> </message> <message> <location filename="addonmanager_workers.py" line="857"/> <source>Some errors were found that prevent to install this workbench</source> <translation>Er zijn enkele fouten gevonden die voorkomen dat deze werkbank wordt geïnstalleerd</translation> </message> <message> <location filename="addonmanager_workers.py" line="859"/> <source>Please install the missing components first.</source> <translation>Installeer eerst de ontbrekende componenten.</translation> </message> <message> <location filename="addonmanager_workers.py" line="880"/> <source>Error: Unable to download</source> <translation>Fout: Kan niet downloaden</translation> </message> <message> <location filename="addonmanager_workers.py" line="893"/> <source>Successfully installed</source> <translation>Succesvol geïnstalleerd</translation> </message> <message> <location filename="addonmanager_workers.py" line="310"/> <source>GitPython not installed! Cannot retrieve macros from git</source> <translation>GitPython niet geïnstalleerd! Macro's kunnen niet worden opgehaald van git</translation> </message> <message> <location filename="AddonManager.py" line="567"/> <source>Installed</source> <translation>Geïnstalleerd</translation> </message> <message> <location filename="AddonManager.py" line="586"/> <source>Update available</source> <translation>Update beschikbaar</translation> </message> <message> <location filename="AddonManager.py" line="542"/> <source>Restart required</source> <translation>Opnieuw opstarten vereist</translation> </message> <message> <location filename="addonmanager_workers.py" line="665"/> <source>This macro is already installed.</source> <translation>Deze macro is al geïnstalleerd.</translation> </message> <message> <location filename="addonmanager_workers.py" line="799"/> <source>A macro has been installed and is available under Macro -&gt; Macros menu</source> <translation>Een macro is geïnstalleerd en is beschikbaar onder Macro -&gt; Macro' s menu</translation> </message> <message> <location filename="addonmanager_workers.py" line="547"/> <source>This addon is marked as obsolete</source> <translation>Deze uitbreiding is gemarkeerd als verouderd</translation> </message> <message> <location filename="addonmanager_workers.py" line="551"/> <source>This usually means it is no longer maintained, and some more advanced addon in this list provides the same functionality.</source> <translation>Dit betekent gewoonlijk dat het niet meer onderhouden wordt, en een geavanceerdere uitbreidingen in deze lijst biedt dezelfde functionaliteit.</translation> </message> <message> <location filename="addonmanager_workers.py" line="873"/> <source>Error: Unable to locate zip from</source> <translation>Fout: Kan zip niet vinden vanuit</translation> </message> <message> <location filename="addonmanager_workers.py" line="319"/> <source>Something went wrong with the Git Macro Retrieval, possibly the Git executable is not in the path</source> <translation>Er is iets misgegaan met het ophalen van de Git Macro. Mogelijk bevindt het uitvoerbare Git-bestand zich niet in het pad</translation> </message> <message> <location filename="addonmanager_workers.py" line="559"/> <source>This addon is marked as Python 2 Only</source> <translation>Deze toevoeging is alleen geschikt voor Python 2</translation> </message> <message> <location filename="addonmanager_workers.py" line="564"/> <source>This workbench may no longer be maintained and installing it on a Python 3 system will more than likely result in errors at startup or while in use.</source> <translation>Deze werkbank wordt wellicht niet langer onderhouden en de installatie ervan op een Python 3-systeem zal hoogstwaarschijnlijk leiden tot fouten bij het opstarten of tijdens het gebruik.</translation> </message> <message> <location filename="addonmanager_workers.py" line="727"/> <source>User requested updating a Python 2 workbench on a system running Python 3 - </source> <translation>De gebruiker verzocht om een Python 2 werkbank bij te werken die alleen geschikt is voor Python 3 </translation> </message> <message> <location filename="addonmanager_workers.py" line="763"/> <source>Workbench successfully updated. Please restart FreeCAD to apply the changes.</source> <translation>Werkbank succesvol bijgewerkt. Herstart FreeCAD om de wijzigingen toe te passen.</translation> </message> <message> <location filename="addonmanager_workers.py" line="771"/> <source>User requested installing a Python 2 workbench on a system running Python 3 - </source> <translation>De gebruiker verzocht om een Python 2 werkbank te installeren op een systeem dat Python 3 draait </translation> </message> <message> <location filename="addonmanager_workers.py" line="343"/> <source>Appears to be an issue connecting to the Wiki, therefore cannot retrieve Wiki macro list at this time</source> <translation>Er lijkt een probleem te zijn met de verbinding met de Wiki, daarom kan de Wiki-macrolijst op dit moment niet worden opgehaald</translation> </message> <message> <location filename="addonmanager_workers.py" line="433"/> <source>Raw markdown displayed</source> <translation>Ongeformateerde tekst weergegeven</translation> </message> <message> <location filename="addonmanager_workers.py" line="435"/> <source>Python Markdown library is missing.</source> <translation>Python Markdown bibliotheek mist.</translation> </message> </context> <context> <name>Dialog</name> <message> <location filename="AddonManager.ui" line="37"/> <source>Workbenches</source> <translation>Werkbanken</translation> </message> <message> <location filename="AddonManager.ui" line="47"/> <source>Macros</source> <translation>Macro's</translation> </message> <message> <location filename="AddonManager.ui" line="59"/> <source>Execute</source> <translation>Uitvoeren</translation> </message> <message> <location filename="AddonManager.ui" line="113"/> <source>Downloading info...</source> <translation>Info downloaden...</translation> </message> <message> <location filename="AddonManager.ui" line="150"/> <source>Update all</source> <translation>Alles bijwerken</translation> </message> <message> <location filename="AddonManager.ui" line="56"/> <source>Executes the selected macro, if installed</source> <translation>Voert de geselecteerde macro uit, indien geïnstalleerd</translation> </message> <message> <location filename="AddonManager.ui" line="127"/> <source>Uninstalls a selected macro or workbench</source> <translation>Verwijder een geselecteerde macro of werkbank</translation> </message> <message> <location filename="AddonManager.ui" line="137"/> <source>Installs or updates the selected macro or workbench</source> <translation>Installeert of de geselecteerde macro of werkbank, of werkt deze bij</translation> </message> <message> <location filename="AddonManager.ui" line="147"/> <source>Download and apply all available updates</source> <translation>Download en pas alle beschikbare updates toe</translation> </message> <message> <location filename="AddonManagerOptions.ui" line="35"/> <source>Custom repositories (one per line):</source> <translation>Aangepaste opslagplaatsen (één per lijn):</translation> </message> <message> <location filename="AddonManager.ui" line="89"/> <source>Sets configuration options for the Addon Manager</source> <translation>Stelt de configuratieopties voor de uitbreidingsmanager in</translation> </message> <message> <location filename="AddonManager.ui" line="92"/> <source>Configure...</source> <translation>Configureer...</translation> </message> <message> <location filename="AddonManagerOptions.ui" line="14"/> <source>Addon manager options</source> <translation>Opties voor de uitbreidingsmanager</translation> </message> <message> <location filename="AddonManager.ui" line="130"/> <source>Uninstall selected</source> <translation>Verwijder geselecteerde</translation> </message> <message> <location filename="AddonManager.ui" line="140"/> <source>Install/update selected</source> <translation>Geselecteerde installeren/bijwerken</translation> </message> <message> <location filename="AddonManager.ui" line="160"/> <source>Close</source> <translation>Sluiten</translation> </message> <message> <location filename="AddonManagerOptions.ui" line="20"/> <source>If this option is selected, when launching the Addon Manager, installed addons will be checked for available updates (this requires the GitPython package installed on your system)</source> <translation>Als deze optie geselecteerd is, zullen bij het starten van de uitbreidingsmanager geïnstalleerde uitbreidingen gecontroleerd worden op beschikbare updates (dit vereist het GitPython-pakket dat op uw systeem geïnstalleerd is)</translation> </message> <message> <location filename="AddonManagerOptions.ui" line="25"/> <source>Automatically check for updates at start (requires GitPython)</source> <translation>Controleer automatisch op updates bij het opstarten (vereist GitPython)</translation> </message> <message> <location filename="AddonManagerOptions.ui" line="57"/> <source>Proxy </source> <translation>Proxy </translation> </message> <message> <location filename="AddonManagerOptions.ui" line="64"/> <source>No proxy</source> <translation>Geen proxy</translation> </message> <message> <location filename="AddonManagerOptions.ui" line="71"/> <source>User system proxy</source> <translation>Proxy van gebruikerssysteem</translation> </message> <message> <location filename="AddonManagerOptions.ui" line="78"/> <source>User defined proxy :</source> <translation>Gebruikergedefinieerde proxy :</translation> </message> <message> <location filename="AddonManager.ui" line="14"/> <source>Addon Manager</source> <translation>Uitbreidingsmanager</translation> </message> <message> <location filename="AddonManager.ui" line="157"/> <source>Close the Addon Manager</source> <translation>Sluit uitbreidingsmanager</translation> </message> <message> <location filename="AddonManagerOptions.ui" line="42"/> <source>You can use this window to specify additional addon repositories to be scanned for available addons</source> <translation>U kunt dit venster gebruiken om extra add-on-opslagplaatsen op te geven die gescand moeten worden voor beschikbare add-ons</translation> </message> </context> <context> <name>Std_AddonMgr</name> <message> <location filename="AddonManager.py" line="68"/> <source>&amp;Addon manager</source> <translation>&amp;Uitbreidingsmanager</translation> </message> <message> <location filename="AddonManager.py" line="69"/> <source>Manage external workbenches and macros</source> <translation>Externe werkbanken en macro's beheren</translation> </message> </context> </TS>
sanguinariojoe/FreeCAD
src/Mod/AddonManager/Resources/translations/AddonManager_nl.ts
TypeScript
lgpl-2.1
19,652
/*********************************************************************** Copyright (c) 1995, 2016, Oracle and/or its affiliates. All Rights Reserved. Copyright (c) 2009, Percona Inc. Copyright (c) 2012, 2017, MariaDB Corporation. All Rights Reserved. Portions of this file contain modifications contributed and copyrighted by Percona Inc.. Those modifications are gratefully acknowledged and are described briefly in the InnoDB documentation. The contributions by Percona Inc. are incorporated with their permission, and subject to the conditions contained in the file COPYING.Percona. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA ***********************************************************************/ /**************************************************//** @file os/os0file.cc The interface to the operating system file i/o primitives Created 10/21/1995 Heikki Tuuri *******************************************************/ #include "os0file.h" #ifdef UNIV_NONINL #include "os0file.ic" #endif #include "ut0mem.h" #include "srv0srv.h" #include "srv0start.h" #include "fil0fil.h" #include "buf0buf.h" #include "srv0mon.h" #ifndef UNIV_HOTBACKUP # include "os0sync.h" # include "os0thread.h" #else /* !UNIV_HOTBACKUP */ # ifdef __WIN__ /* Add includes for the _stat() call to compile on Windows */ # include <sys/types.h> # include <sys/stat.h> # include <errno.h> # endif /* __WIN__ */ #endif /* !UNIV_HOTBACKUP */ #if defined(LINUX_NATIVE_AIO) #include <libaio.h> #endif /** Insert buffer segment id */ static const ulint IO_IBUF_SEGMENT = 0; /** Log segment id */ static const ulint IO_LOG_SEGMENT = 1; /* This specifies the file permissions InnoDB uses when it creates files in Unix; the value of os_innodb_umask is initialized in ha_innodb.cc to my_umask */ #ifndef __WIN__ /** Umask for creating files */ UNIV_INTERN ulint os_innodb_umask = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP; #else /** Umask for creating files */ UNIV_INTERN ulint os_innodb_umask = 0; #endif /* __WIN__ */ #ifndef UNIV_HOTBACKUP /* We use these mutexes to protect lseek + file i/o operation, if the OS does not provide an atomic pread or pwrite, or similar */ #define OS_FILE_N_SEEK_MUTEXES 16 UNIV_INTERN os_ib_mutex_t os_file_seek_mutexes[OS_FILE_N_SEEK_MUTEXES]; /* In simulated aio, merge at most this many consecutive i/os */ #define OS_AIO_MERGE_N_CONSECUTIVE 64 /********************************************************************** InnoDB AIO Implementation: ========================= We support native AIO for windows and linux. For rest of the platforms we simulate AIO by special io-threads servicing the IO-requests. Simulated AIO: ============== In platforms where we 'simulate' AIO following is a rough explanation of the high level design. There are four io-threads (for ibuf, log, read, write). All synchronous IO requests are serviced by the calling thread using os_file_write/os_file_read. The Asynchronous requests are queued up in an array (there are four such arrays) by the calling thread. Later these requests are picked up by the io-thread and are serviced synchronously. Windows native AIO: ================== If srv_use_native_aio is not set then windows follow the same code as simulated AIO. If the flag is set then native AIO interface is used. On windows, one of the limitation is that if a file is opened for AIO no synchronous IO can be done on it. Therefore we have an extra fifth array to queue up synchronous IO requests. There are innodb_file_io_threads helper threads. These threads work on the four arrays mentioned above in Simulated AIO. No thread is required for the sync array. If a synchronous IO request is made, it is first queued in the sync array. Then the calling thread itself waits on the request, thus making the call synchronous. If an AIO request is made the calling thread not only queues it in the array but also submits the requests. The helper thread then collects the completed IO request and calls completion routine on it. Linux native AIO: ================= If we have libaio installed on the system and innodb_use_native_aio is set to TRUE we follow the code path of native AIO, otherwise we do simulated AIO. There are innodb_file_io_threads helper threads. These threads work on the four arrays mentioned above in Simulated AIO. If a synchronous IO request is made, it is handled by calling os_file_write/os_file_read. If an AIO request is made the calling thread not only queues it in the array but also submits the requests. The helper thread then collects the completed IO request and calls completion routine on it. **********************************************************************/ /** Flag: enable debug printout for asynchronous i/o */ UNIV_INTERN ibool os_aio_print_debug = FALSE; #ifdef UNIV_PFS_IO /* Keys to register InnoDB I/O with performance schema */ UNIV_INTERN mysql_pfs_key_t innodb_file_data_key; UNIV_INTERN mysql_pfs_key_t innodb_file_log_key; UNIV_INTERN mysql_pfs_key_t innodb_file_temp_key; #endif /* UNIV_PFS_IO */ /** The asynchronous i/o array slot structure */ struct os_aio_slot_t{ ibool is_read; /*!< TRUE if a read operation */ ulint pos; /*!< index of the slot in the aio array */ ibool reserved; /*!< TRUE if this slot is reserved */ time_t reservation_time;/*!< time when reserved */ ulint len; /*!< length of the block to read or write */ byte* buf; /*!< buffer used in i/o */ ulint type; /*!< OS_FILE_READ or OS_FILE_WRITE */ os_offset_t offset; /*!< file offset in bytes */ os_file_t file; /*!< file where to read or write */ const char* name; /*!< file name or path */ ibool io_already_done;/*!< used only in simulated aio: TRUE if the physical i/o already made and only the slot message needs to be passed to the caller of os_aio_simulated_handle */ fil_node_t* message1; /*!< message which is given by the */ void* message2; /*!< the requester of an aio operation and which can be used to identify which pending aio operation was completed */ #ifdef WIN_ASYNC_IO HANDLE handle; /*!< handle object we need in the OVERLAPPED struct */ OVERLAPPED control; /*!< Windows control block for the aio request */ #elif defined(LINUX_NATIVE_AIO) struct iocb control; /* Linux control block for aio */ int n_bytes; /* bytes written/read. */ int ret; /* AIO return code */ #endif /* WIN_ASYNC_IO */ }; /** The asynchronous i/o array structure */ struct os_aio_array_t{ os_ib_mutex_t mutex; /*!< the mutex protecting the aio array */ os_event_t not_full; /*!< The event which is set to the signaled state when there is space in the aio outside the ibuf segment; os_event_set() and os_event_reset() are protected by os_aio_array_t::mutex */ os_event_t is_empty; /*!< The event which is set to the signaled state when there are no pending i/os in this array; os_event_set() and os_event_reset() are protected by os_aio_array_t::mutex */ ulint n_slots;/*!< Total number of slots in the aio array. This must be divisible by n_threads. */ ulint n_segments; /*!< Number of segments in the aio array of pending aio requests. A thread can wait separately for any one of the segments. */ ulint cur_seg;/*!< We reserve IO requests in round robin fashion to different segments. This points to the segment that is to be used to service next IO request. */ ulint n_reserved; /*!< Number of reserved slots in the aio array outside the ibuf segment */ os_aio_slot_t* slots; /*!< Pointer to the slots in the array */ #ifdef __WIN__ HANDLE* handles; /*!< Pointer to an array of OS native event handles where we copied the handles from slots, in the same order. This can be used in WaitForMultipleObjects; used only in Windows */ #endif /* __WIN__ */ #if defined(LINUX_NATIVE_AIO) io_context_t* aio_ctx; /* completion queue for IO. There is one such queue per segment. Each thread will work on one ctx exclusively. */ struct io_event* aio_events; /* The array to collect completed IOs. There is one such event for each possible pending IO. The size of the array is equal to n_slots. */ #endif /* LINUX_NATIV_AIO */ }; #if defined(LINUX_NATIVE_AIO) /** timeout for each io_getevents() call = 500ms. */ #define OS_AIO_REAP_TIMEOUT (500000000UL) /** time to sleep, in microseconds if io_setup() returns EAGAIN. */ #define OS_AIO_IO_SETUP_RETRY_SLEEP (500000UL) /** number of attempts before giving up on io_setup(). */ #define OS_AIO_IO_SETUP_RETRY_ATTEMPTS 5 #endif /** Array of events used in simulated aio. */ static os_event_t* os_aio_segment_wait_events; /** The aio arrays for non-ibuf i/o and ibuf i/o, as well as sync aio. These are NULL when the module has not yet been initialized. @{ */ static os_aio_array_t* os_aio_read_array = NULL; /*!< Reads */ static os_aio_array_t* os_aio_write_array = NULL; /*!< Writes */ static os_aio_array_t* os_aio_ibuf_array = NULL; /*!< Insert buffer */ static os_aio_array_t* os_aio_log_array = NULL; /*!< Redo log */ static os_aio_array_t* os_aio_sync_array = NULL; /*!< Synchronous I/O */ /* @} */ /** Number of asynchronous I/O segments. Set by os_aio_init(). */ static ulint os_aio_n_segments = ULINT_UNDEFINED; /** If the following is TRUE, read i/o handler threads try to wait until a batch of new read requests have been posted */ static ibool os_aio_recommend_sleep_for_read_threads = FALSE; #endif /* !UNIV_HOTBACKUP */ UNIV_INTERN ulint os_n_file_reads = 0; UNIV_INTERN ulint os_bytes_read_since_printout = 0; UNIV_INTERN ulint os_n_file_writes = 0; UNIV_INTERN ulint os_n_fsyncs = 0; UNIV_INTERN ulint os_n_file_reads_old = 0; UNIV_INTERN ulint os_n_file_writes_old = 0; UNIV_INTERN ulint os_n_fsyncs_old = 0; UNIV_INTERN time_t os_last_printout; UNIV_INTERN ibool os_has_said_disk_full = FALSE; #if !defined(UNIV_HOTBACKUP) \ && (!defined(HAVE_ATOMIC_BUILTINS) || UNIV_WORD_SIZE < 8) /** The mutex protecting the following counts of pending I/O operations */ static os_ib_mutex_t os_file_count_mutex; #endif /* !UNIV_HOTBACKUP && (!HAVE_ATOMIC_BUILTINS || UNIV_WORD_SIZE < 8) */ /** Number of pending os_file_pread() operations */ UNIV_INTERN ulint os_file_n_pending_preads = 0; /** Number of pending os_file_pwrite() operations */ UNIV_INTERN ulint os_file_n_pending_pwrites = 0; /** Number of pending write operations */ UNIV_INTERN ulint os_n_pending_writes = 0; /** Number of pending read operations */ UNIV_INTERN ulint os_n_pending_reads = 0; #ifdef UNIV_DEBUG # ifndef UNIV_HOTBACKUP /**********************************************************************//** Validates the consistency the aio system some of the time. @return TRUE if ok or the check was skipped */ UNIV_INTERN ibool os_aio_validate_skip(void) /*======================*/ { /** Try os_aio_validate() every this many times */ # define OS_AIO_VALIDATE_SKIP 13 /** The os_aio_validate() call skip counter. Use a signed type because of the race condition below. */ static int os_aio_validate_count = OS_AIO_VALIDATE_SKIP; /* There is a race condition below, but it does not matter, because this call is only for heuristic purposes. We want to reduce the call frequency of the costly os_aio_validate() check in debug builds. */ if (--os_aio_validate_count > 0) { return(TRUE); } os_aio_validate_count = OS_AIO_VALIDATE_SKIP; return(os_aio_validate()); } # endif /* !UNIV_HOTBACKUP */ #endif /* UNIV_DEBUG */ #ifdef __WIN__ /***********************************************************************//** Gets the operating system version. Currently works only on Windows. @return OS_WIN95, OS_WIN31, OS_WINNT, OS_WIN2000, OS_WINXP, OS_WINVISTA, OS_WIN7. */ UNIV_INTERN ulint os_get_os_version(void) /*===================*/ { OSVERSIONINFO os_info; os_info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); ut_a(GetVersionEx(&os_info)); if (os_info.dwPlatformId == VER_PLATFORM_WIN32s) { return(OS_WIN31); } else if (os_info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) { return(OS_WIN95); } else if (os_info.dwPlatformId == VER_PLATFORM_WIN32_NT) { switch (os_info.dwMajorVersion) { case 3: case 4: return(OS_WINNT); case 5: return (os_info.dwMinorVersion == 0) ? OS_WIN2000 : OS_WINXP; case 6: return (os_info.dwMinorVersion == 0) ? OS_WINVISTA : OS_WIN7; default: return(OS_WIN7); } } else { ut_error; return(0); } } #endif /* __WIN__ */ /***********************************************************************//** Retrieves the last error number if an error occurs in a file io function. The number should be retrieved before any other OS calls (because they may overwrite the error number). If the number is not known to this program, the OS error number + 100 is returned. @return error number, or OS error number + 100 */ static ulint os_file_get_last_error_low( /*=======================*/ bool report_all_errors, /*!< in: TRUE if we want an error message printed of all errors */ bool on_error_silent) /*!< in: TRUE then don't print any diagnostic to the log */ { #ifdef __WIN__ ulint err = (ulint) GetLastError(); if (err == ERROR_SUCCESS) { return(0); } if (report_all_errors || (!on_error_silent && err != ERROR_DISK_FULL && err != ERROR_FILE_EXISTS)) { ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Operating system error number %lu" " in a file operation.\n", (ulong) err); if (err == ERROR_PATH_NOT_FOUND) { fprintf(stderr, "InnoDB: The error means the system" " cannot find the path specified.\n"); if (srv_is_being_started) { fprintf(stderr, "InnoDB: If you are installing InnoDB," " remember that you must create\n" "InnoDB: directories yourself, InnoDB" " does not create them.\n"); } } else if (err == ERROR_ACCESS_DENIED) { fprintf(stderr, "InnoDB: The error means mysqld does not have" " the access rights to\n" "InnoDB: the directory. It may also be" " you have created a subdirectory\n" "InnoDB: of the same name as a data file.\n"); } else if (err == ERROR_SHARING_VIOLATION || err == ERROR_LOCK_VIOLATION) { fprintf(stderr, "InnoDB: The error means that another program" " is using InnoDB's files.\n" "InnoDB: This might be a backup or antivirus" " software or another instance\n" "InnoDB: of MySQL." " Please close it to get rid of this error.\n"); } else if (err == ERROR_WORKING_SET_QUOTA || err == ERROR_NO_SYSTEM_RESOURCES) { fprintf(stderr, "InnoDB: The error means that there are no" " sufficient system resources or quota to" " complete the operation.\n"); } else if (err == ERROR_OPERATION_ABORTED) { fprintf(stderr, "InnoDB: The error means that the I/O" " operation has been aborted\n" "InnoDB: because of either a thread exit" " or an application request.\n" "InnoDB: Retry attempt is made.\n"); } else { fprintf(stderr, "InnoDB: Some operating system error numbers" " are described at\n" "InnoDB: " REFMAN "operating-system-error-codes.html\n"); } } fflush(stderr); if (err == ERROR_FILE_NOT_FOUND) { return(OS_FILE_NOT_FOUND); } else if (err == ERROR_DISK_FULL) { return(OS_FILE_DISK_FULL); } else if (err == ERROR_FILE_EXISTS) { return(OS_FILE_ALREADY_EXISTS); } else if (err == ERROR_SHARING_VIOLATION || err == ERROR_LOCK_VIOLATION) { return(OS_FILE_SHARING_VIOLATION); } else if (err == ERROR_WORKING_SET_QUOTA || err == ERROR_NO_SYSTEM_RESOURCES) { return(OS_FILE_INSUFFICIENT_RESOURCE); } else if (err == ERROR_OPERATION_ABORTED) { return(OS_FILE_OPERATION_ABORTED); } else if (err == ERROR_ACCESS_DENIED) { return(OS_FILE_ACCESS_VIOLATION); } else if (err == ERROR_BUFFER_OVERFLOW) { return(OS_FILE_NAME_TOO_LONG); } else { return(OS_FILE_ERROR_MAX + err); } #else int err = errno; if (err == 0) { return(0); } if (report_all_errors || (err != ENOSPC && err != EEXIST && !on_error_silent)) { ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Operating system error number %d" " in a file operation.\n", err); if (err == ENOENT) { fprintf(stderr, "InnoDB: The error means the system" " cannot find the path specified.\n"); if (srv_is_being_started) { fprintf(stderr, "InnoDB: If you are installing InnoDB," " remember that you must create\n" "InnoDB: directories yourself, InnoDB" " does not create them.\n"); } } else if (err == EACCES) { fprintf(stderr, "InnoDB: The error means mysqld does not have" " the access rights to\n" "InnoDB: the directory.\n"); } else { if (strerror(err) != NULL) { fprintf(stderr, "InnoDB: Error number %d" " means '%s'.\n", err, strerror(err)); } fprintf(stderr, "InnoDB: Some operating system" " error numbers are described at\n" "InnoDB: " REFMAN "operating-system-error-codes.html\n"); } } fflush(stderr); switch (err) { case ENOSPC: return(OS_FILE_DISK_FULL); case ENOENT: return(OS_FILE_NOT_FOUND); case EEXIST: return(OS_FILE_ALREADY_EXISTS); case ENAMETOOLONG: return(OS_FILE_NAME_TOO_LONG); case EXDEV: case ENOTDIR: case EISDIR: return(OS_FILE_PATH_ERROR); case EAGAIN: if (srv_use_native_aio) { return(OS_FILE_AIO_RESOURCES_RESERVED); } break; case EINTR: if (srv_use_native_aio) { return(OS_FILE_AIO_INTERRUPTED); } break; case EACCES: return(OS_FILE_ACCESS_VIOLATION); } return(OS_FILE_ERROR_MAX + err); #endif } /***********************************************************************//** Retrieves the last error number if an error occurs in a file io function. The number should be retrieved before any other OS calls (because they may overwrite the error number). If the number is not known to this program, the OS error number + 100 is returned. @return error number, or OS error number + 100 */ UNIV_INTERN ulint os_file_get_last_error( /*===================*/ bool report_all_errors) /*!< in: TRUE if we want an error message printed of all errors */ { return(os_file_get_last_error_low(report_all_errors, false)); } /****************************************************************//** Does error handling when a file operation fails. Conditionally exits (calling exit(3)) based on should_exit value and the error type, if should_exit is TRUE then on_error_silent is ignored. @return TRUE if we should retry the operation */ static ibool os_file_handle_error_cond_exit( /*===========================*/ const char* name, /*!< in: name of a file or NULL */ const char* operation, /*!< in: operation */ ibool should_exit, /*!< in: call exit(3) if unknown error and this parameter is TRUE */ ibool on_error_silent)/*!< in: if TRUE then don't print any message to the log iff it is an unknown non-fatal error */ { ulint err; err = os_file_get_last_error_low(false, on_error_silent); switch (err) { case OS_FILE_DISK_FULL: /* We only print a warning about disk full once */ if (os_has_said_disk_full) { return(FALSE); } /* Disk full error is reported irrespective of the on_error_silent setting. */ if (name) { ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Encountered a problem with" " file %s\n", name); } ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Disk is full. Try to clean the disk" " to free space.\n"); os_has_said_disk_full = TRUE; fflush(stderr); ut_error; return(FALSE); case OS_FILE_AIO_RESOURCES_RESERVED: case OS_FILE_AIO_INTERRUPTED: return(TRUE); case OS_FILE_PATH_ERROR: case OS_FILE_ALREADY_EXISTS: case OS_FILE_ACCESS_VIOLATION: return(FALSE); case OS_FILE_SHARING_VIOLATION: os_thread_sleep(10000000); /* 10 sec */ return(TRUE); case OS_FILE_OPERATION_ABORTED: case OS_FILE_INSUFFICIENT_RESOURCE: os_thread_sleep(100000); /* 100 ms */ return(TRUE); default: /* If it is an operation that can crash on error then it is better to ignore on_error_silent and print an error message to the log. */ if (should_exit || !on_error_silent) { ib_logf(IB_LOG_LEVEL_ERROR, "File %s: '%s' returned OS " "error " ULINTPF ".%s", name ? name : "(unknown)", operation, err, should_exit ? " Cannot continue operation" : ""); } if (should_exit) { exit(1); } } return(FALSE); } /****************************************************************//** Does error handling when a file operation fails. @return TRUE if we should retry the operation */ static ibool os_file_handle_error( /*=================*/ const char* name, /*!< in: name of a file or NULL */ const char* operation) /*!< in: operation */ { /* exit in case of unknown error */ return(os_file_handle_error_cond_exit(name, operation, TRUE, FALSE)); } /****************************************************************//** Does error handling when a file operation fails. @return TRUE if we should retry the operation */ ibool os_file_handle_error_no_exit( /*=========================*/ const char* name, /*!< in: name of a file or NULL */ const char* operation, /*!< in: operation */ ibool on_error_silent)/*!< in: if TRUE then don't print any message to the log. */ { /* don't exit in case of unknown error */ return(os_file_handle_error_cond_exit( name, operation, FALSE, on_error_silent)); } #undef USE_FILE_LOCK #define USE_FILE_LOCK #if defined(UNIV_HOTBACKUP) || defined(__WIN__) /* InnoDB Hot Backup does not lock the data files. * On Windows, mandatory locking is used. */ # undef USE_FILE_LOCK #endif #ifdef USE_FILE_LOCK /****************************************************************//** Obtain an exclusive lock on a file. @return 0 on success */ static int os_file_lock( /*=========*/ int fd, /*!< in: file descriptor */ const char* name) /*!< in: file name */ { struct flock lk; ut_ad(!srv_read_only_mode); lk.l_type = F_WRLCK; lk.l_whence = SEEK_SET; lk.l_start = lk.l_len = 0; if (fcntl(fd, F_SETLK, &lk) == -1) { ib_logf(IB_LOG_LEVEL_ERROR, "Unable to lock %s, error: %d", name, errno); if (errno == EAGAIN || errno == EACCES) { ib_logf(IB_LOG_LEVEL_INFO, "Check that you do not already have " "another mysqld process using the " "same InnoDB data or log files."); } return(-1); } return(0); } #endif /* USE_FILE_LOCK */ #ifndef UNIV_HOTBACKUP /****************************************************************//** Creates the seek mutexes used in positioned reads and writes. */ UNIV_INTERN void os_io_init_simple(void) /*===================*/ { #if !defined(HAVE_ATOMIC_BUILTINS) || UNIV_WORD_SIZE < 8 os_file_count_mutex = os_mutex_create(); #endif /* !HAVE_ATOMIC_BUILTINS || UNIV_WORD_SIZE < 8 */ for (ulint i = 0; i < OS_FILE_N_SEEK_MUTEXES; i++) { os_file_seek_mutexes[i] = os_mutex_create(); } } /** Create a temporary file. This function is like tmpfile(3), but the temporary file is created in the given parameter path. If the path is null then it will create the file in the mysql server configuration parameter (--tmpdir). @param[in] path location for creating temporary file @return temporary file handle, or NULL on error */ UNIV_INTERN FILE* os_file_create_tmpfile( const char* path) { FILE* file = NULL; int fd = innobase_mysql_tmpfile(path); ut_ad(!srv_read_only_mode); if (fd >= 0) { file = fdopen(fd, "w+b"); } if (!file) { ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Error: unable to create temporary file;" " errno: %d\n", errno); if (fd >= 0) { close(fd); } } return(file); } #endif /* !UNIV_HOTBACKUP */ /***********************************************************************//** The os_file_opendir() function opens a directory stream corresponding to the directory named by the dirname argument. The directory stream is positioned at the first entry. In both Unix and Windows we automatically skip the '.' and '..' items at the start of the directory listing. @return directory stream, NULL if error */ UNIV_INTERN os_file_dir_t os_file_opendir( /*============*/ const char* dirname, /*!< in: directory name; it must not contain a trailing '\' or '/' */ ibool error_is_fatal) /*!< in: TRUE if we should treat an error as a fatal error; if we try to open symlinks then we do not wish a fatal error if it happens not to be a directory */ { os_file_dir_t dir; #ifdef __WIN__ LPWIN32_FIND_DATA lpFindFileData; char path[OS_FILE_MAX_PATH + 3]; ut_a(strlen(dirname) < OS_FILE_MAX_PATH); strcpy(path, dirname); strcpy(path + strlen(path), "\\*"); /* Note that in Windows opening the 'directory stream' also retrieves the first entry in the directory. Since it is '.', that is no problem, as we will skip over the '.' and '..' entries anyway. */ lpFindFileData = static_cast<LPWIN32_FIND_DATA>( ut_malloc(sizeof(WIN32_FIND_DATA))); dir = FindFirstFile((LPCTSTR) path, lpFindFileData); ut_free(lpFindFileData); if (dir == INVALID_HANDLE_VALUE) { if (error_is_fatal) { os_file_handle_error(dirname, "opendir"); } return(NULL); } return(dir); #else dir = opendir(dirname); if (dir == NULL && error_is_fatal) { os_file_handle_error(dirname, "opendir"); } return(dir); #endif /* __WIN__ */ } /***********************************************************************//** Closes a directory stream. @return 0 if success, -1 if failure */ UNIV_INTERN int os_file_closedir( /*=============*/ os_file_dir_t dir) /*!< in: directory stream */ { #ifdef __WIN__ BOOL ret; ret = FindClose(dir); if (!ret) { os_file_handle_error_no_exit(NULL, "closedir", FALSE); return(-1); } return(0); #else int ret; ret = closedir(dir); if (ret) { os_file_handle_error_no_exit(NULL, "closedir", FALSE); } return(ret); #endif /* __WIN__ */ } /***********************************************************************//** This function returns information of the next file in the directory. We jump over the '.' and '..' entries in the directory. @return 0 if ok, -1 if error, 1 if at the end of the directory */ UNIV_INTERN int os_file_readdir_next_file( /*======================*/ const char* dirname,/*!< in: directory name or path */ os_file_dir_t dir, /*!< in: directory stream */ os_file_stat_t* info) /*!< in/out: buffer where the info is returned */ { #ifdef __WIN__ LPWIN32_FIND_DATA lpFindFileData; BOOL ret; lpFindFileData = static_cast<LPWIN32_FIND_DATA>( ut_malloc(sizeof(WIN32_FIND_DATA))); next_file: ret = FindNextFile(dir, lpFindFileData); if (ret) { ut_a(strlen((char*) lpFindFileData->cFileName) < OS_FILE_MAX_PATH); if (strcmp((char*) lpFindFileData->cFileName, ".") == 0 || strcmp((char*) lpFindFileData->cFileName, "..") == 0) { goto next_file; } strcpy(info->name, (char*) lpFindFileData->cFileName); info->size = (ib_int64_t)(lpFindFileData->nFileSizeLow) + (((ib_int64_t)(lpFindFileData->nFileSizeHigh)) << 32); if (lpFindFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { /* TODO: test Windows symlinks */ /* TODO: MySQL has apparently its own symlink implementation in Windows, dbname.sym can redirect a database directory: REFMAN "windows-symbolic-links.html" */ info->type = OS_FILE_TYPE_LINK; } else if (lpFindFileData->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { info->type = OS_FILE_TYPE_DIR; } else { /* It is probably safest to assume that all other file types are normal. Better to check them rather than blindly skip them. */ info->type = OS_FILE_TYPE_FILE; } } ut_free(lpFindFileData); if (ret) { return(0); } else if (GetLastError() == ERROR_NO_MORE_FILES) { return(1); } else { os_file_handle_error_no_exit(NULL, "readdir_next_file", FALSE); return(-1); } #else struct dirent* ent; char* full_path; int ret; struct stat statinfo; #ifdef HAVE_READDIR_R char dirent_buf[sizeof(struct dirent) + _POSIX_PATH_MAX + 100]; /* In /mysys/my_lib.c, _POSIX_PATH_MAX + 1 is used as the max file name len; but in most standards, the length is NAME_MAX; we add 100 to be even safer */ #endif next_file: #ifdef HAVE_READDIR_R ret = readdir_r(dir, (struct dirent*) dirent_buf, &ent); if (ret != 0 #ifdef UNIV_AIX /* On AIX, only if we got non-NULL 'ent' (result) value and a non-zero 'ret' (return) value, it indicates a failed readdir_r() call. An NULL 'ent' with an non-zero 'ret' would indicate the "end of the directory" is reached. */ && ent != NULL #endif ) { fprintf(stderr, "InnoDB: cannot read directory %s, error %lu\n", dirname, (ulong) ret); return(-1); } if (ent == NULL) { /* End of directory */ return(1); } ut_a(strlen(ent->d_name) < _POSIX_PATH_MAX + 100 - 1); #else ent = readdir(dir); if (ent == NULL) { return(1); } #endif ut_a(strlen(ent->d_name) < OS_FILE_MAX_PATH); if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) { goto next_file; } strcpy(info->name, ent->d_name); full_path = static_cast<char*>( ut_malloc(strlen(dirname) + strlen(ent->d_name) + 10)); sprintf(full_path, "%s/%s", dirname, ent->d_name); ret = stat(full_path, &statinfo); if (ret) { if (errno == ENOENT) { /* readdir() returned a file that does not exist, it must have been deleted in the meantime. Do what would have happened if the file was deleted before readdir() - ignore and go to the next entry. If this is the last entry then info->name will still contain the name of the deleted file when this function returns, but this is not an issue since the caller shouldn't be looking at info when end of directory is returned. */ ut_free(full_path); goto next_file; } os_file_handle_error_no_exit(full_path, "stat", FALSE); ut_free(full_path); return(-1); } info->size = (ib_int64_t) statinfo.st_size; if (S_ISDIR(statinfo.st_mode)) { info->type = OS_FILE_TYPE_DIR; } else if (S_ISLNK(statinfo.st_mode)) { info->type = OS_FILE_TYPE_LINK; } else if (S_ISREG(statinfo.st_mode)) { info->type = OS_FILE_TYPE_FILE; } else { info->type = OS_FILE_TYPE_UNKNOWN; } ut_free(full_path); return(0); #endif } /*****************************************************************//** This function attempts to create a directory named pathname. The new directory gets default permissions. On Unix the permissions are (0770 & ~umask). If the directory exists already, nothing is done and the call succeeds, unless the fail_if_exists arguments is true. If another error occurs, such as a permission error, this does not crash, but reports the error and returns FALSE. @return TRUE if call succeeds, FALSE on error */ UNIV_INTERN ibool os_file_create_directory( /*=====================*/ const char* pathname, /*!< in: directory name as null-terminated string */ ibool fail_if_exists) /*!< in: if TRUE, pre-existing directory is treated as an error. */ { #ifdef __WIN__ BOOL rcode; rcode = CreateDirectory((LPCTSTR) pathname, NULL); if (!(rcode != 0 || (GetLastError() == ERROR_ALREADY_EXISTS && !fail_if_exists))) { os_file_handle_error_no_exit( pathname, "CreateDirectory", FALSE); return(FALSE); } return(TRUE); #else int rcode; rcode = mkdir(pathname, 0770); if (!(rcode == 0 || (errno == EEXIST && !fail_if_exists))) { /* failure */ os_file_handle_error_no_exit(pathname, "mkdir", FALSE); return(FALSE); } return (TRUE); #endif /* __WIN__ */ } /****************************************************************//** NOTE! Use the corresponding macro os_file_create_simple(), not directly this function! A simple function to open or create a file. @return own: handle to the file, not defined if error, error number can be retrieved with os_file_get_last_error */ UNIV_INTERN os_file_t os_file_create_simple_func( /*=======================*/ const char* name, /*!< in: name of the file or path as a null-terminated string */ ulint create_mode,/*!< in: create mode */ ulint access_type,/*!< in: OS_FILE_READ_ONLY or OS_FILE_READ_WRITE */ ibool* success)/*!< out: TRUE if succeed, FALSE if error */ { os_file_t file; ibool retry; *success = FALSE; #ifdef __WIN__ DWORD access; DWORD create_flag; DWORD attributes = 0; ut_a(!(create_mode & OS_FILE_ON_ERROR_SILENT)); ut_a(!(create_mode & OS_FILE_ON_ERROR_NO_EXIT)); if (create_mode == OS_FILE_OPEN) { create_flag = OPEN_EXISTING; } else if (srv_read_only_mode) { create_flag = OPEN_EXISTING; } else if (create_mode == OS_FILE_CREATE) { create_flag = CREATE_NEW; } else if (create_mode == OS_FILE_CREATE_PATH) { ut_a(!srv_read_only_mode); /* Create subdirs along the path if needed */ *success = os_file_create_subdirs_if_needed(name); if (!*success) { ib_logf(IB_LOG_LEVEL_ERROR, "Unable to create subdirectories '%s'", name); return((os_file_t) -1); } create_flag = CREATE_NEW; create_mode = OS_FILE_CREATE; } else { ib_logf(IB_LOG_LEVEL_ERROR, "Unknown file create mode (%lu) for file '%s'", create_mode, name); return((os_file_t) -1); } if (access_type == OS_FILE_READ_ONLY) { access = GENERIC_READ; } else if (srv_read_only_mode) { ib_logf(IB_LOG_LEVEL_INFO, "read only mode set. Unable to " "open file '%s' in RW mode, trying RO mode", name); access = GENERIC_READ; } else if (access_type == OS_FILE_READ_WRITE) { access = GENERIC_READ | GENERIC_WRITE; } else { ib_logf(IB_LOG_LEVEL_ERROR, "Unknown file access type (%lu) for file '%s'", access_type, name); return((os_file_t) -1); } do { /* Use default security attributes and no template file. */ file = CreateFile( (LPCTSTR) name, access, FILE_SHARE_READ, NULL, create_flag, attributes, NULL); if (file == INVALID_HANDLE_VALUE) { *success = FALSE; retry = os_file_handle_error( name, create_mode == OS_FILE_OPEN ? "open" : "create"); } else { *success = TRUE; retry = false; } } while (retry); #else /* __WIN__ */ int create_flag; ut_a(!(create_mode & OS_FILE_ON_ERROR_SILENT)); ut_a(!(create_mode & OS_FILE_ON_ERROR_NO_EXIT)); if (create_mode == OS_FILE_OPEN) { if (access_type == OS_FILE_READ_ONLY) { create_flag = O_RDONLY; } else if (srv_read_only_mode) { create_flag = O_RDONLY; } else { create_flag = O_RDWR; } } else if (srv_read_only_mode) { create_flag = O_RDONLY; } else if (create_mode == OS_FILE_CREATE) { create_flag = O_RDWR | O_CREAT | O_EXCL; } else if (create_mode == OS_FILE_CREATE_PATH) { /* Create subdirs along the path if needed */ *success = os_file_create_subdirs_if_needed(name); if (!*success) { ib_logf(IB_LOG_LEVEL_ERROR, "Unable to create subdirectories '%s'", name); return((os_file_t) -1); } create_flag = O_RDWR | O_CREAT | O_EXCL; create_mode = OS_FILE_CREATE; } else { ib_logf(IB_LOG_LEVEL_ERROR, "Unknown file create mode (%lu) for file '%s'", create_mode, name); return((os_file_t) -1); } do { file = ::open(name, create_flag, os_innodb_umask); if (file == -1) { *success = FALSE; retry = os_file_handle_error( name, create_mode == OS_FILE_OPEN ? "open" : "create"); } else { *success = TRUE; retry = false; } } while (retry); #ifdef USE_FILE_LOCK if (!srv_read_only_mode && *success && access_type == OS_FILE_READ_WRITE && os_file_lock(file, name)) { *success = FALSE; close(file); file = -1; } #endif /* USE_FILE_LOCK */ #endif /* __WIN__ */ return(file); } /****************************************************************//** NOTE! Use the corresponding macro os_file_create_simple_no_error_handling(), not directly this function! A simple function to open or create a file. @return own: handle to the file, not defined if error, error number can be retrieved with os_file_get_last_error */ UNIV_INTERN os_file_t os_file_create_simple_no_error_handling_func( /*=========================================*/ const char* name, /*!< in: name of the file or path as a null-terminated string */ ulint create_mode,/*!< in: create mode */ ulint access_type,/*!< in: OS_FILE_READ_ONLY, OS_FILE_READ_WRITE, or OS_FILE_READ_ALLOW_DELETE; the last option is used by a backup program reading the file */ ibool* success)/*!< out: TRUE if succeed, FALSE if error */ { os_file_t file; *success = FALSE; #ifdef __WIN__ DWORD access; DWORD create_flag; DWORD attributes = 0; DWORD share_mode = FILE_SHARE_READ; ut_a(name); ut_a(!(create_mode & OS_FILE_ON_ERROR_SILENT)); ut_a(!(create_mode & OS_FILE_ON_ERROR_NO_EXIT)); if (create_mode == OS_FILE_OPEN) { create_flag = OPEN_EXISTING; } else if (srv_read_only_mode) { create_flag = OPEN_EXISTING; } else if (create_mode == OS_FILE_CREATE) { create_flag = CREATE_NEW; } else { ib_logf(IB_LOG_LEVEL_ERROR, "Unknown file create mode (%lu) for file '%s'", create_mode, name); return((os_file_t) -1); } if (access_type == OS_FILE_READ_ONLY) { access = GENERIC_READ; } else if (srv_read_only_mode) { access = GENERIC_READ; } else if (access_type == OS_FILE_READ_WRITE) { access = GENERIC_READ | GENERIC_WRITE; } else if (access_type == OS_FILE_READ_ALLOW_DELETE) { ut_a(!srv_read_only_mode); access = GENERIC_READ; /*!< A backup program has to give mysqld the maximum freedom to do what it likes with the file */ share_mode |= FILE_SHARE_DELETE | FILE_SHARE_WRITE; } else { ib_logf(IB_LOG_LEVEL_ERROR, "Unknown file access type (%lu) for file '%s'", access_type, name); return((os_file_t) -1); } file = CreateFile((LPCTSTR) name, access, share_mode, NULL, // Security attributes create_flag, attributes, NULL); // No template file *success = (file != INVALID_HANDLE_VALUE); #else /* __WIN__ */ int create_flag; const char* mode_str = NULL; ut_a(name); ut_a(!(create_mode & OS_FILE_ON_ERROR_SILENT)); ut_a(!(create_mode & OS_FILE_ON_ERROR_NO_EXIT)); if (create_mode == OS_FILE_OPEN) { mode_str = "OPEN"; if (access_type == OS_FILE_READ_ONLY) { create_flag = O_RDONLY; } else if (srv_read_only_mode) { create_flag = O_RDONLY; } else { ut_a(access_type == OS_FILE_READ_WRITE || access_type == OS_FILE_READ_ALLOW_DELETE); create_flag = O_RDWR; } } else if (srv_read_only_mode) { mode_str = "OPEN"; create_flag = O_RDONLY; } else if (create_mode == OS_FILE_CREATE) { mode_str = "CREATE"; create_flag = O_RDWR | O_CREAT | O_EXCL; } else { ib_logf(IB_LOG_LEVEL_ERROR, "Unknown file create mode (%lu) for file '%s'", create_mode, name); return((os_file_t) -1); } file = ::open(name, create_flag, os_innodb_umask); *success = file == -1 ? FALSE : TRUE; /* This function is always called for data files, we should disable OS caching (O_DIRECT) here as we do in os_file_create_func(), so we open the same file in the same mode, see man page of open(2). */ if (!srv_read_only_mode && *success && (srv_unix_file_flush_method == SRV_UNIX_O_DIRECT || srv_unix_file_flush_method == SRV_UNIX_O_DIRECT_NO_FSYNC)) { os_file_set_nocache(file, name, mode_str); } #ifdef USE_FILE_LOCK if (!srv_read_only_mode && *success && access_type == OS_FILE_READ_WRITE && os_file_lock(file, name)) { *success = FALSE; close(file); file = -1; } #endif /* USE_FILE_LOCK */ #endif /* __WIN__ */ return(file); } /****************************************************************//** Tries to disable OS caching on an opened file descriptor. */ UNIV_INTERN void os_file_set_nocache( /*================*/ int fd /*!< in: file descriptor to alter */ MY_ATTRIBUTE((unused)), const char* file_name /*!< in: used in the diagnostic message */ MY_ATTRIBUTE((unused)), const char* operation_name MY_ATTRIBUTE((unused))) /*!< in: "open" or "create"; used in the diagnostic message */ { /* some versions of Solaris may not have DIRECTIO_ON */ #if defined(UNIV_SOLARIS) && defined(DIRECTIO_ON) if (directio(fd, DIRECTIO_ON) == -1) { int errno_save = errno; ib_logf(IB_LOG_LEVEL_ERROR, "Failed to set DIRECTIO_ON on file %s: %s: %s, " "continuing anyway.", file_name, operation_name, strerror(errno_save)); } #elif defined(O_DIRECT) if (fcntl(fd, F_SETFL, O_DIRECT) == -1) { int errno_save = errno; static bool warning_message_printed = false; if (errno_save == EINVAL) { if (!warning_message_printed) { warning_message_printed = true; # ifdef UNIV_LINUX ib_logf(IB_LOG_LEVEL_WARN, "Failed to set O_DIRECT on file " "%s: %s: %s, continuing anyway. " "O_DIRECT is known to result " "in 'Invalid argument' on Linux on " "tmpfs, see MySQL Bug#26662.", file_name, operation_name, strerror(errno_save)); # else /* UNIV_LINUX */ goto short_warning; # endif /* UNIV_LINUX */ } } else { # ifndef UNIV_LINUX short_warning: # endif ib_logf(IB_LOG_LEVEL_WARN, "Failed to set O_DIRECT on file %s: %s: %s, " "continuing anyway.", file_name, operation_name, strerror(errno_save)); } } #endif /* defined(UNIV_SOLARIS) && defined(DIRECTIO_ON) */ } /****************************************************************//** NOTE! Use the corresponding macro os_file_create(), not directly this function! Opens an existing file or creates a new. @return own: handle to the file, not defined if error, error number can be retrieved with os_file_get_last_error */ UNIV_INTERN os_file_t os_file_create_func( /*================*/ const char* name, /*!< in: name of the file or path as a null-terminated string */ ulint create_mode,/*!< in: create mode */ ulint purpose,/*!< in: OS_FILE_AIO, if asynchronous, non-buffered i/o is desired, OS_FILE_NORMAL, if any normal file; NOTE that it also depends on type, os_aio_.. and srv_.. variables whether we really use async i/o or unbuffered i/o: look in the function source code for the exact rules */ ulint type, /*!< in: OS_DATA_FILE or OS_LOG_FILE */ ibool* success)/*!< out: TRUE if succeed, FALSE if error */ { os_file_t file; ibool retry; ibool on_error_no_exit; ibool on_error_silent; #ifdef __WIN__ DBUG_EXECUTE_IF( "ib_create_table_fail_disk_full", *success = FALSE; SetLastError(ERROR_DISK_FULL); return((os_file_t) -1); ); #else /* __WIN__ */ DBUG_EXECUTE_IF( "ib_create_table_fail_disk_full", *success = FALSE; errno = ENOSPC; return((os_file_t) -1); ); #endif /* __WIN__ */ #ifdef __WIN__ DWORD create_flag; DWORD share_mode = FILE_SHARE_READ; on_error_no_exit = create_mode & OS_FILE_ON_ERROR_NO_EXIT ? TRUE : FALSE; on_error_silent = create_mode & OS_FILE_ON_ERROR_SILENT ? TRUE : FALSE; create_mode &= ~OS_FILE_ON_ERROR_NO_EXIT; create_mode &= ~OS_FILE_ON_ERROR_SILENT; if (create_mode == OS_FILE_OPEN_RAW) { ut_a(!srv_read_only_mode); create_flag = OPEN_EXISTING; /* On Windows Physical devices require admin privileges and have to have the write-share mode set. See the remarks section for the CreateFile() function documentation in MSDN. */ share_mode |= FILE_SHARE_WRITE; } else if (create_mode == OS_FILE_OPEN || create_mode == OS_FILE_OPEN_RETRY) { create_flag = OPEN_EXISTING; } else if (srv_read_only_mode) { create_flag = OPEN_EXISTING; } else if (create_mode == OS_FILE_CREATE) { create_flag = CREATE_NEW; } else if (create_mode == OS_FILE_OVERWRITE) { create_flag = CREATE_ALWAYS; } else { ib_logf(IB_LOG_LEVEL_ERROR, "Unknown file create mode (%lu) for file '%s'", create_mode, name); return((os_file_t) -1); } DWORD attributes = 0; #ifdef UNIV_HOTBACKUP attributes |= FILE_FLAG_NO_BUFFERING; #else if (purpose == OS_FILE_AIO) { #ifdef WIN_ASYNC_IO /* If specified, use asynchronous (overlapped) io and no buffering of writes in the OS */ if (srv_use_native_aio) { attributes |= FILE_FLAG_OVERLAPPED; } #endif /* WIN_ASYNC_IO */ } else if (purpose == OS_FILE_NORMAL) { /* Use default setting. */ } else { ib_logf(IB_LOG_LEVEL_ERROR, "Unknown purpose flag (%lu) while opening file '%s'", purpose, name); return((os_file_t)(-1)); } #ifdef UNIV_NON_BUFFERED_IO // TODO: Create a bug, this looks wrong. The flush log // parameter is dynamic. if (type == OS_LOG_FILE && srv_flush_log_at_trx_commit == 2) { /* Do not use unbuffered i/o for the log files because value 2 denotes that we do not flush the log at every commit, but only once per second */ } else if (srv_win_file_flush_method == SRV_WIN_IO_UNBUFFERED) { attributes |= FILE_FLAG_NO_BUFFERING; } #endif /* UNIV_NON_BUFFERED_IO */ #endif /* UNIV_HOTBACKUP */ DWORD access = GENERIC_READ; if (!srv_read_only_mode) { access |= GENERIC_WRITE; } do { /* Use default security attributes and no template file. */ file = CreateFile( (LPCTSTR) name, access, share_mode, NULL, create_flag, attributes, NULL); if (file == INVALID_HANDLE_VALUE) { const char* operation; operation = (create_mode == OS_FILE_CREATE && !srv_read_only_mode) ? "create" : "open"; *success = FALSE; if (on_error_no_exit) { retry = os_file_handle_error_no_exit( name, operation, on_error_silent); } else { retry = os_file_handle_error(name, operation); } } else { *success = TRUE; retry = FALSE; } } while (retry); #else /* __WIN__ */ int create_flag; const char* mode_str = NULL; on_error_no_exit = create_mode & OS_FILE_ON_ERROR_NO_EXIT ? TRUE : FALSE; on_error_silent = create_mode & OS_FILE_ON_ERROR_SILENT ? TRUE : FALSE; create_mode &= ~OS_FILE_ON_ERROR_NO_EXIT; create_mode &= ~OS_FILE_ON_ERROR_SILENT; if (create_mode == OS_FILE_OPEN || create_mode == OS_FILE_OPEN_RAW || create_mode == OS_FILE_OPEN_RETRY) { mode_str = "OPEN"; create_flag = srv_read_only_mode ? O_RDONLY : O_RDWR; } else if (srv_read_only_mode) { mode_str = "OPEN"; create_flag = O_RDONLY; } else if (create_mode == OS_FILE_CREATE) { mode_str = "CREATE"; create_flag = O_RDWR | O_CREAT | O_EXCL; } else if (create_mode == OS_FILE_OVERWRITE) { mode_str = "OVERWRITE"; create_flag = O_RDWR | O_CREAT | O_TRUNC; } else { ib_logf(IB_LOG_LEVEL_ERROR, "Unknown file create mode (%lu) for file '%s'", create_mode, name); return((os_file_t) -1); } ut_a(type == OS_LOG_FILE || type == OS_DATA_FILE); ut_a(purpose == OS_FILE_AIO || purpose == OS_FILE_NORMAL); #ifdef O_SYNC /* We let O_SYNC only affect log files; note that we map O_DSYNC to O_SYNC because the datasync options seemed to corrupt files in 2001 in both Linux and Solaris */ if (!srv_read_only_mode && type == OS_LOG_FILE && srv_unix_file_flush_method == SRV_UNIX_O_DSYNC) { create_flag |= O_SYNC; } #endif /* O_SYNC */ do { file = ::open(name, create_flag, os_innodb_umask); if (file == -1) { const char* operation; operation = (create_mode == OS_FILE_CREATE && !srv_read_only_mode) ? "create" : "open"; *success = FALSE; if (on_error_no_exit) { retry = os_file_handle_error_no_exit( name, operation, on_error_silent); } else { retry = os_file_handle_error(name, operation); } } else { *success = TRUE; retry = false; } } while (retry); /* We disable OS caching (O_DIRECT) only on data files */ if (!srv_read_only_mode && *success && type != OS_LOG_FILE && (srv_unix_file_flush_method == SRV_UNIX_O_DIRECT || srv_unix_file_flush_method == SRV_UNIX_O_DIRECT_NO_FSYNC)) { os_file_set_nocache(file, name, mode_str); } #ifdef USE_FILE_LOCK if (!srv_read_only_mode && *success && create_mode != OS_FILE_OPEN_RAW && os_file_lock(file, name)) { if (create_mode == OS_FILE_OPEN_RETRY) { ut_a(!srv_read_only_mode); ib_logf(IB_LOG_LEVEL_INFO, "Retrying to lock the first data file"); for (int i = 0; i < 100; i++) { os_thread_sleep(1000000); if (!os_file_lock(file, name)) { *success = TRUE; return(file); } } ib_logf(IB_LOG_LEVEL_INFO, "Unable to open the first data file"); } *success = FALSE; close(file); file = -1; } #endif /* USE_FILE_LOCK */ #endif /* __WIN__ */ return(file); } /***********************************************************************//** Deletes a file if it exists. The file has to be closed before calling this. @return TRUE if success */ UNIV_INTERN bool os_file_delete_if_exists_func( /*==========================*/ const char* name) /*!< in: file path as a null-terminated string */ { #ifdef __WIN__ bool ret; ulint count = 0; loop: /* In Windows, deleting an .ibd file may fail if mysqlbackup is copying it */ ret = DeleteFile((LPCTSTR) name); if (ret) { return(true); } DWORD lasterr = GetLastError(); if (lasterr == ERROR_FILE_NOT_FOUND || lasterr == ERROR_PATH_NOT_FOUND) { /* the file does not exist, this not an error */ return(true); } count++; if (count > 100 && 0 == (count % 10)) { os_file_get_last_error(true); /* print error information */ ib_logf(IB_LOG_LEVEL_WARN, "Delete of file %s failed.", name); } os_thread_sleep(500000); /* sleep for 0.5 second */ if (count > 2000) { return(false); } goto loop; #else int ret; ret = unlink(name); if (ret != 0 && errno != ENOENT) { os_file_handle_error_no_exit(name, "delete", FALSE); return(false); } return(true); #endif /* __WIN__ */ } /***********************************************************************//** Deletes a file. The file has to be closed before calling this. @return TRUE if success */ UNIV_INTERN bool os_file_delete_func( /*================*/ const char* name) /*!< in: file path as a null-terminated string */ { #ifdef __WIN__ BOOL ret; ulint count = 0; loop: /* In Windows, deleting an .ibd file may fail if mysqlbackup is copying it */ ret = DeleteFile((LPCTSTR) name); if (ret) { return(true); } if (GetLastError() == ERROR_FILE_NOT_FOUND) { /* If the file does not exist, we classify this as a 'mild' error and return */ return(false); } count++; if (count > 100 && 0 == (count % 10)) { os_file_get_last_error(true); /* print error information */ fprintf(stderr, "InnoDB: Warning: cannot delete file %s\n" "InnoDB: Are you running mysqlbackup" " to back up the file?\n", name); } os_thread_sleep(1000000); /* sleep for a second */ if (count > 2000) { return(false); } goto loop; #else int ret; ret = unlink(name); if (ret != 0) { os_file_handle_error_no_exit(name, "delete", FALSE); return(false); } return(true); #endif } /***********************************************************************//** NOTE! Use the corresponding macro os_file_rename(), not directly this function! Renames a file (can also move it to another directory). It is safest that the file is closed before calling this function. @return TRUE if success */ UNIV_INTERN ibool os_file_rename_func( /*================*/ const char* oldpath,/*!< in: old file path as a null-terminated string */ const char* newpath)/*!< in: new file path */ { #ifdef UNIV_DEBUG os_file_type_t type; ibool exists; /* New path must not exist. */ ut_ad(os_file_status(newpath, &exists, &type)); ut_ad(!exists); /* Old path must exist. */ ut_ad(os_file_status(oldpath, &exists, &type)); ut_ad(exists); #endif /* UNIV_DEBUG */ #ifdef __WIN__ BOOL ret; ret = MoveFile((LPCTSTR) oldpath, (LPCTSTR) newpath); if (ret) { return(TRUE); } os_file_handle_error_no_exit(oldpath, "rename", FALSE); return(FALSE); #else int ret; ret = rename(oldpath, newpath); if (ret != 0) { os_file_handle_error_no_exit(oldpath, "rename", FALSE); return(FALSE); } return(TRUE); #endif /* __WIN__ */ } /***********************************************************************//** NOTE! Use the corresponding macro os_file_close(), not directly this function! Closes a file handle. In case of error, error number can be retrieved with os_file_get_last_error. @return TRUE if success */ UNIV_INTERN ibool os_file_close_func( /*===============*/ os_file_t file) /*!< in, own: handle to a file */ { #ifdef __WIN__ BOOL ret; ret = CloseHandle(file); if (ret) { return(TRUE); } os_file_handle_error(NULL, "close"); return(FALSE); #else int ret; ret = close(file); if (ret == -1) { os_file_handle_error(NULL, "close"); return(FALSE); } return(TRUE); #endif /* __WIN__ */ } #ifdef UNIV_HOTBACKUP /***********************************************************************//** Closes a file handle. @return TRUE if success */ UNIV_INTERN ibool os_file_close_no_error_handling( /*============================*/ os_file_t file) /*!< in, own: handle to a file */ { #ifdef __WIN__ BOOL ret; ret = CloseHandle(file); if (ret) { return(TRUE); } return(FALSE); #else int ret; ret = close(file); if (ret == -1) { return(FALSE); } return(TRUE); #endif /* __WIN__ */ } #endif /* UNIV_HOTBACKUP */ /***********************************************************************//** Gets a file size. @return file size, or (os_offset_t) -1 on failure */ UNIV_INTERN os_offset_t os_file_get_size( /*=============*/ os_file_t file) /*!< in: handle to a file */ { #ifdef __WIN__ os_offset_t offset; DWORD high; DWORD low; low = GetFileSize(file, &high); if ((low == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) { return((os_offset_t) -1); } offset = (os_offset_t) low | ((os_offset_t) high << 32); return(offset); #else return((os_offset_t) lseek(file, 0, SEEK_END)); #endif /* __WIN__ */ } /***********************************************************************//** Write the specified number of zeros to a newly created file. @return TRUE if success */ UNIV_INTERN ibool os_file_set_size( /*=============*/ const char* name, /*!< in: name of the file or path as a null-terminated string */ os_file_t file, /*!< in: handle to a file */ os_offset_t size) /*!< in: file size */ { ibool ret; byte* buf; byte* buf2; ulint buf_size; #ifdef HAVE_POSIX_FALLOCATE if (srv_use_posix_fallocate) { int err; do { err = posix_fallocate(file, 0, size); } while (err == EINTR && srv_shutdown_state == SRV_SHUTDOWN_NONE); if (err) { ib_logf(IB_LOG_LEVEL_ERROR, "preallocating " INT64PF " bytes for" "file %s failed with error %d", size, name, err); } return(!err); } #endif #ifdef _WIN32 /* Write 1 page of zeroes at the desired end. */ buf_size = UNIV_PAGE_SIZE; os_offset_t current_size = size - buf_size; #else /* Write up to 1 megabyte at a time. */ buf_size = ut_min(64, (ulint) (size / UNIV_PAGE_SIZE)) * UNIV_PAGE_SIZE; os_offset_t current_size = 0; #endif buf2 = static_cast<byte*>(calloc(1, buf_size + UNIV_PAGE_SIZE)); if (!buf2) { ib_logf(IB_LOG_LEVEL_ERROR, "Cannot allocate " ULINTPF " bytes to extend file\n", buf_size + UNIV_PAGE_SIZE); return(FALSE); } /* Align the buffer for possible raw i/o */ buf = static_cast<byte*>(ut_align(buf2, UNIV_PAGE_SIZE)); do { ulint n_bytes; if (size - current_size < (os_offset_t) buf_size) { n_bytes = (ulint) (size - current_size); } else { n_bytes = buf_size; } ret = os_file_write(name, file, buf, current_size, n_bytes); if (!ret) { break; } current_size += n_bytes; } while (current_size < size); free(buf2); return(ret && os_file_flush(file)); } /***********************************************************************//** Truncates a file at its current position. @return TRUE if success */ UNIV_INTERN ibool os_file_set_eof( /*============*/ FILE* file) /*!< in: file to be truncated */ { #ifdef __WIN__ HANDLE h = (HANDLE) _get_osfhandle(fileno(file)); return(SetEndOfFile(h)); #else /* __WIN__ */ return(!ftruncate(fileno(file), ftell(file))); #endif /* __WIN__ */ } #ifndef __WIN__ /***********************************************************************//** Wrapper to fsync(2) that retries the call on some errors. Returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error. @return 0 if success, -1 otherwise */ static int os_file_fsync( /*==========*/ os_file_t file) /*!< in: handle to a file */ { int ret; int failures; ibool retry; failures = 0; do { ret = fsync(file); os_n_fsyncs++; if (ret == -1 && errno == ENOLCK) { if (failures % 100 == 0) { ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: fsync(): " "No locks available; retrying\n"); } os_thread_sleep(200000 /* 0.2 sec */); failures++; retry = TRUE; } else { retry = FALSE; } } while (retry); return(ret); } #endif /* !__WIN__ */ /***********************************************************************//** NOTE! Use the corresponding macro os_file_flush(), not directly this function! Flushes the write buffers of a given file to the disk. @return TRUE if success */ UNIV_INTERN ibool os_file_flush_func( /*===============*/ os_file_t file) /*!< in, own: handle to a file */ { #ifdef __WIN__ BOOL ret; os_n_fsyncs++; ret = FlushFileBuffers(file); if (ret) { return(TRUE); } /* Since Windows returns ERROR_INVALID_FUNCTION if the 'file' is actually a raw device, we choose to ignore that error if we are using raw disks */ if (srv_start_raw_disk_in_use && GetLastError() == ERROR_INVALID_FUNCTION) { return(TRUE); } os_file_handle_error(NULL, "flush"); /* It is a fatal error if a file flush does not succeed, because then the database can get corrupt on disk */ ut_error; return(FALSE); #else int ret; #if defined(HAVE_DARWIN_THREADS) # ifndef F_FULLFSYNC /* The following definition is from the Mac OS X 10.3 <sys/fcntl.h> */ # define F_FULLFSYNC 51 /* fsync + ask the drive to flush to the media */ # elif F_FULLFSYNC != 51 # error "F_FULLFSYNC != 51: ABI incompatibility with Mac OS X 10.3" # endif /* Apple has disabled fsync() for internal disk drives in OS X. That caused corruption for a user when he tested a power outage. Let us in OS X use a nonstandard flush method recommended by an Apple engineer. */ if (!srv_have_fullfsync) { /* If we are not on an operating system that supports this, then fall back to a plain fsync. */ ret = os_file_fsync(file); } else { ret = fcntl(file, F_FULLFSYNC, NULL); if (ret) { /* If we are not on a file system that supports this, then fall back to a plain fsync. */ ret = os_file_fsync(file); } } #else ret = os_file_fsync(file); #endif if (ret == 0) { return(TRUE); } /* Since Linux returns EINVAL if the 'file' is actually a raw device, we choose to ignore that error if we are using raw disks */ if (srv_start_raw_disk_in_use && errno == EINVAL) { return(TRUE); } ib_logf(IB_LOG_LEVEL_ERROR, "The OS said file flush did not succeed"); os_file_handle_error(NULL, "flush"); /* It is a fatal error if a file flush does not succeed, because then the database can get corrupt on disk */ ut_error; return(FALSE); #endif } #ifndef __WIN__ /*******************************************************************//** Does a synchronous read operation in Posix. @return number of bytes read, -1 if error */ static MY_ATTRIBUTE((nonnull, warn_unused_result)) ssize_t os_file_pread( /*==========*/ os_file_t file, /*!< in: handle to a file */ void* buf, /*!< in: buffer where to read */ ulint n, /*!< in: number of bytes to read */ os_offset_t offset) /*!< in: file offset from where to read */ { off_t offs; #if defined(HAVE_PREAD) && !defined(HAVE_BROKEN_PREAD) ssize_t n_bytes; #endif /* HAVE_PREAD && !HAVE_BROKEN_PREAD */ ut_ad(n); /* If off_t is > 4 bytes in size, then we assume we can pass a 64-bit address */ offs = (off_t) offset; if (sizeof(off_t) <= 4) { if (offset != (os_offset_t) offs) { ib_logf(IB_LOG_LEVEL_ERROR, "File read at offset > 4 GB"); } } os_n_file_reads++; #if defined(HAVE_PREAD) && !defined(HAVE_BROKEN_PREAD) #if defined(HAVE_ATOMIC_BUILTINS) && UNIV_WORD_SIZE == 8 (void) os_atomic_increment_ulint(&os_n_pending_reads, 1); (void) os_atomic_increment_ulint(&os_file_n_pending_preads, 1); MONITOR_ATOMIC_INC(MONITOR_OS_PENDING_READS); #else os_mutex_enter(os_file_count_mutex); os_file_n_pending_preads++; os_n_pending_reads++; MONITOR_INC(MONITOR_OS_PENDING_READS); os_mutex_exit(os_file_count_mutex); #endif /* HAVE_ATOMIC_BUILTINS && UNIV_WORD == 8 */ n_bytes = pread(file, buf, n, offs); #if defined(HAVE_ATOMIC_BUILTINS) && UNIV_WORD_SIZE == 8 (void) os_atomic_decrement_ulint(&os_n_pending_reads, 1); (void) os_atomic_decrement_ulint(&os_file_n_pending_preads, 1); MONITOR_ATOMIC_DEC(MONITOR_OS_PENDING_READS); #else os_mutex_enter(os_file_count_mutex); os_file_n_pending_preads--; os_n_pending_reads--; MONITOR_DEC(MONITOR_OS_PENDING_READS); os_mutex_exit(os_file_count_mutex); #endif /* !HAVE_ATOMIC_BUILTINS || UNIV_WORD == 8 */ return(n_bytes); #else { off_t ret_offset; ssize_t ret; #ifndef UNIV_HOTBACKUP ulint i; #endif /* !UNIV_HOTBACKUP */ #if defined(HAVE_ATOMIC_BUILTINS) && UNIV_WORD_SIZE == 8 (void) os_atomic_increment_ulint(&os_n_pending_reads, 1); MONITOR_ATOMIC_INC(MONITOR_OS_PENDING_READS); #else os_mutex_enter(os_file_count_mutex); os_n_pending_reads++; MONITOR_INC(MONITOR_OS_PENDING_READS); os_mutex_exit(os_file_count_mutex); #endif /* HAVE_ATOMIC_BUILTINS && UNIV_WORD == 8 */ #ifndef UNIV_HOTBACKUP /* Protect the seek / read operation with a mutex */ i = ((ulint) file) % OS_FILE_N_SEEK_MUTEXES; os_mutex_enter(os_file_seek_mutexes[i]); #endif /* !UNIV_HOTBACKUP */ ret_offset = lseek(file, offs, SEEK_SET); if (ret_offset < 0) { ret = -1; } else { ret = read(file, buf, (ssize_t) n); } #ifndef UNIV_HOTBACKUP os_mutex_exit(os_file_seek_mutexes[i]); #endif /* !UNIV_HOTBACKUP */ #if defined(HAVE_ATOMIC_BUILTINS) && UNIV_WORD_SIZE == 8 (void) os_atomic_decrement_ulint(&os_n_pending_reads, 1); MONITOR_ATOIC_DEC(MONITOR_OS_PENDING_READS); #else os_mutex_enter(os_file_count_mutex); os_n_pending_reads--; MONITOR_DEC(MONITOR_OS_PENDING_READS); os_mutex_exit(os_file_count_mutex); #endif /* HAVE_ATOMIC_BUILTINS && UNIV_WORD_SIZE == 8 */ return(ret); } #endif } /*******************************************************************//** Does a synchronous write operation in Posix. @return number of bytes written, -1 if error */ static MY_ATTRIBUTE((nonnull, warn_unused_result)) ssize_t os_file_pwrite( /*===========*/ os_file_t file, /*!< in: handle to a file */ const void* buf, /*!< in: buffer from where to write */ ulint n, /*!< in: number of bytes to write */ os_offset_t offset) /*!< in: file offset where to write */ { ssize_t ret; off_t offs; ut_ad(n); ut_ad(!srv_read_only_mode); /* If off_t is > 4 bytes in size, then we assume we can pass a 64-bit address */ offs = (off_t) offset; if (sizeof(off_t) <= 4) { if (offset != (os_offset_t) offs) { ib_logf(IB_LOG_LEVEL_ERROR, "File write at offset > 4 GB."); } } os_n_file_writes++; #if defined(HAVE_PWRITE) && !defined(HAVE_BROKEN_PREAD) #if !defined(HAVE_ATOMIC_BUILTINS) || UNIV_WORD_SIZE < 8 os_mutex_enter(os_file_count_mutex); os_file_n_pending_pwrites++; os_n_pending_writes++; MONITOR_INC(MONITOR_OS_PENDING_WRITES); os_mutex_exit(os_file_count_mutex); #else (void) os_atomic_increment_ulint(&os_n_pending_writes, 1); (void) os_atomic_increment_ulint(&os_file_n_pending_pwrites, 1); MONITOR_ATOMIC_INC(MONITOR_OS_PENDING_WRITES); #endif /* !HAVE_ATOMIC_BUILTINS || UNIV_WORD < 8 */ ret = pwrite(file, buf, (ssize_t) n, offs); #if !defined(HAVE_ATOMIC_BUILTINS) || UNIV_WORD_SIZE < 8 os_mutex_enter(os_file_count_mutex); os_file_n_pending_pwrites--; os_n_pending_writes--; MONITOR_DEC(MONITOR_OS_PENDING_WRITES); os_mutex_exit(os_file_count_mutex); #else (void) os_atomic_decrement_ulint(&os_n_pending_writes, 1); (void) os_atomic_decrement_ulint(&os_file_n_pending_pwrites, 1); MONITOR_ATOMIC_DEC(MONITOR_OS_PENDING_WRITES); #endif /* !HAVE_ATOMIC_BUILTINS || UNIV_WORD < 8 */ return(ret); #else { off_t ret_offset; # ifndef UNIV_HOTBACKUP ulint i; # endif /* !UNIV_HOTBACKUP */ os_mutex_enter(os_file_count_mutex); os_n_pending_writes++; MONITOR_INC(MONITOR_OS_PENDING_WRITES); os_mutex_exit(os_file_count_mutex); # ifndef UNIV_HOTBACKUP /* Protect the seek / write operation with a mutex */ i = ((ulint) file) % OS_FILE_N_SEEK_MUTEXES; os_mutex_enter(os_file_seek_mutexes[i]); # endif /* UNIV_HOTBACKUP */ ret_offset = lseek(file, offs, SEEK_SET); if (ret_offset < 0) { ret = -1; goto func_exit; } ret = write(file, buf, (ssize_t) n); func_exit: # ifndef UNIV_HOTBACKUP os_mutex_exit(os_file_seek_mutexes[i]); # endif /* !UNIV_HOTBACKUP */ os_mutex_enter(os_file_count_mutex); os_n_pending_writes--; MONITOR_DEC(MONITOR_OS_PENDING_WRITES); os_mutex_exit(os_file_count_mutex); return(ret); } #endif /* !UNIV_HOTBACKUP */ } #endif /*******************************************************************//** NOTE! Use the corresponding macro os_file_read(), not directly this function! Requests a synchronous positioned read operation. @return TRUE if request was successful, FALSE if fail */ UNIV_INTERN ibool os_file_read_func( /*==============*/ os_file_t file, /*!< in: handle to a file */ void* buf, /*!< in: buffer where to read */ os_offset_t offset, /*!< in: file offset where to read */ ulint n) /*!< in: number of bytes to read */ { #ifdef __WIN__ BOOL ret; DWORD len; DWORD ret2; DWORD low; DWORD high; ibool retry; #ifndef UNIV_HOTBACKUP ulint i; #endif /* !UNIV_HOTBACKUP */ /* On 64-bit Windows, ulint is 64 bits. But offset and n should be no more than 32 bits. */ ut_a((n & 0xFFFFFFFFUL) == n); os_n_file_reads++; os_bytes_read_since_printout += n; try_again: ut_ad(buf); ut_ad(n > 0); low = (DWORD) offset & 0xFFFFFFFF; high = (DWORD) (offset >> 32); os_mutex_enter(os_file_count_mutex); os_n_pending_reads++; MONITOR_INC(MONITOR_OS_PENDING_READS); os_mutex_exit(os_file_count_mutex); #ifndef UNIV_HOTBACKUP /* Protect the seek / read operation with a mutex */ i = ((ulint) file) % OS_FILE_N_SEEK_MUTEXES; os_mutex_enter(os_file_seek_mutexes[i]); #endif /* !UNIV_HOTBACKUP */ ret2 = SetFilePointer( file, low, reinterpret_cast<PLONG>(&high), FILE_BEGIN); if (ret2 == 0xFFFFFFFF && GetLastError() != NO_ERROR) { #ifndef UNIV_HOTBACKUP os_mutex_exit(os_file_seek_mutexes[i]); #endif /* !UNIV_HOTBACKUP */ os_mutex_enter(os_file_count_mutex); os_n_pending_reads--; MONITOR_DEC(MONITOR_OS_PENDING_READS); os_mutex_exit(os_file_count_mutex); goto error_handling; } ret = ReadFile(file, buf, (DWORD) n, &len, NULL); #ifndef UNIV_HOTBACKUP os_mutex_exit(os_file_seek_mutexes[i]); #endif /* !UNIV_HOTBACKUP */ os_mutex_enter(os_file_count_mutex); os_n_pending_reads--; MONITOR_DEC(MONITOR_OS_PENDING_READS); os_mutex_exit(os_file_count_mutex); if (ret && len == n) { return(TRUE); } #else /* __WIN__ */ ibool retry; ssize_t ret; os_bytes_read_since_printout += n; try_again: ret = os_file_pread(file, buf, n, offset); if ((ulint) ret == n) { return(TRUE); } else if (ret == -1) { ib_logf(IB_LOG_LEVEL_ERROR, "Error in system call pread(). The operating" " system error number is %lu.",(ulint) errno); } else { /* Partial read occurred */ ib_logf(IB_LOG_LEVEL_ERROR, "Tried to read " ULINTPF " bytes at offset " UINT64PF ". Was only able to read %ld.", n, offset, (lint) ret); } #endif /* __WIN__ */ #ifdef __WIN__ error_handling: #endif retry = os_file_handle_error(NULL, "read"); if (retry) { goto try_again; } fprintf(stderr, "InnoDB: Fatal error: cannot read from file." " OS error number %lu.\n", #ifdef __WIN__ (ulong) GetLastError() #else (ulong) errno #endif /* __WIN__ */ ); fflush(stderr); ut_error; return(FALSE); } /*******************************************************************//** NOTE! Use the corresponding macro os_file_read_no_error_handling(), not directly this function! Requests a synchronous positioned read operation. This function does not do any error handling. In case of error it returns FALSE. @return TRUE if request was successful, FALSE if fail */ UNIV_INTERN ibool os_file_read_no_error_handling_func( /*================================*/ os_file_t file, /*!< in: handle to a file */ void* buf, /*!< in: buffer where to read */ os_offset_t offset, /*!< in: file offset where to read */ ulint n) /*!< in: number of bytes to read */ { #ifdef __WIN__ BOOL ret; DWORD len; DWORD ret2; DWORD low; DWORD high; ibool retry; #ifndef UNIV_HOTBACKUP ulint i; #endif /* !UNIV_HOTBACKUP */ /* On 64-bit Windows, ulint is 64 bits. But offset and n should be no more than 32 bits. */ ut_a((n & 0xFFFFFFFFUL) == n); os_n_file_reads++; os_bytes_read_since_printout += n; try_again: ut_ad(buf); ut_ad(n > 0); low = (DWORD) offset & 0xFFFFFFFF; high = (DWORD) (offset >> 32); os_mutex_enter(os_file_count_mutex); os_n_pending_reads++; MONITOR_INC(MONITOR_OS_PENDING_READS); os_mutex_exit(os_file_count_mutex); #ifndef UNIV_HOTBACKUP /* Protect the seek / read operation with a mutex */ i = ((ulint) file) % OS_FILE_N_SEEK_MUTEXES; os_mutex_enter(os_file_seek_mutexes[i]); #endif /* !UNIV_HOTBACKUP */ ret2 = SetFilePointer( file, low, reinterpret_cast<PLONG>(&high), FILE_BEGIN); if (ret2 == 0xFFFFFFFF && GetLastError() != NO_ERROR) { #ifndef UNIV_HOTBACKUP os_mutex_exit(os_file_seek_mutexes[i]); #endif /* !UNIV_HOTBACKUP */ os_mutex_enter(os_file_count_mutex); os_n_pending_reads--; MONITOR_DEC(MONITOR_OS_PENDING_READS); os_mutex_exit(os_file_count_mutex); goto error_handling; } ret = ReadFile(file, buf, (DWORD) n, &len, NULL); #ifndef UNIV_HOTBACKUP os_mutex_exit(os_file_seek_mutexes[i]); #endif /* !UNIV_HOTBACKUP */ os_mutex_enter(os_file_count_mutex); os_n_pending_reads--; MONITOR_DEC(MONITOR_OS_PENDING_READS); os_mutex_exit(os_file_count_mutex); if (ret && len == n) { return(TRUE); } #else /* __WIN__ */ ibool retry; ssize_t ret; os_bytes_read_since_printout += n; try_again: ret = os_file_pread(file, buf, n, offset); if ((ulint) ret == n) { return(TRUE); } else if (ret == -1) { ib_logf(IB_LOG_LEVEL_ERROR, "Error in system call pread(). The operating" " system error number is %lu.",(ulint) errno); } else { /* Partial read occurred */ ib_logf(IB_LOG_LEVEL_ERROR, "Tried to read " ULINTPF " bytes at offset " UINT64PF ". Was only able to read %ld.", n, offset, (lint) ret); } #endif /* __WIN__ */ #ifdef __WIN__ error_handling: #endif retry = os_file_handle_error_no_exit(NULL, "read", FALSE); if (retry) { goto try_again; } return(FALSE); } /*******************************************************************//** Rewind file to its start, read at most size - 1 bytes from it to str, and NUL-terminate str. All errors are silently ignored. This function is mostly meant to be used with temporary files. */ UNIV_INTERN void os_file_read_string( /*================*/ FILE* file, /*!< in: file to read from */ char* str, /*!< in: buffer where to read */ ulint size) /*!< in: size of buffer */ { size_t flen; if (size == 0) { return; } rewind(file); flen = fread(str, 1, size - 1, file); str[flen] = '\0'; } /*******************************************************************//** NOTE! Use the corresponding macro os_file_write(), not directly this function! Requests a synchronous write operation. @return TRUE if request was successful, FALSE if fail */ UNIV_INTERN ibool os_file_write_func( /*===============*/ const char* name, /*!< in: name of the file or path as a null-terminated string */ os_file_t file, /*!< in: handle to a file */ const void* buf, /*!< in: buffer from which to write */ os_offset_t offset, /*!< in: file offset where to write */ ulint n) /*!< in: number of bytes to write */ { ut_ad(!srv_read_only_mode); #ifdef __WIN__ BOOL ret; DWORD len; DWORD ret2; DWORD low; DWORD high; ulint n_retries = 0; ulint err; DWORD saved_error = 0; #ifndef UNIV_HOTBACKUP ulint i; #endif /* !UNIV_HOTBACKUP */ /* On 64-bit Windows, ulint is 64 bits. But offset and n should be no more than 32 bits. */ ut_a((n & 0xFFFFFFFFUL) == n); os_n_file_writes++; ut_ad(buf); ut_ad(n > 0); retry: low = (DWORD) offset & 0xFFFFFFFF; high = (DWORD) (offset >> 32); os_mutex_enter(os_file_count_mutex); os_n_pending_writes++; MONITOR_INC(MONITOR_OS_PENDING_WRITES); os_mutex_exit(os_file_count_mutex); #ifndef UNIV_HOTBACKUP /* Protect the seek / write operation with a mutex */ i = ((ulint) file) % OS_FILE_N_SEEK_MUTEXES; os_mutex_enter(os_file_seek_mutexes[i]); #endif /* !UNIV_HOTBACKUP */ ret2 = SetFilePointer( file, low, reinterpret_cast<PLONG>(&high), FILE_BEGIN); if (ret2 == 0xFFFFFFFF && GetLastError() != NO_ERROR) { #ifndef UNIV_HOTBACKUP os_mutex_exit(os_file_seek_mutexes[i]); #endif /* !UNIV_HOTBACKUP */ os_mutex_enter(os_file_count_mutex); os_n_pending_writes--; MONITOR_DEC(MONITOR_OS_PENDING_WRITES); os_mutex_exit(os_file_count_mutex); ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Error: File pointer positioning to" " file %s failed at\n" "InnoDB: offset %llu. Operating system" " error number %lu.\n" "InnoDB: Some operating system error numbers" " are described at\n" "InnoDB: " REFMAN "operating-system-error-codes.html\n", name, offset, (ulong) GetLastError()); return(FALSE); } ret = WriteFile(file, buf, (DWORD) n, &len, NULL); #ifndef UNIV_HOTBACKUP os_mutex_exit(os_file_seek_mutexes[i]); #endif /* !UNIV_HOTBACKUP */ os_mutex_enter(os_file_count_mutex); os_n_pending_writes--; MONITOR_DEC(MONITOR_OS_PENDING_WRITES); os_mutex_exit(os_file_count_mutex); if (ret && len == n) { return(TRUE); } /* If some background file system backup tool is running, then, at least in Windows 2000, we may get here a specific error. Let us retry the operation 100 times, with 1 second waits. */ if (GetLastError() == ERROR_LOCK_VIOLATION && n_retries < 100) { os_thread_sleep(1000000); n_retries++; goto retry; } if (!os_has_said_disk_full) { char *winmsg = NULL; saved_error = GetLastError(); err = (ulint) saved_error; ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Error: Write to file %s failed" " at offset %llu.\n" "InnoDB: %lu bytes should have been written," " only %lu were written.\n" "InnoDB: Operating system error number %lu.\n" "InnoDB: Check that your OS and file system" " support files of this size.\n" "InnoDB: Check also that the disk is not full" " or a disk quota exceeded.\n", name, offset, (ulong) n, (ulong) len, (ulong) err); /* Ask Windows to prepare a standard message for a GetLastError() */ FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, saved_error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&winmsg, 0, NULL); if (winmsg) { fprintf(stderr, "InnoDB: FormatMessage: Error number %lu means '%s'.\n", (ulong) saved_error, winmsg); LocalFree(winmsg); } if (strerror((int) err) != NULL) { fprintf(stderr, "InnoDB: Error number %lu means '%s'.\n", (ulong) err, strerror((int) err)); } fprintf(stderr, "InnoDB: Some operating system error numbers" " are described at\n" "InnoDB: " REFMAN "operating-system-error-codes.html\n"); os_has_said_disk_full = TRUE; } return(FALSE); #else ssize_t ret; ret = os_file_pwrite(file, buf, n, offset); if ((ulint) ret == n) { return(TRUE); } if (!os_has_said_disk_full) { ut_print_timestamp(stderr); if(ret == -1) { ib_logf(IB_LOG_LEVEL_ERROR, "Failure of system call pwrite(). Operating" " system error number is %lu.", (ulint) errno); } else { fprintf(stderr, " InnoDB: Error: Write to file %s failed" " at offset " UINT64PF ".\n" "InnoDB: %lu bytes should have been written," " only %ld were written.\n" "InnoDB: Operating system error number %lu.\n" "InnoDB: Check that your OS and file system" " support files of this size.\n" "InnoDB: Check also that the disk is not full" " or a disk quota exceeded.\n", name, offset, n, (lint) ret, (ulint) errno); } if (strerror(errno) != NULL) { fprintf(stderr, "InnoDB: Error number %d means '%s'.\n", errno, strerror(errno)); } fprintf(stderr, "InnoDB: Some operating system error numbers" " are described at\n" "InnoDB: " REFMAN "operating-system-error-codes.html\n"); os_has_said_disk_full = TRUE; } return(FALSE); #endif } /*******************************************************************//** Check the existence and type of the given file. @return TRUE if call succeeded */ UNIV_INTERN ibool os_file_status( /*===========*/ const char* path, /*!< in: pathname of the file */ ibool* exists, /*!< out: TRUE if file exists */ os_file_type_t* type) /*!< out: type of the file (if it exists) */ { #ifdef __WIN__ int ret; struct _stat64 statinfo; ret = _stat64(path, &statinfo); if (ret && (errno == ENOENT || errno == ENOTDIR || errno == ENAMETOOLONG)) { /* file does not exist */ *exists = FALSE; return(TRUE); } else if (ret) { /* file exists, but stat call failed */ os_file_handle_error_no_exit(path, "stat", FALSE); return(FALSE); } if (_S_IFDIR & statinfo.st_mode) { *type = OS_FILE_TYPE_DIR; } else if (_S_IFREG & statinfo.st_mode) { *type = OS_FILE_TYPE_FILE; } else { *type = OS_FILE_TYPE_UNKNOWN; } *exists = TRUE; return(TRUE); #else int ret; struct stat statinfo; ret = stat(path, &statinfo); if (ret && (errno == ENOENT || errno == ENOTDIR || errno == ENAMETOOLONG)) { /* file does not exist */ *exists = FALSE; return(TRUE); } else if (ret) { /* file exists, but stat call failed */ os_file_handle_error_no_exit(path, "stat", FALSE); return(FALSE); } if (S_ISDIR(statinfo.st_mode)) { *type = OS_FILE_TYPE_DIR; } else if (S_ISLNK(statinfo.st_mode)) { *type = OS_FILE_TYPE_LINK; } else if (S_ISREG(statinfo.st_mode)) { *type = OS_FILE_TYPE_FILE; } else { *type = OS_FILE_TYPE_UNKNOWN; } *exists = TRUE; return(TRUE); #endif } /*******************************************************************//** This function returns information about the specified file @return DB_SUCCESS if all OK */ UNIV_INTERN dberr_t os_file_get_status( /*===============*/ const char* path, /*!< in: pathname of the file */ os_file_stat_t* stat_info, /*!< information of a file in a directory */ bool check_rw_perm) /*!< in: for testing whether the file can be opened in RW mode */ { int ret; #ifdef __WIN__ struct _stat64 statinfo; ret = _stat64(path, &statinfo); if (ret && (errno == ENOENT || errno == ENOTDIR)) { /* file does not exist */ return(DB_NOT_FOUND); } else if (ret) { /* file exists, but stat call failed */ os_file_handle_error_no_exit(path, "stat", FALSE); return(DB_FAIL); } else if (_S_IFDIR & statinfo.st_mode) { stat_info->type = OS_FILE_TYPE_DIR; } else if (_S_IFREG & statinfo.st_mode) { DWORD access = GENERIC_READ; if (!srv_read_only_mode) { access |= GENERIC_WRITE; } stat_info->type = OS_FILE_TYPE_FILE; /* Check if we can open it in read-only mode. */ if (check_rw_perm) { HANDLE fh; fh = CreateFile( (LPCTSTR) path, // File to open access, 0, // No sharing NULL, // Default security OPEN_EXISTING, // Existing file only FILE_ATTRIBUTE_NORMAL, // Normal file NULL); // No attr. template if (fh == INVALID_HANDLE_VALUE) { stat_info->rw_perm = false; } else { stat_info->rw_perm = true; CloseHandle(fh); } } } else { stat_info->type = OS_FILE_TYPE_UNKNOWN; } #else struct stat statinfo; ret = stat(path, &statinfo); if (ret && (errno == ENOENT || errno == ENOTDIR)) { /* file does not exist */ return(DB_NOT_FOUND); } else if (ret) { /* file exists, but stat call failed */ os_file_handle_error_no_exit(path, "stat", FALSE); return(DB_FAIL); } switch (statinfo.st_mode & S_IFMT) { case S_IFDIR: stat_info->type = OS_FILE_TYPE_DIR; break; case S_IFLNK: stat_info->type = OS_FILE_TYPE_LINK; break; case S_IFBLK: /* Handle block device as regular file. */ case S_IFCHR: /* Handle character device as regular file. */ case S_IFREG: stat_info->type = OS_FILE_TYPE_FILE; break; default: stat_info->type = OS_FILE_TYPE_UNKNOWN; } if (check_rw_perm && stat_info->type == OS_FILE_TYPE_FILE) { int fh; int access; access = !srv_read_only_mode ? O_RDWR : O_RDONLY; fh = ::open(path, access, os_innodb_umask); if (fh == -1) { stat_info->rw_perm = false; } else { stat_info->rw_perm = true; close(fh); } } #endif /* _WIN_ */ stat_info->ctime = statinfo.st_ctime; stat_info->atime = statinfo.st_atime; stat_info->mtime = statinfo.st_mtime; stat_info->size = statinfo.st_size; return(DB_SUCCESS); } /* path name separator character */ #ifdef __WIN__ # define OS_FILE_PATH_SEPARATOR '\\' #else # define OS_FILE_PATH_SEPARATOR '/' #endif /****************************************************************//** This function returns a new path name after replacing the basename in an old path with a new basename. The old_path is a full path name including the extension. The tablename is in the normal form "databasename/tablename". The new base name is found after the forward slash. Both input strings are null terminated. This function allocates memory to be returned. It is the callers responsibility to free the return value after it is no longer needed. @return own: new full pathname */ UNIV_INTERN char* os_file_make_new_pathname( /*======================*/ const char* old_path, /*!< in: pathname */ const char* tablename) /*!< in: contains new base name */ { ulint dir_len; char* last_slash; char* base_name; char* new_path; ulint new_path_len; /* Split the tablename into its database and table name components. They are separated by a '/'. */ last_slash = strrchr((char*) tablename, '/'); base_name = last_slash ? last_slash + 1 : (char*) tablename; /* Find the offset of the last slash. We will strip off the old basename.ibd which starts after that slash. */ last_slash = strrchr((char*) old_path, OS_FILE_PATH_SEPARATOR); dir_len = last_slash ? last_slash - old_path : strlen(old_path); /* allocate a new path and move the old directory path to it. */ new_path_len = dir_len + strlen(base_name) + sizeof "/.ibd"; new_path = static_cast<char*>(mem_alloc(new_path_len)); memcpy(new_path, old_path, dir_len); ut_snprintf(new_path + dir_len, new_path_len - dir_len, "%c%s.ibd", OS_FILE_PATH_SEPARATOR, base_name); return(new_path); } /****************************************************************//** This function returns a remote path name by combining a data directory path provided in a DATA DIRECTORY clause with the tablename which is in the form 'database/tablename'. It strips the file basename (which is the tablename) found after the last directory in the path provided. The full filepath created will include the database name as a directory under the path provided. The filename is the tablename with the '.ibd' extension. All input and output strings are null-terminated. This function allocates memory to be returned. It is the callers responsibility to free the return value after it is no longer needed. @return own: A full pathname; data_dir_path/databasename/tablename.ibd */ UNIV_INTERN char* os_file_make_remote_pathname( /*=========================*/ const char* data_dir_path, /*!< in: pathname */ const char* tablename, /*!< in: tablename */ const char* extention) /*!< in: file extention; ibd,cfg */ { ulint data_dir_len; char* last_slash; char* new_path; ulint new_path_len; ut_ad(extention && strlen(extention) == 3); /* Find the offset of the last slash. We will strip off the old basename or tablename which starts after that slash. */ last_slash = strrchr((char*) data_dir_path, OS_FILE_PATH_SEPARATOR); data_dir_len = last_slash ? last_slash - data_dir_path : strlen(data_dir_path); /* allocate a new path and move the old directory path to it. */ new_path_len = data_dir_len + strlen(tablename) + sizeof "/." + strlen(extention); new_path = static_cast<char*>(mem_alloc(new_path_len)); memcpy(new_path, data_dir_path, data_dir_len); ut_snprintf(new_path + data_dir_len, new_path_len - data_dir_len, "%c%s.%s", OS_FILE_PATH_SEPARATOR, tablename, extention); srv_normalize_path_for_win(new_path); return(new_path); } /****************************************************************//** This function reduces a null-terminated full remote path name into the path that is sent by MySQL for DATA DIRECTORY clause. It replaces the 'databasename/tablename.ibd' found at the end of the path with just 'tablename'. Since the result is always smaller than the path sent in, no new memory is allocated. The caller should allocate memory for the path sent in. This function manipulates that path in place. If the path format is not as expected, just return. The result is used to inform a SHOW CREATE TABLE command. */ UNIV_INTERN void os_file_make_data_dir_path( /*========================*/ char* data_dir_path) /*!< in/out: full path/data_dir_path */ { char* ptr; char* tablename; ulint tablename_len; /* Replace the period before the extension with a null byte. */ ptr = strrchr((char*) data_dir_path, '.'); if (!ptr) { return; } ptr[0] = '\0'; /* The tablename starts after the last slash. */ ptr = strrchr((char*) data_dir_path, OS_FILE_PATH_SEPARATOR); if (!ptr) { return; } ptr[0] = '\0'; tablename = ptr + 1; /* The databasename starts after the next to last slash. */ ptr = strrchr((char*) data_dir_path, OS_FILE_PATH_SEPARATOR); if (!ptr) { return; } tablename_len = ut_strlen(tablename); ut_memmove(++ptr, tablename, tablename_len); ptr[tablename_len] = '\0'; } /****************************************************************//** The function os_file_dirname returns a directory component of a null-terminated pathname string. In the usual case, dirname returns the string up to, but not including, the final '/', and basename is the component following the final '/'. Trailing '/' characters are not counted as part of the pathname. If path does not contain a slash, dirname returns the string ".". Concatenating the string returned by dirname, a "/", and the basename yields a complete pathname. The return value is a copy of the directory component of the pathname. The copy is allocated from heap. It is the caller responsibility to free it after it is no longer needed. The following list of examples (taken from SUSv2) shows the strings returned by dirname and basename for different paths: path dirname basename "/usr/lib" "/usr" "lib" "/usr/" "/" "usr" "usr" "." "usr" "/" "/" "/" "." "." "." ".." "." ".." @return own: directory component of the pathname */ UNIV_INTERN char* os_file_dirname( /*============*/ const char* path) /*!< in: pathname */ { /* Find the offset of the last slash */ const char* last_slash = strrchr(path, OS_FILE_PATH_SEPARATOR); if (!last_slash) { /* No slash in the path, return "." */ return(mem_strdup(".")); } /* Ok, there is a slash */ if (last_slash == path) { /* last slash is the first char of the path */ return(mem_strdup("/")); } /* Non-trivial directory component */ return(mem_strdupl(path, last_slash - path)); } /****************************************************************//** Creates all missing subdirectories along the given path. @return TRUE if call succeeded FALSE otherwise */ UNIV_INTERN ibool os_file_create_subdirs_if_needed( /*=============================*/ const char* path) /*!< in: path name */ { if (srv_read_only_mode) { ib_logf(IB_LOG_LEVEL_ERROR, "read only mode set. Can't create subdirectories '%s'", path); return(FALSE); } char* subdir = os_file_dirname(path); if (strlen(subdir) == 1 && (*subdir == OS_FILE_PATH_SEPARATOR || *subdir == '.')) { /* subdir is root or cwd, nothing to do */ mem_free(subdir); return(TRUE); } /* Test if subdir exists */ os_file_type_t type; ibool subdir_exists; ibool success = os_file_status(subdir, &subdir_exists, &type); if (success && !subdir_exists) { /* subdir does not exist, create it */ success = os_file_create_subdirs_if_needed(subdir); if (!success) { mem_free(subdir); return(FALSE); } success = os_file_create_directory(subdir, FALSE); } mem_free(subdir); return(success); } #ifndef UNIV_HOTBACKUP /****************************************************************//** Returns a pointer to the nth slot in the aio array. @return pointer to slot */ static os_aio_slot_t* os_aio_array_get_nth_slot( /*======================*/ os_aio_array_t* array, /*!< in: aio array */ ulint index) /*!< in: index of the slot */ { ut_a(index < array->n_slots); return(&array->slots[index]); } #if defined(LINUX_NATIVE_AIO) /******************************************************************//** Creates an io_context for native linux AIO. @return TRUE on success. */ static ibool os_aio_linux_create_io_ctx( /*=======================*/ ulint max_events, /*!< in: number of events. */ io_context_t* io_ctx) /*!< out: io_ctx to initialize. */ { int ret; ulint retries = 0; retry: memset(io_ctx, 0x0, sizeof(*io_ctx)); /* Initialize the io_ctx. Tell it how many pending IO requests this context will handle. */ ret = io_setup(max_events, io_ctx); if (ret == 0) { #if defined(UNIV_AIO_DEBUG) fprintf(stderr, "InnoDB: Linux native AIO:" " initialized io_ctx for segment\n"); #endif /* Success. Return now. */ return(TRUE); } /* If we hit EAGAIN we'll make a few attempts before failing. */ switch (ret) { case -EAGAIN: if (retries == 0) { /* First time around. */ ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Warning: io_setup() failed" " with EAGAIN. Will make %d attempts" " before giving up.\n", OS_AIO_IO_SETUP_RETRY_ATTEMPTS); } if (retries < OS_AIO_IO_SETUP_RETRY_ATTEMPTS) { ++retries; fprintf(stderr, "InnoDB: Warning: io_setup() attempt" " %lu failed.\n", retries); os_thread_sleep(OS_AIO_IO_SETUP_RETRY_SLEEP); goto retry; } /* Have tried enough. Better call it a day. */ ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Error: io_setup() failed" " with EAGAIN after %d attempts.\n", OS_AIO_IO_SETUP_RETRY_ATTEMPTS); break; case -ENOSYS: ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Error: Linux Native AIO interface" " is not supported on this platform. Please" " check your OS documentation and install" " appropriate binary of InnoDB.\n"); break; default: ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Error: Linux Native AIO setup" " returned following error[%d]\n", -ret); break; } fprintf(stderr, "InnoDB: You can disable Linux Native AIO by" " setting innodb_use_native_aio = 0 in my.cnf\n"); return(FALSE); } /******************************************************************//** Checks if the system supports native linux aio. On some kernel versions where native aio is supported it won't work on tmpfs. In such cases we can't use native aio as it is not possible to mix simulated and native aio. @return: TRUE if supported, FALSE otherwise. */ static ibool os_aio_native_aio_supported(void) /*=============================*/ { int fd; io_context_t io_ctx; char name[1000]; if (!os_aio_linux_create_io_ctx(1, &io_ctx)) { /* The platform does not support native aio. */ return(FALSE); } else if (!srv_read_only_mode) { /* Now check if tmpdir supports native aio ops. */ fd = innobase_mysql_tmpfile(NULL); if (fd < 0) { ib_logf(IB_LOG_LEVEL_WARN, "Unable to create temp file to check " "native AIO support."); return(FALSE); } } else { srv_normalize_path_for_win(srv_log_group_home_dir); ulint dirnamelen = strlen(srv_log_group_home_dir); ut_a(dirnamelen < (sizeof name) - 10 - sizeof "ib_logfile"); memcpy(name, srv_log_group_home_dir, dirnamelen); /* Add a path separator if needed. */ if (dirnamelen && name[dirnamelen - 1] != SRV_PATH_SEPARATOR) { name[dirnamelen++] = SRV_PATH_SEPARATOR; } strcpy(name + dirnamelen, "ib_logfile0"); fd = ::open(name, O_RDONLY); if (fd == -1) { ib_logf(IB_LOG_LEVEL_WARN, "Unable to open \"%s\" to check " "native AIO read support.", name); return(FALSE); } } struct io_event io_event; memset(&io_event, 0x0, sizeof(io_event)); byte* buf = static_cast<byte*>(ut_malloc(UNIV_PAGE_SIZE * 2)); byte* ptr = static_cast<byte*>(ut_align(buf, UNIV_PAGE_SIZE)); struct iocb iocb; /* Suppress valgrind warning. */ memset(buf, 0x00, UNIV_PAGE_SIZE * 2); memset(&iocb, 0x0, sizeof(iocb)); struct iocb* p_iocb = &iocb; if (!srv_read_only_mode) { io_prep_pwrite(p_iocb, fd, ptr, UNIV_PAGE_SIZE, 0); } else { ut_a(UNIV_PAGE_SIZE >= 512); io_prep_pread(p_iocb, fd, ptr, 512, 0); } int err = io_submit(io_ctx, 1, &p_iocb); if (err >= 1) { /* Now collect the submitted IO request. */ err = io_getevents(io_ctx, 1, 1, &io_event, NULL); } ut_free(buf); close(fd); switch (err) { case 1: return(TRUE); case -EINVAL: case -ENOSYS: ib_logf(IB_LOG_LEVEL_ERROR, "Linux Native AIO not supported. You can either " "move %s to a file system that supports native " "AIO or you can set innodb_use_native_aio to " "FALSE to avoid this message.", srv_read_only_mode ? name : "tmpdir"); /* fall through. */ default: ib_logf(IB_LOG_LEVEL_ERROR, "Linux Native AIO check on %s returned error[%d]", srv_read_only_mode ? name : "tmpdir", -err); } return(FALSE); } #endif /* LINUX_NATIVE_AIO */ /******************************************************************//** Creates an aio wait array. Note that we return NULL in case of failure. We don't care about freeing memory here because we assume that a failure will result in server refusing to start up. @return own: aio array, NULL on failure */ static os_aio_array_t* os_aio_array_create( /*================*/ ulint n, /*!< in: maximum number of pending aio operations allowed; n must be divisible by n_segments */ ulint n_segments) /*!< in: number of segments in the aio array */ { os_aio_array_t* array; #ifdef WIN_ASYNC_IO OVERLAPPED* over; #elif defined(LINUX_NATIVE_AIO) struct io_event* io_event = NULL; #endif /* WIN_ASYNC_IO */ ut_a(n > 0); ut_a(n_segments > 0); array = static_cast<os_aio_array_t*>(ut_malloc(sizeof(*array))); memset(array, 0x0, sizeof(*array)); array->mutex = os_mutex_create(); array->not_full = os_event_create(); array->is_empty = os_event_create(); os_event_set(array->is_empty); array->n_slots = n; array->n_segments = n_segments; array->slots = static_cast<os_aio_slot_t*>( ut_malloc(n * sizeof(*array->slots))); memset(array->slots, 0x0, sizeof(n * sizeof(*array->slots))); #ifdef __WIN__ array->handles = static_cast<HANDLE*>(ut_malloc(n * sizeof(HANDLE))); #endif /* __WIN__ */ #if defined(LINUX_NATIVE_AIO) array->aio_ctx = NULL; array->aio_events = NULL; /* If we are not using native aio interface then skip this part of initialization. */ if (!srv_use_native_aio) { goto skip_native_aio; } /* Initialize the io_context array. One io_context per segment in the array. */ array->aio_ctx = static_cast<io_context**>( ut_malloc(n_segments * sizeof(*array->aio_ctx))); for (ulint i = 0; i < n_segments; ++i) { if (!os_aio_linux_create_io_ctx(n/n_segments, &array->aio_ctx[i])) { /* If something bad happened during aio setup we disable linux native aio. The disadvantage will be a small memory leak at shutdown but that's ok compared to a crash or a not working server. This frequently happens when running the test suite with many threads on a system with low fs.aio-max-nr! */ fprintf(stderr, " InnoDB: Warning: Linux Native AIO disabled " "because os_aio_linux_create_io_ctx() " "failed. To get rid of this warning you can " "try increasing system " "fs.aio-max-nr to 1048576 or larger or " "setting innodb_use_native_aio = 0 in my.cnf\n"); srv_use_native_aio = FALSE; goto skip_native_aio; } } /* Initialize the event array. One event per slot. */ io_event = static_cast<struct io_event*>( ut_malloc(n * sizeof(*io_event))); memset(io_event, 0x0, sizeof(*io_event) * n); array->aio_events = io_event; skip_native_aio: #endif /* LINUX_NATIVE_AIO */ for (ulint i = 0; i < n; i++) { os_aio_slot_t* slot; slot = os_aio_array_get_nth_slot(array, i); slot->pos = i; slot->reserved = FALSE; #ifdef WIN_ASYNC_IO slot->handle = CreateEvent(NULL,TRUE, FALSE, NULL); over = &slot->control; over->hEvent = slot->handle; array->handles[i] = over->hEvent; #elif defined(LINUX_NATIVE_AIO) memset(&slot->control, 0x0, sizeof(slot->control)); slot->n_bytes = 0; slot->ret = 0; #endif /* WIN_ASYNC_IO */ } return(array); } /************************************************************************//** Frees an aio wait array. */ static void os_aio_array_free( /*==============*/ os_aio_array_t*& array) /*!< in, own: array to free */ { #ifdef WIN_ASYNC_IO ulint i; for (i = 0; i < array->n_slots; i++) { os_aio_slot_t* slot = os_aio_array_get_nth_slot(array, i); CloseHandle(slot->handle); } #endif /* WIN_ASYNC_IO */ #ifdef __WIN__ ut_free(array->handles); #endif /* __WIN__ */ os_mutex_free(array->mutex); os_event_free(array->not_full); os_event_free(array->is_empty); #if defined(LINUX_NATIVE_AIO) if (srv_use_native_aio) { ut_free(array->aio_events); ut_free(array->aio_ctx); } #endif /* LINUX_NATIVE_AIO */ ut_free(array->slots); ut_free(array); array = 0; } /*********************************************************************** Initializes the asynchronous io system. Creates one array each for ibuf and log i/o. Also creates one array each for read and write where each array is divided logically into n_read_segs and n_write_segs respectively. The caller must create an i/o handler thread for each segment in these arrays. This function also creates the sync array. No i/o handler thread needs to be created for that */ UNIV_INTERN ibool os_aio_init( /*========*/ ulint n_per_seg, /*<! in: maximum number of pending aio operations allowed per segment */ ulint n_read_segs, /*<! in: number of reader threads */ ulint n_write_segs, /*<! in: number of writer threads */ ulint n_slots_sync) /*<! in: number of slots in the sync aio array */ { os_io_init_simple(); #if defined(LINUX_NATIVE_AIO) /* Check if native aio is supported on this system and tmpfs */ if (srv_use_native_aio && !os_aio_native_aio_supported()) { ib_logf(IB_LOG_LEVEL_WARN, "Linux Native AIO disabled."); srv_use_native_aio = FALSE; } #endif /* LINUX_NATIVE_AIO */ srv_reset_io_thread_op_info(); os_aio_read_array = os_aio_array_create( n_read_segs * n_per_seg, n_read_segs); if (os_aio_read_array == NULL) { return(FALSE); } ulint start = (srv_read_only_mode) ? 0 : 2; ulint n_segs = n_read_segs + start; /* 0 is the ibuf segment and 1 is the insert buffer segment. */ for (ulint i = start; i < n_segs; ++i) { ut_a(i < SRV_MAX_N_IO_THREADS); srv_io_thread_function[i] = "read thread"; } ulint n_segments = n_read_segs; if (!srv_read_only_mode) { os_aio_log_array = os_aio_array_create(n_per_seg, 1); if (os_aio_log_array == NULL) { return(FALSE); } ++n_segments; srv_io_thread_function[1] = "log thread"; os_aio_ibuf_array = os_aio_array_create(n_per_seg, 1); if (os_aio_ibuf_array == NULL) { return(FALSE); } ++n_segments; srv_io_thread_function[0] = "insert buffer thread"; os_aio_write_array = os_aio_array_create( n_write_segs * n_per_seg, n_write_segs); if (os_aio_write_array == NULL) { return(FALSE); } n_segments += n_write_segs; for (ulint i = start + n_read_segs; i < n_segments; ++i) { ut_a(i < SRV_MAX_N_IO_THREADS); srv_io_thread_function[i] = "write thread"; } ut_ad(n_segments >= 4); } else { ut_ad(n_segments > 0); } os_aio_sync_array = os_aio_array_create(n_slots_sync, 1); if (os_aio_sync_array == NULL) { return(FALSE); } os_aio_n_segments = n_segments; os_aio_validate(); os_last_printout = ut_time(); if (srv_use_native_aio) { return(TRUE); } os_aio_segment_wait_events = static_cast<os_event_t*>( ut_malloc(n_segments * sizeof *os_aio_segment_wait_events)); for (ulint i = 0; i < n_segments; ++i) { os_aio_segment_wait_events[i] = os_event_create(); } return(TRUE); } /*********************************************************************** Frees the asynchronous io system. */ UNIV_INTERN void os_aio_free(void) /*=============*/ { if (os_aio_ibuf_array != 0) { os_aio_array_free(os_aio_ibuf_array); } if (os_aio_log_array != 0) { os_aio_array_free(os_aio_log_array); } if (os_aio_write_array != 0) { os_aio_array_free(os_aio_write_array); } if (os_aio_sync_array != 0) { os_aio_array_free(os_aio_sync_array); } os_aio_array_free(os_aio_read_array); if (!srv_use_native_aio) { for (ulint i = 0; i < os_aio_n_segments; i++) { os_event_free(os_aio_segment_wait_events[i]); } } ut_free(os_aio_segment_wait_events); os_aio_segment_wait_events = 0; os_aio_n_segments = 0; } #ifdef WIN_ASYNC_IO /************************************************************************//** Wakes up all async i/o threads in the array in Windows async i/o at shutdown. */ static void os_aio_array_wake_win_aio_at_shutdown( /*==================================*/ os_aio_array_t* array) /*!< in: aio array */ { ulint i; for (i = 0; i < array->n_slots; i++) { SetEvent((array->slots + i)->handle); } } #endif /************************************************************************//** Wakes up all async i/o threads so that they know to exit themselves in shutdown. */ UNIV_INTERN void os_aio_wake_all_threads_at_shutdown(void) /*=====================================*/ { #ifdef WIN_ASYNC_IO /* This code wakes up all ai/o threads in Windows native aio */ os_aio_array_wake_win_aio_at_shutdown(os_aio_read_array); if (os_aio_write_array != 0) { os_aio_array_wake_win_aio_at_shutdown(os_aio_write_array); } if (os_aio_ibuf_array != 0) { os_aio_array_wake_win_aio_at_shutdown(os_aio_ibuf_array); } if (os_aio_log_array != 0) { os_aio_array_wake_win_aio_at_shutdown(os_aio_log_array); } #elif defined(LINUX_NATIVE_AIO) /* When using native AIO interface the io helper threads wait on io_getevents with a timeout value of 500ms. At each wake up these threads check the server status. No need to do anything to wake them up. */ #endif /* !WIN_ASYNC_AIO */ if (srv_use_native_aio) { return; } /* This loop wakes up all simulated ai/o threads */ for (ulint i = 0; i < os_aio_n_segments; i++) { os_event_set(os_aio_segment_wait_events[i]); } } /************************************************************************//** Waits until there are no pending writes in os_aio_write_array. There can be other, synchronous, pending writes. */ UNIV_INTERN void os_aio_wait_until_no_pending_writes(void) /*=====================================*/ { ut_ad(!srv_read_only_mode); os_event_wait(os_aio_write_array->is_empty); } /**********************************************************************//** Calculates segment number for a slot. @return segment number (which is the number used by, for example, i/o-handler threads) */ static ulint os_aio_get_segment_no_from_slot( /*============================*/ os_aio_array_t* array, /*!< in: aio wait array */ os_aio_slot_t* slot) /*!< in: slot in this array */ { ulint segment; ulint seg_len; if (array == os_aio_ibuf_array) { ut_ad(!srv_read_only_mode); segment = IO_IBUF_SEGMENT; } else if (array == os_aio_log_array) { ut_ad(!srv_read_only_mode); segment = IO_LOG_SEGMENT; } else if (array == os_aio_read_array) { seg_len = os_aio_read_array->n_slots / os_aio_read_array->n_segments; segment = (srv_read_only_mode ? 0 : 2) + slot->pos / seg_len; } else { ut_ad(!srv_read_only_mode); ut_a(array == os_aio_write_array); seg_len = os_aio_write_array->n_slots / os_aio_write_array->n_segments; segment = os_aio_read_array->n_segments + 2 + slot->pos / seg_len; } return(segment); } /**********************************************************************//** Calculates local segment number and aio array from global segment number. @return local segment number within the aio array */ static ulint os_aio_get_array_and_local_segment( /*===============================*/ os_aio_array_t** array, /*!< out: aio wait array */ ulint global_segment)/*!< in: global segment number */ { ulint segment; ut_a(global_segment < os_aio_n_segments); if (srv_read_only_mode) { *array = os_aio_read_array; return(global_segment); } else if (global_segment == IO_IBUF_SEGMENT) { *array = os_aio_ibuf_array; segment = 0; } else if (global_segment == IO_LOG_SEGMENT) { *array = os_aio_log_array; segment = 0; } else if (global_segment < os_aio_read_array->n_segments + 2) { *array = os_aio_read_array; segment = global_segment - 2; } else { *array = os_aio_write_array; segment = global_segment - (os_aio_read_array->n_segments + 2); } return(segment); } /*******************************************************************//** Requests for a slot in the aio array. If no slot is available, waits until not_full-event becomes signaled. @return pointer to slot */ static os_aio_slot_t* os_aio_array_reserve_slot( /*======================*/ ulint type, /*!< in: OS_FILE_READ or OS_FILE_WRITE */ os_aio_array_t* array, /*!< in: aio array */ fil_node_t* message1,/*!< in: message to be passed along with the aio operation */ void* message2,/*!< in: message to be passed along with the aio operation */ os_file_t file, /*!< in: file handle */ const char* name, /*!< in: name of the file or path as a null-terminated string */ void* buf, /*!< in: buffer where to read or from which to write */ os_offset_t offset, /*!< in: file offset */ ulint len) /*!< in: length of the block to read or write */ { os_aio_slot_t* slot = NULL; #ifdef WIN_ASYNC_IO OVERLAPPED* control; #elif defined(LINUX_NATIVE_AIO) struct iocb* iocb; off_t aio_offset; #endif /* WIN_ASYNC_IO */ ulint i; ulint counter; ulint slots_per_seg; ulint local_seg; #ifdef WIN_ASYNC_IO ut_a((len & 0xFFFFFFFFUL) == len); #endif /* WIN_ASYNC_IO */ /* No need of a mutex. Only reading constant fields */ slots_per_seg = array->n_slots / array->n_segments; /* We attempt to keep adjacent blocks in the same local segment. This can help in merging IO requests when we are doing simulated AIO */ local_seg = (offset >> (UNIV_PAGE_SIZE_SHIFT + 6)) % array->n_segments; loop: os_mutex_enter(array->mutex); if (array->n_reserved == array->n_slots) { os_mutex_exit(array->mutex); if (!srv_use_native_aio) { /* If the handler threads are suspended, wake them so that we get more slots */ os_aio_simulated_wake_handler_threads(); } os_event_wait(array->not_full); goto loop; } /* We start our search for an available slot from our preferred local segment and do a full scan of the array. We are guaranteed to find a slot in full scan. */ for (i = local_seg * slots_per_seg, counter = 0; counter < array->n_slots; i++, counter++) { i %= array->n_slots; slot = os_aio_array_get_nth_slot(array, i); if (slot->reserved == FALSE) { goto found; } } /* We MUST always be able to get hold of a reserved slot. */ ut_error; found: ut_a(slot->reserved == FALSE); array->n_reserved++; if (array->n_reserved == 1) { os_event_reset(array->is_empty); } if (array->n_reserved == array->n_slots) { os_event_reset(array->not_full); } slot->reserved = TRUE; slot->reservation_time = ut_time(); slot->message1 = message1; slot->message2 = message2; slot->file = file; slot->name = name; slot->len = len; slot->type = type; slot->buf = static_cast<byte*>(buf); slot->offset = offset; slot->io_already_done = FALSE; #ifdef WIN_ASYNC_IO control = &slot->control; control->Offset = (DWORD) offset & 0xFFFFFFFF; control->OffsetHigh = (DWORD) (offset >> 32); ResetEvent(slot->handle); #elif defined(LINUX_NATIVE_AIO) /* If we are not using native AIO skip this part. */ if (!srv_use_native_aio) { goto skip_native_aio; } /* Check if we are dealing with 64 bit arch. If not then make sure that offset fits in 32 bits. */ aio_offset = (off_t) offset; ut_a(sizeof(aio_offset) >= sizeof(offset) || ((os_offset_t) aio_offset) == offset); iocb = &slot->control; if (type == OS_FILE_READ) { io_prep_pread(iocb, file, buf, len, aio_offset); } else { ut_a(type == OS_FILE_WRITE); io_prep_pwrite(iocb, file, buf, len, aio_offset); } iocb->data = (void*) slot; slot->n_bytes = 0; slot->ret = 0; skip_native_aio: #endif /* LINUX_NATIVE_AIO */ os_mutex_exit(array->mutex); return(slot); } /*******************************************************************//** Frees a slot in the aio array. */ static void os_aio_array_free_slot( /*===================*/ os_aio_array_t* array, /*!< in: aio array */ os_aio_slot_t* slot) /*!< in: pointer to slot */ { os_mutex_enter(array->mutex); ut_ad(slot->reserved); slot->reserved = FALSE; array->n_reserved--; if (array->n_reserved == array->n_slots - 1) { os_event_set(array->not_full); } if (array->n_reserved == 0) { os_event_set(array->is_empty); } #ifdef WIN_ASYNC_IO ResetEvent(slot->handle); #elif defined(LINUX_NATIVE_AIO) if (srv_use_native_aio) { memset(&slot->control, 0x0, sizeof(slot->control)); slot->n_bytes = 0; slot->ret = 0; /*fprintf(stderr, "Freed up Linux native slot.\n");*/ } else { /* These fields should not be used if we are not using native AIO. */ ut_ad(slot->n_bytes == 0); ut_ad(slot->ret == 0); } #endif os_mutex_exit(array->mutex); } /**********************************************************************//** Wakes up a simulated aio i/o-handler thread if it has something to do. */ static void os_aio_simulated_wake_handler_thread( /*=================================*/ ulint global_segment) /*!< in: the number of the segment in the aio arrays */ { os_aio_array_t* array; ulint segment; ut_ad(!srv_use_native_aio); segment = os_aio_get_array_and_local_segment(&array, global_segment); ulint n = array->n_slots / array->n_segments; segment *= n; /* Look through n slots after the segment * n'th slot */ os_mutex_enter(array->mutex); for (ulint i = 0; i < n; ++i) { const os_aio_slot_t* slot; slot = os_aio_array_get_nth_slot(array, segment + i); if (slot->reserved) { /* Found an i/o request */ os_mutex_exit(array->mutex); os_event_t event; event = os_aio_segment_wait_events[global_segment]; os_event_set(event); return; } } os_mutex_exit(array->mutex); } /**********************************************************************//** Wakes up simulated aio i/o-handler threads if they have something to do. */ UNIV_INTERN void os_aio_simulated_wake_handler_threads(void) /*=======================================*/ { if (srv_use_native_aio) { /* We do not use simulated aio: do nothing */ return; } os_aio_recommend_sleep_for_read_threads = FALSE; for (ulint i = 0; i < os_aio_n_segments; i++) { os_aio_simulated_wake_handler_thread(i); } } #ifdef _WIN32 /**********************************************************************//** This function can be called if one wants to post a batch of reads and prefers an i/o-handler thread to handle them all at once later. You must call os_aio_simulated_wake_handler_threads later to ensure the threads are not left sleeping! */ UNIV_INTERN void os_aio_simulated_put_read_threads_to_sleep() { /* The idea of putting background IO threads to sleep is only for Windows when using simulated AIO. Windows XP seems to schedule background threads too eagerly to allow for coalescing during readahead requests. */ os_aio_array_t* array; if (srv_use_native_aio) { /* We do not use simulated aio: do nothing */ return; } os_aio_recommend_sleep_for_read_threads = TRUE; for (ulint i = 0; i < os_aio_n_segments; i++) { os_aio_get_array_and_local_segment(&array, i); if (array == os_aio_read_array) { os_event_reset(os_aio_segment_wait_events[i]); } } } #endif /* _WIN32 */ #if defined(LINUX_NATIVE_AIO) /*******************************************************************//** Dispatch an AIO request to the kernel. @return TRUE on success. */ static ibool os_aio_linux_dispatch( /*==================*/ os_aio_array_t* array, /*!< in: io request array. */ os_aio_slot_t* slot) /*!< in: an already reserved slot. */ { int ret; ulint io_ctx_index; struct iocb* iocb; ut_ad(slot != NULL); ut_ad(array); ut_a(slot->reserved); /* Find out what we are going to work with. The iocb struct is directly in the slot. The io_context is one per segment. */ iocb = &slot->control; io_ctx_index = (slot->pos * array->n_segments) / array->n_slots; ret = io_submit(array->aio_ctx[io_ctx_index], 1, &iocb); #if defined(UNIV_AIO_DEBUG) fprintf(stderr, "io_submit[%c] ret[%d]: slot[%p] ctx[%p] seg[%lu]\n", (slot->type == OS_FILE_WRITE) ? 'w' : 'r', ret, slot, array->aio_ctx[io_ctx_index], (ulong) io_ctx_index); #endif /* io_submit returns number of successfully queued requests or -errno. */ if (UNIV_UNLIKELY(ret != 1)) { errno = -ret; return(FALSE); } return(TRUE); } #endif /* LINUX_NATIVE_AIO */ /*******************************************************************//** NOTE! Use the corresponding macro os_aio(), not directly this function! Requests an asynchronous i/o operation. @return TRUE if request was queued successfully, FALSE if fail */ UNIV_INTERN ibool os_aio_func( /*========*/ ulint type, /*!< in: OS_FILE_READ or OS_FILE_WRITE */ ulint mode, /*!< in: OS_AIO_NORMAL, ..., possibly ORed to OS_AIO_SIMULATED_WAKE_LATER: the last flag advises this function not to wake i/o-handler threads, but the caller will do the waking explicitly later, in this way the caller can post several requests in a batch; NOTE that the batch must not be so big that it exhausts the slots in aio arrays! NOTE that a simulated batch may introduce hidden chances of deadlocks, because i/os are not actually handled until all have been posted: use with great caution! */ const char* name, /*!< in: name of the file or path as a null-terminated string */ os_file_t file, /*!< in: handle to a file */ void* buf, /*!< in: buffer where to read or from which to write */ os_offset_t offset, /*!< in: file offset where to read or write */ ulint n, /*!< in: number of bytes to read or write */ fil_node_t* message1,/*!< in: message for the aio handler (can be used to identify a completed aio operation); ignored if mode is OS_AIO_SYNC */ void* message2)/*!< in: message for the aio handler (can be used to identify a completed aio operation); ignored if mode is OS_AIO_SYNC */ { os_aio_array_t* array; os_aio_slot_t* slot; #ifdef WIN_ASYNC_IO ibool retval; BOOL ret = TRUE; DWORD len = (DWORD) n; struct fil_node_t* dummy_mess1; void* dummy_mess2; ulint dummy_type; #endif /* WIN_ASYNC_IO */ ulint wake_later; ut_ad(buf); ut_ad(n > 0); ut_ad(n % OS_FILE_LOG_BLOCK_SIZE == 0); ut_ad(offset % OS_FILE_LOG_BLOCK_SIZE == 0); ut_ad(os_aio_validate_skip()); #ifdef WIN_ASYNC_IO ut_ad((n & 0xFFFFFFFFUL) == n); #endif wake_later = mode & OS_AIO_SIMULATED_WAKE_LATER; mode = mode & (~OS_AIO_SIMULATED_WAKE_LATER); DBUG_EXECUTE_IF("ib_os_aio_func_io_failure_28", mode = OS_AIO_SYNC; os_has_said_disk_full = FALSE;); if (mode == OS_AIO_SYNC #ifdef WIN_ASYNC_IO && !srv_use_native_aio #endif /* WIN_ASYNC_IO */ ) { ibool ret; /* This is actually an ordinary synchronous read or write: no need to use an i/o-handler thread. NOTE that if we use Windows async i/o, Windows does not allow us to use ordinary synchronous os_file_read etc. on the same file, therefore we have built a special mechanism for synchronous wait in the Windows case. Also note that the Performance Schema instrumentation has been performed by current os_aio_func()'s wrapper function pfs_os_aio_func(). So we would no longer need to call Performance Schema instrumented os_file_read() and os_file_write(). Instead, we should use os_file_read_func() and os_file_write_func() */ if (type == OS_FILE_READ) { ret = os_file_read_func(file, buf, offset, n); } else { ut_ad(!srv_read_only_mode); ut_a(type == OS_FILE_WRITE); ret = os_file_write_func(name, file, buf, offset, n); DBUG_EXECUTE_IF("ib_os_aio_func_io_failure_28", os_has_said_disk_full = FALSE; ret = 0; errno = 28;); if (!ret) { os_file_handle_error_cond_exit(name, "os_file_write_func", TRUE, FALSE); } } return ret; } try_again: switch (mode) { case OS_AIO_NORMAL: if (type == OS_FILE_READ) { array = os_aio_read_array; } else { ut_ad(!srv_read_only_mode); array = os_aio_write_array; } break; case OS_AIO_IBUF: ut_ad(type == OS_FILE_READ); /* Reduce probability of deadlock bugs in connection with ibuf: do not let the ibuf i/o handler sleep */ wake_later = FALSE; if (srv_read_only_mode) { array = os_aio_read_array; } else { array = os_aio_ibuf_array; } break; case OS_AIO_LOG: if (srv_read_only_mode) { array = os_aio_read_array; } else { array = os_aio_log_array; } break; case OS_AIO_SYNC: array = os_aio_sync_array; #if defined(LINUX_NATIVE_AIO) /* In Linux native AIO we don't use sync IO array. */ ut_a(!srv_use_native_aio); #endif /* LINUX_NATIVE_AIO */ break; default: ut_error; array = NULL; /* Eliminate compiler warning */ } slot = os_aio_array_reserve_slot(type, array, message1, message2, file, name, buf, offset, n); if (type == OS_FILE_READ) { if (srv_use_native_aio) { os_n_file_reads++; os_bytes_read_since_printout += n; #ifdef WIN_ASYNC_IO ret = ReadFile(file, buf, (DWORD) n, &len, &(slot->control)); #elif defined(LINUX_NATIVE_AIO) if (!os_aio_linux_dispatch(array, slot)) { goto err_exit; } #endif /* WIN_ASYNC_IO */ } else { if (!wake_later) { os_aio_simulated_wake_handler_thread( os_aio_get_segment_no_from_slot( array, slot)); } } } else if (type == OS_FILE_WRITE) { ut_ad(!srv_read_only_mode); if (srv_use_native_aio) { os_n_file_writes++; #ifdef WIN_ASYNC_IO ret = WriteFile(file, buf, (DWORD) n, &len, &(slot->control)); #elif defined(LINUX_NATIVE_AIO) if (!os_aio_linux_dispatch(array, slot)) { goto err_exit; } #endif /* WIN_ASYNC_IO */ } else { if (!wake_later) { os_aio_simulated_wake_handler_thread( os_aio_get_segment_no_from_slot( array, slot)); } } } else { ut_error; } #ifdef WIN_ASYNC_IO if (srv_use_native_aio) { if ((ret && len == n) || (!ret && GetLastError() == ERROR_IO_PENDING)) { /* aio was queued successfully! */ if (mode == OS_AIO_SYNC) { /* We want a synchronous i/o operation on a file where we also use async i/o: in Windows we must use the same wait mechanism as for async i/o */ retval = os_aio_windows_handle( ULINT_UNDEFINED, slot->pos, &dummy_mess1, &dummy_mess2, &dummy_type); return(retval); } return(TRUE); } goto err_exit; } #endif /* WIN_ASYNC_IO */ /* aio was queued successfully! */ return(TRUE); #if defined LINUX_NATIVE_AIO || defined WIN_ASYNC_IO err_exit: #endif /* LINUX_NATIVE_AIO || WIN_ASYNC_IO */ os_aio_array_free_slot(array, slot); if (os_file_handle_error( name,type == OS_FILE_READ ? "aio read" : "aio write")) { goto try_again; } return(FALSE); } #ifdef WIN_ASYNC_IO /**********************************************************************//** This function is only used in Windows asynchronous i/o. Waits for an aio operation to complete. This function is used to wait the for completed requests. The aio array of pending requests is divided into segments. The thread specifies which segment or slot it wants to wait for. NOTE: this function will also take care of freeing the aio slot, therefore no other thread is allowed to do the freeing! @return TRUE if the aio operation succeeded */ UNIV_INTERN ibool os_aio_windows_handle( /*==================*/ ulint segment, /*!< in: the number of the segment in the aio arrays to wait for; segment 0 is the ibuf i/o thread, segment 1 the log i/o thread, then follow the non-ibuf read threads, and as the last are the non-ibuf write threads; if this is ULINT_UNDEFINED, then it means that sync aio is used, and this parameter is ignored */ ulint pos, /*!< this parameter is used only in sync aio: wait for the aio slot at this position */ fil_node_t**message1, /*!< out: the messages passed with the aio request; note that also in the case where the aio operation failed, these output parameters are valid and can be used to restart the operation, for example */ void** message2, ulint* type) /*!< out: OS_FILE_WRITE or ..._READ */ { ulint orig_seg = segment; os_aio_array_t* array; os_aio_slot_t* slot; ulint n; ulint i; ibool ret_val; BOOL ret; DWORD len; BOOL retry = FALSE; if (segment == ULINT_UNDEFINED) { segment = 0; array = os_aio_sync_array; } else { segment = os_aio_get_array_and_local_segment(&array, segment); } /* NOTE! We only access constant fields in os_aio_array. Therefore we do not have to acquire the protecting mutex yet */ ut_ad(os_aio_validate_skip()); ut_ad(segment < array->n_segments); n = array->n_slots / array->n_segments; if (array == os_aio_sync_array) { WaitForSingleObject( os_aio_array_get_nth_slot(array, pos)->handle, INFINITE); i = pos; } else { if (orig_seg != ULINT_UNDEFINED) { srv_set_io_thread_op_info(orig_seg, "wait Windows aio"); } i = WaitForMultipleObjects( (DWORD) n, array->handles + segment * n, FALSE, INFINITE); } os_mutex_enter(array->mutex); if (srv_shutdown_state == SRV_SHUTDOWN_EXIT_THREADS && array->n_reserved == 0) { *message1 = NULL; *message2 = NULL; os_mutex_exit(array->mutex); return(TRUE); } ut_a(i >= WAIT_OBJECT_0 && i <= WAIT_OBJECT_0 + n); slot = os_aio_array_get_nth_slot(array, i + segment * n); ut_a(slot->reserved); if (orig_seg != ULINT_UNDEFINED) { srv_set_io_thread_op_info( orig_seg, "get windows aio return value"); } ret = GetOverlappedResult(slot->file, &(slot->control), &len, TRUE); *message1 = slot->message1; *message2 = slot->message2; *type = slot->type; if (ret && len == slot->len) { ret_val = TRUE; } else if (os_file_handle_error(slot->name, "Windows aio")) { retry = TRUE; } else { ret_val = FALSE; } os_mutex_exit(array->mutex); if (retry) { /* retry failed read/write operation synchronously. No need to hold array->mutex. */ #ifdef UNIV_PFS_IO /* This read/write does not go through os_file_read and os_file_write APIs, need to register with performance schema explicitly here. */ struct PSI_file_locker* locker = NULL; register_pfs_file_io_begin(locker, slot->file, slot->len, (slot->type == OS_FILE_WRITE) ? PSI_FILE_WRITE : PSI_FILE_READ, __FILE__, __LINE__); #endif ut_a((slot->len & 0xFFFFFFFFUL) == slot->len); switch (slot->type) { case OS_FILE_WRITE: ret = WriteFile(slot->file, slot->buf, (DWORD) slot->len, &len, &(slot->control)); break; case OS_FILE_READ: ret = ReadFile(slot->file, slot->buf, (DWORD) slot->len, &len, &(slot->control)); break; default: ut_error; } #ifdef UNIV_PFS_IO register_pfs_file_io_end(locker, len); #endif if (!ret && GetLastError() == ERROR_IO_PENDING) { /* aio was queued successfully! We want a synchronous i/o operation on a file where we also use async i/o: in Windows we must use the same wait mechanism as for async i/o */ ret = GetOverlappedResult(slot->file, &(slot->control), &len, TRUE); } ret_val = ret && len == slot->len; } os_aio_array_free_slot(array, slot); return(ret_val); } #endif #if defined(LINUX_NATIVE_AIO) /******************************************************************//** This function is only used in Linux native asynchronous i/o. This is called from within the io-thread. If there are no completed IO requests in the slot array, the thread calls this function to collect more requests from the kernel. The io-thread waits on io_getevents(), which is a blocking call, with a timeout value. Unless the system is very heavy loaded, keeping the io-thread very busy, the io-thread will spend most of its time waiting in this function. The io-thread also exits in this function. It checks server status at each wakeup and that is why we use timed wait in io_getevents(). */ static void os_aio_linux_collect( /*=================*/ os_aio_array_t* array, /*!< in/out: slot array. */ ulint segment, /*!< in: local segment no. */ ulint seg_size) /*!< in: segment size. */ { int i; int ret; ulint start_pos; ulint end_pos; struct timespec timeout; struct io_event* events; struct io_context* io_ctx; /* sanity checks. */ ut_ad(array != NULL); ut_ad(seg_size > 0); ut_ad(segment < array->n_segments); /* Which part of event array we are going to work on. */ events = &array->aio_events[segment * seg_size]; /* Which io_context we are going to use. */ io_ctx = array->aio_ctx[segment]; /* Starting point of the segment we will be working on. */ start_pos = segment * seg_size; /* End point. */ end_pos = start_pos + seg_size; retry: /* Initialize the events. The timeout value is arbitrary. We probably need to experiment with it a little. */ memset(events, 0, sizeof(*events) * seg_size); timeout.tv_sec = 0; timeout.tv_nsec = OS_AIO_REAP_TIMEOUT; ret = io_getevents(io_ctx, 1, seg_size, events, &timeout); if (ret > 0) { for (i = 0; i < ret; i++) { os_aio_slot_t* slot; struct iocb* control; control = (struct iocb*) events[i].obj; ut_a(control != NULL); slot = (os_aio_slot_t*) control->data; /* Some sanity checks. */ ut_a(slot != NULL); ut_a(slot->reserved); #if defined(UNIV_AIO_DEBUG) fprintf(stderr, "io_getevents[%c]: slot[%p] ctx[%p]" " seg[%lu]\n", (slot->type == OS_FILE_WRITE) ? 'w' : 'r', slot, io_ctx, segment); #endif /* We are not scribbling previous segment. */ ut_a(slot->pos >= start_pos); /* We have not overstepped to next segment. */ ut_a(slot->pos < end_pos); /* Mark this request as completed. The error handling will be done in the calling function. */ os_mutex_enter(array->mutex); slot->n_bytes = events[i].res; slot->ret = events[i].res2; slot->io_already_done = TRUE; os_mutex_exit(array->mutex); } return; } if (UNIV_UNLIKELY(srv_shutdown_state == SRV_SHUTDOWN_EXIT_THREADS)) { return; } /* This error handling is for any error in collecting the IO requests. The errors, if any, for any particular IO request are simply passed on to the calling routine. */ switch (ret) { case -EAGAIN: /* Not enough resources! Try again. */ case -EINTR: /* Interrupted! I have tested the behaviour in case of an interrupt. If we have some completed IOs available then the return code will be the number of IOs. We get EINTR only if there are no completed IOs and we have been interrupted. */ case 0: /* No pending request! Go back and check again. */ goto retry; } /* All other errors should cause a trap for now. */ ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: unexpected ret_code[%d] from io_getevents()!\n", ret); ut_error; } /**********************************************************************//** This function is only used in Linux native asynchronous i/o. Waits for an aio operation to complete. This function is used to wait for the completed requests. The aio array of pending requests is divided into segments. The thread specifies which segment or slot it wants to wait for. NOTE: this function will also take care of freeing the aio slot, therefore no other thread is allowed to do the freeing! @return TRUE if the IO was successful */ UNIV_INTERN ibool os_aio_linux_handle( /*================*/ ulint global_seg, /*!< in: segment number in the aio array to wait for; segment 0 is the ibuf i/o thread, segment 1 is log i/o thread, then follow the non-ibuf read threads, and the last are the non-ibuf write threads. */ fil_node_t**message1, /*!< out: the messages passed with the */ void** message2, /*!< aio request; note that in case the aio operation failed, these output parameters are valid and can be used to restart the operation. */ ulint* type) /*!< out: OS_FILE_WRITE or ..._READ */ { ulint segment; os_aio_array_t* array; os_aio_slot_t* slot; ulint n; ulint i; ibool ret = FALSE; /* Should never be doing Sync IO here. */ ut_a(global_seg != ULINT_UNDEFINED); /* Find the array and the local segment. */ segment = os_aio_get_array_and_local_segment(&array, global_seg); n = array->n_slots / array->n_segments; /* Loop until we have found a completed request. */ for (;;) { ibool any_reserved = FALSE; os_mutex_enter(array->mutex); for (i = 0; i < n; ++i) { slot = os_aio_array_get_nth_slot( array, i + segment * n); if (!slot->reserved) { continue; } else if (slot->io_already_done) { /* Something for us to work on. */ goto found; } else { any_reserved = TRUE; } } os_mutex_exit(array->mutex); /* There is no completed request. If there is no pending request at all, and the system is being shut down, exit. */ if (UNIV_UNLIKELY (!any_reserved && srv_shutdown_state == SRV_SHUTDOWN_EXIT_THREADS)) { *message1 = NULL; *message2 = NULL; return(TRUE); } /* Wait for some request. Note that we return from wait iff we have found a request. */ srv_set_io_thread_op_info(global_seg, "waiting for completed aio requests"); os_aio_linux_collect(array, segment, n); } found: /* Note that it may be that there are more then one completed IO requests. We process them one at a time. We may have a case here to improve the performance slightly by dealing with all requests in one sweep. */ srv_set_io_thread_op_info(global_seg, "processing completed aio requests"); /* Ensure that we are scribbling only our segment. */ ut_a(i < n); ut_ad(slot != NULL); ut_ad(slot->reserved); ut_ad(slot->io_already_done); *message1 = slot->message1; *message2 = slot->message2; *type = slot->type; if (slot->ret == 0 && slot->n_bytes == (long) slot->len) { ret = TRUE; } else { errno = -slot->ret; /* os_file_handle_error does tell us if we should retry this IO. As it stands now, we don't do this retry when reaping requests from a different context than the dispatcher. This non-retry logic is the same for windows and linux native AIO. We should probably look into this to transparently re-submit the IO. */ os_file_handle_error(slot->name, "Linux aio"); ret = FALSE; } os_mutex_exit(array->mutex); os_aio_array_free_slot(array, slot); return(ret); } #endif /* LINUX_NATIVE_AIO */ /**********************************************************************//** Does simulated aio. This function should be called by an i/o-handler thread. @return TRUE if the aio operation succeeded */ UNIV_INTERN ibool os_aio_simulated_handle( /*====================*/ ulint global_segment, /*!< in: the number of the segment in the aio arrays to wait for; segment 0 is the ibuf i/o thread, segment 1 the log i/o thread, then follow the non-ibuf read threads, and as the last are the non-ibuf write threads */ fil_node_t**message1, /*!< out: the messages passed with the aio request; note that also in the case where the aio operation failed, these output parameters are valid and can be used to restart the operation, for example */ void** message2, ulint* type) /*!< out: OS_FILE_WRITE or ..._READ */ { os_aio_array_t* array; ulint segment; os_aio_slot_t* consecutive_ios[OS_AIO_MERGE_N_CONSECUTIVE]; ulint n_consecutive; ulint total_len; ulint offs; os_offset_t lowest_offset; ulint biggest_age; ulint age; byte* combined_buf; byte* combined_buf2; ibool ret; ibool any_reserved; ulint n; os_aio_slot_t* aio_slot; /* Fix compiler warning */ *consecutive_ios = NULL; segment = os_aio_get_array_and_local_segment(&array, global_segment); restart: /* NOTE! We only access constant fields in os_aio_array. Therefore we do not have to acquire the protecting mutex yet */ srv_set_io_thread_op_info(global_segment, "looking for i/o requests (a)"); ut_ad(os_aio_validate_skip()); ut_ad(segment < array->n_segments); n = array->n_slots / array->n_segments; /* Look through n slots after the segment * n'th slot */ if (array == os_aio_read_array && os_aio_recommend_sleep_for_read_threads) { /* Give other threads chance to add several i/os to the array at once. */ goto recommended_sleep; } srv_set_io_thread_op_info(global_segment, "looking for i/o requests (b)"); /* Check if there is a slot for which the i/o has already been done */ any_reserved = FALSE; os_mutex_enter(array->mutex); for (ulint i = 0; i < n; i++) { os_aio_slot_t* slot; slot = os_aio_array_get_nth_slot(array, i + segment * n); if (!slot->reserved) { continue; } else if (slot->io_already_done) { if (os_aio_print_debug) { fprintf(stderr, "InnoDB: i/o for slot %lu" " already done, returning\n", (ulong) i); } aio_slot = slot; ret = TRUE; goto slot_io_done; } else { any_reserved = TRUE; } } /* There is no completed request. If there is no pending request at all, and the system is being shut down, exit. */ if (!any_reserved && srv_shutdown_state == SRV_SHUTDOWN_EXIT_THREADS) { os_mutex_exit(array->mutex); *message1 = NULL; *message2 = NULL; return(TRUE); } n_consecutive = 0; /* If there are at least 2 seconds old requests, then pick the oldest one to prevent starvation. If several requests have the same age, then pick the one at the lowest offset. */ biggest_age = 0; lowest_offset = IB_UINT64_MAX; for (ulint i = 0; i < n; i++) { os_aio_slot_t* slot; slot = os_aio_array_get_nth_slot(array, i + segment * n); if (slot->reserved) { age = (ulint) difftime( ut_time(), slot->reservation_time); if ((age >= 2 && age > biggest_age) || (age >= 2 && age == biggest_age && slot->offset < lowest_offset)) { /* Found an i/o request */ consecutive_ios[0] = slot; n_consecutive = 1; biggest_age = age; lowest_offset = slot->offset; } } } if (n_consecutive == 0) { /* There were no old requests. Look for an i/o request at the lowest offset in the array (we ignore the high 32 bits of the offset in these heuristics) */ lowest_offset = IB_UINT64_MAX; for (ulint i = 0; i < n; i++) { os_aio_slot_t* slot; slot = os_aio_array_get_nth_slot( array, i + segment * n); if (slot->reserved && slot->offset < lowest_offset) { /* Found an i/o request */ consecutive_ios[0] = slot; n_consecutive = 1; lowest_offset = slot->offset; } } } if (n_consecutive == 0) { /* No i/o requested at the moment */ goto wait_for_io; } /* if n_consecutive != 0, then we have assigned something valid to consecutive_ios[0] */ ut_ad(n_consecutive != 0); ut_ad(consecutive_ios[0] != NULL); aio_slot = consecutive_ios[0]; /* Check if there are several consecutive blocks to read or write */ consecutive_loop: for (ulint i = 0; i < n; i++) { os_aio_slot_t* slot; slot = os_aio_array_get_nth_slot(array, i + segment * n); if (slot->reserved && slot != aio_slot && slot->offset == aio_slot->offset + aio_slot->len && slot->type == aio_slot->type && slot->file == aio_slot->file) { /* Found a consecutive i/o request */ consecutive_ios[n_consecutive] = slot; n_consecutive++; aio_slot = slot; if (n_consecutive < OS_AIO_MERGE_N_CONSECUTIVE) { goto consecutive_loop; } else { break; } } } srv_set_io_thread_op_info(global_segment, "consecutive i/o requests"); /* We have now collected n_consecutive i/o requests in the array; allocate a single buffer which can hold all data, and perform the i/o */ total_len = 0; aio_slot = consecutive_ios[0]; for (ulint i = 0; i < n_consecutive; i++) { total_len += consecutive_ios[i]->len; } if (n_consecutive == 1) { /* We can use the buffer of the i/o request */ combined_buf = aio_slot->buf; combined_buf2 = NULL; } else { combined_buf2 = static_cast<byte*>( ut_malloc(total_len + UNIV_PAGE_SIZE)); ut_a(combined_buf2); combined_buf = static_cast<byte*>( ut_align(combined_buf2, UNIV_PAGE_SIZE)); } /* We release the array mutex for the time of the i/o: NOTE that this assumes that there is just one i/o-handler thread serving a single segment of slots! */ os_mutex_exit(array->mutex); if (aio_slot->type == OS_FILE_WRITE && n_consecutive > 1) { /* Copy the buffers to the combined buffer */ offs = 0; for (ulint i = 0; i < n_consecutive; i++) { ut_memcpy(combined_buf + offs, consecutive_ios[i]->buf, consecutive_ios[i]->len); offs += consecutive_ios[i]->len; } } srv_set_io_thread_op_info(global_segment, "doing file i/o"); /* Do the i/o with ordinary, synchronous i/o functions: */ if (aio_slot->type == OS_FILE_WRITE) { ut_ad(!srv_read_only_mode); ret = os_file_write( aio_slot->name, aio_slot->file, combined_buf, aio_slot->offset, total_len); DBUG_EXECUTE_IF("ib_os_aio_func_io_failure_28", os_has_said_disk_full = FALSE; ret = 0; errno = 28;); if (!ret) { os_file_handle_error_cond_exit(aio_slot->name, "os_file_write_func", TRUE, FALSE); } } else { ret = os_file_read( aio_slot->file, combined_buf, aio_slot->offset, total_len); } srv_set_io_thread_op_info(global_segment, "file i/o done"); if (aio_slot->type == OS_FILE_READ && n_consecutive > 1) { /* Copy the combined buffer to individual buffers */ offs = 0; for (ulint i = 0; i < n_consecutive; i++) { ut_memcpy(consecutive_ios[i]->buf, combined_buf + offs, consecutive_ios[i]->len); offs += consecutive_ios[i]->len; } } if (combined_buf2) { ut_free(combined_buf2); } os_mutex_enter(array->mutex); /* Mark the i/os done in slots */ for (ulint i = 0; i < n_consecutive; i++) { consecutive_ios[i]->io_already_done = TRUE; } /* We return the messages for the first slot now, and if there were several slots, the messages will be returned with subsequent calls of this function */ slot_io_done: ut_a(aio_slot->reserved); *message1 = aio_slot->message1; *message2 = aio_slot->message2; *type = aio_slot->type; os_mutex_exit(array->mutex); os_aio_array_free_slot(array, aio_slot); return(ret); wait_for_io: srv_set_io_thread_op_info(global_segment, "resetting wait event"); /* We wait here until there again can be i/os in the segment of this thread */ os_event_reset(os_aio_segment_wait_events[global_segment]); os_mutex_exit(array->mutex); recommended_sleep: srv_set_io_thread_op_info(global_segment, "waiting for i/o request"); os_event_wait(os_aio_segment_wait_events[global_segment]); goto restart; } /**********************************************************************//** Validates the consistency of an aio array. @return true if ok */ static bool os_aio_array_validate( /*==================*/ os_aio_array_t* array) /*!< in: aio wait array */ { ulint i; ulint n_reserved = 0; os_mutex_enter(array->mutex); ut_a(array->n_slots > 0); ut_a(array->n_segments > 0); for (i = 0; i < array->n_slots; i++) { os_aio_slot_t* slot; slot = os_aio_array_get_nth_slot(array, i); if (slot->reserved) { n_reserved++; ut_a(slot->len > 0); } } ut_a(array->n_reserved == n_reserved); os_mutex_exit(array->mutex); return(true); } /**********************************************************************//** Validates the consistency the aio system. @return TRUE if ok */ UNIV_INTERN ibool os_aio_validate(void) /*=================*/ { os_aio_array_validate(os_aio_read_array); if (os_aio_write_array != 0) { os_aio_array_validate(os_aio_write_array); } if (os_aio_ibuf_array != 0) { os_aio_array_validate(os_aio_ibuf_array); } if (os_aio_log_array != 0) { os_aio_array_validate(os_aio_log_array); } if (os_aio_sync_array != 0) { os_aio_array_validate(os_aio_sync_array); } return(TRUE); } /**********************************************************************//** Prints pending IO requests per segment of an aio array. We probably don't need per segment statistics but they can help us during development phase to see if the IO requests are being distributed as expected. */ static void os_aio_print_segment_info( /*======================*/ FILE* file, /*!< in: file where to print */ ulint* n_seg, /*!< in: pending IO array */ os_aio_array_t* array) /*!< in: array to process */ { ulint i; ut_ad(array); ut_ad(n_seg); ut_ad(array->n_segments > 0); if (array->n_segments == 1) { return; } fprintf(file, " ["); for (i = 0; i < array->n_segments; i++) { if (i != 0) { fprintf(file, ", "); } fprintf(file, "%lu", n_seg[i]); } fprintf(file, "] "); } /**********************************************************************//** Prints info about the aio array. */ UNIV_INTERN void os_aio_print_array( /*==============*/ FILE* file, /*!< in: file where to print */ os_aio_array_t* array) /*!< in: aio array to print */ { ulint n_reserved = 0; ulint n_res_seg[SRV_MAX_N_IO_THREADS]; os_mutex_enter(array->mutex); ut_a(array->n_slots > 0); ut_a(array->n_segments > 0); memset(n_res_seg, 0x0, sizeof(n_res_seg)); for (ulint i = 0; i < array->n_slots; ++i) { os_aio_slot_t* slot; ulint seg_no; slot = os_aio_array_get_nth_slot(array, i); seg_no = (i * array->n_segments) / array->n_slots; if (slot->reserved) { ++n_reserved; ++n_res_seg[seg_no]; ut_a(slot->len > 0); } } ut_a(array->n_reserved == n_reserved); fprintf(file, " %lu", (ulong) n_reserved); os_aio_print_segment_info(file, n_res_seg, array); os_mutex_exit(array->mutex); } /**********************************************************************//** Prints info of the aio arrays. */ UNIV_INTERN void os_aio_print( /*=========*/ FILE* file) /*!< in: file where to print */ { time_t current_time; double time_elapsed; double avg_bytes_read; for (ulint i = 0; i < srv_n_file_io_threads; ++i) { fprintf(file, "I/O thread %lu state: %s (%s)", (ulong) i, srv_io_thread_op_info[i], srv_io_thread_function[i]); #ifndef _WIN32 if (!srv_use_native_aio && os_aio_segment_wait_events[i]->is_set) { fprintf(file, " ev set"); } #endif /* _WIN32 */ fprintf(file, "\n"); } fputs("Pending normal aio reads:", file); os_aio_print_array(file, os_aio_read_array); if (os_aio_write_array != 0) { fputs(", aio writes:", file); os_aio_print_array(file, os_aio_write_array); } if (os_aio_ibuf_array != 0) { fputs(",\n ibuf aio reads:", file); os_aio_print_array(file, os_aio_ibuf_array); } if (os_aio_log_array != 0) { fputs(", log i/o's:", file); os_aio_print_array(file, os_aio_log_array); } if (os_aio_sync_array != 0) { fputs(", sync i/o's:", file); os_aio_print_array(file, os_aio_sync_array); } putc('\n', file); current_time = ut_time(); time_elapsed = 0.001 + difftime(current_time, os_last_printout); fprintf(file, "Pending flushes (fsync) log: %lu; buffer pool: %lu\n" "%lu OS file reads, %lu OS file writes, %lu OS fsyncs\n", (ulong) fil_n_pending_log_flushes, (ulong) fil_n_pending_tablespace_flushes, (ulong) os_n_file_reads, (ulong) os_n_file_writes, (ulong) os_n_fsyncs); if (os_file_n_pending_preads != 0 || os_file_n_pending_pwrites != 0) { fprintf(file, "%lu pending preads, %lu pending pwrites\n", (ulong) os_file_n_pending_preads, (ulong) os_file_n_pending_pwrites); } if (os_n_file_reads == os_n_file_reads_old) { avg_bytes_read = 0.0; } else { avg_bytes_read = (double) os_bytes_read_since_printout / (os_n_file_reads - os_n_file_reads_old); } fprintf(file, "%.2f reads/s, %lu avg bytes/read," " %.2f writes/s, %.2f fsyncs/s\n", (os_n_file_reads - os_n_file_reads_old) / time_elapsed, (ulong) avg_bytes_read, (os_n_file_writes - os_n_file_writes_old) / time_elapsed, (os_n_fsyncs - os_n_fsyncs_old) / time_elapsed); os_n_file_reads_old = os_n_file_reads; os_n_file_writes_old = os_n_file_writes; os_n_fsyncs_old = os_n_fsyncs; os_bytes_read_since_printout = 0; os_last_printout = current_time; } /**********************************************************************//** Refreshes the statistics used to print per-second averages. */ UNIV_INTERN void os_aio_refresh_stats(void) /*======================*/ { os_n_file_reads_old = os_n_file_reads; os_n_file_writes_old = os_n_file_writes; os_n_fsyncs_old = os_n_fsyncs; os_bytes_read_since_printout = 0; os_last_printout = time(NULL); } #ifdef UNIV_DEBUG /**********************************************************************//** Checks that all slots in the system have been freed, that is, there are no pending io operations. @return TRUE if all free */ UNIV_INTERN ibool os_aio_all_slots_free(void) /*=======================*/ { os_aio_array_t* array; ulint n_res = 0; array = os_aio_read_array; os_mutex_enter(array->mutex); n_res += array->n_reserved; os_mutex_exit(array->mutex); if (!srv_read_only_mode) { ut_a(os_aio_write_array == 0); array = os_aio_write_array; os_mutex_enter(array->mutex); n_res += array->n_reserved; os_mutex_exit(array->mutex); ut_a(os_aio_ibuf_array == 0); array = os_aio_ibuf_array; os_mutex_enter(array->mutex); n_res += array->n_reserved; os_mutex_exit(array->mutex); } ut_a(os_aio_log_array == 0); array = os_aio_log_array; os_mutex_enter(array->mutex); n_res += array->n_reserved; os_mutex_exit(array->mutex); array = os_aio_sync_array; os_mutex_enter(array->mutex); n_res += array->n_reserved; os_mutex_exit(array->mutex); if (n_res == 0) { return(TRUE); } return(FALSE); } #endif /* UNIV_DEBUG */ #endif /* !UNIV_HOTBACKUP */
cloudlinux/MariaDB-10.0-governor
storage/innobase/os/os0file.cc
C++
lgpl-2.1
148,531
import math, os from bup import _helpers, helpers from bup.helpers import sc_page_size _fmincore = getattr(helpers, 'fmincore', None) BLOB_MAX = 8192*4 # 8192 is the "typical" blob size for bupsplit BLOB_READ_SIZE = 1024*1024 MAX_PER_TREE = 256 progress_callback = None fanout = 16 GIT_MODE_FILE = 0100644 GIT_MODE_TREE = 040000 GIT_MODE_SYMLINK = 0120000 assert(GIT_MODE_TREE != 40000) # 0xxx should be treated as octal # The purpose of this type of buffer is to avoid copying on peek(), get(), # and eat(). We do copy the buffer contents on put(), but that should # be ok if we always only put() large amounts of data at a time. class Buf: def __init__(self): self.data = '' self.start = 0 def put(self, s): if s: self.data = buffer(self.data, self.start) + s self.start = 0 def peek(self, count): return buffer(self.data, self.start, count) def eat(self, count): self.start += count def get(self, count): v = buffer(self.data, self.start, count) self.start += count return v def used(self): return len(self.data) - self.start def _fadvise_pages_done(fd, first_page, count): assert(first_page >= 0) assert(count >= 0) if count > 0: _helpers.fadvise_done(fd, first_page * sc_page_size, count * sc_page_size) def _nonresident_page_regions(status_bytes, max_region_len=None): """Return (start_page, count) pairs in ascending start_page order for each contiguous region of nonresident pages indicated by the mincore() status_bytes. Limit the number of pages in each region to max_region_len.""" assert(max_region_len is None or max_region_len > 0) start = None for i, x in enumerate(status_bytes): in_core = x & helpers.MINCORE_INCORE if start is None: if not in_core: start = i else: count = i - start if in_core: yield (start, count) start = None elif max_region_len and count >= max_region_len: yield (start, count) start = i if start is not None: yield (start, len(status_bytes) - start) def _uncache_ours_upto(fd, offset, first_region, remaining_regions): """Uncache the pages of fd indicated by first_region and remaining_regions that are before offset, where each region is a (start_page, count) pair. The final region must have a start_page of None.""" rstart, rlen = first_region while rstart is not None and (rstart + rlen) * sc_page_size <= offset: _fadvise_pages_done(fd, rstart, rlen) rstart, rlen = next(remaining_regions, (None, None)) return (rstart, rlen) def readfile_iter(files, progress=None): for filenum,f in enumerate(files): ofs = 0 b = '' fd = rpr = rstart = rlen = None if _fmincore and hasattr(f, 'fileno'): fd = f.fileno() max_chunk = max(1, (8 * 1024 * 1024) / sc_page_size) rpr = _nonresident_page_regions(_fmincore(fd), max_chunk) rstart, rlen = next(rpr, (None, None)) while 1: if progress: progress(filenum, len(b)) b = f.read(BLOB_READ_SIZE) ofs += len(b) if rpr: rstart, rlen = _uncache_ours_upto(fd, ofs, (rstart, rlen), rpr) if not b: break yield b if rpr: rstart, rlen = _uncache_ours_upto(fd, ofs, (rstart, rlen), rpr) def _splitbuf(buf, basebits, fanbits): while 1: b = buf.peek(buf.used()) (ofs, bits) = _helpers.splitbuf(b) if ofs: if ofs > BLOB_MAX: ofs = BLOB_MAX level = 0 else: level = (bits-basebits)//fanbits # integer division buf.eat(ofs) yield buffer(b, 0, ofs), level else: break while buf.used() >= BLOB_MAX: # limit max blob size yield buf.get(BLOB_MAX), 0 def _hashsplit_iter(files, progress): assert(BLOB_READ_SIZE > BLOB_MAX) basebits = _helpers.blobbits() fanbits = int(math.log(fanout or 128, 2)) buf = Buf() for inblock in readfile_iter(files, progress): buf.put(inblock) for buf_and_level in _splitbuf(buf, basebits, fanbits): yield buf_and_level if buf.used(): yield buf.get(buf.used()), 0 def _hashsplit_iter_keep_boundaries(files, progress): for real_filenum,f in enumerate(files): if progress: def prog(filenum, nbytes): # the inner _hashsplit_iter doesn't know the real file count, # so we'll replace it here. return progress(real_filenum, nbytes) else: prog = None for buf_and_level in _hashsplit_iter([f], progress=prog): yield buf_and_level def hashsplit_iter(files, keep_boundaries, progress): if keep_boundaries: return _hashsplit_iter_keep_boundaries(files, progress) else: return _hashsplit_iter(files, progress) total_split = 0 def split_to_blobs(makeblob, files, keep_boundaries, progress): global total_split for (blob, level) in hashsplit_iter(files, keep_boundaries, progress): sha = makeblob(blob) total_split += len(blob) if progress_callback: progress_callback(len(blob)) yield (sha, len(blob), level) def _make_shalist(l): ofs = 0 l = list(l) total = sum(size for mode,sha,size, in l) vlen = len('%x' % total) shalist = [] for (mode, sha, size) in l: shalist.append((mode, '%0*x' % (vlen,ofs), sha)) ofs += size assert(ofs == total) return (shalist, total) def _squish(maketree, stacks, n): i = 0 while i < n or len(stacks[i]) >= MAX_PER_TREE: while len(stacks) <= i+1: stacks.append([]) if len(stacks[i]) == 1: stacks[i+1] += stacks[i] elif stacks[i]: (shalist, size) = _make_shalist(stacks[i]) tree = maketree(shalist) stacks[i+1].append((GIT_MODE_TREE, tree, size)) stacks[i] = [] i += 1 def split_to_shalist(makeblob, maketree, files, keep_boundaries, progress=None): sl = split_to_blobs(makeblob, files, keep_boundaries, progress) assert(fanout != 0) if not fanout: shal = [] for (sha,size,level) in sl: shal.append((GIT_MODE_FILE, sha, size)) return _make_shalist(shal)[0] else: stacks = [[]] for (sha,size,level) in sl: stacks[0].append((GIT_MODE_FILE, sha, size)) _squish(maketree, stacks, level) #log('stacks: %r\n' % [len(i) for i in stacks]) _squish(maketree, stacks, len(stacks)-1) #log('stacks: %r\n' % [len(i) for i in stacks]) return _make_shalist(stacks[-1])[0] def split_to_blob_or_tree(makeblob, maketree, files, keep_boundaries, progress=None): shalist = list(split_to_shalist(makeblob, maketree, files, keep_boundaries, progress)) if len(shalist) == 1: return (shalist[0][0], shalist[0][2]) elif len(shalist) == 0: return (GIT_MODE_FILE, makeblob('')) else: return (GIT_MODE_TREE, maketree(shalist)) def open_noatime(name): fd = _helpers.open_noatime(name) try: return os.fdopen(fd, 'rb', 1024*1024) except: try: os.close(fd) except: pass raise
jbaber/bup
lib/bup/hashsplit.py
Python
lgpl-2.1
7,757
package com.kitsu.medievalcraft.item.craftingtools.filters; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import com.kitsu.medievalcraft.Main; import com.kitsu.medievalcraft.util.CustomTab; import cpw.mods.fml.common.registry.GameRegistry; public class FineFilter extends Item { private String name = "fineFilter"; private Item item; public FineFilter() { setMaxStackSize(1); setUnlocalizedName(name); setCreativeTab(CustomTab.MedievalCraftTab); setTextureName(Main.MODID + ":" + name); setMaxDamage(300); setNoRepair(); item = this; GameRegistry.registerItem(this, name); } public boolean getIsRepairable(ItemStack p_82789_1_, ItemStack p_82789_2_) { return false; } }
kitsushadow/ForgeCraft
old_src/1.10.2/1-7-10Resources/src/main/java/com/kitsu/medievalcraft/item/craftingtools/filters/FineFilter.java
Java
lgpl-2.1
745
package com.stijnhero.forgery.common.block; import java.util.List; import com.stijnhero.forgery.Forgery; import net.minecraft.block.Block; import net.minecraft.block.BlockFence; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class BlockChimney extends Block { public BlockChimney(Material materialIn) { super(materialIn); this.setCreativeTab(Forgery.Forgery); } @Override public void addCollisionBoxesToList(World worldIn, BlockPos pos, IBlockState state, AxisAlignedBB mask, List list, Entity collidingEntity) { this.setBlockBounds(0.312F, 0.0F, 0.312F, 0.6875F, 1.0F, 0.6875F); super.addCollisionBoxesToList(worldIn, pos, state, mask, list, collidingEntity); } @Override public AxisAlignedBB getCollisionBoundingBox(World worldIn, BlockPos pos, IBlockState state) { return new AxisAlignedBB(pos.getX() + 0.312F, pos.getY() + 0.0F, pos.getZ() + 0.312F, pos.getX() + 0.6875F, pos.getY() + 1.0F, pos.getZ() + 0.6875F); } @Override public void setBlockBoundsBasedOnState(IBlockAccess worldIn, BlockPos pos) { this.setBlockBounds(0.312F, 0.0F, 0.312F, 0.6875F, 1.0F, 0.6875F); } public boolean isOpaqueCube() { return false; } public boolean isFullCube() { return false; } public boolean isPassable(IBlockAccess worldIn, BlockPos pos) { return false; } }
stijnhero/Forgery
src/main/java/com/stijnhero/forgery/common/block/BlockChimney.java
Java
lgpl-2.1
1,674
<?php /* * This file is part of EC-CUBE * * Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved. * https://www.ec-cube.co.jp/ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Plugin\Point\Event\WorkPlace; use Eccube\Event\EventArgs; use Symfony\Component\Validator\Constraints as Assert; const ENCODING = 'UTF-8'; /** * フックポイント汎用処理具象クラス * - 拡張元 : 受注メール * - 拡張項目 : メール内容 * Class ServiceMail * * @package Plugin\Point\Event\WorkPlace */ class ServiceMail extends AbstractWorkPlace { /** * メール本文の置き換え * * @param EventArgs $event * @return bool */ public function save(EventArgs $event) { $this->app['monolog.point']->addInfo('save start'); // 基本情報の取得 $message = $event->getArgument('message'); $order = $event->getArgument('Order'); // 必要情報判定 if (empty($message) || empty($order)) { return false; } $customer = $order->getCustomer(); if (empty($customer)) { return false; } // 計算ヘルパーの取得 $calculator = $this->app['eccube.plugin.point.calculate.helper.factory']; // 利用ポイントの取得と設定 $usePoint = $this->app['eccube.plugin.point.repository.point']->getLatestUsePoint($order); $usePoint = abs($usePoint); $calculator->setUsePoint($usePoint); // 計算に必要なエンティティの設定 $calculator->addEntity('Order', $order); $calculator->addEntity('Customer', $customer); // 計算値取得 $addPoint = $this->app['eccube.plugin.point.repository.point']->getLatestAddPointByOrder($order); $this->app['monolog.point']->addInfo('save add point', array( 'customer_id' => $customer->getId(), 'order_id' => $order->getId(), 'add point' => $addPoint, 'use point' => $usePoint, ) ); // メールボディ取得 $body = $message->getBody(); // エンコード方式取得 $charset = $message->getCharset(); if ($charset != ENCODING) { // 一旦UTF-8に $body = mb_convert_encoding($body, ENCODING, $charset); } // 情報置換用のキーを取得 $search = array(); preg_match_all('/合 計.*\\n/u', $body, $search); // メール本文置換 $snippet = PHP_EOL; $snippet .= PHP_EOL; $snippet .= '***********************************************'.PHP_EOL; $snippet .= ' ポイント情報 '.PHP_EOL; $snippet .= '***********************************************'.PHP_EOL; $snippet .= PHP_EOL; $snippet .= '利用ポイント:'.number_format($usePoint).' pt'.PHP_EOL; $snippet .= '加算ポイント:'.number_format($addPoint).' pt'.PHP_EOL; $snippet .= PHP_EOL; $replace = $search[0][0].$snippet; $body = preg_replace('/'.$search[0][0].'/u', $replace, $body); if ($charset != ENCODING) { // エンコーディングを元に戻す $body = mb_convert_encoding($body, $charset, ENCODING); } // メッセージにメールボディをセット $message->setBody($body); $this->app['monolog.point']->addInfo('save end'); } }
EC-CUBE/point-plugin
Event/WorkPlace/ServiceMail.php
PHP
lgpl-2.1
3,603
/* * eXist Open Source Native XML Database * Copyright (C) 2001-2014 Wolfgang M. Meier * wolfgang@exist-db.org * http://exist.sourceforge.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.dom.memtree; import org.exist.Indexer; import org.exist.Namespaces; import org.exist.dom.QName; import org.exist.dom.persistent.NodeProxy; import org.exist.xquery.Constants; import org.exist.xquery.XQueryContext; import org.w3c.dom.DOMException; import org.w3c.dom.Node; import org.xml.sax.Attributes; import javax.xml.XMLConstants; import java.util.Arrays; /** * Use this class to build a new in-memory DOM document. * * @author <a href="mailto:wolfgang@exist-db.org">Wolfgang</a> */ public class MemTreeBuilder { private final XQueryContext context; private DocumentImpl doc; private short level = 1; private int[] prevNodeInLevel; private String defaultNamespaceURI = XMLConstants.NULL_NS_URI; public MemTreeBuilder() { this(null); } public MemTreeBuilder(final XQueryContext context) { super(); this.context = context; prevNodeInLevel = new int[15]; Arrays.fill(prevNodeInLevel, -1); prevNodeInLevel[0] = 0; } /** * Returns the created document object. * * @return DOCUMENT ME! */ public DocumentImpl getDocument() { return doc; } public XQueryContext getContext() { return context; } public int getSize() { return doc.getSize(); } /** * Start building the document. */ public void startDocument() { this.doc = new DocumentImpl(context, false); } /** * Start building the document. * * @param explicitCreation DOCUMENT ME! */ public void startDocument(final boolean explicitCreation) { this.doc = new DocumentImpl(context, explicitCreation); } /** * End building the document. */ public void endDocument() { } /** * Create a new element. * * @param namespaceURI DOCUMENT ME! * @param localName DOCUMENT ME! * @param qname DOCUMENT ME! * @param attributes DOCUMENT ME! * @return the node number of the created element */ public int startElement(final String namespaceURI, String localName, final String qname, final Attributes attributes) { final int prefixIdx = qname.indexOf(':'); String prefix = null; if (context != null && !getDefaultNamespace().equals(namespaceURI == null ? XMLConstants.NULL_NS_URI : namespaceURI)) { prefix = context.getPrefixForURI(namespaceURI); } if (prefix == null) { prefix = (prefixIdx != Constants.STRING_NOT_FOUND) ? qname.substring(0, prefixIdx) : null; } if (localName.isEmpty()) { if (prefixIdx > -1) { localName = qname.substring(prefixIdx + 1); } else { localName = qname; } } final QName qn = new QName(localName, namespaceURI, prefix); return startElement(qn, attributes); } /** * Create a new element. * * @param qname DOCUMENT ME! * @param attributes DOCUMENT ME! * @return the node number of the created element */ public int startElement(final QName qname, final Attributes attributes) { final int nodeNr = doc.addNode(Node.ELEMENT_NODE, level, qname); if(attributes != null) { // parse attributes for(int i = 0; i < attributes.getLength(); i++) { final String attrQName = attributes.getQName(i); // skip xmlns-attributes and attributes in eXist's namespace if(!(attrQName.startsWith(XMLConstants.XMLNS_ATTRIBUTE))) { // || attrNS.equals(Namespaces.EXIST_NS))) { final int p = attrQName.indexOf(':'); final String attrNS = attributes.getURI(i); final String attrPrefix = (p != Constants.STRING_NOT_FOUND) ? attrQName.substring(0, p) : null; final String attrLocalName = attributes.getLocalName(i); final QName attrQn = new QName(attrLocalName, attrNS, attrPrefix); final int type = getAttribType(attrQn, attributes.getType(i)); doc.addAttribute(nodeNr, attrQn, attributes.getValue(i), type); } } } // update links if((level + 1) >= prevNodeInLevel.length) { final int[] t = new int[level + 2]; System.arraycopy(prevNodeInLevel, 0, t, 0, prevNodeInLevel.length); prevNodeInLevel = t; } final int prevNr = prevNodeInLevel[level]; // TODO: remove potential ArrayIndexOutOfBoundsException if(prevNr > -1) { doc.next[prevNr] = nodeNr; } doc.next[nodeNr] = prevNodeInLevel[level - 1]; prevNodeInLevel[level] = nodeNr; ++level; return nodeNr; } private int getAttribType(final QName qname, final String type) { if(qname.equals(Namespaces.XML_ID_QNAME) || type.equals(Indexer.ATTR_ID_TYPE)) { // an xml:id attribute. return AttrImpl.ATTR_ID_TYPE; } else if(type.equals(Indexer.ATTR_IDREF_TYPE)) { return AttrImpl.ATTR_IDREF_TYPE; } else if(type.equals(Indexer.ATTR_IDREFS_TYPE)) { return AttrImpl.ATTR_IDREFS_TYPE; } else { return AttrImpl.ATTR_CDATA_TYPE; } } /** * Close the last element created. */ public void endElement() { // System.out.println("end-element: level = " + level); prevNodeInLevel[level] = -1; --level; } public int addReferenceNode(final NodeProxy proxy) { final int lastNode = doc.getLastNode(); if((lastNode > 0) && (level == doc.getTreeLevel(lastNode))) { if((doc.getNodeType(lastNode) == Node.TEXT_NODE) && (proxy.getNodeType() == Node.TEXT_NODE)) { // if the last node is a text node, we have to append the // characters to this node. XML does not allow adjacent text nodes. doc.appendChars(lastNode, proxy.getNodeValue()); return lastNode; } if(doc.getNodeType(lastNode) == NodeImpl.REFERENCE_NODE) { // check if the previous node is a reference node. if yes, check if it is a text node final int p = doc.alpha[lastNode]; if((doc.references[p].getNodeType() == Node.TEXT_NODE) && (proxy.getNodeType() == Node.TEXT_NODE)) { // found a text node reference. create a new char sequence containing // the concatenated text of both nodes final String s = doc.references[p].getStringValue() + proxy.getStringValue(); doc.replaceReferenceNode(lastNode, s); return lastNode; } } } final int nodeNr = doc.addNode(NodeImpl.REFERENCE_NODE, level, null); doc.addReferenceNode(nodeNr, proxy); linkNode(nodeNr); return nodeNr; } public int addAttribute(final QName qname, final String value) { final int lastNode = doc.getLastNode(); //if(0 < lastNode && doc.nodeKind[lastNode] != Node.ELEMENT_NODE) { //Definitely wrong ! //lastNode = characters(value); //} else { //lastNode = doc.addAttribute(lastNode, qname, value); //} final int nodeNr = doc.addAttribute(lastNode, qname, value, getAttribType(qname, Indexer.ATTR_CDATA_TYPE)); //TODO : //1) call linkNode(nodeNr); ? //2) is there a relationship between lastNode and nodeNr ? return nodeNr; } /** * Create a new text node. * * @param ch DOCUMENT ME! * @param start DOCUMENT ME! * @param len DOCUMENT ME! * @return the node number of the created node */ public int characters(final char[] ch, final int start, final int len) { final int lastNode = doc.getLastNode(); if((lastNode > 0) && (level == doc.getTreeLevel(lastNode))) { if(doc.getNodeType(lastNode) == Node.TEXT_NODE) { // if the last node is a text node, we have to append the // characters to this node. XML does not allow adjacent text nodes. doc.appendChars(lastNode, ch, start, len); return lastNode; } if(doc.getNodeType(lastNode) == NodeImpl.REFERENCE_NODE) { // check if the previous node is a reference node. if yes, check if it is a text node final int p = doc.alpha[lastNode]; if(doc.references[p].getNodeType() == Node.TEXT_NODE) { // found a text node reference. create a new char sequence containing // the concatenated text of both nodes final StringBuilder s = new StringBuilder(doc.references[p].getStringValue()); s.append(ch, start, len); doc.replaceReferenceNode(lastNode, s); return lastNode; } // fall through and add the node below } } final int nodeNr = doc.addNode(Node.TEXT_NODE, level, null); doc.addChars(nodeNr, ch, start, len); linkNode(nodeNr); return nodeNr; } /** * Create a new text node. * * @param s DOCUMENT ME! * @return the node number of the created node, -1 if no node was created */ public int characters(final CharSequence s) { if(s == null) { return -1; } final int lastNode = doc.getLastNode(); if((lastNode > 0) && (level == doc.getTreeLevel(lastNode))) { if((doc.getNodeType(lastNode) == Node.TEXT_NODE) || (doc.getNodeType(lastNode) == Node.CDATA_SECTION_NODE)) { // if the last node is a text node, we have to append the // characters to this node. XML does not allow adjacent text nodes. doc.appendChars(lastNode, s); return lastNode; } if(doc.getNodeType(lastNode) == NodeImpl.REFERENCE_NODE) { // check if the previous node is a reference node. if yes, check if it is a text node final int p = doc.alpha[lastNode]; if((doc.references[p].getNodeType() == Node.TEXT_NODE) || (doc.references[p].getNodeType() == Node.CDATA_SECTION_NODE)) { // found a text node reference. create a new char sequence containing // the concatenated text of both nodes doc.replaceReferenceNode(lastNode, doc.references[p].getStringValue() + s); return lastNode; } // fall through and add the node below } } final int nodeNr = doc.addNode(Node.TEXT_NODE, level, null); doc.addChars(nodeNr, s); linkNode(nodeNr); return nodeNr; } public int comment(final CharSequence data) { final int nodeNr = doc.addNode(Node.COMMENT_NODE, level, null); doc.addChars(nodeNr, data); linkNode(nodeNr); return nodeNr; } public int comment(final char[] ch, final int start, final int len) { final int nodeNr = doc.addNode(Node.COMMENT_NODE, level, null); doc.addChars(nodeNr, ch, start, len); linkNode(nodeNr); return nodeNr; } public int cdataSection(final CharSequence data) { final int lastNode = doc.getLastNode(); if((lastNode > 0) && (level == doc.getTreeLevel(lastNode))) { if((doc.getNodeType(lastNode) == Node.TEXT_NODE) || (doc.getNodeType(lastNode) == Node.CDATA_SECTION_NODE)) { // if the last node is a text node, we have to append the // characters to this node. XML does not allow adjacent text nodes. doc.appendChars(lastNode, data); return lastNode; } if(doc.getNodeType(lastNode) == NodeImpl.REFERENCE_NODE) { // check if the previous node is a reference node. if yes, check if it is a text node final int p = doc.alpha[lastNode]; if((doc.references[p].getNodeType() == Node.TEXT_NODE) || (doc.references[p].getNodeType() == Node.CDATA_SECTION_NODE)) { // found a text node reference. create a new char sequence containing // the concatenated text of both nodes doc.replaceReferenceNode(lastNode, doc.references[p].getStringValue() + data); return lastNode; } // fall through and add the node below } } final int nodeNr = doc.addNode(Node.CDATA_SECTION_NODE, level, null); doc.addChars(nodeNr, data); linkNode(nodeNr); return nodeNr; } public int processingInstruction(final String target, final String data) { final QName qname = new QName(target, null, null); final int nodeNr = doc.addNode(Node.PROCESSING_INSTRUCTION_NODE, level, qname); doc.addChars(nodeNr, (data == null) ? "" : data); linkNode(nodeNr); return nodeNr; } public int namespaceNode(final String prefix, final String uri) { final QName qname; if(prefix == null || prefix.isEmpty()) { qname = new QName(XMLConstants.XMLNS_ATTRIBUTE, uri); } else { qname = new QName(prefix, uri, XMLConstants.XMLNS_ATTRIBUTE); } return namespaceNode(qname); } public int namespaceNode(final QName qname) { return namespaceNode(qname, false); } public int namespaceNode(final QName qname, final boolean checkNS) { final int lastNode = doc.getLastNode(); boolean addNode = true; if(doc.nodeName != null) { final QName elemQN = doc.nodeName[lastNode]; if(elemQN != null) { final String elemPrefix = (elemQN.getPrefix() == null) ? XMLConstants.DEFAULT_NS_PREFIX : elemQN.getPrefix(); final String elemNs = (elemQN.getNamespaceURI() == null) ? XMLConstants.NULL_NS_URI : elemQN.getNamespaceURI(); final String qnPrefix = (qname.getPrefix() == null) ? XMLConstants.DEFAULT_NS_PREFIX : qname.getPrefix(); if (checkNS && XMLConstants.DEFAULT_NS_PREFIX.equals(elemPrefix) && XMLConstants.NULL_NS_URI.equals(elemNs) && XMLConstants.DEFAULT_NS_PREFIX.equals(qnPrefix) && XMLConstants.XMLNS_ATTRIBUTE.equals(qname.getLocalPart())) { throw new DOMException( DOMException.NAMESPACE_ERR, "Cannot output a namespace node for the default namespace when the element is in no namespace." ); } if(elemPrefix.equals(qname.getLocalPart()) && (elemQN.getNamespaceURI() != null)) { addNode = false; } } } return (addNode ? doc.addNamespace(lastNode, qname) : -1); } public int documentType(final String publicId, final String systemId) { // int nodeNr = doc.addNode(Node.DOCUMENT_TYPE_NODE, level, null); // doc.addChars(nodeNr, data); // linkNode(nodeNr); // return nodeNr; return -1; } public void documentType(final String name, final String publicId, final String systemId) { } private void linkNode(final int nodeNr) { final int prevNr = prevNodeInLevel[level]; if(prevNr > -1) { doc.next[prevNr] = nodeNr; } doc.next[nodeNr] = prevNodeInLevel[level - 1]; prevNodeInLevel[level] = nodeNr; } public void setReplaceAttributeFlag(final boolean replaceAttribute) { doc.replaceAttribute = replaceAttribute; } public void setDefaultNamespace(final String defaultNamespaceURI) { this.defaultNamespaceURI = defaultNamespaceURI; } private String getDefaultNamespace() { // guard against someone setting null as the defaultNamespaceURI return defaultNamespaceURI == null ? XMLConstants.NULL_NS_URI : defaultNamespaceURI; } }
windauer/exist
exist-core/src/main/java/org/exist/dom/memtree/MemTreeBuilder.java
Java
lgpl-2.1
17,300
/*************************************************************************** * Temporal Convergence * Copyright (C) 2017 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA **************************************************************************/ package daxum.temporalconvergence.item; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemArmor; public class ItemPhaseClothHelmet extends ItemArmor { public ItemPhaseClothHelmet() { super(ModItems.PHASE_CLOTH_ARMOR, 0, EntityEquipmentSlot.HEAD); setRegistryName("phase_cloth_helmet"); setUnlocalizedName("phase_cloth_helmet"); setCreativeTab(ModItems.TEMPCONVTAB); } }
daxum/TemporalConvergence
src/main/java/daxum/temporalconvergence/item/ItemPhaseClothHelmet.java
Java
lgpl-2.1
1,360
/** */ package net.opengis.gml311; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Multi Point Domain Type</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link net.opengis.gml311.MultiPointDomainType#getMultiPoint <em>Multi Point</em>}</li> * </ul> * * @see net.opengis.gml311.Gml311Package#getMultiPointDomainType() * @model extendedMetaData="name='MultiPointDomainType' kind='elementOnly'" * @generated */ public interface MultiPointDomainType extends DomainSetType { /** * Returns the value of the '<em><b>Multi Point</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Multi Point</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Multi Point</em>' containment reference. * @see #setMultiPoint(MultiPointType) * @see net.opengis.gml311.Gml311Package#getMultiPointDomainType_MultiPoint() * @model containment="true" * extendedMetaData="kind='element' name='MultiPoint' namespace='##targetNamespace'" * @generated */ MultiPointType getMultiPoint(); /** * Sets the value of the '{@link net.opengis.gml311.MultiPointDomainType#getMultiPoint <em>Multi Point</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Multi Point</em>' containment reference. * @see #getMultiPoint() * @generated */ void setMultiPoint(MultiPointType value); } // MultiPointDomainType
geotools/geotools
modules/ogc/net.opengis.wmts/src/net/opengis/gml311/MultiPointDomainType.java
Java
lgpl-2.1
1,714
/*! * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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. * * Copyright (c) 2002-2013 Pentaho Corporation.. All rights reserved. */ package org.pentaho.reporting.engine.classic.extensions.datasources.mondrian; import mondrian.mdx.MemberExpr; import mondrian.olap.CacheControl; import mondrian.olap.Connection; import mondrian.olap.Cube; import mondrian.olap.Exp; import mondrian.olap.Hierarchy; import mondrian.olap.Literal; import mondrian.olap.Member; import mondrian.olap.MondrianException; import mondrian.olap.MondrianProperties; import mondrian.olap.OlapElement; import mondrian.olap.Parameter; import mondrian.olap.Position; import mondrian.olap.Query; import mondrian.olap.Result; import mondrian.olap.Util; import mondrian.olap.type.MemberType; import mondrian.olap.type.NumericType; import mondrian.olap.type.SetType; import mondrian.olap.type.StringType; import mondrian.olap.type.Type; import mondrian.server.Statement; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.reporting.engine.classic.core.AbstractDataFactory; import org.pentaho.reporting.engine.classic.core.ClassicEngineBoot; import org.pentaho.reporting.engine.classic.core.DataFactory; import org.pentaho.reporting.engine.classic.core.DataFactoryContext; import org.pentaho.reporting.engine.classic.core.DataRow; import org.pentaho.reporting.engine.classic.core.ReportDataFactoryException; import org.pentaho.reporting.engine.classic.core.util.PropertyLookupParser; import org.pentaho.reporting.libraries.base.config.Configuration; import org.pentaho.reporting.libraries.base.util.CSVTokenizer; import org.pentaho.reporting.libraries.base.util.ObjectUtilities; import org.pentaho.reporting.libraries.base.util.StringUtils; import org.pentaho.reporting.libraries.formatting.FastMessageFormat; import java.lang.reflect.Array; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.Set; import java.util.regex.PatternSyntaxException; /** * This data-factory operates in Legacy-Mode providing a preprocessed view on the mondrian result. It behaves exactly as * known from the Pentaho-Platform and the Pentaho-Report-Designer. This mode of operation breaks the structure of the * resulting table as soon as new rows are returned by the server. * * @author Thomas Morgner */ public abstract class AbstractMDXDataFactory extends AbstractDataFactory { /** * The message compiler maps all named references into numeric references. */ protected static class MDXCompiler extends PropertyLookupParser { private HashSet<String> collectedParameter; private DataRow parameters; private Locale locale; /** * Default Constructor. */ protected MDXCompiler( final DataRow parameters, final Locale locale ) { if ( locale == null ) { throw new NullPointerException( "Locale must not be null" ); } if ( parameters == null ) { throw new NullPointerException( "Parameter datarow must not be null" ); } this.collectedParameter = new HashSet<String>(); this.parameters = parameters; this.locale = locale; setMarkerChar( '$' ); setOpeningBraceChar( '{' ); setClosingBraceChar( '}' ); } /** * Looks up the property with the given name. This replaces the name with the current index position. * * @param name the name of the property to look up. * @return the translated value. */ protected String lookupVariable( final String name ) { final CSVTokenizer tokenizer = new CSVTokenizer( name, false ); if ( tokenizer.hasMoreTokens() == false ) { // invalid reference .. return null; } final String parameterName = tokenizer.nextToken(); collectedParameter.add( parameterName ); final Object o = parameters.get( parameterName ); String subType = null; final StringBuilder b = new StringBuilder( name.length() + 4 ); b.append( '{' ); b.append( "0" ); while ( tokenizer.hasMoreTokens() ) { b.append( ',' ); final String token = tokenizer.nextToken(); b.append( token ); if ( subType == null ) { subType = token; } } b.append( '}' ); final String formatString = b.toString(); if ( "string".equals( subType ) ) { if ( o == null ) { return "null"; // NON-NLS } return quote( String.valueOf( o ) ); } final FastMessageFormat messageFormat = new FastMessageFormat( formatString, locale ); return messageFormat.format( new Object[] { o } ); } public Set<String> getCollectedParameter() { return Collections.unmodifiableSet( (Set<String>) collectedParameter.clone() ); } } private static final String ACCEPT_ROLES_CONFIG_KEY = "org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.role-filter.static.accept"; private static final String ACCEPT_REGEXP_CONFIG_KEY = "org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.role-filter.reg-exp.accept"; private static final String DENY_ROLE_CONFIG_KEY = "org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.role-filter.static.deny"; private static final String DENY_REGEXP_CONFIG_KEY = "org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.role-filter.reg-exp.deny"; private static final String ROLE_FILTER_ENABLE_CONFIG_KEY = "org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.role-filter.enable"; private String jdbcUser; private String jdbcUserField; private String jdbcPassword; private String jdbcPasswordField; private String dynamicSchemaProcessor; private Boolean useSchemaPool; private Boolean useContentChecksum; private Properties baseConnectionProperties; private String role; private String roleField; private CubeFileProvider cubeFileProvider; private DataSourceProvider dataSourceProvider; private MondrianConnectionProvider mondrianConnectionProvider; private String designTimeName; private transient Connection connection; private static final String[] EMPTY_QUERYNAMES = new String[ 0 ]; private static final Log logger = LogFactory.getLog( AbstractMDXDataFactory.class ); private boolean membersOnAxisSorted; public AbstractMDXDataFactory() { this.mondrianConnectionProvider = ClassicEngineBoot.getInstance().getObjectFactory().get( MondrianConnectionProvider.class ); this.baseConnectionProperties = new Properties(); } public MondrianConnectionProvider getMondrianConnectionProvider() { return mondrianConnectionProvider; } public void setMondrianConnectionProvider( final MondrianConnectionProvider mondrianConnectionProvider ) { if ( mondrianConnectionProvider == null ) { throw new NullPointerException(); } this.mondrianConnectionProvider = mondrianConnectionProvider; } public String getDynamicSchemaProcessor() { return dynamicSchemaProcessor; } public void setDynamicSchemaProcessor( final String dynamicSchemaProcessor ) { this.dynamicSchemaProcessor = dynamicSchemaProcessor; } public boolean isMembersOnAxisSorted() { return membersOnAxisSorted; } public void setMembersOnAxisSorted( final boolean membersOnAxisSorted ) { this.membersOnAxisSorted = membersOnAxisSorted; } public Boolean isUseSchemaPool() { return useSchemaPool; } public void setUseSchemaPool( final Boolean useSchemaPool ) { this.useSchemaPool = useSchemaPool; } public Boolean isUseContentChecksum() { return useContentChecksum; } public void setUseContentChecksum( final Boolean useContentChecksum ) { this.useContentChecksum = useContentChecksum; } public String getRole() { return role; } public void setRole( final String role ) { this.role = role; } public String getRoleField() { return roleField; } public void setRoleField( final String roleField ) { this.roleField = roleField; } public CubeFileProvider getCubeFileProvider() { return cubeFileProvider; } public void setCubeFileProvider( final CubeFileProvider cubeFileProvider ) { this.cubeFileProvider = cubeFileProvider; } public DataSourceProvider getDataSourceProvider() { return dataSourceProvider; } public void setDataSourceProvider( final DataSourceProvider dataSourceProvider ) { this.dataSourceProvider = dataSourceProvider; } public String getJdbcUser() { return jdbcUser; } public void setJdbcUser( final String jdbcUser ) { this.jdbcUser = jdbcUser; } public String getJdbcPassword() { return jdbcPassword; } public void setJdbcPassword( final String jdbcPassword ) { this.jdbcPassword = jdbcPassword; } public String getJdbcUserField() { return jdbcUserField; } public void setJdbcUserField( final String jdbcUserField ) { this.jdbcUserField = jdbcUserField; } public String getJdbcPasswordField() { return jdbcPasswordField; } public void setJdbcPasswordField( final String jdbcPasswordField ) { this.jdbcPasswordField = jdbcPasswordField; } public Properties getBaseConnectionProperties() { return (Properties) baseConnectionProperties.clone(); } /** * Sets base connection properties. These will be overriden by any programatically set properties. * * @param connectionProperties */ public void setBaseConnectionProperties( final Properties connectionProperties ) { if ( connectionProperties != null ) { this.baseConnectionProperties.clear(); this.baseConnectionProperties.putAll( connectionProperties ); } } /** * Checks whether the query would be executable by this datafactory. This performs a rough check, not a full query. * * @param query * @param parameters * @return */ public boolean isQueryExecutable( final String query, final DataRow parameters ) { return true; } /** * Closes the data factory and frees all resources held by this instance. */ public void close() { if ( connection != null ) { connection.close(); } connection = null; } /** * Access the cache control on a per-datasource level. Setting "onlyCurrentSchema" to true will selectively purge the * mondrian cache for the specifc schema only. * * @param parameters * @param onlyCurrentSchema * @throws ReportDataFactoryException */ public void clearCache( final DataRow parameters, final boolean onlyCurrentSchema ) throws ReportDataFactoryException { try { final Connection connection = mondrianConnectionProvider .createConnection( computeProperties( parameters ), dataSourceProvider.getDataSource() ); try { final CacheControl cacheControl = connection.getCacheControl( null ); if ( onlyCurrentSchema ) { cacheControl.flushSchema( connection.getSchema() ); } else { cacheControl.flushSchemaCache(); } } finally { connection.close(); } } catch ( SQLException e ) { logger.error( e ); throw new ReportDataFactoryException( "Failed to create DataSource (SQL Exception - error code: " + e.getErrorCode() + "):" + e.toString(), e ); } catch ( MondrianException e ) { logger.error( e ); throw new ReportDataFactoryException( "Failed to create DataSource (Mondrian Exception):" + e.toString(), e ); } } /** * Queries a datasource. The string 'query' defines the name of the query. The Parameterset given here may contain * more data than actually needed for the query. * <p/> * The parameter-dataset may change between two calls, do not assume anything, and do not hold references to the * parameter-dataset or the position of the columns in the dataset. * * @param rawMdxQuery the mdx Query string. * @param parameters the parameters for the query * @return the result of the query as table model. * @throws org.pentaho.reporting.engine.classic.core.ReportDataFactoryException if an error occured while performing * the query. */ public Result performQuery( final String rawMdxQuery, final DataRow parameters ) throws ReportDataFactoryException { try { if ( connection == null ) { connection = mondrianConnectionProvider .createConnection( computeProperties( parameters ), dataSourceProvider.getDataSource() ); } } catch ( SQLException e ) { throw new ReportDataFactoryException( "Failed to create datasource:" + e.getLocalizedMessage(), e ); } catch ( MondrianException e ) { throw new ReportDataFactoryException( "Failed to create datasource:" + e.getLocalizedMessage(), e ); } try { if ( connection == null ) { throw new ReportDataFactoryException( "Factory is closed." ); } final MDXCompiler compiler = new MDXCompiler( parameters, getLocale() ); final String mdxQuery = compiler.translateAndLookup( rawMdxQuery, parameters ); // Alternatively, JNDI is possible. Maybe even more .. final Query query = connection.parseQuery( mdxQuery ); final Statement statement = query.getStatement(); final int queryTimeoutValue = calculateQueryTimeOut( parameters ); if ( queryTimeoutValue > 0 ) { statement.setQueryTimeoutMillis( queryTimeoutValue * 1000 ); } parametrizeQuery( parameters, query ); //noinspection deprecation final Result resultSet = connection.execute( query ); if ( resultSet == null ) { throw new ReportDataFactoryException( "query returned no resultset" ); } return resultSet; } catch ( MondrianException e ) { throw new ReportDataFactoryException( "Failed to create datasource:" + e.getLocalizedMessage(), e ); } } private void parametrizeQuery( final DataRow parameters, final Query query ) throws ReportDataFactoryException { final Parameter[] parameterDefs = query.getParameters(); for ( int i = 0; i < parameterDefs.length; i++ ) { final Parameter def = parameterDefs[ i ]; final Type parameterType = def.getType(); final Object parameterValue = preprocessMemberParameter( def, parameters, parameterType ); final Object processedParamValue = computeParameterValue( query, parameterValue, parameterType ); // Mondrian allows null values to be passed in, so we'll go ahead and // convert null values to their defaults for now until MONDRIAN-745 is // resolved. final Exp exp = def.getDefaultExp(); if ( processedParamValue == null && exp != null && exp instanceof Literal ) { Literal exp1 = (Literal) exp; def.setValue( exp1.getValue() ); } else { def.setValue( processedParamValue ); } } } private Object preprocessMemberParameter( final Parameter def, final DataRow parameters, final Type parameterType ) { Object parameterValue = parameters.get( def.getName() ); // Mondrian doesn't handle null MemberType/SetType parameters well (http://jira.pentaho.com/browse/MONDRIAN-745) // If parameterValue is null, give it the default value if ( parameterValue != null ) { return parameterValue; } try { if ( parameterType instanceof MemberType || parameterType instanceof SetType ) { return def.getDefaultExp().toString(); } } catch ( final Exception e ) { // Ignore - this is a safety procedure anyway } return null; } private Object computeParameterValue( final Query query, final Object parameterValue, final Type parameterType ) throws ReportDataFactoryException { final Object processedParamValue; if ( parameterValue != null ) { if ( parameterType instanceof StringType ) { if ( !( parameterValue instanceof String ) ) { throw new ReportDataFactoryException( parameterValue + " is incorrect for type " + parameterType ); } processedParamValue = parameterValue; } else if ( parameterType instanceof NumericType ) { if ( !( parameterValue instanceof Number ) ) { throw new ReportDataFactoryException( parameterValue + " is incorrect for type " + parameterType ); } processedParamValue = parameterValue; } else if ( parameterType instanceof MemberType ) { final MemberType memberType = (MemberType) parameterType; final Hierarchy hierarchy = memberType.getHierarchy(); if ( parameterValue instanceof String ) { final Member member = findMember( query, hierarchy, query.getCube(), String.valueOf( parameterValue ) ); if ( member != null ) { processedParamValue = new MemberExpr( member ); } else { processedParamValue = null; } } else { if ( !( parameterValue instanceof OlapElement ) ) { throw new ReportDataFactoryException( parameterValue + " is incorrect for type " + parameterType ); } else { processedParamValue = parameterValue; } } } else if ( parameterType instanceof SetType ) { final SetType setType = (SetType) parameterType; final Hierarchy hierarchy = setType.getHierarchy(); if ( parameterValue instanceof String ) { final String rawString = (String) parameterValue; final String[] memberStr = rawString.replaceFirst( "^ *\\{", "" ).replaceFirst( "} *$", "" ).split( "," ); final List<Member> list = new ArrayList<Member>( memberStr.length ); for ( int j = 0; j < memberStr.length; j++ ) { final String str = memberStr[ j ]; final Member member = findMember( query, hierarchy, query.getCube(), String.valueOf( str ) ); if ( member != null ) { list.add( member ); } } processedParamValue = list; } else { if ( !( parameterValue instanceof OlapElement ) ) { throw new ReportDataFactoryException( parameterValue + " is incorrect for type " + parameterType ); } else { processedParamValue = parameterValue; } } } else { processedParamValue = parameterValue; } } else { processedParamValue = null; } return processedParamValue; } private Member findMember( final Query query, final Hierarchy hierarchy, final Cube cube, final String parameter ) throws ReportDataFactoryException { try { final Member directValue = yuckyInternalMondrianLookup( query, hierarchy, parameter ); if ( directValue != null ) { return directValue; } } catch ( Exception e ) { // It is non fatal if that fails. Invalid input has this effect. } Member memberById = null; Member memberByUniqueId = null; final boolean searchForNames = MondrianProperties.instance().NeedDimensionPrefix.get() == false; final boolean missingMembersIsFatal = MondrianProperties.instance().IgnoreInvalidMembersDuringQuery.get(); try { final Member directValue = lookupDirectly( hierarchy, cube, parameter, searchForNames ); if ( directValue != null ) { return directValue; } } catch ( Exception e ) { // It is non fatal if that fails. Invalid input has this effect. } final Query memberQuery = connection.parseQuery( "SELECT " + hierarchy.getQualifiedName() // NON-NLS + ".AllMembers ON 0, {} ON 1 FROM " + cube.getQualifiedName() ); // NON-NLS final Result result = connection.execute( memberQuery ); try { final List<Position> positionList = result.getAxes()[ 0 ].getPositions(); for ( int i = 0; i < positionList.size(); i++ ) { final Position position = positionList.get( i ); for ( int j = 0; j < position.size(); j++ ) { final Member member = position.get( j ); if ( parameter.equals( MondrianUtil.getUniqueMemberName( member ) ) ) { if ( memberByUniqueId == null ) { memberByUniqueId = member; } else { logger .warn( "Encountered a member with a duplicate unique key: " + member.getQualifiedName() ); // NON-NLS } } if ( searchForNames == false ) { continue; } if ( parameter.equals( member.getName() ) ) { if ( memberById == null ) { memberById = member; } else { logger.warn( "Encountered a member with a duplicate name: " + member.getQualifiedName() ); // NON-NLS } } } } } finally { result.close(); } if ( memberByUniqueId != null ) { return memberByUniqueId; } if ( memberById != null ) { return memberById; } if ( missingMembersIsFatal ) { throw new ReportDataFactoryException( "No member matches parameter value '" + parameter + "'." ); } return null; } private Member lookupDirectly( final Hierarchy hierarchy, final Cube cube, final String parameter, final boolean searchForNames ) { Member memberById = null; Member memberByUniqueId = null; final Query queryDirect = connection.parseQuery( "SELECT STRTOMEMBER(" + quote( parameter ) + ") ON 0, {} ON 1 FROM " // NON-NLS + cube.getQualifiedName() ); final Result resultDirect = connection.execute( queryDirect ); try { final List<Position> positionList = resultDirect.getAxes()[ 0 ].getPositions(); for ( int i = 0; i < positionList.size(); i++ ) { final Position position = positionList.get( i ); for ( int j = 0; j < position.size(); j++ ) { final Member member = position.get( j ); // If the parameter starts with '[', we'll assume we have the full // member specification specification. Otherwise, keep the funky lookup // route. We do check whether we get a second member (heck, should not // happen, but I've seen pigs fly already). if ( parameter.startsWith( "[" ) ) { if ( memberByUniqueId == null ) { memberByUniqueId = member; } else { logger.warn( "Encountered a member with a duplicate key: " + member.getQualifiedName() ); // NON-NLS } } if ( searchForNames == false ) { continue; } if ( parameter.equals( member.getName() ) ) { if ( memberById == null ) { memberById = member; } else { logger.warn( "Encountered a member with a duplicate name: " + member.getQualifiedName() ); // NON-NLS } } } } } finally { resultDirect.close(); } if ( memberByUniqueId != null ) { final Hierarchy memberHierarchy = memberByUniqueId.getHierarchy(); if ( hierarchy != memberHierarchy ) { if ( ObjectUtilities.equal( hierarchy, memberHierarchy ) == false ) { logger .warn( "Cannot match hierarchy of member found with the hierarchy specfied in the parameter: " // NON-NLS + "Unabe to guarantee that the correct member has been queried, returning null." ); // NON-NLS return null; } } return memberByUniqueId; } if ( memberById != null ) { final Hierarchy memberHierarchy = memberById.getHierarchy(); if ( hierarchy != memberHierarchy ) { if ( ObjectUtilities.equal( hierarchy, memberHierarchy ) == false ) { logger .warn( "Cannot match hierarchy of member found with the hierarchy specfied in the parameter: " // NON-NLS + "Unabe to guarantee that the correct member has been queried, returning null" ); // NON-NLS return null; } } return memberById; } return null; } protected Member yuckyInternalMondrianLookup( final Query query, final Hierarchy hierarchy, final String parameter ) { final Member memberById = (Member) Util.lookup( query, Util.parseIdentifier( parameter ) ); if ( memberById != null ) { final Hierarchy memberHierarchy = memberById.getHierarchy(); if ( hierarchy != memberHierarchy ) { if ( ObjectUtilities.equal( hierarchy, memberHierarchy ) == false ) { logger .warn( "Cannot match hierarchy of member found with the hierarchy specfied in the parameter: " // NON-NLS + "Unabe to guarantee that the correct member has been queried, returning null" ); // NON-NLS return null; } } return memberById; } return null; } protected int extractQueryLimit( final DataRow parameters ) { final Object queryLimit = parameters.get( DataFactory.QUERY_LIMIT ); final int queryLimitValue; if ( queryLimit instanceof Number ) { final Number i = (Number) queryLimit; queryLimitValue = Math.max( 0, i.intValue() ); } else { // means no limit at all queryLimitValue = 0; } return queryLimitValue; } private String computeRole( final DataRow parameters ) throws ReportDataFactoryException { if ( roleField != null ) { final Object field = parameters.get( roleField ); if ( field != null ) { if ( field instanceof Object[] ) { final Object[] roleArray = (Object[]) field; final StringBuffer buffer = new StringBuffer(); final int length = roleArray.length; for ( int i = 0; i < length; i++ ) { final Object o = roleArray[ i ]; if ( o == null ) { continue; } final String role = filter( String.valueOf( o ) ); if ( role == null ) { continue; } buffer.append( quoteRole( role ) ); } return buffer.toString(); } else if ( field.getClass().isArray() ) { final StringBuffer buffer = new StringBuffer(); final int length = Array.getLength( field ); for ( int i = 0; i < length; i++ ) { final Object o = Array.get( field, i ); if ( o == null ) { continue; } final String role = filter( String.valueOf( o ) ); if ( role == null ) { continue; } buffer.append( quoteRole( role ) ); } return buffer.toString(); } final String role = filter( String.valueOf( field ) ); if ( role != null ) { return role; } } } return filter( role ); } private String quoteRole( final String role ) { if ( role.indexOf( ',' ) == -1 ) { return role; } final StringBuffer b = new StringBuffer( role.length() + 5 ); final char[] chars = role.toCharArray(); for ( int i = 0; i < chars.length; i++ ) { final char c = chars[ i ]; if ( c == ',' ) { b.append( c ); } b.append( c ); } return b.toString(); } private String computeJdbcUser( final DataRow parameters ) { if ( jdbcUserField != null ) { final Object field = parameters.get( jdbcUserField ); if ( field != null ) { return String.valueOf( field ); } } return jdbcUser; } private String computeJdbcPassword( final DataRow parameters ) { if ( jdbcPasswordField != null ) { final Object field = parameters.get( jdbcPasswordField ); if ( field != null ) { return String.valueOf( field ); } } return jdbcPassword; } private Properties computeProperties( final DataRow parameters ) throws ReportDataFactoryException { if ( cubeFileProvider == null ) { throw new ReportDataFactoryException( "No CubeFileProvider" ); } final Properties properties = getBaseConnectionProperties(); final String catalog = cubeFileProvider.getCubeFile( getResourceManager(), getContextKey() ); if ( catalog == null ) { throw new ReportDataFactoryException( "No valid catalog given." ); } properties.setProperty( "Catalog", catalog ); // NON-NLS final String role = computeRole( parameters ); if ( role != null ) { properties.setProperty( "Role", role ); // NON-NLS } final String jdbcUser = computeJdbcUser( parameters ); if ( StringUtils.isEmpty( jdbcUser ) == false ) { properties.setProperty( "JdbcUser", jdbcUser ); // NON-NLS } final String jdbcPassword = computeJdbcPassword( parameters ); if ( StringUtils.isEmpty( jdbcPassword ) == false ) { properties.setProperty( "JdbcPassword", jdbcPassword ); // NON-NLS } final Locale locale = getLocale(); if ( locale != null ) { properties.setProperty( "Locale", locale.toString() ); // NON-NLS } if ( isUseContentChecksum() != null ) { properties.setProperty( "UseContentChecksum", String.valueOf( isUseContentChecksum() ) ); // NON-NLS } if ( isUseSchemaPool() != null ) { properties.setProperty( "UseSchemaPool", String.valueOf( isUseSchemaPool() ) ); // NON-NLS } if ( getDynamicSchemaProcessor() != null ) { properties.setProperty( "DynamicSchemaProcessor", getDynamicSchemaProcessor() ); // NON-NLS } return properties; } public AbstractMDXDataFactory clone() { final AbstractMDXDataFactory dataFactory = (AbstractMDXDataFactory) super.clone(); dataFactory.connection = null; if ( this.baseConnectionProperties != null ) { dataFactory.baseConnectionProperties = (Properties) this.baseConnectionProperties.clone(); } return dataFactory; } public String getDesignTimeName() { return designTimeName; } public void setDesignTimeName( final String designTimeName ) { this.designTimeName = designTimeName; } /** * Returns all known query-names. A data-factory may accept more than the query-names returned here. * * @return the known query names. */ public String[] getQueryNames() { return EMPTY_QUERYNAMES; } /** * Attempts to cancel the query process that is generating the data for this data factory. If it is not possible to * cancel the query, this call should be ignored. */ public void cancelRunningQuery() { } protected static String quote( final String original ) { // This solution needs improvements. Copy blocks instead of single // characters. final int length = original.length(); final StringBuffer b = new StringBuffer( length * 12 / 10 ); b.append( '"' ); for ( int i = 0; i < length; i++ ) { final char c = original.charAt( i ); if ( c == '"' ) { b.append( '"' ); b.append( '"' ); } else { b.append( c ); } } b.append( '"' ); return b.toString(); } private String filter( final String role ) throws ReportDataFactoryException { final Configuration configuration = ClassicEngineBoot.getInstance().getGlobalConfig(); if ( "true".equals( configuration.getConfigProperty( ROLE_FILTER_ENABLE_CONFIG_KEY ) ) == false ) { return role; } final Iterator staticDenyKeys = configuration.findPropertyKeys( DENY_ROLE_CONFIG_KEY ); while ( staticDenyKeys.hasNext() ) { final String key = (String) staticDenyKeys.next(); final String value = configuration.getConfigProperty( key ); if ( ObjectUtilities.equal( value, role ) ) { return null; } } final Iterator regExpDenyKeys = configuration.findPropertyKeys( DENY_REGEXP_CONFIG_KEY ); while ( regExpDenyKeys.hasNext() ) { final String key = (String) regExpDenyKeys.next(); final String value = configuration.getConfigProperty( key ); try { if ( role.matches( value ) ) { return null; } } catch ( PatternSyntaxException pe ) { throw new ReportDataFactoryException( "Unable to match reg-exp role filter:", pe ); } } boolean hasAccept = false; final Iterator staticAcceptKeys = configuration.findPropertyKeys( ACCEPT_ROLES_CONFIG_KEY ); while ( staticAcceptKeys.hasNext() ) { hasAccept = true; final String key = (String) staticAcceptKeys.next(); final String value = configuration.getConfigProperty( key ); if ( ObjectUtilities.equal( value, role ) ) { return role; } } final Iterator regExpAcceptKeys = configuration.findPropertyKeys( ACCEPT_REGEXP_CONFIG_KEY ); while ( regExpAcceptKeys.hasNext() ) { hasAccept = true; final String key = (String) regExpAcceptKeys.next(); final String value = configuration.getConfigProperty( key ); try { if ( role.matches( value ) ) { return role; } } catch ( PatternSyntaxException pe ) { throw new ReportDataFactoryException( "Unable to match reg-exp role filter:", pe ); } } if ( hasAccept == false ) { return role; } return null; } protected String translateQuery( final String query ) { return query; } protected String computedQuery( final String queryName, final DataRow parameters ) throws ReportDataFactoryException { return queryName; } public ArrayList<Object> getQueryHash( final String queryRaw, final DataRow parameter ) throws ReportDataFactoryException { final ArrayList<Object> list = new ArrayList<Object>(); list.add( getClass().getName() ); list.add( translateQuery( queryRaw ) ); if ( getCubeFileProvider() != null ) { list.add( getCubeFileProvider().getConnectionHash() ); } if ( getDataSourceProvider() != null ) { list.add( getDataSourceProvider().getConnectionHash() ); } list.add( getMondrianConnectionProvider().getConnectionHash( computeProperties( parameter ) ) ); list.add( computeProperties( parameter ) ); return list; } public String[] getReferencedFields( final String queryName, final DataRow parameters ) throws ReportDataFactoryException { final boolean isNewConnection = connection == null; try { if ( connection == null ) { connection = mondrianConnectionProvider.createConnection ( computeProperties( parameters ), dataSourceProvider.getDataSource() ); } } catch ( SQLException e ) { logger.error( e ); throw new ReportDataFactoryException( "Failed to create DataSource (SQL Exception - error code: " + e.getErrorCode() + "):" + e.toString(), e ); } catch ( MondrianException e ) { logger.error( e ); throw new ReportDataFactoryException( "Failed to create DataSource (Mondrian Exception):" + e.toString(), e ); } try { if ( connection == null ) { throw new ReportDataFactoryException( "Factory is closed." ); } final LinkedHashSet<String> parameter = new LinkedHashSet<String>(); final MDXCompiler compiler = new MDXCompiler( parameters, getLocale() ); final String computedQuery = computedQuery( queryName, parameters ); final String mdxQuery = compiler.translateAndLookup( computedQuery, parameters ); parameter.addAll( compiler.getCollectedParameter() ); // Alternatively, JNDI is possible. Maybe even more .. final Query query = connection.parseQuery( mdxQuery ); final Parameter[] queryParameters = query.getParameters(); for ( int i = 0; i < queryParameters.length; i++ ) { final Parameter queryParameter = queryParameters[ i ]; parameter.add( queryParameter.getName() ); } if ( jdbcUserField != null ) { parameter.add( jdbcUserField ); } if ( roleField != null ) { parameter.add( roleField ); } parameter.add( DataFactory.QUERY_LIMIT ); return parameter.toArray( new String[ parameter.size() ] ); } catch ( MondrianException e ) { throw new ReportDataFactoryException( "Failed to create datasource:" + e.getLocalizedMessage(), e ); } finally { if ( isNewConnection ) { close(); } } } public void initialize( final DataFactoryContext dataFactoryContext ) throws ReportDataFactoryException { super.initialize( dataFactoryContext ); membersOnAxisSorted = "true".equals ( dataFactoryContext.getConfiguration() .getConfigProperty( MondrianDataFactoryModule.MEMBER_ON_AXIS_SORTED_KEY ) ); } }
EgorZhuk/pentaho-reporting
engine/extensions-mondrian/src/main/java/org/pentaho/reporting/engine/classic/extensions/datasources/mondrian/AbstractMDXDataFactory.java
Java
lgpl-2.1
37,834
<?php $root=""; ?> <?php require($root."navigation.php"); ?> <html> <head> <?php load_style($root); ?> </head> <body> <?php make_navigation("subdomains_ex2",$root)?> <div class="content"> <a name="comments"></a> <div class = "comment"> <h1>Subdomains Example 2 - Subdomain-Restricted Variables</h1> <br><br>This example builds on the fourth example program by showing how to restrict solution fields to a subdomain (or union of subdomains). <br><br> <br><br>C++ include files that we need </div> <div class ="fragment"> <pre> #include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;math.h&gt; </pre> </div> <div class = "comment"> Basic include file needed for the mesh functionality. </div> <div class ="fragment"> <pre> #include "libmesh.h" #include "mesh.h" #include "mesh_generation.h" #include "exodusII_io.h" #include "gnuplot_io.h" #include "linear_implicit_system.h" #include "equation_systems.h" </pre> </div> <div class = "comment"> Define the Finite Element object. </div> <div class ="fragment"> <pre> #include "fe.h" </pre> </div> <div class = "comment"> Define Gauss quadrature rules. </div> <div class ="fragment"> <pre> #include "quadrature_gauss.h" </pre> </div> <div class = "comment"> Define the DofMap, which handles degree of freedom indexing. </div> <div class ="fragment"> <pre> #include "dof_map.h" </pre> </div> <div class = "comment"> Define useful datatypes for finite element matrix and vector components. </div> <div class ="fragment"> <pre> #include "sparse_matrix.h" #include "numeric_vector.h" #include "dense_matrix.h" #include "dense_vector.h" </pre> </div> <div class = "comment"> Define the PerfLog, a performance logging utility. It is useful for timing events in a code and giving you an idea where bottlenecks lie. </div> <div class ="fragment"> <pre> #include "perf_log.h" </pre> </div> <div class = "comment"> The definition of a geometric element </div> <div class ="fragment"> <pre> #include "elem.h" #include "string_to_enum.h" #include "getpot.h" </pre> </div> <div class = "comment"> Bring in everything from the libMesh namespace </div> <div class ="fragment"> <pre> using namespace libMesh; </pre> </div> <div class = "comment"> Function prototype. This is the function that will assemble the linear system for our Poisson problem. Note that the function will take the \p EquationSystems object and the name of the system we are assembling as input. From the \p EquationSystems object we have acess to the \p Mesh and other objects we might need. </div> <div class ="fragment"> <pre> void assemble_poisson(EquationSystems& es, const std::string& system_name); </pre> </div> <div class = "comment"> Exact solution function prototype. </div> <div class ="fragment"> <pre> Real exact_solution (const Real x, const Real y = 0., const Real z = 0.); </pre> </div> <div class = "comment"> Begin the main program. </div> <div class ="fragment"> <pre> int main (int argc, char** argv) { </pre> </div> <div class = "comment"> Initialize libMesh and any dependent libaries, like in example 2. </div> <div class ="fragment"> <pre> LibMeshInit init (argc, argv); </pre> </div> <div class = "comment"> Declare a performance log for the main program PerfLog perf_main("Main Program"); <br><br>Create a GetPot object to parse the command line </div> <div class ="fragment"> <pre> GetPot command_line (argc, argv); </pre> </div> <div class = "comment"> Check for proper calling arguments. </div> <div class ="fragment"> <pre> if (argc &lt; 3) { if (libMesh::processor_id() == 0) std::cerr &lt;&lt; "Usage:\n" &lt;&lt;"\t " &lt;&lt; argv[0] &lt;&lt; " -d 2(3)" &lt;&lt; " -n 15" &lt;&lt; std::endl; </pre> </div> <div class = "comment"> This handy function will print the file name, line number, and then abort. Currrently the library does not use C++ exception handling. </div> <div class ="fragment"> <pre> libmesh_error(); } </pre> </div> <div class = "comment"> Brief message to the user regarding the program name and command line arguments. </div> <div class ="fragment"> <pre> else { std::cout &lt;&lt; "Running " &lt;&lt; argv[0]; for (int i=1; i&lt;argc; i++) std::cout &lt;&lt; " " &lt;&lt; argv[i]; std::cout &lt;&lt; std::endl &lt;&lt; std::endl; } </pre> </div> <div class = "comment"> Read problem dimension from command line. Use int instead of unsigned since the GetPot overload is ambiguous otherwise. </div> <div class ="fragment"> <pre> int dim = 2; if ( command_line.search(1, "-d") ) dim = command_line.next(dim); </pre> </div> <div class = "comment"> Skip higher-dimensional examples on a lower-dimensional libMesh build </div> <div class ="fragment"> <pre> libmesh_example_assert(dim &lt;= LIBMESH_DIM, "2D/3D support"); </pre> </div> <div class = "comment"> Create a mesh with user-defined dimension. </div> <div class ="fragment"> <pre> Mesh mesh (dim); </pre> </div> <div class = "comment"> Read number of elements from command line </div> <div class ="fragment"> <pre> int ps = 15; if ( command_line.search(1, "-n") ) ps = command_line.next(ps); </pre> </div> <div class = "comment"> Read FE order from command line </div> <div class ="fragment"> <pre> std::string order = "SECOND"; if ( command_line.search(2, "-Order", "-o") ) order = command_line.next(order); </pre> </div> <div class = "comment"> Read FE Family from command line </div> <div class ="fragment"> <pre> std::string family = "LAGRANGE"; if ( command_line.search(2, "-FEFamily", "-f") ) family = command_line.next(family); </pre> </div> <div class = "comment"> Cannot use discontinuous basis. </div> <div class ="fragment"> <pre> if ((family == "MONOMIAL") || (family == "XYZ")) { if (libMesh::processor_id() == 0) std::cerr &lt;&lt; "ex28 currently requires a C^0 (or higher) FE basis." &lt;&lt; std::endl; libmesh_error(); } </pre> </div> <div class = "comment"> Use the MeshTools::Generation mesh generator to create a uniform grid on the square [-1,1]^D. We instruct the mesh generator to build a mesh of 8x8 \p Quad9 elements in 2D, or \p Hex27 elements in 3D. Building these higher-order elements allows us to use higher-order approximation, as in example 3. <br><br></div> <div class ="fragment"> <pre> Real halfwidth = dim &gt; 1 ? 1. : 0.; Real halfheight = dim &gt; 2 ? 1. : 0.; if ((family == "LAGRANGE") && (order == "FIRST")) { </pre> </div> <div class = "comment"> No reason to use high-order geometric elements if we are solving with low-order finite elements. </div> <div class ="fragment"> <pre> MeshTools::Generation::build_cube (mesh, ps, (dim&gt;1) ? ps : 0, (dim&gt;2) ? ps : 0, -1., 1., -halfwidth, halfwidth, -halfheight, halfheight, (dim==1) ? EDGE2 : ((dim == 2) ? QUAD4 : HEX8)); } else { MeshTools::Generation::build_cube (mesh, ps, (dim&gt;1) ? ps : 0, (dim&gt;2) ? ps : 0, -1., 1., -halfwidth, halfwidth, -halfheight, halfheight, (dim==1) ? EDGE3 : ((dim == 2) ? QUAD9 : HEX27)); } { MeshBase::element_iterator el = mesh.elements_begin(); const MeshBase::element_iterator end_el = mesh.elements_end(); for ( ; el != end_el; ++el) { Elem* elem = *el; const Point cent = elem-&gt;centroid(); if (dim &gt; 1) { if ((cent(0) &gt; 0) == (cent(1) &gt; 0)) elem-&gt;subdomain_id() = 1; } else { if (cent(0) &gt; 0) elem-&gt;subdomain_id() = 1; } } } </pre> </div> <div class = "comment"> Print information about the mesh to the screen. </div> <div class ="fragment"> <pre> mesh.print_info(); </pre> </div> <div class = "comment"> Create an equation systems object. </div> <div class ="fragment"> <pre> EquationSystems equation_systems (mesh); </pre> </div> <div class = "comment"> Declare the system and its variables. Create a system named "Poisson" </div> <div class ="fragment"> <pre> LinearImplicitSystem& system = equation_systems.add_system&lt;LinearImplicitSystem&gt; ("Poisson"); std::set&lt;subdomain_id_type&gt; active_subdomains; </pre> </div> <div class = "comment"> Add the variable "u" to "Poisson". "u" will be approximated using second-order approximation. </div> <div class ="fragment"> <pre> active_subdomains.clear(); active_subdomains.insert(0); system.add_variable("u", Utility::string_to_enum&lt;Order&gt; (order), Utility::string_to_enum&lt;FEFamily&gt;(family), &active_subdomains); </pre> </div> <div class = "comment"> Add the variable "v" to "Poisson". "v" will be approximated using second-order approximation. </div> <div class ="fragment"> <pre> active_subdomains.clear(); active_subdomains.insert(1); system.add_variable("v", Utility::string_to_enum&lt;Order&gt; (order), Utility::string_to_enum&lt;FEFamily&gt;(family), &active_subdomains); </pre> </div> <div class = "comment"> Give the system a pointer to the matrix assembly function. </div> <div class ="fragment"> <pre> system.attach_assemble_function (assemble_poisson); </pre> </div> <div class = "comment"> Initialize the data structures for the equation system. </div> <div class ="fragment"> <pre> equation_systems.init(); </pre> </div> <div class = "comment"> Print information about the system to the screen. </div> <div class ="fragment"> <pre> equation_systems.print_info(); mesh.print_info(); </pre> </div> <div class = "comment"> Solve the system "Poisson", just like example 2. </div> <div class ="fragment"> <pre> equation_systems.get_system("Poisson").solve(); </pre> </div> <div class = "comment"> After solving the system write the solution to a GMV-formatted plot file. </div> <div class ="fragment"> <pre> if(dim == 1) { GnuPlotIO plot(mesh,"Example 4, 1D",GnuPlotIO::GRID_ON); plot.write_equation_systems("out_1",equation_systems); } else { #ifdef LIBMESH_HAVE_EXODUS_API ExodusII_IO (mesh).write_equation_systems ((dim == 3) ? "out_3.e" : "out_2.e",equation_systems); #endif // #ifdef LIBMESH_HAVE_EXODUS_API } </pre> </div> <div class = "comment"> All done. </div> <div class ="fragment"> <pre> return 0; } </pre> </div> <div class = "comment"> <br><br> <br><br> <br><br>We now define the matrix assembly function for the Poisson system. We need to first compute element matrices and right-hand sides, and then take into account the boundary conditions, which will be handled via a penalty method. </div> <div class ="fragment"> <pre> void assemble_poisson(EquationSystems& es, const std::string& system_name) { </pre> </div> <div class = "comment"> It is a good idea to make sure we are assembling the proper system. </div> <div class ="fragment"> <pre> libmesh_assert (system_name == "Poisson"); </pre> </div> <div class = "comment"> Declare a performance log. Give it a descriptive string to identify what part of the code we are logging, since there may be many PerfLogs in an application. </div> <div class ="fragment"> <pre> PerfLog perf_log ("Matrix Assembly"); </pre> </div> <div class = "comment"> Get a constant reference to the mesh object. </div> <div class ="fragment"> <pre> const MeshBase& mesh = es.get_mesh(); </pre> </div> <div class = "comment"> The dimension that we are running </div> <div class ="fragment"> <pre> const unsigned int dim = mesh.mesh_dimension(); </pre> </div> <div class = "comment"> Get a reference to the LinearImplicitSystem we are solving </div> <div class ="fragment"> <pre> LinearImplicitSystem& system = es.get_system&lt;LinearImplicitSystem&gt;("Poisson"); </pre> </div> <div class = "comment"> A reference to the \p DofMap object for this system. The \p DofMap object handles the index translation from node and element numbers to degree of freedom numbers. We will talk more about the \p DofMap in future examples. </div> <div class ="fragment"> <pre> const DofMap& dof_map = system.get_dof_map(); </pre> </div> <div class = "comment"> Get a constant reference to the Finite Element type for the first (and only) variable in the system. </div> <div class ="fragment"> <pre> FEType fe_type = dof_map.variable_type(0); </pre> </div> <div class = "comment"> Build a Finite Element object of the specified type. Since the \p FEBase::build() member dynamically creates memory we will store the object as an \p AutoPtr<FEBase>. This can be thought of as a pointer that will clean up after itself. </div> <div class ="fragment"> <pre> AutoPtr&lt;FEBase&gt; fe (FEBase::build(dim, fe_type)); </pre> </div> <div class = "comment"> A 5th order Gauss quadrature rule for numerical integration. </div> <div class ="fragment"> <pre> QGauss qrule (dim, FIFTH); </pre> </div> <div class = "comment"> Tell the finite element object to use our quadrature rule. </div> <div class ="fragment"> <pre> fe-&gt;attach_quadrature_rule (&qrule); </pre> </div> <div class = "comment"> Declare a special finite element object for boundary integration. </div> <div class ="fragment"> <pre> AutoPtr&lt;FEBase&gt; fe_face (FEBase::build(dim, fe_type)); </pre> </div> <div class = "comment"> Boundary integration requires one quadraure rule, with dimensionality one less than the dimensionality of the element. </div> <div class ="fragment"> <pre> QGauss qface(dim-1, FIFTH); </pre> </div> <div class = "comment"> Tell the finte element object to use our quadrature rule. </div> <div class ="fragment"> <pre> fe_face-&gt;attach_quadrature_rule (&qface); </pre> </div> <div class = "comment"> Here we define some references to cell-specific data that will be used to assemble the linear system. We begin with the element Jacobian * quadrature weight at each integration point. </div> <div class ="fragment"> <pre> const std::vector&lt;Real&gt;& JxW = fe-&gt;get_JxW(); </pre> </div> <div class = "comment"> The physical XY locations of the quadrature points on the element. These might be useful for evaluating spatially varying material properties at the quadrature points. </div> <div class ="fragment"> <pre> const std::vector&lt;Point&gt;& q_point = fe-&gt;get_xyz(); </pre> </div> <div class = "comment"> The element shape functions evaluated at the quadrature points. </div> <div class ="fragment"> <pre> const std::vector&lt;std::vector&lt;Real&gt; &gt;& phi = fe-&gt;get_phi(); </pre> </div> <div class = "comment"> The element shape function gradients evaluated at the quadrature points. </div> <div class ="fragment"> <pre> const std::vector&lt;std::vector&lt;RealGradient&gt; &gt;& dphi = fe-&gt;get_dphi(); </pre> </div> <div class = "comment"> Define data structures to contain the element matrix and right-hand-side vector contribution. Following basic finite element terminology we will denote these "Ke" and "Fe". More detail is in example 3. </div> <div class ="fragment"> <pre> DenseMatrix&lt;Number&gt; Ke; DenseVector&lt;Number&gt; Fe; </pre> </div> <div class = "comment"> This vector will hold the degree of freedom indices for the element. These define where in the global system the element degrees of freedom get mapped. </div> <div class ="fragment"> <pre> std::vector&lt;unsigned int&gt; dof_indices, dof_indices2; </pre> </div> <div class = "comment"> Now we will loop over all the elements in the mesh. We will compute the element matrix and right-hand-side contribution. See example 3 for a discussion of the element iterators. Here we use the \p const_local_elem_iterator to indicate we only want to loop over elements that are assigned to the local processor. This allows each processor to compute its components of the global matrix. <br><br>"PARALLEL CHANGE" </div> <div class ="fragment"> <pre> MeshBase::const_element_iterator el = mesh.local_elements_begin(); const MeshBase::const_element_iterator end_el = mesh.local_elements_end(); for ( ; el != end_el; ++el) { </pre> </div> <div class = "comment"> Start logging the shape function initialization. This is done through a simple function call with the name of the event to log. </div> <div class ="fragment"> <pre> perf_log.push("elem init"); </pre> </div> <div class = "comment"> Store a pointer to the element we are currently working on. This allows for nicer syntax later. </div> <div class ="fragment"> <pre> const Elem* elem = *el; </pre> </div> <div class = "comment"> Get the degree of freedom indices for the current element. These define where in the global matrix and right-hand-side this element will contribute to. </div> <div class ="fragment"> <pre> dof_map.dof_indices (elem, dof_indices,0); dof_map.dof_indices (elem, dof_indices2,1); </pre> </div> <div class = "comment"> std::cout << "dof_indices.size()=" << dof_indices.size() << ", dof_indices2.size()=" << dof_indices2.size() << std::endl; <br><br>Compute the element-specific data for the current element. This involves computing the location of the quadrature points (q_point) and the shape functions (phi, dphi) for the current element. </div> <div class ="fragment"> <pre> fe-&gt;reinit (elem); </pre> </div> <div class = "comment"> Zero the element matrix and right-hand side before summing them. We use the resize member here because the number of degrees of freedom might have changed from the last element. Note that this will be the case if the element type is different (i.e. the last element was a triangle, now we are on a quadrilateral). </div> <div class ="fragment"> <pre> Ke.resize (std::max(dof_indices.size(), dof_indices2.size()), std::max(dof_indices.size(), dof_indices2.size())); Fe.resize (std::max(dof_indices.size(), dof_indices2.size())); </pre> </div> <div class = "comment"> Stop logging the shape function initialization. If you forget to stop logging an event the PerfLog object will probably catch the error and abort. </div> <div class ="fragment"> <pre> perf_log.pop("elem init"); </pre> </div> <div class = "comment"> Now we will build the element matrix. This involves a double loop to integrate the test funcions (i) against the trial functions (j). <br><br>We have split the numeric integration into two loops so that we can log the matrix and right-hand-side computation seperately. <br><br>Now start logging the element matrix computation </div> <div class ="fragment"> <pre> perf_log.push ("Ke"); for (unsigned int qp=0; qp&lt;qrule.n_points(); qp++) for (unsigned int i=0; i&lt;phi.size(); i++) for (unsigned int j=0; j&lt;phi.size(); j++) Ke(i,j) += JxW[qp]*(dphi[i][qp]*dphi[j][qp]); </pre> </div> <div class = "comment"> Stop logging the matrix computation </div> <div class ="fragment"> <pre> perf_log.pop ("Ke"); </pre> </div> <div class = "comment"> Now we build the element right-hand-side contribution. This involves a single loop in which we integrate the "forcing function" in the PDE against the test functions. <br><br>Start logging the right-hand-side computation </div> <div class ="fragment"> <pre> perf_log.push ("Fe"); for (unsigned int qp=0; qp&lt;qrule.n_points(); qp++) { </pre> </div> <div class = "comment"> fxy is the forcing function for the Poisson equation. In this case we set fxy to be a finite difference Laplacian approximation to the (known) exact solution. <br><br>We will use the second-order accurate FD Laplacian approximation, which in 2D on a structured grid is <br><br>u_xx + u_yy = (u(i-1,j) + u(i+1,j) + u(i,j-1) + u(i,j+1) + -4*u(i,j))/h^2 <br><br>Since the value of the forcing function depends only on the location of the quadrature point (q_point[qp]) we will compute it here, outside of the i-loop </div> <div class ="fragment"> <pre> const Real x = q_point[qp](0); #if LIBMESH_DIM &gt; 1 const Real y = q_point[qp](1); #else const Real y = 0; #endif #if LIBMESH_DIM &gt; 2 const Real z = q_point[qp](2); #else const Real z = 0; #endif const Real eps = 1.e-3; const Real uxx = (exact_solution(x-eps,y,z) + exact_solution(x+eps,y,z) + -2.*exact_solution(x,y,z))/eps/eps; const Real uyy = (exact_solution(x,y-eps,z) + exact_solution(x,y+eps,z) + -2.*exact_solution(x,y,z))/eps/eps; const Real uzz = (exact_solution(x,y,z-eps) + exact_solution(x,y,z+eps) + -2.*exact_solution(x,y,z))/eps/eps; Real fxy; if(dim==1) { </pre> </div> <div class = "comment"> In 1D, compute the rhs by differentiating the exact solution twice. </div> <div class ="fragment"> <pre> const Real pi = libMesh::pi; fxy = (0.25*pi*pi)*sin(.5*pi*x); } else { fxy = - (uxx + uyy + ((dim==2) ? 0. : uzz)); } </pre> </div> <div class = "comment"> Add the RHS contribution </div> <div class ="fragment"> <pre> for (unsigned int i=0; i&lt;phi.size(); i++) Fe(i) += JxW[qp]*fxy*phi[i][qp]; } </pre> </div> <div class = "comment"> Stop logging the right-hand-side computation </div> <div class ="fragment"> <pre> perf_log.pop ("Fe"); </pre> </div> <div class = "comment"> At this point the interior element integration has been completed. However, we have not yet addressed boundary conditions. For this example we will only consider simple Dirichlet boundary conditions imposed via the penalty method. This is discussed at length in example 3. </div> <div class ="fragment"> <pre> { </pre> </div> <div class = "comment"> Start logging the boundary condition computation </div> <div class ="fragment"> <pre> perf_log.push ("BCs"); </pre> </div> <div class = "comment"> The following loops over the sides of the element. If the element has no neighbor on a side then that side MUST live on a boundary of the domain. </div> <div class ="fragment"> <pre> for (unsigned int side=0; side&lt;elem-&gt;n_sides(); side++) if ((elem-&gt;neighbor(side) == NULL) || (elem-&gt;neighbor(side)-&gt;subdomain_id() != elem-&gt;subdomain_id())) { </pre> </div> <div class = "comment"> The penalty value. \frac{1}{\epsilon} in the discussion above. </div> <div class ="fragment"> <pre> const Real penalty = 1.e10; </pre> </div> <div class = "comment"> The value of the shape functions at the quadrature points. </div> <div class ="fragment"> <pre> const std::vector&lt;std::vector&lt;Real&gt; &gt;& phi_face = fe_face-&gt;get_phi(); </pre> </div> <div class = "comment"> The Jacobian * Quadrature Weight at the quadrature points on the face. </div> <div class ="fragment"> <pre> const std::vector&lt;Real&gt;& JxW_face = fe_face-&gt;get_JxW(); </pre> </div> <div class = "comment"> The XYZ locations (in physical space) of the quadrature points on the face. This is where we will interpolate the boundary value function. </div> <div class ="fragment"> <pre> const std::vector&lt;Point &gt;& qface_point = fe_face-&gt;get_xyz(); </pre> </div> <div class = "comment"> Compute the shape function values on the element face. </div> <div class ="fragment"> <pre> fe_face-&gt;reinit(elem, side); </pre> </div> <div class = "comment"> Loop over the face quadrature points for integration. </div> <div class ="fragment"> <pre> for (unsigned int qp=0; qp&lt;qface.n_points(); qp++) { </pre> </div> <div class = "comment"> The location on the boundary of the current face quadrature point. </div> <div class ="fragment"> <pre> const Real xf = qface_point[qp](0); #if LIBMESH_DIM &gt; 1 const Real yf = qface_point[qp](1); #else const Real yf = 0.; #endif #if LIBMESH_DIM &gt; 2 const Real zf = qface_point[qp](2); #else const Real zf = 0.; #endif </pre> </div> <div class = "comment"> The boundary value. </div> <div class ="fragment"> <pre> const Real value = exact_solution(xf, yf, zf); </pre> </div> <div class = "comment"> Matrix contribution of the L2 projection. </div> <div class ="fragment"> <pre> for (unsigned int i=0; i&lt;phi_face.size(); i++) for (unsigned int j=0; j&lt;phi_face.size(); j++) Ke(i,j) += JxW_face[qp]*penalty*phi_face[i][qp]*phi_face[j][qp]; </pre> </div> <div class = "comment"> Right-hand-side contribution of the L2 projection. </div> <div class ="fragment"> <pre> for (unsigned int i=0; i&lt;phi_face.size(); i++) Fe(i) += JxW_face[qp]*penalty*value*phi_face[i][qp]; } } </pre> </div> <div class = "comment"> Stop logging the boundary condition computation </div> <div class ="fragment"> <pre> perf_log.pop ("BCs"); } </pre> </div> <div class = "comment"> The element matrix and right-hand-side are now built for this element. Add them to the global matrix and right-hand-side vector. The \p PetscMatrix::add_matrix() and \p PetscVector::add_vector() members do this for us. Start logging the insertion of the local (element) matrix and vector into the global matrix and vector </div> <div class ="fragment"> <pre> perf_log.push ("matrix insertion"); if (dof_indices.size()) { system.matrix-&gt;add_matrix (Ke, dof_indices); system.rhs-&gt;add_vector (Fe, dof_indices); } if (dof_indices2.size()) { system.matrix-&gt;add_matrix (Ke, dof_indices2); system.rhs-&gt;add_vector (Fe, dof_indices2); } </pre> </div> <div class = "comment"> Start logging the insertion of the local (element) matrix and vector into the global matrix and vector </div> <div class ="fragment"> <pre> perf_log.pop ("matrix insertion"); } </pre> </div> <div class = "comment"> That's it. We don't need to do anything else to the PerfLog. When it goes out of scope (at this function return) it will print its log to the screen. Pretty easy, huh? </div> <div class ="fragment"> <pre> } </pre> </div> <a name="nocomments"></a> <br><br><br> <h1> The program without comments: </h1> <pre> #include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;math.h&gt; #include <B><FONT COLOR="#BC8F8F">&quot;libmesh.h&quot;</FONT></B> #include <B><FONT COLOR="#BC8F8F">&quot;mesh.h&quot;</FONT></B> #include <B><FONT COLOR="#BC8F8F">&quot;mesh_generation.h&quot;</FONT></B> #include <B><FONT COLOR="#BC8F8F">&quot;exodusII_io.h&quot;</FONT></B> #include <B><FONT COLOR="#BC8F8F">&quot;gnuplot_io.h&quot;</FONT></B> #include <B><FONT COLOR="#BC8F8F">&quot;linear_implicit_system.h&quot;</FONT></B> #include <B><FONT COLOR="#BC8F8F">&quot;equation_systems.h&quot;</FONT></B> #include <B><FONT COLOR="#BC8F8F">&quot;fe.h&quot;</FONT></B> #include <B><FONT COLOR="#BC8F8F">&quot;quadrature_gauss.h&quot;</FONT></B> #include <B><FONT COLOR="#BC8F8F">&quot;dof_map.h&quot;</FONT></B> #include <B><FONT COLOR="#BC8F8F">&quot;sparse_matrix.h&quot;</FONT></B> #include <B><FONT COLOR="#BC8F8F">&quot;numeric_vector.h&quot;</FONT></B> #include <B><FONT COLOR="#BC8F8F">&quot;dense_matrix.h&quot;</FONT></B> #include <B><FONT COLOR="#BC8F8F">&quot;dense_vector.h&quot;</FONT></B> #include <B><FONT COLOR="#BC8F8F">&quot;perf_log.h&quot;</FONT></B> #include <B><FONT COLOR="#BC8F8F">&quot;elem.h&quot;</FONT></B> #include <B><FONT COLOR="#BC8F8F">&quot;string_to_enum.h&quot;</FONT></B> #include <B><FONT COLOR="#BC8F8F">&quot;getpot.h&quot;</FONT></B> using namespace libMesh; <B><FONT COLOR="#228B22">void</FONT></B> assemble_poisson(EquationSystems&amp; es, <B><FONT COLOR="#228B22">const</FONT></B> std::string&amp; system_name); Real exact_solution (<B><FONT COLOR="#228B22">const</FONT></B> Real x, <B><FONT COLOR="#228B22">const</FONT></B> Real y = 0., <B><FONT COLOR="#228B22">const</FONT></B> Real z = 0.); <B><FONT COLOR="#228B22">int</FONT></B> main (<B><FONT COLOR="#228B22">int</FONT></B> argc, <B><FONT COLOR="#228B22">char</FONT></B>** argv) { LibMeshInit init (argc, argv); GetPot command_line (argc, argv); <B><FONT COLOR="#A020F0">if</FONT></B> (argc &lt; 3) { <B><FONT COLOR="#A020F0">if</FONT></B> (libMesh::processor_id() == 0) <B><FONT COLOR="#5F9EA0">std</FONT></B>::cerr &lt;&lt; <B><FONT COLOR="#BC8F8F">&quot;Usage:\n&quot;</FONT></B> &lt;&lt;<B><FONT COLOR="#BC8F8F">&quot;\t &quot;</FONT></B> &lt;&lt; argv[0] &lt;&lt; <B><FONT COLOR="#BC8F8F">&quot; -d 2(3)&quot;</FONT></B> &lt;&lt; <B><FONT COLOR="#BC8F8F">&quot; -n 15&quot;</FONT></B> &lt;&lt; std::endl; libmesh_error(); } <B><FONT COLOR="#A020F0">else</FONT></B> { <B><FONT COLOR="#5F9EA0">std</FONT></B>::cout &lt;&lt; <B><FONT COLOR="#BC8F8F">&quot;Running &quot;</FONT></B> &lt;&lt; argv[0]; <B><FONT COLOR="#A020F0">for</FONT></B> (<B><FONT COLOR="#228B22">int</FONT></B> i=1; i&lt;argc; i++) <B><FONT COLOR="#5F9EA0">std</FONT></B>::cout &lt;&lt; <B><FONT COLOR="#BC8F8F">&quot; &quot;</FONT></B> &lt;&lt; argv[i]; <B><FONT COLOR="#5F9EA0">std</FONT></B>::cout &lt;&lt; std::endl &lt;&lt; std::endl; } <B><FONT COLOR="#228B22">int</FONT></B> dim = 2; <B><FONT COLOR="#A020F0">if</FONT></B> ( command_line.search(1, <B><FONT COLOR="#BC8F8F">&quot;-d&quot;</FONT></B>) ) dim = command_line.next(dim); libmesh_example_assert(dim &lt;= LIBMESH_DIM, <B><FONT COLOR="#BC8F8F">&quot;2D/3D support&quot;</FONT></B>); Mesh mesh (dim); <B><FONT COLOR="#228B22">int</FONT></B> ps = 15; <B><FONT COLOR="#A020F0">if</FONT></B> ( command_line.search(1, <B><FONT COLOR="#BC8F8F">&quot;-n&quot;</FONT></B>) ) ps = command_line.next(ps); <B><FONT COLOR="#5F9EA0">std</FONT></B>::string order = <B><FONT COLOR="#BC8F8F">&quot;SECOND&quot;</FONT></B>; <B><FONT COLOR="#A020F0">if</FONT></B> ( command_line.search(2, <B><FONT COLOR="#BC8F8F">&quot;-Order&quot;</FONT></B>, <B><FONT COLOR="#BC8F8F">&quot;-o&quot;</FONT></B>) ) order = command_line.next(order); <B><FONT COLOR="#5F9EA0">std</FONT></B>::string family = <B><FONT COLOR="#BC8F8F">&quot;LAGRANGE&quot;</FONT></B>; <B><FONT COLOR="#A020F0">if</FONT></B> ( command_line.search(2, <B><FONT COLOR="#BC8F8F">&quot;-FEFamily&quot;</FONT></B>, <B><FONT COLOR="#BC8F8F">&quot;-f&quot;</FONT></B>) ) family = command_line.next(family); <B><FONT COLOR="#A020F0">if</FONT></B> ((family == <B><FONT COLOR="#BC8F8F">&quot;MONOMIAL&quot;</FONT></B>) || (family == <B><FONT COLOR="#BC8F8F">&quot;XYZ&quot;</FONT></B>)) { <B><FONT COLOR="#A020F0">if</FONT></B> (libMesh::processor_id() == 0) <B><FONT COLOR="#5F9EA0">std</FONT></B>::cerr &lt;&lt; <B><FONT COLOR="#BC8F8F">&quot;ex28 currently requires a C^0 (or higher) FE basis.&quot;</FONT></B> &lt;&lt; std::endl; libmesh_error(); } Real halfwidth = dim &gt; 1 ? 1. : 0.; Real halfheight = dim &gt; 2 ? 1. : 0.; <B><FONT COLOR="#A020F0">if</FONT></B> ((family == <B><FONT COLOR="#BC8F8F">&quot;LAGRANGE&quot;</FONT></B>) &amp;&amp; (order == <B><FONT COLOR="#BC8F8F">&quot;FIRST&quot;</FONT></B>)) { <B><FONT COLOR="#5F9EA0">MeshTools</FONT></B>::Generation::build_cube (mesh, ps, (dim&gt;1) ? ps : 0, (dim&gt;2) ? ps : 0, -1., 1., -halfwidth, halfwidth, -halfheight, halfheight, (dim==1) ? EDGE2 : ((dim == 2) ? QUAD4 : HEX8)); } <B><FONT COLOR="#A020F0">else</FONT></B> { <B><FONT COLOR="#5F9EA0">MeshTools</FONT></B>::Generation::build_cube (mesh, ps, (dim&gt;1) ? ps : 0, (dim&gt;2) ? ps : 0, -1., 1., -halfwidth, halfwidth, -halfheight, halfheight, (dim==1) ? EDGE3 : ((dim == 2) ? QUAD9 : HEX27)); } { <B><FONT COLOR="#5F9EA0">MeshBase</FONT></B>::element_iterator el = mesh.elements_begin(); <B><FONT COLOR="#228B22">const</FONT></B> MeshBase::element_iterator end_el = mesh.elements_end(); <B><FONT COLOR="#A020F0">for</FONT></B> ( ; el != end_el; ++el) { Elem* elem = *el; <B><FONT COLOR="#228B22">const</FONT></B> Point cent = elem-&gt;centroid(); <B><FONT COLOR="#A020F0">if</FONT></B> (dim &gt; 1) { <B><FONT COLOR="#A020F0">if</FONT></B> ((cent(0) &gt; 0) == (cent(1) &gt; 0)) elem-&gt;subdomain_id() = 1; } <B><FONT COLOR="#A020F0">else</FONT></B> { <B><FONT COLOR="#A020F0">if</FONT></B> (cent(0) &gt; 0) elem-&gt;subdomain_id() = 1; } } } mesh.print_info(); EquationSystems equation_systems (mesh); LinearImplicitSystem&amp; system = equation_systems.add_system&lt;LinearImplicitSystem&gt; (<B><FONT COLOR="#BC8F8F">&quot;Poisson&quot;</FONT></B>); <B><FONT COLOR="#5F9EA0">std</FONT></B>::set&lt;subdomain_id_type&gt; active_subdomains; active_subdomains.clear(); active_subdomains.insert(0); system.add_variable(<B><FONT COLOR="#BC8F8F">&quot;u&quot;</FONT></B>, <B><FONT COLOR="#5F9EA0">Utility</FONT></B>::string_to_enum&lt;Order&gt; (order), <B><FONT COLOR="#5F9EA0">Utility</FONT></B>::string_to_enum&lt;FEFamily&gt;(family), &amp;active_subdomains); active_subdomains.clear(); active_subdomains.insert(1); system.add_variable(<B><FONT COLOR="#BC8F8F">&quot;v&quot;</FONT></B>, <B><FONT COLOR="#5F9EA0">Utility</FONT></B>::string_to_enum&lt;Order&gt; (order), <B><FONT COLOR="#5F9EA0">Utility</FONT></B>::string_to_enum&lt;FEFamily&gt;(family), &amp;active_subdomains); system.attach_assemble_function (assemble_poisson); equation_systems.init(); equation_systems.print_info(); mesh.print_info(); equation_systems.get_system(<B><FONT COLOR="#BC8F8F">&quot;Poisson&quot;</FONT></B>).solve(); <B><FONT COLOR="#A020F0">if</FONT></B>(dim == 1) { GnuPlotIO plot(mesh,<B><FONT COLOR="#BC8F8F">&quot;Example 4, 1D&quot;</FONT></B>,GnuPlotIO::GRID_ON); plot.write_equation_systems(<B><FONT COLOR="#BC8F8F">&quot;out_1&quot;</FONT></B>,equation_systems); } <B><FONT COLOR="#A020F0">else</FONT></B> { #ifdef LIBMESH_HAVE_EXODUS_API ExodusII_IO (mesh).write_equation_systems ((dim == 3) ? <B><FONT COLOR="#BC8F8F">&quot;out_3.e&quot;</FONT></B> : <B><FONT COLOR="#BC8F8F">&quot;out_2.e&quot;</FONT></B>,equation_systems); #endif <I><FONT COLOR="#B22222">// #ifdef LIBMESH_HAVE_EXODUS_API </FONT></I> } <B><FONT COLOR="#A020F0">return</FONT></B> 0; } <B><FONT COLOR="#228B22">void</FONT></B> assemble_poisson(EquationSystems&amp; es, <B><FONT COLOR="#228B22">const</FONT></B> std::string&amp; system_name) { libmesh_assert (system_name == <B><FONT COLOR="#BC8F8F">&quot;Poisson&quot;</FONT></B>); PerfLog perf_log (<B><FONT COLOR="#BC8F8F">&quot;Matrix Assembly&quot;</FONT></B>); <B><FONT COLOR="#228B22">const</FONT></B> MeshBase&amp; mesh = es.get_mesh(); <B><FONT COLOR="#228B22">const</FONT></B> <B><FONT COLOR="#228B22">unsigned</FONT></B> <B><FONT COLOR="#228B22">int</FONT></B> dim = mesh.mesh_dimension(); LinearImplicitSystem&amp; system = es.get_system&lt;LinearImplicitSystem&gt;(<B><FONT COLOR="#BC8F8F">&quot;Poisson&quot;</FONT></B>); <B><FONT COLOR="#228B22">const</FONT></B> DofMap&amp; dof_map = system.get_dof_map(); FEType fe_type = dof_map.variable_type(0); AutoPtr&lt;FEBase&gt; fe (FEBase::build(dim, fe_type)); QGauss qrule (dim, FIFTH); fe-&gt;attach_quadrature_rule (&amp;qrule); AutoPtr&lt;FEBase&gt; fe_face (FEBase::build(dim, fe_type)); QGauss qface(dim-1, FIFTH); fe_face-&gt;attach_quadrature_rule (&amp;qface); <B><FONT COLOR="#228B22">const</FONT></B> std::vector&lt;Real&gt;&amp; JxW = fe-&gt;get_JxW(); <B><FONT COLOR="#228B22">const</FONT></B> std::vector&lt;Point&gt;&amp; q_point = fe-&gt;get_xyz(); <B><FONT COLOR="#228B22">const</FONT></B> std::vector&lt;std::vector&lt;Real&gt; &gt;&amp; phi = fe-&gt;get_phi(); <B><FONT COLOR="#228B22">const</FONT></B> std::vector&lt;std::vector&lt;RealGradient&gt; &gt;&amp; dphi = fe-&gt;get_dphi(); DenseMatrix&lt;Number&gt; Ke; DenseVector&lt;Number&gt; Fe; <B><FONT COLOR="#5F9EA0">std</FONT></B>::vector&lt;<B><FONT COLOR="#228B22">unsigned</FONT></B> <B><FONT COLOR="#228B22">int</FONT></B>&gt; dof_indices, dof_indices2; <B><FONT COLOR="#5F9EA0">MeshBase</FONT></B>::const_element_iterator el = mesh.local_elements_begin(); <B><FONT COLOR="#228B22">const</FONT></B> MeshBase::const_element_iterator end_el = mesh.local_elements_end(); <B><FONT COLOR="#A020F0">for</FONT></B> ( ; el != end_el; ++el) { perf_log.push(<B><FONT COLOR="#BC8F8F">&quot;elem init&quot;</FONT></B>); <B><FONT COLOR="#228B22">const</FONT></B> Elem* elem = *el; dof_map.dof_indices (elem, dof_indices,0); dof_map.dof_indices (elem, dof_indices2,1); fe-&gt;reinit (elem); Ke.resize (std::max(dof_indices.size(), dof_indices2.size()), <B><FONT COLOR="#5F9EA0">std</FONT></B>::max(dof_indices.size(), dof_indices2.size())); Fe.resize (std::max(dof_indices.size(), dof_indices2.size())); perf_log.pop(<B><FONT COLOR="#BC8F8F">&quot;elem init&quot;</FONT></B>); perf_log.push (<B><FONT COLOR="#BC8F8F">&quot;Ke&quot;</FONT></B>); <B><FONT COLOR="#A020F0">for</FONT></B> (<B><FONT COLOR="#228B22">unsigned</FONT></B> <B><FONT COLOR="#228B22">int</FONT></B> qp=0; qp&lt;qrule.n_points(); qp++) <B><FONT COLOR="#A020F0">for</FONT></B> (<B><FONT COLOR="#228B22">unsigned</FONT></B> <B><FONT COLOR="#228B22">int</FONT></B> i=0; i&lt;phi.size(); i++) <B><FONT COLOR="#A020F0">for</FONT></B> (<B><FONT COLOR="#228B22">unsigned</FONT></B> <B><FONT COLOR="#228B22">int</FONT></B> j=0; j&lt;phi.size(); j++) Ke(i,j) += JxW[qp]*(dphi[i][qp]*dphi[j][qp]); perf_log.pop (<B><FONT COLOR="#BC8F8F">&quot;Ke&quot;</FONT></B>); perf_log.push (<B><FONT COLOR="#BC8F8F">&quot;Fe&quot;</FONT></B>); <B><FONT COLOR="#A020F0">for</FONT></B> (<B><FONT COLOR="#228B22">unsigned</FONT></B> <B><FONT COLOR="#228B22">int</FONT></B> qp=0; qp&lt;qrule.n_points(); qp++) { <B><FONT COLOR="#228B22">const</FONT></B> Real x = q_point[qp](0); #<B><FONT COLOR="#A020F0">if</FONT></B> LIBMESH_DIM &gt; 1 <B><FONT COLOR="#228B22">const</FONT></B> Real y = q_point[qp](1); #<B><FONT COLOR="#A020F0">else</FONT></B> <B><FONT COLOR="#228B22">const</FONT></B> Real y = 0; #endif #<B><FONT COLOR="#A020F0">if</FONT></B> LIBMESH_DIM &gt; 2 <B><FONT COLOR="#228B22">const</FONT></B> Real z = q_point[qp](2); #<B><FONT COLOR="#A020F0">else</FONT></B> <B><FONT COLOR="#228B22">const</FONT></B> Real z = 0; #endif <B><FONT COLOR="#228B22">const</FONT></B> Real eps = 1.e-3; <B><FONT COLOR="#228B22">const</FONT></B> Real uxx = (exact_solution(x-eps,y,z) + exact_solution(x+eps,y,z) + -2.*exact_solution(x,y,z))/eps/eps; <B><FONT COLOR="#228B22">const</FONT></B> Real uyy = (exact_solution(x,y-eps,z) + exact_solution(x,y+eps,z) + -2.*exact_solution(x,y,z))/eps/eps; <B><FONT COLOR="#228B22">const</FONT></B> Real uzz = (exact_solution(x,y,z-eps) + exact_solution(x,y,z+eps) + -2.*exact_solution(x,y,z))/eps/eps; Real fxy; <B><FONT COLOR="#A020F0">if</FONT></B>(dim==1) { <B><FONT COLOR="#228B22">const</FONT></B> Real pi = libMesh::pi; fxy = (0.25*pi*pi)*sin(.5*pi*x); } <B><FONT COLOR="#A020F0">else</FONT></B> { fxy = - (uxx + uyy + ((dim==2) ? 0. : uzz)); } <B><FONT COLOR="#A020F0">for</FONT></B> (<B><FONT COLOR="#228B22">unsigned</FONT></B> <B><FONT COLOR="#228B22">int</FONT></B> i=0; i&lt;phi.size(); i++) Fe(i) += JxW[qp]*fxy*phi[i][qp]; } perf_log.pop (<B><FONT COLOR="#BC8F8F">&quot;Fe&quot;</FONT></B>); { perf_log.push (<B><FONT COLOR="#BC8F8F">&quot;BCs&quot;</FONT></B>); <B><FONT COLOR="#A020F0">for</FONT></B> (<B><FONT COLOR="#228B22">unsigned</FONT></B> <B><FONT COLOR="#228B22">int</FONT></B> side=0; side&lt;elem-&gt;n_sides(); side++) <B><FONT COLOR="#A020F0">if</FONT></B> ((elem-&gt;neighbor(side) == NULL) || (elem-&gt;neighbor(side)-&gt;subdomain_id() != elem-&gt;subdomain_id())) { <B><FONT COLOR="#228B22">const</FONT></B> Real penalty = 1.e10; <B><FONT COLOR="#228B22">const</FONT></B> std::vector&lt;std::vector&lt;Real&gt; &gt;&amp; phi_face = fe_face-&gt;get_phi(); <B><FONT COLOR="#228B22">const</FONT></B> std::vector&lt;Real&gt;&amp; JxW_face = fe_face-&gt;get_JxW(); <B><FONT COLOR="#228B22">const</FONT></B> std::vector&lt;Point &gt;&amp; qface_point = fe_face-&gt;get_xyz(); fe_face-&gt;reinit(elem, side); <B><FONT COLOR="#A020F0">for</FONT></B> (<B><FONT COLOR="#228B22">unsigned</FONT></B> <B><FONT COLOR="#228B22">int</FONT></B> qp=0; qp&lt;qface.n_points(); qp++) { <B><FONT COLOR="#228B22">const</FONT></B> Real xf = qface_point[qp](0); #<B><FONT COLOR="#A020F0">if</FONT></B> LIBMESH_DIM &gt; 1 <B><FONT COLOR="#228B22">const</FONT></B> Real yf = qface_point[qp](1); #<B><FONT COLOR="#A020F0">else</FONT></B> <B><FONT COLOR="#228B22">const</FONT></B> Real yf = 0.; #endif #<B><FONT COLOR="#A020F0">if</FONT></B> LIBMESH_DIM &gt; 2 <B><FONT COLOR="#228B22">const</FONT></B> Real zf = qface_point[qp](2); #<B><FONT COLOR="#A020F0">else</FONT></B> <B><FONT COLOR="#228B22">const</FONT></B> Real zf = 0.; #endif <B><FONT COLOR="#228B22">const</FONT></B> Real value = exact_solution(xf, yf, zf); <B><FONT COLOR="#A020F0">for</FONT></B> (<B><FONT COLOR="#228B22">unsigned</FONT></B> <B><FONT COLOR="#228B22">int</FONT></B> i=0; i&lt;phi_face.size(); i++) <B><FONT COLOR="#A020F0">for</FONT></B> (<B><FONT COLOR="#228B22">unsigned</FONT></B> <B><FONT COLOR="#228B22">int</FONT></B> j=0; j&lt;phi_face.size(); j++) Ke(i,j) += JxW_face[qp]*penalty*phi_face[i][qp]*phi_face[j][qp]; <B><FONT COLOR="#A020F0">for</FONT></B> (<B><FONT COLOR="#228B22">unsigned</FONT></B> <B><FONT COLOR="#228B22">int</FONT></B> i=0; i&lt;phi_face.size(); i++) Fe(i) += JxW_face[qp]*penalty*value*phi_face[i][qp]; } } perf_log.pop (<B><FONT COLOR="#BC8F8F">&quot;BCs&quot;</FONT></B>); } perf_log.push (<B><FONT COLOR="#BC8F8F">&quot;matrix insertion&quot;</FONT></B>); <B><FONT COLOR="#A020F0">if</FONT></B> (dof_indices.size()) { system.matrix-&gt;add_matrix (Ke, dof_indices); system.rhs-&gt;add_vector (Fe, dof_indices); } <B><FONT COLOR="#A020F0">if</FONT></B> (dof_indices2.size()) { system.matrix-&gt;add_matrix (Ke, dof_indices2); system.rhs-&gt;add_vector (Fe, dof_indices2); } perf_log.pop (<B><FONT COLOR="#BC8F8F">&quot;matrix insertion&quot;</FONT></B>); } } </pre> <a name="output"></a> <br><br><br> <h1> The console output of the program: </h1> <pre> Compiling C++ (in optimized mode) subdomains_ex2.C... Linking subdomains_ex2-opt... *************************************************************** * Running Example ./subdomains_ex2-opt *************************************************************** Running ./subdomains_ex2-opt -d 1 -n 20 Mesh Information: mesh_dimension()=1 spatial_dimension()=3 n_nodes()=41 n_local_nodes()=41 n_elem()=20 n_local_elem()=20 n_active_elem()=20 n_subdomains()=2 n_partitions()=1 n_processors()=1 n_threads()=1 processor_id()=0 EquationSystems n_systems()=1 System #0, "Poisson" Type "LinearImplicit" Variables="u" "v" Finite Element Types="LAGRANGE", "JACOBI_20_00" "LAGRANGE", "JACOBI_20_00" Infinite Element Mapping="CARTESIAN" "CARTESIAN" Approximation Orders="SECOND", "THIRD" "SECOND", "THIRD" n_dofs()=42 n_local_dofs()=42 n_constrained_dofs()=0 n_local_constrained_dofs()=0 n_vectors()=1 n_matrices()=1 DofMap Sparsity Average On-Processor Bandwidth <= 3.85714 Average Off-Processor Bandwidth <= 0 Maximum On-Processor Bandwidth <= 5 Maximum Off-Processor Bandwidth <= 0 DofMap Constraints Number of DoF Constraints = 0 Number of Node Constraints = 0 Mesh Information: mesh_dimension()=1 spatial_dimension()=3 n_nodes()=41 n_local_nodes()=41 n_elem()=20 n_local_elem()=20 n_active_elem()=20 n_subdomains()=2 n_partitions()=1 n_processors()=1 n_threads()=1 processor_id()=0 ------------------------------------------------------------------- | Time: Sat Apr 7 16:03:19 2012 | | OS: Linux | | HostName: lkirk-home | | OS Release: 3.0.0-17-generic | | OS Version: #30-Ubuntu SMP Thu Mar 8 20:45:39 UTC 2012 | | Machine: x86_64 | | Username: benkirk | | Configuration: ./configure run on Sat Apr 7 15:49:27 CDT 2012 | ------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- | Matrix Assembly Performance: Alive time=0.001311, Active time=0.000867 | ----------------------------------------------------------------------------------------------------------- | Event nCalls Total Time Avg Time Total Time Avg Time % of Active Time | | w/o Sub w/o Sub With Sub With Sub w/o S With S | |-----------------------------------------------------------------------------------------------------------| | | | BCs 20 0.0002 0.000009 0.0002 0.000009 20.30 20.30 | | Fe 20 0.0002 0.000010 0.0002 0.000010 24.22 24.22 | | Ke 20 0.0000 0.000001 0.0000 0.000001 1.85 1.85 | | elem init 20 0.0004 0.000020 0.0004 0.000020 46.48 46.48 | | matrix insertion 20 0.0001 0.000003 0.0001 0.000003 7.15 7.15 | ----------------------------------------------------------------------------------------------------------- | Totals: 100 0.0009 100.00 | ----------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------ | libMesh Performance: Alive time=0.078748, Active time=0.005497 | ------------------------------------------------------------------------------------------------------------ | Event nCalls Total Time Avg Time Total Time Avg Time % of Active Time | | w/o Sub w/o Sub With Sub With Sub w/o S With S | |------------------------------------------------------------------------------------------------------------| | | | | | DofMap | | add_neighbors_to_send_list() 1 0.0000 0.000034 0.0000 0.000034 0.62 0.62 | | compute_sparsity() 1 0.0002 0.000249 0.0003 0.000282 4.53 5.13 | | create_dof_constraints() 1 0.0000 0.000001 0.0000 0.000001 0.02 0.02 | | distribute_dofs() 1 0.0002 0.000161 0.0003 0.000347 2.93 6.31 | | dof_indices() 80 0.0001 0.000001 0.0001 0.000001 1.69 1.69 | | prepare_send_list() 1 0.0000 0.000002 0.0000 0.000002 0.04 0.04 | | reinit() 1 0.0002 0.000184 0.0002 0.000184 3.35 3.35 | | | | EquationSystems | | build_solution_vector() 1 0.0002 0.000152 0.0002 0.000185 2.77 3.37 | | | | FE | | compute_affine_map() 24 0.0000 0.000002 0.0000 0.000002 0.71 0.71 | | compute_face_map() 4 0.0000 0.000002 0.0000 0.000002 0.15 0.15 | | compute_shape_functions() 24 0.0000 0.000001 0.0000 0.000001 0.29 0.29 | | init_face_shape_functions() 1 0.0000 0.000008 0.0000 0.000008 0.15 0.15 | | init_shape_functions() 5 0.0001 0.000020 0.0001 0.000020 1.82 1.82 | | | | GnuPlotIO | | write_nodal_data() 1 0.0007 0.000696 0.0007 0.000696 12.66 12.66 | | | | Mesh | | find_neighbors() 1 0.0002 0.000202 0.0002 0.000202 3.67 3.67 | | renumber_nodes_and_elem() 2 0.0000 0.000005 0.0000 0.000005 0.16 0.16 | | | | MeshOutput | | write_equation_systems() 1 0.0000 0.000040 0.0009 0.000922 0.73 16.77 | | | | MeshTools::Generation | | build_cube() 1 0.0001 0.000141 0.0001 0.000141 2.57 2.57 | | | | Parallel | | allgather() 1 0.0000 0.000001 0.0000 0.000001 0.02 0.02 | | | | Partitioner | | single_partition() 1 0.0000 0.000024 0.0000 0.000024 0.44 0.44 | | | | PetscLinearSolver | | solve() 1 0.0020 0.002015 0.0020 0.002015 36.66 36.66 | | | | System | | assemble() 1 0.0013 0.001322 0.0016 0.001563 24.05 28.43 | ------------------------------------------------------------------------------------------------------------ | Totals: 155 0.0055 100.00 | ------------------------------------------------------------------------------------------------------------ Running ./subdomains_ex2-opt -d 2 -n 15 Mesh Information: mesh_dimension()=2 spatial_dimension()=3 n_nodes()=961 n_local_nodes()=961 n_elem()=225 n_local_elem()=225 n_active_elem()=225 n_subdomains()=2 n_partitions()=1 n_processors()=1 n_threads()=1 processor_id()=0 EquationSystems n_systems()=1 System #0, "Poisson" Type "LinearImplicit" Variables="u" "v" Finite Element Types="LAGRANGE", "JACOBI_20_00" "LAGRANGE", "JACOBI_20_00" Infinite Element Mapping="CARTESIAN" "CARTESIAN" Approximation Orders="SECOND", "THIRD" "SECOND", "THIRD" n_dofs()=1022 n_local_dofs()=1022 n_constrained_dofs()=0 n_local_constrained_dofs()=0 n_vectors()=1 n_matrices()=1 DofMap Sparsity Average On-Processor Bandwidth <= 14.5616 Average Off-Processor Bandwidth <= 0 Maximum On-Processor Bandwidth <= 25 Maximum Off-Processor Bandwidth <= 0 DofMap Constraints Number of DoF Constraints = 0 Number of Node Constraints = 0 Mesh Information: mesh_dimension()=2 spatial_dimension()=3 n_nodes()=961 n_local_nodes()=961 n_elem()=225 n_local_elem()=225 n_active_elem()=225 n_subdomains()=2 n_partitions()=1 n_processors()=1 n_threads()=1 processor_id()=0 ------------------------------------------------------------------- | Time: Sat Apr 7 16:03:19 2012 | | OS: Linux | | HostName: lkirk-home | | OS Release: 3.0.0-17-generic | | OS Version: #30-Ubuntu SMP Thu Mar 8 20:45:39 UTC 2012 | | Machine: x86_64 | | Username: benkirk | | Configuration: ./configure run on Sat Apr 7 15:49:27 CDT 2012 | ------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- | Matrix Assembly Performance: Alive time=0.021012, Active time=0.019377 | ----------------------------------------------------------------------------------------------------------- | Event nCalls Total Time Avg Time Total Time Avg Time % of Active Time | | w/o Sub w/o Sub With Sub With Sub w/o S With S | |-----------------------------------------------------------------------------------------------------------| | | | BCs 225 0.0073 0.000032 0.0073 0.000032 37.68 37.68 | | Fe 225 0.0040 0.000018 0.0040 0.000018 20.57 20.57 | | Ke 225 0.0016 0.000007 0.0016 0.000007 8.24 8.24 | | elem init 225 0.0046 0.000021 0.0046 0.000021 23.97 23.97 | | matrix insertion 225 0.0018 0.000008 0.0018 0.000008 9.54 9.54 | ----------------------------------------------------------------------------------------------------------- | Totals: 1125 0.0194 100.00 | ----------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------ | libMesh Performance: Alive time=0.107728, Active time=0.040074 | ------------------------------------------------------------------------------------------------------------ | Event nCalls Total Time Avg Time Total Time Avg Time % of Active Time | | w/o Sub w/o Sub With Sub With Sub w/o S With S | |------------------------------------------------------------------------------------------------------------| | | | | | DofMap | | add_neighbors_to_send_list() 1 0.0002 0.000236 0.0002 0.000236 0.59 0.59 | | compute_sparsity() 1 0.0026 0.002559 0.0030 0.002991 6.39 7.46 | | create_dof_constraints() 1 0.0002 0.000184 0.0002 0.000184 0.46 0.46 | | distribute_dofs() 1 0.0008 0.000772 0.0021 0.002117 1.93 5.28 | | dof_indices() 900 0.0014 0.000002 0.0014 0.000002 3.41 3.41 | | prepare_send_list() 1 0.0000 0.000002 0.0000 0.000002 0.00 0.00 | | reinit() 1 0.0013 0.001343 0.0013 0.001343 3.35 3.35 | | | | EquationSystems | | build_solution_vector() 1 0.0005 0.000459 0.0008 0.000779 1.15 1.94 | | | | ExodusII_IO | | write_nodal_data() 1 0.0016 0.001648 0.0016 0.001648 4.11 4.11 | | | | FE | | compute_affine_map() 345 0.0010 0.000003 0.0010 0.000003 2.54 2.54 | | compute_face_map() 120 0.0013 0.000011 0.0032 0.000027 3.36 7.95 | | compute_shape_functions() 345 0.0005 0.000002 0.0005 0.000002 1.36 1.36 | | init_face_shape_functions() 1 0.0000 0.000018 0.0000 0.000018 0.04 0.04 | | init_shape_functions() 121 0.0018 0.000014 0.0018 0.000014 4.37 4.37 | | inverse_map() 360 0.0017 0.000005 0.0017 0.000005 4.30 4.30 | | | | Mesh | | find_neighbors() 1 0.0010 0.000958 0.0010 0.000958 2.39 2.39 | | renumber_nodes_and_elem() 2 0.0001 0.000066 0.0001 0.000066 0.33 0.33 | | | | MeshOutput | | write_equation_systems() 1 0.0000 0.000039 0.0025 0.002467 0.10 6.16 | | | | MeshTools::Generation | | build_cube() 1 0.0010 0.001015 0.0010 0.001015 2.53 2.53 | | | | Parallel | | allgather() 1 0.0000 0.000001 0.0000 0.000001 0.00 0.00 | | | | Partitioner | | single_partition() 1 0.0001 0.000107 0.0001 0.000107 0.27 0.27 | | | | PetscLinearSolver | | solve() 1 0.0092 0.009198 0.0092 0.009198 22.95 22.95 | | | | System | | assemble() 1 0.0137 0.013651 0.0213 0.021300 34.06 53.15 | ------------------------------------------------------------------------------------------------------------ | Totals: 2209 0.0401 100.00 | ------------------------------------------------------------------------------------------------------------ Running ./subdomains_ex2-opt -d 3 -n 6 Mesh Information: mesh_dimension()=3 spatial_dimension()=3 n_nodes()=2197 n_local_nodes()=2197 n_elem()=216 n_local_elem()=216 n_active_elem()=216 n_subdomains()=2 n_partitions()=1 n_processors()=1 n_threads()=1 processor_id()=0 EquationSystems n_systems()=1 System #0, "Poisson" Type "LinearImplicit" Variables="u" "v" Finite Element Types="LAGRANGE", "JACOBI_20_00" "LAGRANGE", "JACOBI_20_00" Infinite Element Mapping="CARTESIAN" "CARTESIAN" Approximation Orders="SECOND", "THIRD" "SECOND", "THIRD" n_dofs()=2522 n_local_dofs()=2522 n_constrained_dofs()=0 n_local_constrained_dofs()=0 n_vectors()=1 n_matrices()=1 DofMap Sparsity Average On-Processor Bandwidth <= 48.5337 Average Off-Processor Bandwidth <= 0 Maximum On-Processor Bandwidth <= 125 Maximum Off-Processor Bandwidth <= 0 DofMap Constraints Number of DoF Constraints = 0 Number of Node Constraints = 0 Mesh Information: mesh_dimension()=3 spatial_dimension()=3 n_nodes()=2197 n_local_nodes()=2197 n_elem()=216 n_local_elem()=216 n_active_elem()=216 n_subdomains()=2 n_partitions()=1 n_processors()=1 n_threads()=1 processor_id()=0 ------------------------------------------------------------------- | Time: Sat Apr 7 16:03:19 2012 | | OS: Linux | | HostName: lkirk-home | | OS Release: 3.0.0-17-generic | | OS Version: #30-Ubuntu SMP Thu Mar 8 20:45:39 UTC 2012 | | Machine: x86_64 | | Username: benkirk | | Configuration: ./configure run on Sat Apr 7 15:49:27 CDT 2012 | ------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- | Matrix Assembly Performance: Alive time=0.105987, Active time=0.104937 | ----------------------------------------------------------------------------------------------------------- | Event nCalls Total Time Avg Time Total Time Avg Time % of Active Time | | w/o Sub w/o Sub With Sub With Sub w/o S With S | |-----------------------------------------------------------------------------------------------------------| | | | BCs 216 0.0599 0.000277 0.0599 0.000277 57.04 57.04 | | Fe 216 0.0073 0.000034 0.0073 0.000034 6.98 6.98 | | Ke 216 0.0202 0.000093 0.0202 0.000093 19.24 19.24 | | elem init 216 0.0082 0.000038 0.0082 0.000038 7.81 7.81 | | matrix insertion 216 0.0094 0.000043 0.0094 0.000043 8.93 8.93 | ----------------------------------------------------------------------------------------------------------- | Totals: 1080 0.1049 100.00 | ----------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------ | libMesh Performance: Alive time=0.242877, Active time=0.161441 | ------------------------------------------------------------------------------------------------------------ | Event nCalls Total Time Avg Time Total Time Avg Time % of Active Time | | w/o Sub w/o Sub With Sub With Sub w/o S With S | |------------------------------------------------------------------------------------------------------------| | | | | | DofMap | | add_neighbors_to_send_list() 1 0.0005 0.000463 0.0005 0.000463 0.29 0.29 | | compute_sparsity() 1 0.0100 0.010022 0.0115 0.011502 6.21 7.12 | | create_dof_constraints() 1 0.0002 0.000177 0.0002 0.000177 0.11 0.11 | | distribute_dofs() 1 0.0012 0.001190 0.0034 0.003390 0.74 2.10 | | dof_indices() 864 0.0025 0.000003 0.0025 0.000003 1.56 1.56 | | prepare_send_list() 1 0.0000 0.000001 0.0000 0.000001 0.00 0.00 | | reinit() 1 0.0022 0.002198 0.0022 0.002198 1.36 1.36 | | | | EquationSystems | | build_solution_vector() 1 0.0008 0.000845 0.0012 0.001180 0.52 0.73 | | | | ExodusII_IO | | write_nodal_data() 1 0.0030 0.003007 0.0030 0.003007 1.86 1.86 | | | | FE | | compute_affine_map() 576 0.0041 0.000007 0.0041 0.000007 2.51 2.51 | | compute_face_map() 360 0.0015 0.000004 0.0015 0.000004 0.91 0.91 | | compute_shape_functions() 576 0.0024 0.000004 0.0024 0.000004 1.49 1.49 | | init_face_shape_functions() 1 0.0001 0.000070 0.0001 0.000070 0.04 0.04 | | init_shape_functions() 361 0.0401 0.000111 0.0401 0.000111 24.83 24.83 | | | | Mesh | | find_neighbors() 1 0.0011 0.001122 0.0011 0.001122 0.69 0.69 | | renumber_nodes_and_elem() 2 0.0003 0.000150 0.0003 0.000150 0.19 0.19 | | | | MeshOutput | | write_equation_systems() 1 0.0000 0.000038 0.0042 0.004226 0.02 2.62 | | | | MeshTools::Generation | | build_cube() 1 0.0018 0.001791 0.0018 0.001791 1.11 1.11 | | | | Parallel | | allgather() 1 0.0000 0.000001 0.0000 0.000001 0.00 0.00 | | | | Partitioner | | single_partition() 1 0.0002 0.000153 0.0002 0.000153 0.09 0.09 | | | | PetscLinearSolver | | solve() 1 0.0327 0.032663 0.0327 0.032663 20.23 20.23 | | | | System | | assemble() 1 0.0569 0.056867 0.1062 0.106167 35.22 65.76 | ------------------------------------------------------------------------------------------------------------ | Totals: 2755 0.1614 100.00 | ------------------------------------------------------------------------------------------------------------ *************************************************************** * Done Running Example ./subdomains_ex2-opt *************************************************************** </pre> </div> <?php make_footer() ?> </body> </html> <?php if (0) { ?> \#Local Variables: \#mode: html \#End: <?php } ?>
certik/libmesh
doc/html/subdomains_ex2.php
PHP
lgpl-2.1
78,660
/* $Id: QAInfo.java,v 1.6 2007/12/04 13:22:01 mke Exp $ * $Revision: 1.6 $ * $Date: 2007/12/04 13:22:01 $ * $Author: mke $ * * The SB Util Library. * Copyright (C) 2005-2007 The State and University Library of Denmark * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package dk.statsbiblioteket.util.qa; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Annotation containing all information relevant to extracting QA reports. */ @Documented @Retention(RetentionPolicy.RUNTIME) public @interface QAInfo { /** * Java doc needed. */ String JAVADOCS_NEEDED = "Javadocs needed"; /** * Code not finished. */ String UNFINISHED_CODE = "Unfinished code"; /** * Code isn't working properly. */ String FAULTY_CODE = "Faulty code"; /** * Code is messy. */ String MESSY_CODE = "Messy code"; /** * Enumeration describing the state of the QA process this class, method, * or field is in. */ public enum State { /** * Default state. Never use this manually. */ UNDEFINED, /** * No review should be performed. This is normally used when code is * under active development. */ IN_DEVELOPMENT, /** * The code should be reviewed and unit tests performed. */ QA_NEEDED, /** * Reviews and unit tests has been made and passed for this code. * The code is judged to be satisfiable. This annotation should be * changed as soon as the code is changed again. */ QA_OK } /** * Enumeration describing the possible QA levels a class, method, or field * can have. */ public enum Level { /** * Default level. Never use this manually. */ UNDEFINED, /** * The code is of utmost importance and should be thoroughly reviewed * and unit tested. */ PEDANTIC, /** * The code is important or complex and extra care should be taken when * reviewing and unit testing. */ FINE, /** * The code is standard and should be reviewed and unit tested * normally. */ NORMAL, /** * The code does not need reviewing or unit testing. */ NOT_NEEDED } /** * A free form string naming the author. For clarity use the same author * format as in {@link #reviewers}. * It is suggested to use the {@code Author} keyword for CVS controlled * code. * This annotation should name the primary responsibly party for this * piece of code. In most cases it will be the original author of the * document, but if the file receives heavy editing by other parties, they * may end up being more appropriate for the listed author. * @return the author. */ String author() default ""; /** * The current revision of the annotated element. Mostly for use on classes. * It is suggested to use the CVS {@code Id} keyword for CVS controlled * repositories. * @return the revision. */ String revision() default ""; /** * Free form string describing the deadline. * @return the deadline. */ String deadline() default ""; /** * Developers responsible for reviewing this class or method. * Fx <code>{"mke", "te"}</code> - use same convention as * {@link #author}. * It is advised to keep a list of all reviewers here, with the last * one in the list being the last person to review the code. This way it * will be easy to construct a simple audit trail for the code. * @return a list of reviewers. */ String[] reviewers() default {}; // Note use of array /** * A freeform comment that can be included in QA reports. * @return the comment. */ String comment() default ""; /** * The {@link Level} of the annotated element. * @return the severity level. */ Level level() default Level.UNDEFINED; /** * The {@link State} of the annotated element. * @return the state. */ State state() default State.UNDEFINED; }
statsbiblioteket/sbutil
sbutil-qa/src/main/java/dk/statsbiblioteket/util/qa/QAInfo.java
Java
lgpl-2.1
5,049
#!/usr/bin/python """Test of ARIA horizontal sliders using Firefox.""" from macaroon.playback import * import utils sequence = MacroSequence() #sequence.append(WaitForDocLoad()) sequence.append(PauseAction(10000)) sequence.append(KeyComboAction("Tab")) sequence.append(KeyComboAction("Tab")) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Tab")) sequence.append(utils.AssertPresentationAction( "1. Tab to Volume Horizontal Slider", ["BRAILLE LINE: 'Volume 0 % horizontal slider'", " VISIBLE: 'Volume 0 % horizontal slider', cursor=1", "SPEECH OUTPUT: 'Volume horizontal slider 0 %'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Right")) sequence.append(utils.AssertPresentationAction( "2. Volume Right Arrow", ["BRAILLE LINE: 'Volume 1 % horizontal slider'", " VISIBLE: 'Volume 1 % horizontal slider', cursor=1", "SPEECH OUTPUT: '1 %'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Right")) sequence.append(utils.AssertPresentationAction( "3. Volume Right Arrow", ["BRAILLE LINE: 'Volume 2 % horizontal slider'", " VISIBLE: 'Volume 2 % horizontal slider', cursor=1", "SPEECH OUTPUT: '2 %'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Left")) sequence.append(utils.AssertPresentationAction( "4. Volume Left Arrow", ["BRAILLE LINE: 'Volume 1 % horizontal slider'", " VISIBLE: 'Volume 1 % horizontal slider', cursor=1", "SPEECH OUTPUT: '1 %'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Left")) sequence.append(utils.AssertPresentationAction( "5. Volume Left Arrow", ["BRAILLE LINE: 'Volume 0 % horizontal slider'", " VISIBLE: 'Volume 0 % horizontal slider', cursor=1", "SPEECH OUTPUT: '0 %'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Up")) sequence.append(utils.AssertPresentationAction( "6. Volume Up Arrow", ["BRAILLE LINE: 'Volume 1 % horizontal slider'", " VISIBLE: 'Volume 1 % horizontal slider', cursor=1", "SPEECH OUTPUT: '1 %'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Up")) sequence.append(utils.AssertPresentationAction( "7. Volume Up Arrow", ["BRAILLE LINE: 'Volume 2 % horizontal slider'", " VISIBLE: 'Volume 2 % horizontal slider', cursor=1", "SPEECH OUTPUT: '2 %'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Down")) sequence.append(utils.AssertPresentationAction( "8. Volume Down Arrow", ["BRAILLE LINE: 'Volume 1 % horizontal slider'", " VISIBLE: 'Volume 1 % horizontal slider', cursor=1", "SPEECH OUTPUT: '1 %'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Down")) sequence.append(utils.AssertPresentationAction( "9. Volume Down Arrow", ["BRAILLE LINE: 'Volume 0 % horizontal slider'", " VISIBLE: 'Volume 0 % horizontal slider', cursor=1", "SPEECH OUTPUT: '0 %'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Page_Up")) sequence.append(utils.AssertPresentationAction( "10. Volume Page Up", ["BRAILLE LINE: 'Volume 25 % horizontal slider'", " VISIBLE: 'Volume 25 % horizontal slider', cursor=1", "SPEECH OUTPUT: '25 %'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Page_Down")) sequence.append(utils.AssertPresentationAction( "11. Volume Page Down", ["BRAILLE LINE: 'Volume 0 % horizontal slider'", " VISIBLE: 'Volume 0 % horizontal slider', cursor=1", "SPEECH OUTPUT: '0 %'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("End")) sequence.append(utils.AssertPresentationAction( "12. Volume End", ["BRAILLE LINE: 'Volume 100 % horizontal slider'", " VISIBLE: 'Volume 100 % horizontal slider', cursor=1", "SPEECH OUTPUT: '100 %'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Home")) sequence.append(utils.AssertPresentationAction( "13. Volume Home", ["BRAILLE LINE: 'Volume 0 % horizontal slider'", " VISIBLE: 'Volume 0 % horizontal slider', cursor=1", "SPEECH OUTPUT: '0 %'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Tab")) sequence.append(utils.AssertPresentationAction( "14. Tab to Food Quality Horizontal Slider", ["KNOWN ISSUE: The double-presentation is because of the authoring, putting the name and value into the description", "BRAILLE LINE: 'Food Quality terrible horizontal slider'", " VISIBLE: 'Food Quality terrible horizontal', cursor=1", "SPEECH OUTPUT: 'Food Quality horizontal slider terrible.'", "SPEECH OUTPUT: 'Food Quality: terrible (1 of 5)'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Right")) sequence.append(utils.AssertPresentationAction( "15. Food Quality Right Arrow", ["BRAILLE LINE: 'Food Quality bad horizontal slider'", " VISIBLE: 'Food Quality bad horizontal slid', cursor=1", "SPEECH OUTPUT: 'bad'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Right")) sequence.append(utils.AssertPresentationAction( "16. Food Quality Right Arrow", ["BRAILLE LINE: 'Food Quality decent horizontal slider'", " VISIBLE: 'Food Quality decent horizontal s', cursor=1", "SPEECH OUTPUT: 'decent'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Left")) sequence.append(utils.AssertPresentationAction( "17. Food Quality Left Arrow", ["BRAILLE LINE: 'Food Quality bad horizontal slider'", " VISIBLE: 'Food Quality bad horizontal slid', cursor=1", "SPEECH OUTPUT: 'bad'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Up")) sequence.append(utils.AssertPresentationAction( "18. Food Quality Up Arrow", ["BRAILLE LINE: 'Food Quality decent horizontal slider'", " VISIBLE: 'Food Quality decent horizontal s', cursor=1", "SPEECH OUTPUT: 'decent'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Down")) sequence.append(utils.AssertPresentationAction( "19. Food Quality Down Arrow", ["BRAILLE LINE: 'Food Quality bad horizontal slider'", " VISIBLE: 'Food Quality bad horizontal slid', cursor=1", "SPEECH OUTPUT: 'bad'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Down")) sequence.append(utils.AssertPresentationAction( "20. Food Quality Down Arrow", ["BRAILLE LINE: 'Food Quality terrible horizontal slider'", " VISIBLE: 'Food Quality terrible horizontal', cursor=1", "SPEECH OUTPUT: 'terrible'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Page_Up")) sequence.append(utils.AssertPresentationAction( "21. Food Quality Page Up", ["BRAILLE LINE: 'Food Quality bad horizontal slider'", " VISIBLE: 'Food Quality bad horizontal slid', cursor=1", "SPEECH OUTPUT: 'bad'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Page_Down")) sequence.append(utils.AssertPresentationAction( "22. Food Quality Page Down", ["BRAILLE LINE: 'Food Quality terrible horizontal slider'", " VISIBLE: 'Food Quality terrible horizontal', cursor=1", "SPEECH OUTPUT: 'terrible'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("End")) sequence.append(utils.AssertPresentationAction( "23. Food Quality End", ["BRAILLE LINE: 'Food Quality excellent horizontal slider'", " VISIBLE: 'Food Quality excellent horizonta', cursor=1", "SPEECH OUTPUT: 'excellent'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Home")) sequence.append(utils.AssertPresentationAction( "24. Food Quality Home", ["BRAILLE LINE: 'Food Quality terrible horizontal slider'", " VISIBLE: 'Food Quality terrible horizontal', cursor=1", "SPEECH OUTPUT: 'terrible'"])) sequence.append(utils.AssertionSummaryAction()) sequence.start()
GNOME/orca
test/keystrokes/firefox/aria_slider_tpg.py
Python
lgpl-2.1
8,352
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.type.descriptor.java; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.sql.Blob; import java.sql.SQLException; import org.hibernate.HibernateException; import org.hibernate.engine.jdbc.BinaryStream; import org.hibernate.engine.jdbc.internal.BinaryStreamImpl; import org.hibernate.type.descriptor.WrapperOptions; /** * Descriptor for {@code Byte[]} handling. * * @author Steve Ebersole */ public class ByteArrayTypeDescriptor extends AbstractTypeDescriptor<Byte[]> { public static final ByteArrayTypeDescriptor INSTANCE = new ByteArrayTypeDescriptor(); @SuppressWarnings({ "unchecked" }) public ByteArrayTypeDescriptor() { super( Byte[].class, ArrayMutabilityPlan.INSTANCE ); } @Override public String toString(Byte[] bytes) { final StringBuilder buf = new StringBuilder(); for ( Byte aByte : bytes ) { final String hexStr = Integer.toHexString( aByte - Byte.MIN_VALUE ); if ( hexStr.length() == 1 ) { buf.append( '0' ); } buf.append( hexStr ); } return buf.toString(); } @Override public Byte[] fromString(String string) { if ( string == null ) { return null; } if ( string.length() % 2 != 0 ) { throw new IllegalArgumentException( "The string is not a valid string representation of a binary content." ); } Byte[] bytes = new Byte[string.length() / 2]; for ( int i = 0; i < bytes.length; i++ ) { final String hexStr = string.substring( i * 2, (i + 1) * 2 ); bytes[i] = (byte) ( Integer.parseInt( hexStr, 16 ) + Byte.MIN_VALUE ); } return bytes; } @SuppressWarnings({ "unchecked" }) @Override public <X> X unwrap(Byte[] value, Class<X> type, WrapperOptions options) { if ( value == null ) { return null; } if ( Byte[].class.isAssignableFrom( type ) ) { return (X) value; } if ( byte[].class.isAssignableFrom( type ) ) { return (X) unwrapBytes( value ); } if ( InputStream.class.isAssignableFrom( type ) ) { return (X) new ByteArrayInputStream( unwrapBytes( value ) ); } if ( BinaryStream.class.isAssignableFrom( type ) ) { return (X) new BinaryStreamImpl( unwrapBytes( value ) ); } if ( Blob.class.isAssignableFrom( type ) ) { return (X) options.getLobCreator().createBlob( unwrapBytes( value ) ); } throw unknownUnwrap( type ); } @Override public <X> Byte[] wrap(X value, WrapperOptions options) { if ( value == null ) { return null; } if ( Byte[].class.isInstance( value ) ) { return (Byte[]) value; } if ( byte[].class.isInstance( value ) ) { return wrapBytes( (byte[]) value ); } if ( InputStream.class.isInstance( value ) ) { return wrapBytes( DataHelper.extractBytes( (InputStream) value ) ); } if ( Blob.class.isInstance( value ) || DataHelper.isNClob( value.getClass() ) ) { try { return wrapBytes( DataHelper.extractBytes( ( (Blob) value ).getBinaryStream() ) ); } catch ( SQLException e ) { throw new HibernateException( "Unable to access lob stream", e ); } } throw unknownWrap( value.getClass() ); } private Byte[] wrapBytes(byte[] bytes) { if ( bytes == null ) { return null; } final Byte[] result = new Byte[bytes.length]; for ( int i = 0; i < bytes.length; i++ ) { result[i] = bytes[i]; } return result; } private byte[] unwrapBytes(Byte[] bytes) { if ( bytes == null ) { return null; } final byte[] result = new byte[bytes.length]; for ( int i = 0; i < bytes.length; i++ ) { result[i] = bytes[i]; } return result; } }
kevin-chen-hw/LDAE
com.huawei.soa.ldae/src/main/java/org/hibernate/type/descriptor/java/ByteArrayTypeDescriptor.java
Java
lgpl-2.1
4,548
#ifndef FILE_OBJECTS #define FILE_OBJECTS /* *************************************************************************/ /* File: geomobjects.hpp */ /* Author: Joachim Schoeberl */ /* Date: 20. Jul. 02 */ /* *************************************************************************/ namespace netgen { template <int D, typename T = double> class Vec; template <int D, typename T = double> class Point; template <int D, typename T> class Point { protected: T x[D]; public: Point () { ; } Point (T ax) { for (int i = 0; i < D; i++) x[i] = ax; } Point (T ax, T ay) { // static_assert(D==2, "Point<D> constructor with 2 args called"); x[0] = ax; x[1] = ay; } Point (T ax, T ay, T az) { // static_assert(D==3, "Point<D> constructor with 3 args called"); x[0] = ax; x[1] = ay; x[2] = az; } Point (T ax, T ay, T az, T au) { x[0] = ax; x[1] = ay; x[2] = az; x[3] = au;} template <typename T2> Point (const Point<D,T2> & p2) { for (int i = 0; i < D; i++) x[i] = p2(i); } explicit Point (const Vec<D,T> & v) { for (int i = 0; i < D; i++) x[i] = v(i); } template <typename T2> Point & operator= (const Point<D,T2> & p2) { for (int i = 0; i < D; i++) x[i] = p2(i); return *this; } Point & operator= (T val) { for (int i = 0; i < D; i++) x[i] = val; return *this; } T & operator() (int i) { return x[i]; } const T & operator() (int i) const { return x[i]; } T& operator[] (int i) { return x[i]; } const T& operator[] (int i) const { return x[i]; } operator const T* () const { return x; } void DoArchive(Archive& archive) { for(int i=0; i<D; i++) archive & x[i]; } }; template <int D, typename T> class Vec { protected: T x[D]; public: Vec () { ; } // for (int i = 0; i < D; i++) x[i] = 0; } Vec (T ax) { for (int i = 0; i < D; i++) x[i] = ax; } Vec (T ax, T ay) { // static_assert(D==2, "Vec<D> constructor with 2 args called"); x[0] = ax; x[1] = ay; } Vec (T ax, T ay, T az) { // static_assert(D==3, "Vec<D> constructor with 3 args called"); x[0] = ax; x[1] = ay; x[2] = az; } Vec (T ax, T ay, T az, T au) { x[0] = ax; x[1] = ay; x[2] = az; x[3] = au; } Vec (const Vec<D> & p2) { for (int i = 0; i < D; i++) x[i] = p2.x[i]; } explicit Vec (const Point<D,T> & p) { for (int i = 0; i < D; i++) x[i] = p(i); } explicit Vec(const Point<D,T>& p1, const Point<D,T>& p2) { for(int i=0; i<D; i++) x[i] = p2(i)-p1(i); } template <typename T2> Vec & operator= (const Vec<D,T2> & p2) { for (int i = 0; i < D; i++) x[i] = p2(i); return *this; } Vec & operator= (T s) { for (int i = 0; i < D; i++) x[i] = s; return *this; } bool operator== (const Vec<D,T> &a) const { bool res = true; for (auto i : Range(D)) res &= (x[i]==a.x[i]); return res; } T & operator() (int i) { return x[i]; } const T & operator() (int i) const { return x[i]; } T& operator[] (int i) { return x[i]; } const T& operator[] (int i) const { return x[i]; } operator const T* () const { return x; } void DoArchive(Archive& archive) { for(int i=0; i<D; i++) archive & x[i]; } T Length () const { T l = 0; for (int i = 0; i < D; i++) l += x[i] * x[i]; return sqrt (l); } T Length2 () const { T l = 0; for (int i = 0; i < D; i++) l += x[i] * x[i]; return l; } Vec & Normalize () { T l = Length(); // if (l != 0) for (int i = 0; i < D; i++) x[i] /= (l+1e-40); return *this; } Vec<D> GetNormal () const; }; template<int D> inline Vec<D> operator-(const Point<D>& p1, const Point<D>& p2) { Vec<D> result; for(auto i : Range(D)) result[i] = p1[i] - p2[i]; return result; } template<int D> inline Vec<D> operator*(const Vec<D>& v, double d) { Vec<D> result; for(auto i : Range(D)) result[i] = d*v[i]; return result; } inline double Cross2(const Vec<2>& v1, const Vec<2>& v2) { return v1[0] * v2[1] - v1[1] * v2[0]; } // are points clockwise? inline bool CW(const Point<2>& p1, const Point<2>& p2, const Point<2>& p3) { return Cross2(p2-p1, p3-p2) < 0; } // are points counterclockwise? inline bool CCW(const Point<2>& p1, const Point<2>& p2, const Point<2>& p3) { return Cross2(p2-p1, p3-p2) > 0; } // are strictly points counterclockwise? inline bool CCW(const Point<2>& p1, const Point<2>& p2, const Point<2>& p3, double eps) { auto v1 = p2-p1; auto v2 = p3-p2; return Cross2(v1, v2) > eps*eps*max2(v1.Length2(), v2.Length2()); } template <int H, int W=H, typename T = double> class Mat { protected: T x[H*W]; public: Mat () { ; } Mat (const Mat & b) { for (int i = 0; i < H*W; i++) x[i] = b.x[i]; } Mat & operator= (T s) { for (int i = 0; i < H*W; i++) x[i] = s; return *this; } Mat & operator= (const Mat & b) { for (int i = 0; i < H*W; i++) x[i] = b.x[i]; return *this; } T & operator() (int i, int j) { return x[i*W+j]; } const T & operator() (int i, int j) const { return x[i*W+j]; } T & operator() (int i) { return x[i]; } const T & operator() (int i) const { return x[i]; } Vec<H,T> Col (int i) const { Vec<H,T> hv; for (int j = 0; j < H; j++) hv(j) = x[j*W+i]; return hv; } Vec<W,T> Row (int i) const { Vec<W,T> hv; for (int j = 0; j < W; j++) hv(j) = x[i*W+j]; return hv; } void Solve (const Vec<H,T> & rhs, Vec<W,T> & sol) const { Mat<W,H,T> inv; CalcInverse (*this, inv); sol = inv * rhs; } void DoArchive(Archive & ar) { ar.Do(x, H*W); } }; template <int D> class Box { protected: Point<D> pmin, pmax; public: Box () { ; } Box ( const Point<D> & p1) { for (int i = 0; i < D; i++) pmin(i) = pmax(i) = p1(i); } Box ( const Point<D> & p1, const Point<D> & p2) { for (int i = 0; i < D; i++) { pmin(i) = min2(p1(i), p2(i)); pmax(i) = max2(p1(i), p2(i)); } } Box (const Point<D> & p1, const Point<D> & p2, const Point<D> & p3) : Box(p1,p2) { Add (p3); } enum EB_TYPE { EMPTY_BOX = 1 }; Box ( EB_TYPE et ) { for (int i = 0; i < D; i++) { pmin(i) = 1e99; pmax(i) = -1e99; } // pmin = Point<D> (1e99, 1e99, 1e99); // pmax = Point<D> (-1e99, -1e99, -1e99); } const Point<D> & PMin () const { return pmin; } const Point<D> & PMax () const { return pmax; } void Set (const Point<D> & p) { pmin = pmax = p; } void Add (const Point<D> & p) { for (int i = 0; i < D; i++) { if (p(i) < pmin(i)) pmin(i) = p(i); /* else */ if (p(i) > pmax(i)) pmax(i) = p(i); // optimization invalid for empty-box ! } } template <typename T1, typename T2> void Set (const IndirectArray<T1, T2> & points) { // Set (points[points.Begin()]); Set (points[*points.Range().begin()]); // for (int i = points.Begin()+1; i < points.End(); i++) for (int i : points.Range().Modify(1,0)) Add (points[i]); } template <typename T1, typename T2> void Add (const IndirectArray<T1, T2> & points) { // for (int i = points.Begin(); i < points.End(); i++) for (int i : points.Range()) Add (points[i]); } Point<D> Center () const { Point<D> c; for (int i = 0; i < D; i++) c(i) = 0.5 * (pmin(i)+pmax(i)); return c; } double Diam () const { return Abs (pmax-pmin); } Point<D> GetPointNr (int nr) const { Point<D> p; for (int i = 0; i < D; i++) { p(i) = (nr & 1) ? pmax(i) : pmin(i); nr >>= 1; } return p; } bool Intersect (const Box<D> & box2) const { for (int i = 0; i < D; i++) if (pmin(i) > box2.pmax(i) || pmax(i) < box2.pmin(i)) return 0; return 1; } bool IsIn (const Point<D> & p) const { for (int i = 0; i < D; i++) if (p(i) < pmin(i) || p(i) > pmax(i)) return false; return true; } // is point in eps-increased box bool IsIn (const Point<D> & p, double eps) const { for (int i = 0; i < D; i++) if (p(i) < pmin(i)-eps || p(i) > pmax(i)+eps) return false; return true; } void Increase (double dist) { for (int i = 0; i < D; i++) { pmin(i) -= dist; pmax(i) += dist; } } void Scale (double factor) { auto center = Center(); pmin = center + factor*(pmin-center); pmax = center + factor*(pmax-center); } void DoArchive(Archive& archive) { archive & pmin & pmax; } }; template <int D> class BoxSphere : public Box<D> { protected: /// Point<D> c; /// double diam; /// double inner; public: /// BoxSphere () { }; /// BoxSphere (const Box<D> & box) : Box<D> (box) { CalcDiamCenter(); }; /// BoxSphere ( Point<D> apmin, Point<D> apmax ) : Box<D> (apmin, apmax) { CalcDiamCenter(); } /// const Point<D> & Center () const { return c; } /// double Diam () const { return diam; } /// double Inner () const { return inner; } /// void GetSubBox (int nr, BoxSphere & sbox) const { for (int i = 0; i < D; i++) { if (nr & 1) { sbox.pmin(i) = c(i); sbox.pmax(i) = this->pmax(i); } else { sbox.pmin(i) = this->pmin(i); sbox.pmax(i) = c(i); } sbox.c(i) = 0.5 * (sbox.pmin(i) + sbox.pmax(i)); nr >>= 1; } sbox.diam = 0.5 * diam; sbox.inner = 0.5 * inner; } /// void CalcDiamCenter () { c = Box<D>::Center (); diam = Dist (this->pmin, this->pmax); inner = this->pmax(0) - this->pmin(0); for (int i = 1; i < D; i++) if (this->pmax(i) - this->pmin(i) < inner) inner = this->pmax(i) - this->pmin(i); } }; #ifdef PARALLEL_OLD template <> inline MPI_Datatype MyGetMPIType<Vec<3, double> > () { static MPI_Datatype MPI_T = 0; if (!MPI_T) { MPI_Type_contiguous ( 3, MPI_DOUBLE, &MPI_T); MPI_Type_commit ( &MPI_T ); } return MPI_T; }; #endif } #endif
live-clones/netgen
libsrc/gprim/geomobjects.hpp
C++
lgpl-2.1
10,864
package com.teambrmodding.neotech.client.gui.machines.processors; import com.teambr.bookshelf.client.gui.GuiColor; import com.teambr.bookshelf.client.gui.GuiTextFormat; import com.teambr.bookshelf.client.gui.component.control.GuiComponentItemStackButton; import com.teambr.bookshelf.client.gui.component.display.GuiComponentColoredZone; import com.teambr.bookshelf.client.gui.component.display.GuiComponentFluidTank; import com.teambr.bookshelf.client.gui.component.display.GuiComponentTextureAnimated; import com.teambr.bookshelf.network.PacketManager; import com.teambr.bookshelf.util.ClientUtils; import com.teambr.bookshelf.util.EnergyUtils; import com.teambrmodding.neotech.client.gui.machines.GuiAbstractMachine; import com.teambrmodding.neotech.collections.EnumInputOutputMode; import com.teambrmodding.neotech.common.container.machines.processors.ContainerSolidifier; import com.teambrmodding.neotech.common.tiles.MachineProcessor; import com.teambrmodding.neotech.common.tiles.machines.processors.TileSolidifier; import com.teambrmodding.neotech.lib.Reference; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraftforge.energy.CapabilityEnergy; import javax.annotation.Nullable; import java.awt.*; import java.util.ArrayList; import java.util.List; /** * This file was created for NeoTech * * NeoTech is licensed under the * Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License: * http://creativecommons.org/licenses/by-nc-sa/4.0/ * * @author Paul Davis - pauljoda * @since 2/17/2017 */ public class GuiSolidifier extends GuiAbstractMachine<ContainerSolidifier> { protected TileSolidifier solidifier; public GuiSolidifier(EntityPlayer player, TileSolidifier solidifier) { super(new ContainerSolidifier(player.inventory, solidifier), 175, 165, "neotech.electricSolidifier.title", new ResourceLocation(Reference.MOD_ID, "textures/gui/electricSolidifier.png"), solidifier, player); this.solidifier = solidifier; addComponents(); } /** * This will be called after the GUI has been initialized and should be where you add all components. */ @Override protected void addComponents() { if(solidifier != null) { // Progress Arrow components.add(new GuiComponentTextureAnimated(this, 95, 35, 176, 80, 24, 17, GuiComponentTextureAnimated.ANIMATION_DIRECTION.RIGHT) { @Override protected int getCurrentProgress(int scale) { return ((MachineProcessor)machine).getCookProgressScaled(24); } }); // Power Bar components.add(new GuiComponentTextureAnimated(this, 16, 12, 176, 97, 16, 62, GuiComponentTextureAnimated.ANIMATION_DIRECTION.UP) { @Override protected int getCurrentProgress(int scale) { return machine.getEnergyStored() * scale / machine.getMaxEnergyStored(); } /** * Used to determine if a dynamic tooltip is needed at runtime * * @param mouseX Mouse X Pos * @param mouseY Mouse Y Pos * @return A list of string to display */ @Nullable @Override public List<String> getDynamicToolTip(int mouseX, int mouseY) { List<String> toolTip = new ArrayList<>(); EnergyUtils.addToolTipInfo(machine.getCapability(CapabilityEnergy.ENERGY, null), toolTip, machine.energyStorage.getMaxInsert(), machine.energyStorage.getMaxExtract()); return toolTip; } }); // Input Tanks components.add(new GuiComponentFluidTank(this, 40, 12, 49, 62, solidifier.tanks[TileSolidifier.TANK]){ /** * Used to determine if a dynamic tooltip is needed at runtime * * @param mouseX Mouse X Pos * @param mouseY Mouse Y Pos * @return A list of string to display */ @Nullable @Override public List<String> getDynamicToolTip(int mouseX, int mouseY) { List<String> toolTip = new ArrayList<>(); toolTip.add(solidifier.tanks[TileSolidifier.TANK].getFluid() != null ? GuiColor.ORANGE + solidifier.tanks[TileSolidifier.TANK].getFluid().getLocalizedName() : GuiColor.RED + ClientUtils.translate("neotech.text.empty")); toolTip.add(ClientUtils.formatNumber(solidifier.tanks[TileSolidifier.TANK].getFluidAmount()) + " / " + ClientUtils.formatNumber(solidifier.tanks[TileSolidifier.TANK].getCapacity()) + " mb"); toolTip.add(""); toolTip.add(GuiColor.GRAY + "" + GuiTextFormat.ITALICS + ClientUtils.translate("neotech.text.clearTank")); return toolTip; } /** * Called when the mouse is pressed * * @param x Mouse X Position * @param y Mouse Y Position * @param button Mouse Button */ @Override public void mouseDown(int x, int y, int button) { if(ClientUtils.isCtrlPressed() && ClientUtils.isShiftPressed()) { solidifier.tanks[TileSolidifier.TANK].setFluid(null); PacketManager.updateTileWithClientInfo(solidifier); } } }); components.add(new GuiComponentColoredZone(this, 39, 11, 51, 63, new Color(0, 0, 0, 0)){ /** * Override this to change the color * * @return The color, by default the passed color */ @Override protected Color getDynamicColor() { Color color = new Color(0, 0, 0, 0); // Checking if input is enabled for(EnumFacing dir : EnumFacing.values()) { if(machine.getModeForSide(dir) == EnumInputOutputMode.ALL_MODES) { color = EnumInputOutputMode.ALL_MODES.getHighlightColor(); break; } else if(machine.getModeForSide(dir) == EnumInputOutputMode.INPUT_ALL) color = EnumInputOutputMode.INPUT_ALL.getHighlightColor(); } // Color was assigned if(color.getAlpha() != 0) color = new Color(color.getRed(), color.getGreen(), color.getBlue(), 80); return color; } }); // Output Item components.add(new GuiComponentColoredZone(this, 127, 29, 28, 28, new Color(0, 0, 0, 0)){ /** * Override this to change the color * * @return The color, by default the passed color */ @Override protected Color getDynamicColor() { Color color = new Color(0, 0, 0, 0); // Checking if input is enabled for(EnumFacing dir : EnumFacing.values()) { if(machine.getModeForSide(dir) == EnumInputOutputMode.ALL_MODES) { color = EnumInputOutputMode.ALL_MODES.getHighlightColor(); break; } else if(machine.getModeForSide(dir) == EnumInputOutputMode.OUTPUT_ALL) color = EnumInputOutputMode.OUTPUT_ALL.getHighlightColor(); } // Color was assigned if(color.getAlpha() != 0) color = new Color(color.getRed(), color.getGreen(), color.getBlue(), 80); return color; } }); // Item Stack Button components.add(new GuiComponentItemStackButton(this, 96, 54, 224, 111, 22, 22, solidifier.currentMode.getDisplayStack()) { @Override protected void doAction() { solidifier.toggleMode(); solidifier.sendValueToServer(TileSolidifier.UPDATE_MODE_NBT, 0); setDisplayStack(solidifier.currentMode.getDisplayStack()); } }); } } }
HickGamer/Better-Utilites
Reference Code/Neotech Code/java/com/teambrmodding/neotech/client/gui/machines/processors/GuiSolidifier.java
Java
lgpl-2.1
8,916
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.collection.spi; import java.io.Serializable; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.Iterator; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.loader.CollectionAliases; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.type.Type; /** * Persistent collections are treated as value objects by Hibernate. * ie. they have no independent existence beyond the object holding * a reference to them. Unlike instances of entity classes, they are * automatically deleted when unreferenced and automatically become * persistent when held by a persistent object. Collections can be * passed between different objects (change "roles") and this might * cause their elements to move from one database table to another.<br> * <br> * Hibernate "wraps" a java collection in an instance of * PersistentCollection. This mechanism is designed to support * tracking of changes to the collection's persistent state and * lazy instantiation of collection elements. The downside is that * only certain abstract collection types are supported and any * extra semantics are lost<br> * <br> * Applications should <em>never</em> use classes in this package * directly, unless extending the "framework" here.<br> * <br> * Changes to <em>structure</em> of the collection are recorded by the * collection calling back to the session. Changes to mutable * elements (ie. composite elements) are discovered by cloning their * state when the collection is initialized and comparing at flush * time. * * @author Gavin King */ public interface PersistentCollection { /** * Get the owning entity. Note that the owner is only * set during the flush cycle, and when a new collection * wrapper is created while loading an entity. * * @return The owner */ public Object getOwner(); /** * Set the reference to the owning entity * * @param entity The owner */ public void setOwner(Object entity); /** * Is the collection empty? (don't try to initialize the collection) * * @return {@code false} if the collection is non-empty; {@code true} otherwise. */ public boolean empty(); /** * After flushing, re-init snapshot state. * * @param key The collection instance key (fk value). * @param role The collection role * @param snapshot The snapshot state */ public void setSnapshot(Serializable key, String role, Serializable snapshot); /** * After flushing, clear any "queued" additions, since the * database state is now synchronized with the memory state. */ public void postAction(); /** * Return the user-visible collection (or array) instance * * @return The underlying collection/array */ public Object getValue(); /** * Called just before reading any rows from the JDBC result set */ public void beginRead(); /** * Called after reading all rows from the JDBC result set * * @return Whether to end the read. */ public boolean endRead(); /** * Called after initializing from cache * * @return ?? */ public boolean afterInitialize(); /** * Could the application possibly have a direct reference to * the underlying collection implementation? * * @return {@code true} indicates that the application might have access to the underlying collection/array. */ public boolean isDirectlyAccessible(); /** * Disassociate this collection from the given session. * * @param currentSession The session we are disassociating from. Used for validations. * * @return true if this was currently associated with the given session */ public boolean unsetSession(SessionImplementor currentSession); /** * Associate the collection with the given session. * * @param session The session to associate with * * @return false if the collection was already associated with the session * * @throws HibernateException if the collection was already associated * with another open session */ public boolean setCurrentSession(SessionImplementor session) throws HibernateException; /** * Read the state of the collection from a disassembled cached value * * @param persister The collection persister * @param disassembled The disassembled cached state * @param owner The collection owner */ public void initializeFromCache(CollectionPersister persister, Serializable disassembled, Object owner); /** * Iterate all collection entries, during update of the database * * @param persister The collection persister. * * @return The iterator */ public Iterator entries(CollectionPersister persister); /** * Read a row from the JDBC result set * * @param rs The JDBC ResultSet * @param role The collection role * @param descriptor The aliases used for the columns making up the collection * @param owner The collection owner * * @return The read object * * @throws HibernateException Generally indicates a problem resolving data read from the ResultSet * @throws SQLException Indicates a problem accessing the ResultSet */ public Object readFrom(ResultSet rs, CollectionPersister role, CollectionAliases descriptor, Object owner) throws HibernateException, SQLException; /** * Get the identifier of the given collection entry. This refers to the collection identifier, not the * identifier of the (possibly) entity elements. This is only valid for invocation on the * {@code idbag} collection. * * @param entry The collection entry/element * @param i The assumed identifier (?) * * @return The identifier value */ public Object getIdentifier(Object entry, int i); /** * Get the index of the given collection entry * * @param entry The collection entry/element * @param i The assumed index * @param persister it was more elegant before we added this... * * @return The index value */ public Object getIndex(Object entry, int i, CollectionPersister persister); /** * Get the value of the given collection entry. Generally the given entry parameter value will just be returned. * Might get a different value for a duplicate entries in a Set. * * @param entry The object instance for which to get the collection element instance. * * @return The corresponding object that is part of the collection elements. */ public Object getElement(Object entry); /** * Get the snapshot value of the given collection entry * * @param entry The entry * @param i The index * * @return The snapshot state for that element */ public Object getSnapshotElement(Object entry, int i); /** * Called before any elements are read into the collection, * allowing appropriate initializations to occur. * * @param persister The underlying collection persister. * @param anticipatedSize The anticipated size of the collection after initialization is complete. */ public void beforeInitialize(CollectionPersister persister, int anticipatedSize); /** * Does the current state exactly match the snapshot? * * @param persister The collection persister * * @return {@code true} if the current state and the snapshot state match. * */ public boolean equalsSnapshot(CollectionPersister persister); /** * Is the snapshot empty? * * @param snapshot The snapshot to check * * @return {@code true} if the given snapshot is empty */ public boolean isSnapshotEmpty(Serializable snapshot); /** * Disassemble the collection to get it ready for the cache * * @param persister The collection persister * * @return The disassembled state */ public Serializable disassemble(CollectionPersister persister) ; /** * Do we need to completely recreate this collection when it changes? * * @param persister The collection persister * * @return {@code true} if a change requires a recreate. */ public boolean needsRecreate(CollectionPersister persister); /** * Return a new snapshot of the current state of the collection * * @param persister The collection persister * * @return The snapshot */ public Serializable getSnapshot(CollectionPersister persister); /** * To be called internally by the session, forcing immediate initialization. */ public void forceInitialization(); /** * Does the given element/entry exist in the collection? * * @param entry The object to check if it exists as a collection element * @param i Unused * * @return {@code true} if the given entry is a collection element */ public boolean entryExists(Object entry, int i); /** * Do we need to insert this element? * * @param entry The collection element to check * @param i The index (for indexed collections) * @param elemType The type for the element * * @return {@code true} if the element needs inserting */ public boolean needsInserting(Object entry, int i, Type elemType); /** * Do we need to update this element? * * @param entry The collection element to check * @param i The index (for indexed collections) * @param elemType The type for the element * * @return {@code true} if the element needs updating */ public boolean needsUpdating(Object entry, int i, Type elemType); /** * Can each element in the collection be mapped unequivocally to a single row in the database? Generally * bags and sets are the only collections that cannot be. * * @return {@code true} if the row for each element is known */ public boolean isRowUpdatePossible(); /** * Get all the elements that need deleting * * @param persister The collection persister * @param indexIsFormula For indexed collections, tells whether the index is a formula (calculated value) mapping * * @return An iterator over the elements to delete */ public Iterator getDeletes(CollectionPersister persister, boolean indexIsFormula); /** * Is this the wrapper for the given collection instance? * * @param collection The collection to check whether this is wrapping it * * @return {@code true} if this is a wrapper around that given collection instance. */ public boolean isWrapper(Object collection); /** * Is this instance initialized? * * @return Was this collection initialized? Or is its data still not (fully) loaded? */ public boolean wasInitialized(); /** * Does this instance have any "queued" operations? * * @return {@code true} indicates there are pending, queued, delayed operations */ public boolean hasQueuedOperations(); /** * Iterator over the "queued" additions * * @return The iterator */ public Iterator queuedAdditionIterator(); /** * Get the "queued" orphans * * @param entityName The name of the entity that makes up the elements * * @return The orphaned elements */ public Collection getQueuedOrphans(String entityName); /** * Get the current collection key value * * @return the current collection key value */ public Serializable getKey(); /** * Get the current role name * * @return the collection role name */ public String getRole(); /** * Is the collection unreferenced? * * @return {@code true} if the collection is no longer referenced by an owner */ public boolean isUnreferenced(); /** * Is the collection dirty? Note that this is only * reliable during the flush cycle, after the * collection elements are dirty checked against * the snapshot. * * @return {@code true} if the collection is dirty */ public boolean isDirty(); /** * Clear the dirty flag, after flushing changes * to the database. */ public void clearDirty(); /** * Get the snapshot cached by the collection instance * * @return The internally stored snapshot state */ public Serializable getStoredSnapshot(); /** * Mark the collection as dirty */ public void dirty(); /** * Called before inserting rows, to ensure that any surrogate keys * are fully generated * * @param persister The collection persister */ public void preInsert(CollectionPersister persister); /** * Called after inserting a row, to fetch the natively generated id * * @param persister The collection persister * @param entry The collection element just inserted * @param i The element position/index */ public void afterRowInsert(CollectionPersister persister, Object entry, int i); /** * get all "orphaned" elements * * @param snapshot The snapshot state * @param entityName The name of the entity that are the elements of the collection * * @return The orphans */ public Collection getOrphans(Serializable snapshot, String entityName); }
kevin-chen-hw/LDAE
com.huawei.soa.ldae/src/main/java/org/hibernate/collection/spi/PersistentCollection.java
Java
lgpl-2.1
13,745
<?php /** * @package tikiwiki */ // (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id: tiki-view_tracker_item.php 60689 2016-12-16 14:14:38Z xavidp $ $section = 'trackers'; require_once ('tiki-setup.php'); $access->check_feature('feature_trackers'); $trklib = TikiLib::lib('trk'); if ($prefs['feature_categories'] == 'y') { $categlib = TikiLib::lib('categ'); } $filegallib = TikiLib::lib('filegal'); $notificationlib = TikiLib::lib('notification'); if ($prefs['feature_groupalert'] == 'y') { $groupalertlib = TikiLib::lib('groupalert'); } $auto_query_args = array( 'offset', 'trackerId', 'reloff', 'itemId', 'maxRecords', 'status', 'sort_mode', 'initial', 'filterfield', 'filtervalue', 'view', 'exactvalue' ); $special = false; if (!isset($_REQUEST['trackerId']) && $prefs['userTracker'] == 'y' && !isset($_REQUEST['user'])) { if (isset($_REQUEST['view']) and $_REQUEST['view'] == ' user') { if (empty($user)) { $smarty->assign('msg', tra("You are not logged in")); $smarty->assign('errortype', '402'); $smarty->display("error.tpl"); die; } $utid = $userlib->get_tracker_usergroup($user); if (isset($utid['usersTrackerId'])) { $_REQUEST['trackerId'] = $utid['usersTrackerId']; $_REQUEST["itemId"] = $trklib->get_item_id($_REQUEST['trackerId'], $utid['usersFieldId'], $user); if ($_REQUEST['itemId'] == NULL) { $addit = array(); $addit[] = array( 'fieldId' => $utid['usersFieldId'], 'type' => 'u', 'value' => $user, ); $definition = Tracker_Definition::get($_REQUEST['trackerId']); if ($definition && $f = $definition->getUserField()) { if ($f != $utid['usersFieldId']) { $addit[] = array( 'fieldId' => $f, 'type' => 'u', 'value' => $user, ); } } if ($definition && $f = $definition->getWriterGroupField()) { $addit[] = array( 'fieldId' => $f, 'type' => 'g', 'value' => $group, ); } $_REQUEST['itemId'] = $trklib->replace_item($_REQUEST["trackerId"], 0, array('data' => $addit), 'o'); } $special = 'user'; } } elseif (isset($_REQUEST["usertracker"]) and $tiki_p_admin == 'y') { $utid = $userlib->get_tracker_usergroup($_REQUEST['usertracker']); if (isset($utid['usersTrackerId'])) { $_REQUEST['trackerId'] = $utid['usersTrackerId']; $_REQUEST["itemId"] = $trklib->get_item_id($_REQUEST['trackerId'], $utid['usersFieldId'], $_REQUEST["usertracker"]); } } } if (!isset($_REQUEST['trackerId']) && $prefs['groupTracker'] == 'y') { if (isset($_REQUEST['view']) and $_REQUEST['view'] == ' group') { $gtid = $userlib->get_grouptrackerid($group); if (isset($gtid['groupTrackerId'])) { $_REQUEST["trackerId"] = $gtid['groupTrackerId']; $_REQUEST["itemId"] = $trklib->get_item_id($_REQUEST['trackerId'], $gtid['groupFieldId'], $group); if ($_REQUEST['itemId'] == NULL) { $addit = array('data' => array( 'fieldId' => $gtid['groupFieldId'], 'type' => 'g', 'value' => $group, )); $_REQUEST['itemId'] = $trklib->replace_item($_REQUEST["trackerId"], 0, $addit, 'o'); } $special = 'group'; } } elseif (isset($_REQUEST["grouptracker"]) and $tiki_p_admin == 'y') { $gtid = $userlib->get_grouptrackerid($_REQUEST["grouptracker"]); if (isset($gtid['groupTrackerId'])) { $_REQUEST["trackerId"] = $gtid['groupTrackerId']; $_REQUEST["itemId"] = $trklib->get_item_id($_REQUEST['trackerId'], $gtid['groupFieldId'], $_REQUEST["grouptracker"]); } } } $smarty->assign_by_ref('special', $special); //url to a user user tracker tiki-view_tracker_item.php?user=yyyyy&view=+user or tiki-view_tracker_item.php?greoup=yyy&user=yyyyy&view=+user or tiki-view_tracker_item.php?trackerId=xxx&user=yyyyy&view=+user if ($prefs['userTracker'] == 'y' && isset($_REQUEST['view']) && $_REQUEST['view'] = ' user' && !empty($_REQUEST['user'])) { if (empty($_REQUEST['trackerId']) && empty($_REQUEST['group'])) { $_REQUEST['group'] = $userlib->get_user_default_group($_REQUEST['user']); } if (empty($_REQUEST['trackerId']) && !empty($_REQUEST['group'])) { $utid = $userlib->get_usertrackerid($_REQUEST['group']); if (!empty($utid['usersTrackerId']) && !empty($utid['usersFieldId'])) { $_REQUEST['trackerId'] = $utid['usersTrackerId']; $fieldId = $utid['usersFieldId']; } } if (!empty($_REQUEST['trackerId']) && empty($fieldId)) { $definition = Tracker_Definition::get($_REQUEST['trackerId']); if ($definition) { $fieldId = $definition->getUserField(); } } if (!empty($_REQUEST['trackerId']) && !empty($fieldId)) { $_REQUEST['itemId'] = $trklib->get_item_id($_REQUEST['trackerId'], $fieldId, $_REQUEST['user']); if (!$_REQUEST['itemId']) { $smarty->assign( 'msg', tra("You don't have a personal tracker item yet. Click here to make one:") . '<br /><a href="tiki-view_tracker.php?trackerId=' . $_REQUEST['trackerId'] . '&cookietab=2">' . tra('Create tracker item') . '</a>' ); $smarty->display("error.tpl"); die; } } } if ((!isset($_REQUEST["trackerId"]) || !$_REQUEST["trackerId"]) && isset($_REQUEST["itemId"])) { $item_info = $trklib->get_tracker_item($_REQUEST["itemId"]); $_REQUEST['trackerId'] = $item_info['trackerId']; } if (!isset($_REQUEST["trackerId"]) || !$_REQUEST["trackerId"]) { $smarty->assign('msg', tra("No tracker indicated")); $smarty->display("error.tpl"); die; } if (isset($_REQUEST["itemId"])) { $item_info = $trklib->get_tracker_item($_REQUEST["itemId"]); $currentItemId = $_REQUEST["itemId"]; TikiLib::events()->trigger('tiki.trackeritem.view', array( 'type' => 'trackeritem', 'object' => $currentItemId, 'owner' => $item_info['createdBy'], 'user' => $GLOBALS['user'], ) ); } $definition = Tracker_Definition::get($_REQUEST['trackerId']); $xfields = array('data' => $definition->getFields()); $smarty->assign('tracker_is_multilingual', $prefs['feature_multilingual'] == 'y' && $definition->getLanguageField()); if (!isset($utid) and !isset($gtid) and (!isset($_REQUEST["itemId"]) or !$_REQUEST["itemId"]) and !isset($_REQUEST["offset"])) { $smarty->assign('msg', tra("No item indicated")); $smarty->display("error.tpl"); die; } if ($prefs['feature_groupalert'] == 'y') { $groupforalert = $groupalertlib->GetGroup('tracker', $_REQUEST['trackerId']); if ($groupforalert != "") { $showeachuser = $groupalertlib->GetShowEachUser('tracker', $_REQUEST['trackerId'], $groupforalert); $listusertoalert = $userlib->get_users(0, -1, 'login_asc', '', '', false, $groupforalert, ''); $smarty->assign_by_ref('listusertoalert', $listusertoalert['data']); } $smarty->assign_by_ref('groupforalert', $groupforalert); $smarty->assign_by_ref('showeachuser', $showeachuser); } if (!isset($_REQUEST["sort_mode"])) { $sort_mode = 'created_desc'; } else { $sort_mode = $_REQUEST["sort_mode"]; } $smarty->assign_by_ref('sort_mode', $sort_mode); if (!isset($_REQUEST["offset"])) { $offset = 0; } else { $offset = $_REQUEST["offset"]; } $smarty->assign_by_ref('offset', $offset); if (isset($_REQUEST["find"])) { $find = $_REQUEST["find"]; } else { $find = ''; } $smarty->assign('find', $find); // ************* previous/next ************** foreach (array( 'status', 'filterfield', 'filtervalue', 'initial', 'exactvalue', 'reloff' ) as $reqfld) { $trynam = 'try' . $reqfld; if (isset($_REQUEST[$reqfld])) { $$trynam = $_REQUEST[$reqfld]; } else { $$trynam = ''; } } if (isset($_REQUEST['filterfield'])) { if (is_array($_REQUEST['filtervalue']) and isset($_REQUEST['filtervalue'][$tryfilterfield])) { $tryfiltervalue = $_REQUEST['filtervalue'][$tryfilterfield]; } else { $tryfilterfield = preg_split('/\s*:\s*/', $_REQUEST['filterfield']); $tryfiltervalue = preg_split('/\s*:\s*/', $_REQUEST['filtervalue']); $tryexactvalue = preg_split('/\s*:\s*/', $_REQUEST['exactvalue']); } } //*********** handle prev/next links ***************** if (isset($_REQUEST['reloff'])) { if (isset($_REQUEST['move'])) { switch ($_REQUEST['move']) { case 'prev': $tryreloff+= - 1; break; case 'next': $tryreloff+= 1; break; default: $tryreloff = (int)$_REQUEST['move']; } } $cant = 0; $listfields = array(); if (substr($sort_mode, 0, 2) == 'f_') { //look at the field in case the field needs some processing to find the sort list($a, $i, $o) = explode('_', $sort_mode); foreach ($xfields['data'] as $f) { if ($f['fieldId'] == $i) { $listfields = array( $i => $f ); break; } } } if (isset($_REQUEST['cant'])) { $cant = $_REQUEST['cant']; } else { if (is_array($tryfiltervalue)) { $tryfiltervalue = array_values($tryfiltervalue); } $trymove = $trklib->list_items($_REQUEST['trackerId'], $offset + $tryreloff, 1, $sort_mode, $listfields, $tryfilterfield, $tryfiltervalue, $trystatus, $tryinitial, $tryexactvalue); if (isset($trymove['data'][0]['itemId'])) { // Autodetect itemId if not specified if (!isset($_REQUEST['itemId'])) { $_REQUEST['itemId'] = $trymove['data'][0]['itemId']; unset($item_info); } $cant = $trymove['cant']; } } $smarty->assign('cant', $cant); } //*********** that's all for prev/next ***************** $smarty->assign('itemId', $_REQUEST["itemId"]); if (!isset($item_info)) { $item_info = $trklib->get_tracker_item($_REQUEST["itemId"]); if (empty($item_info)) { $smarty->assign('msg', tra("No item indicated")); $smarty->display("error.tpl"); die; } } $item_info['logs'] = $trklib->get_item_history($item_info, 0, '', 0, 1); $smarty->assign_by_ref('item_info', $item_info); $smarty->assign('item', array('itemId' => $_REQUEST['itemId'], 'trackerId' => $_REQUEST['trackerId'])); $cat_objid = $_REQUEST['itemId']; $cat_type = 'trackeritem'; $tracker_info = $definition->getInformation(); $itemObject = Tracker_Item::fromInfo($item_info); if (!isset($tracker_info["writerCanModify"]) or (isset($utid) and ($_REQUEST['trackerId'] != $utid['usersTrackerId']))) { $tracker_info["writerCanModify"] = 'n'; } if (!isset($tracker_info["userCanSeeOwn"]) or (isset($utid) and ($_REQUEST['trackerId'] != $utid['usersTrackerId']))) { $tracker_info["userCanSeeOwn"] = 'n'; } if (!isset($tracker_info["writerGroupCanModify"]) or (isset($gtid) and ($_REQUEST['trackerId'] != $gtid['groupTrackerId']))) { $tracker_info["writerGroupCanModify"] = 'n'; } $tikilib->get_perm_object($_REQUEST['trackerId'], 'tracker', $tracker_info); if (! $itemObject->canView()) { $smarty->assign('errortype', 401); $smarty->assign('msg', tra("Permission denied")); $smarty->display("error.tpl"); die; } if (isset($tracker_info['adminOnlyViewEditItem']) && $tracker_info['adminOnlyViewEditItem'] === 'y') { $access->check_permission('tiki_p_admin_trackers', tra('Admin this tracker'), 'tracker', $tracker_info['trackerId']); } include_once('tiki-sefurl.php'); if (!empty($_REQUEST['moveto']) && $tiki_p_admin_trackers == 'y') { // mo to another tracker fields with same name $perms = Perms::get('tracker', $_REQUEST['moveto']); if ($perms->create_tracker_items) { $trklib->move_item($_REQUEST['trackerId'], $_REQUEST['itemId'], $_REQUEST['moveto']); header('Location: '.filter_out_sefurl('tiki-view_tracker_item.php?itemId=' . $_REQUEST['itemId'])); exit; } else { $smarty->assign('errortype', 401); $smarty->assign('msg', tra("Permission denied")); $smarty->display("error.tpl"); die; } } if (isset($_REQUEST["removeattach"])) { check_ticket('view-trackers-items'); $owner = $trklib->get_item_attachment_owner($_REQUEST["removeattach"]); if (($user && ($owner == $user)) || ($tiki_p_admin_trackers == 'y')) { $access->check_authenticity(tra('Are you sure you want to remove this attachment?')); $trklib->remove_item_attachment($_REQUEST["removeattach"]); } } $status_types = $trklib->status_types(); $smarty->assign('status_types', $status_types); $fields = array(); $ins_fields = array(); $usecategs = false; $cookietab = 1; $itemUsers = $trklib->get_item_creators($_REQUEST['trackerId'], $_REQUEST['itemId']); $smarty->assign_by_ref('itemUsers', $itemUsers); $plugins_loaded = false; if (empty($tracker_info)) { $item_info = array(); } $fieldFactory = $definition->getFieldFactory(); foreach ($xfields["data"] as $i => $current_field) { $fid = $current_field["fieldId"]; $ins_id = 'ins_' . $fid; $filter_id = 'filter_' . $fid; $current_field["ins_id"] = $ins_id; $current_field["filter_id"] = $filter_id; $xfields['data'][$i] = $current_field; $current_field_ins = null; $fieldIsVisible = $itemObject->canViewField($fid); $fieldIsEditable = $itemObject->canModifyField($fid); if ($fieldIsVisible || $fieldIsEditable) { $current_field_ins = $current_field; $handler = $fieldFactory->getHandler($current_field, $item_info); if ($handler) { $insert_values = $handler->getFieldData($_REQUEST); if ($insert_values) { $current_field_ins = array_merge($current_field_ins, $insert_values); } } } if (! empty($current_field_ins)) { if ($fieldIsEditable) { $ins_fields['data'][$i] = $current_field_ins; } if ($fieldIsVisible) { $fields['data'][$i] = $current_field_ins; } } } $authorfield = $definition->getAuthorField(); if ($authorfield) { $tracker_info['authorindiv'] = $trklib->get_item_value($_REQUEST["trackerId"], $_REQUEST["itemId"], $authorfield); } if (! $itemObject->canView()) { $smarty->assign('errortype', 401); $smarty->assign('msg', tra("You do not have permission to use this feature")); $smarty->display("error.tpl"); die; } if ($itemObject->canRemove()) { if (isset($_REQUEST["remove"])) { check_ticket('view-trackers-items'); $access->check_authenticity(tr('Are you sure you want to permantently delete this item?')); $trklib->remove_tracker_item($_REQUEST["remove"]); $access->redirect(filter_out_sefurl('tiki-view_tracker.php?trackerId=' . $_REQUEST['trackerId'])); } } $rateFieldId = $definition->getRateField(); if ($itemObject->canModify()) { if (isset($_REQUEST["save"]) || isset($_REQUEST["save_return"])) { $captchalib = TikiLib::lib('captcha'); if (empty($user) && $prefs['feature_antibot'] == 'y' && !$captchalib->validate()) { $smarty->assign('msg', $captchalib->getErrors()); $smarty->assign('errortype', 'no_redirect_login'); $smarty->display("error.tpl"); die; } // Check field values for each type and presence of mandatory ones $mandatory_missing = array(); $err_fields = array(); $categorized_fields = $definition->getCategorizedFields(); $field_errors = $trklib->check_field_values($ins_fields, $categorized_fields, $_REQUEST['trackerId'], empty($_REQUEST['itemId'])?'':$_REQUEST['itemId']); $smarty->assign('err_mandatory', $field_errors['err_mandatory']); $smarty->assign('err_value', $field_errors['err_value']); // values are OK, then lets save the item if (count($field_errors['err_mandatory']) == 0 && count($field_errors['err_value']) == 0) { $smarty->assign('input_err', '0'); // no warning to display if ($prefs['feature_groupalert'] == 'y') { $groupalertlib->Notify(isset($_REQUEST['listtoalert']) ? $_REQUEST['listtoalert'] : '', "tiki-view_tracker_item.php?itemId=" . $_REQUEST["itemId"]); } check_ticket('view-trackers-items'); if (!isset($_REQUEST["edstatus"]) or ($tracker_info["showStatus"] != 'y' and $tiki_p_admin_trackers != 'y')) { $_REQUEST["edstatus"] = $tracker_info["modItemStatus"]; } $trklib->replace_item($_REQUEST["trackerId"], $_REQUEST["itemId"], $ins_fields, $_REQUEST["edstatus"]); if (isset($rateFieldId) && isset($_REQUEST["ins_$rateFieldId"])) { $trklib->replace_rating($_REQUEST["trackerId"], $_REQUEST["itemId"], $rateFieldId, $user, $_REQUEST["ins_$rateFieldId"]); } $_REQUEST['show'] = 'view'; foreach ($fields["data"] as $i => $array) { if (isset($fields["data"][$i])) { $fid = $fields["data"][$i]["fieldId"]; $ins_id = 'ins_' . $fid; $ins_fields["data"][$i]["value"] = ''; } } $item_info = $trklib->get_tracker_item($_REQUEST["itemId"]); $item_info['logs'] = $trklib->get_item_history($item_info, 0, '', 0, 1); $smarty->assign('item_info', $item_info); } else { $error = $ins_fields; $cookietab = "2"; if ($tracker_info['useAttachments'] == 'y') { ++$cookietab; } if ($tracker_info['useComments'] == 'y') { ++$cookietab; } $smarty->assign('input_err', '1'); // warning to display // can't go back if there are errors if (isset($_REQUEST['save_return'])) { $_REQUEST['save'] = 'save'; unset($_REQUEST['save_return']); } } if (isset($_REQUEST['save_return']) && isset($_REQUEST['from'])) { $fromUrl = filter_out_sefurl('tiki-index.php?page=' . urlencode($_REQUEST['from'])); header("Location: {$fromUrl}"); exit; } } } // remove image from an image field if (isset($_REQUEST["removeImage"])) { $img_field = array( 'data' => array() ); $img_field['data'][] = array( 'fieldId' => $_REQUEST["fieldId"], 'type' => 'i', 'name' => $_REQUEST["fieldName"], 'value' => 'blank' ); $trklib->replace_item($_REQUEST["trackerId"], $_REQUEST["itemId"], $img_field); $_REQUEST['show'] = "mod"; } // ************* return to list *************************** if (isset($_REQUEST["returntracker"]) || isset($_REQUEST["save_return"])) { require_once ('lib/smarty_tiki/block.self_link.php'); header( 'Location: ' . smarty_block_self_link( array( '_script' => 'tiki-view_tracker.php', '_tag' => 'n', '_urlencode' => 'n', 'itemId' => 'NULL', 'trackerId' => $_REQUEST['trackerId'] ), '', $smarty ) ); die; } // ******************************************************** if (isset($tracker_info['useRatings']) and $tracker_info['useRatings'] == 'y' and $tiki_p_tracker_vote_ratings == 'y') { if ($user and $tiki_p_tracker_vote_ratings == 'y' and isset($rateFieldId) and isset($_REQUEST['ins_' . $rateFieldId])) { $trklib->replace_rating($_REQUEST['trackerId'], $_REQUEST['itemId'], $rateFieldId, $user, $_REQUEST['ins_' . $rateFieldId]); header('Location: tiki-view_tracker_item.php?trackerId=' . $_REQUEST['trackerId'] . '&itemId=' . $_REQUEST['itemId']); die; } } if ($_REQUEST["itemId"]) { $info = $trklib->get_tracker_item($_REQUEST["itemId"]); $itemObject = Tracker_Item::fromInfo($info); if (!isset($info['trackerId'])) { $info['trackerId'] = $_REQUEST['trackerId']; } if (! $itemObject->canView()) { $smarty->assign('errortype', 401); $smarty->assign('msg', tra('Permission denied')); $smarty->display('error.tpl'); die; } $last = array(); $lst = ''; $tracker_item_main_value = ''; $fieldFactory = $definition->getFieldFactory(); foreach ($xfields["data"] as $i => $current_field) { $current_field_ins = null; $fid = $current_field['fieldId']; $handler = $fieldFactory->getHandler($current_field, $info); $fieldIsVisible = $itemObject->canViewField($fid); $fieldIsEditable = $itemObject->canModifyField($fid); if ($fieldIsVisible || $fieldIsEditable) { $current_field_ins = $current_field; if ($handler) { $insert_values = $handler->getFieldData(); if ($insert_values) { $current_field_ins = array_merge($current_field_ins, $insert_values); } } } if (! empty($current_field_ins)) { if ($fieldIsVisible) { $fields['data'][$i] = $current_field_ins; } if ($fieldIsEditable) { $ins_fields['data'][$i] = $current_field_ins; } } } $smarty->assign('tracker_item_main_value', $trklib->get_isMain_value($_REQUEST['trackerId'], $_REQUEST['itemId'])); } //restore types values if there is an error if (isset($error)) { foreach ($ins_fields["data"] as $i => $current_field) { if (isset($error["data"][$i]["value"])) { $ins_fields["data"][$i]["value"] = $error["data"][$i]["value"]; } } } // dynamic list process $id_fields = array(); foreach ($xfields['data'] as $sid => $onefield) { $id_fields[$xfields['data'][$sid]['fieldId']] = $sid; } // Pull realname for user. $info["createdByReal"] = $tikilib->get_user_preference($info["createdBy"], 'realName', ''); $info["lastModifByReal"] = $tikilib->get_user_preference($info["lastModifBy"], 'realName', ''); $smarty->assign('id_fields', $id_fields); $smarty->assign('trackerId', $_REQUEST["trackerId"]); $smarty->assign('tracker_info', $tracker_info); $smarty->assign_by_ref('info', $info); $smarty->assign_by_ref('fields', $fields["data"]); $smarty->assign_by_ref('ins_fields', $ins_fields["data"]); if ($prefs['feature_user_watches'] == 'y' and $tiki_p_watch_trackers == 'y') { if ($user and isset($_REQUEST['watch'])) { check_ticket('view-trackers'); if ($_REQUEST['watch'] == 'add') { $tikilib->add_user_watch($user, 'tracker_item_modified', $_REQUEST["itemId"], 'tracker ' . $_REQUEST["trackerId"], $tracker_info['name'], "tiki-view_tracker_item.php?trackerId=" . $_REQUEST["trackerId"] . "&amp;itemId=" . $_REQUEST["itemId"]); } else { $remove_watch_tracker_type = 'tracker ' . $_REQUEST['trackerId']; $tikilib->remove_user_watch($user, 'tracker_item_modified', $_REQUEST["itemId"], $remove_watch_tracker_type); } } $smarty->assign('user_watching_tracker', 'n'); $it = $tikilib->user_watches($user, 'tracker_item_modified', $_REQUEST['itemId'], 'tracker ' . $_REQUEST["trackerId"]); if ($user and $tikilib->user_watches($user, 'tracker_item_modified', $_REQUEST['itemId'], 'tracker ' . $_REQUEST["trackerId"])) { $smarty->assign('user_watching_tracker', 'y'); } // Check, if the user is watching this trackers' item by a category. if ($prefs['feature_categories'] == 'y') { $watching_categories_temp = $categlib->get_watching_categories($_REQUEST['trackerId'], 'tracker', $user); $smarty->assign('category_watched', 'n'); if (count($watching_categories_temp) > 0) { $smarty->assign('category_watched', 'y'); $watching_categories = array(); foreach ($watching_categories_temp as $wct) { $watching_categories[] = array( "categId" => $wct, "name" => $categlib->get_category_name($wct) ); } $smarty->assign('watching_categories', $watching_categories); } } } if ($tracker_info['useComments'] == 'y') { $comCount = $trklib->get_item_nb_comments($_REQUEST["itemId"]); $smarty->assign("comCount", $comCount); } if ($tracker_info["useAttachments"] == 'y') { if (isset($_REQUEST["removeattach"])) { $_REQUEST["show"] = "att"; } if (isset($_REQUEST["editattach"])) { $att = $trklib->get_item_attachment($_REQUEST["editattach"]); $smarty->assign("attach_comment", $att['comment']); $smarty->assign("attach_version", $att['version']); $smarty->assign("attach_longdesc", $att['longdesc']); $smarty->assign("attach_file", $att["filename"]); $smarty->assign("attId", $att["attId"]); $_REQUEST["show"] = "att"; } if (isset($_REQUEST['attach']) && $tiki_p_attach_trackers == 'y' && isset($_FILES['userfile1'])) { // Process an attachment here if (is_uploaded_file($_FILES['userfile1']['tmp_name'])) { $fp = fopen($_FILES['userfile1']['tmp_name'], "rb"); $data = ''; $fhash = ''; if ($prefs['t_use_db'] == 'n') { $fhash = md5($_FILES['userfile1']['name'] . $tikilib->now); $fw = fopen($prefs['t_use_dir'] . $fhash, "wb"); if (!$fw) { $smarty->assign('msg', tra('Cannot write to this file:') . $fhash); $smarty->display("error.tpl"); die; } } while (!feof($fp)) { if ($prefs['t_use_db'] == 'n') { $data = fread($fp, 8192 * 16); fwrite($fw, $data); } else { $data.= fread($fp, 8192 * 16); } } fclose($fp); if ($prefs['t_use_db'] == 'n') { fclose($fw); $data = ''; } $size = $_FILES['userfile1']['size']; $name = $_FILES['userfile1']['name']; $type = $_FILES['userfile1']['type']; } else { $smarty->assign('msg', $_FILES['userfile1']['name'] . ': ' . tra('Upload was not successful') . ': ' . $tikilib->uploaded_file_error($_FILES['userfile1']['error'])); $smarty->display("error.tpl"); die; } $trklib->replace_item_attachment($_REQUEST["attId"], $name, $type, $size, $data, $_REQUEST["attach_comment"], $user, $fhash, $_REQUEST["attach_version"], $_REQUEST["attach_longdesc"], $_REQUEST['trackerId'], $_REQUEST['itemId'], $tracker_info); $_REQUEST["attId"] = 0; $_REQUEST['show'] = "att"; } // If anything below here is changed, please change lib/wiki-plugins/wikiplugin_attach.php as well. $attextra = 'n'; if (strstr($tracker_info["orderAttachments"], '|')) { $attextra = 'y'; } $attfields = explode(',', strtok($tracker_info["orderAttachments"], '|')); $atts = $trklib->list_item_attachments($_REQUEST["itemId"], 0, -1, 'comment_asc', ''); $smarty->assign('atts', $atts["data"]); $smarty->assign('attCount', $atts["cant"]); $smarty->assign('attfields', $attfields); $smarty->assign('attextra', $attextra); } if (isset($_REQUEST['moveto']) && empty($_REQUEST['moveto'])) { $trackers = $trklib->list_trackers(); $smarty->assign_by_ref('trackers', $trackers['data']); $_REQUEST['show'] = 'mod'; } if (isset($_REQUEST['show'])) { if ($_REQUEST['show'] == 'view') { $cookietab = 1; } elseif ($tracker_info["useComments"] == 'y' and $_REQUEST['show'] == 'com') { $cookietab = 2; } elseif ($_REQUEST['show'] == "mod") { $cookietab = 2; if ($tracker_info["useAttachments"] == 'y') $cookietab++; if ($tracker_info["useComments"] == 'y' && $tiki_p_tracker_view_comments == 'y') $cookietab++; } elseif ($_REQUEST['show'] == "att") { $cookietab = 2; if ($tracker_info["useComments"] == 'y' && $tiki_p_tracker_view_comments == 'y') $cookietab = 3; } } if (isset($_REQUEST['from'])) { $from = $_REQUEST['from']; } else { $from = false; } $smarty->assign('from', $from); if (isset($_REQUEST['status'])) $smarty->assign_by_ref('status', $_REQUEST['status']); include_once ('tiki-section_options.php'); $smarty->assign('uses_tabs', 'y'); ask_ticket('view-trackers-items'); if ($prefs['feature_actionlog'] == 'y') { $logslib = TikiLib::lib('logs'); $logslib->add_action('Viewed', $_REQUEST['itemId'], 'trackeritem'); } // Generate validation js if ($prefs['feature_jquery'] == 'y' && $prefs['feature_jquery_validation'] == 'y') { $validatorslib = TikiLib::lib('validators'); $validationjs = $validatorslib->generateTrackerValidateJS($fields['data']); $smarty->assign('validationjs', $validationjs); } if ($itemObject->canRemove()) { $smarty->assign('editTitle', tr('Edit/Delete')); } else { $smarty->assign('editTitle', tr('Edit')); } $smarty->assign('canView', $itemObject->canView()); $smarty->assign('canModify', $itemObject->canModify()); $smarty->assign('canRemove', $itemObject->canRemove()); // Add view/edit template. Override an optional template defined in the tracker by a template passed via request // Note: Override is only allowed if a default template was set already in the tracker. // View $viewItemPretty = array( 'override' => false, 'value' => $tracker_info['viewItemPretty'], 'type' => 'wiki' ); if (!empty($tracker_info['viewItemPretty'])) { if (isset($_REQUEST['vi_tpl'])) { $viewItemPretty['override'] = true; $viewItemPretty['value'] = $_REQUEST['vi_tpl']; } // Need to check wether this is a wiki: or tpl: template, bc the smarty template needs to take care of this if (strpos(strtolower($viewItemPretty['value']), 'wiki:') === false) { $viewItemPretty['type'] = 'tpl'; } } $smarty->assign('viewItemPretty', $viewItemPretty); // Edit $editItemPretty = array( 'override' => false, 'value' => $tracker_info['editItemPretty'], 'type' => 'wiki' ); if (!empty($tracker_info['editItemPretty'])) { if (isset($_REQUEST['ei_tpl'])) { $editItemPretty['override'] = true; $editItemPretty['value'] = $_REQUEST['ei_tpl']; } if (strpos(strtolower($editItemPretty['value']), 'wiki:') === false) { $editItemPretty['type'] = 'tpl'; } } $smarty->assign('editItemPretty', $editItemPretty); // add referer url to setup the back button in tpl // check wether we have been called from a different page than ourselfs to save a link to the referer for a back buttom. // this can be a wikipage with the trackerlist item and and view item temlate set using vi_tpl=wiki:mytemplate // if we do anything on the current page (i.e. adding a comment) we need to keep that saved link. $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''; $temp = strtolower($referer); if (strpos($temp, 'vi_tpl=') || strpos($temp, 'ei_tpl=')) { $referer = $_SESSION['item_tpl_referer']; } else { $_SESSION['item_tpl_referer'] = $referer; } unset($temp); $smarty->assign('referer', $referer); // Display the template $smarty->assign('mid', 'tiki-view_tracker_item.tpl'); try { if (isset($_REQUEST['print'])) { $smarty->assign('print_page', 'y'); $smarty->display('tiki-print.tpl'); } else { $smarty->display('tiki.tpl'); } } catch (SmartyException $e) { //$message = tr('This element cannot be displayed correctly. One of the view/edit templates is missing or has errors (%0)/(%1). Contact the administrator.', $viewItemPretty['value'], $editItemPretty['value']); $message = tr('This element cannot be displayed correctly. One of the view/edit templates is missing or has errors. Contact the administrator. (%0)', $e->getMessage()); $smarty->loadPlugin('smarty_modifier_sefurl'); $access->redirect(smarty_modifier_sefurl($info['trackerId'], 'tracker'), $message); }
lorddavy/TikiWiki-Improvement-Project
tiki-view_tracker_item.php
PHP
lgpl-2.1
29,456
/* * Copyright (C) 2010-2011 * Written by: * Aly Hirani <alyhirani@gmail.com> * James Chou <uohcsemaj@gmail.com> * * All Rights Reserved * * 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. * */ #ifndef LIBFACEBOOKCPP_ENUM_H_ #define LIBFACEBOOKCPP_ENUM_H_ #include "AuthorizedObject.hpp" namespace LibFacebookCpp { template<class T, T none, T count, const char *str_array[]> class Enum : public AuthorizedObject { public: // ctor Enum() : t_(none) { } public: // public interface operator T() const { return t_; } private: // callback methods void _Deserialize(const AuthorizedObject &parent_obj, const Json::Value &json) { if(!json.isConvertibleTo(Json::stringValue)) throw UnexpectedException("!json.isConvertibleTo(Json::stringValue)"); const std::string &str = json.asString(); bool found = false; // Hack: This is nasty, but required to do a complete iteration. Hopefully, we never have to go over the int limit! for(int s = (int)none; s < (int)count; ++s) { if(stricmp(str.c_str(), str_array[s]) == 0) { t_ = (T)s; break; } } if(!found) throw UnexpectedException("!found"); } private: // member variables T t_; }; } // namespace LibFacebookCpp #endif // LIBFACEBOOKCPP_ENUM_H_
kemcoi/libfacebookcpp
include/LibFacebookCpp/Enum.hpp
C++
lgpl-2.1
1,783
package com.mhfs.controller.hotplug; import java.io.File; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; import com.mhfs.controller.config.Config; import com.mhfs.controller.daemon.DaemonMain; import com.mhfs.ipc.InvocationManager; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioDatagramChannel; public class DaemonManager { private static Process process; private static Channel channel; public static InvocationManager startDaemon() throws Exception { int port = findFreePort(); String javaHome = System.getProperty("java.home"); String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; String classpath = System.getProperty("java.class.path"); String libPath = "-Djava.library.path=" + System.getProperty("java.library.path"); String className = DaemonMain.class.getCanonicalName(); String args = Config.INSTANCE.shouldDebugInput() ? "debugControllerInput" : ""; ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, libPath, className, String.valueOf(port), args); builder.inheritIO(); process = builder.start(); Thread.sleep(2000);//Waiting for Daemon to start. ClientNetworkHandler cnw = new ClientNetworkHandler(); InetSocketAddress adr = new InetSocketAddress("localhost", port); Bootstrap b = new Bootstrap(); b.group(new NioEventLoopGroup()); b.channel(NioDatagramChannel.class); b.handler(cnw); ChannelFuture future = b.connect(adr).syncUninterruptibly(); cnw.init(future.channel(), adr); InvocationManager manager = new InvocationManager(cnw); cnw.setInvocationManager(manager); manager.init(); Thread t = new Thread(() -> { future.channel().closeFuture().syncUninterruptibly(); b.group().shutdownGracefully(); }); t.setDaemon(true); t.setName("Netty-IPC Shutdown Waiter"); Runtime.getRuntime().addShutdownHook(new Thread(() -> stopDaemon())); return manager; } private static int findFreePort() throws SocketException { DatagramSocket socket = new DatagramSocket(); int port = socket.getLocalPort(); socket.close(); return port; } public static void stopDaemon() { if(process != null) { process.destroy(); } if(channel != null) { channel.close(); } } }
thilokru/Controller-Support
src/main/java/com/mhfs/controller/hotplug/DaemonManager.java
Java
lgpl-2.1
2,505
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef TEXT_PLACEMENTS_LIST_HPP #define TEXT_PLACEMENTS_LIST_HPP #include <mapnik/text/placements/base.hpp> namespace mapnik { class text_placement_info_list; class feature_impl; struct attribute; // Tries a list of placements. class text_placements_list: public text_placements { public: text_placements_list(); text_placement_info_ptr get_placement_info(double scale_factor, feature_impl const& feature, attributes const& vars, symbol_cache const& sc) const; virtual void add_expressions(expression_set & output) const; text_symbolizer_properties & add(); text_symbolizer_properties & get(unsigned i); std::size_t size() const; static text_placements_ptr from_xml(xml_node const& xml, fontset_map const& fontsets, bool is_shield); private: std::vector<text_symbolizer_properties> list_; friend class text_placement_info_list; }; // List placement strategy. // See parent class for documentation of each function. class text_placement_info_list : public text_placement_info { public: text_placement_info_list(text_placements_list const* parent, double scale_factor) : text_placement_info(parent, scale_factor), state(0), parent_(parent) {} bool next() const; virtual void reset_state() { state = 0; } private: mutable unsigned state; text_placements_list const* parent_; }; } //namespace #endif
mapycz/mapnik
include/mapnik/text/placements/list.hpp
C++
lgpl-2.1
2,373
package org.openswing.swing.table.client; import java.awt.*; import javax.swing.*; import javax.swing.plaf.*; import com.sun.java.swing.plaf.mac.*; /** * <p>Title: OpenSwing Framework</p> * <p>Description: Vertical scrollbar UI, used inside the pagination vertical scrollbar of the grid control, for Mac LnF.</p> * <p>Copyright: Copyright (C) 2006 Mauro Carniel</p> * * <p> This file is part of OpenSwing Framework. * This library is free software; you can redistribute it and/or * modify it under the terms of the (LGPL) Lesser General Public * License as published by the Free Software Foundation; * * GNU LESSER GENERAL PUBLIC LICENSE * Version 2.1, February 1999 * * 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * The author may be contacted at: * maurocarniel@tin.it</p> * * @author Mauro Carniel * @version 1.0 */ public class MacPaginationVerticalScrollBarUI extends MacScrollBarUI implements PaginationVerticalScrollbarUI { protected JButton nextPgButton; protected JButton prevPgButton; public MacPaginationVerticalScrollBarUI() { super(); } public static ComponentUI createUI(JComponent c) { return new MacPaginationVerticalScrollBarUI(); } protected JButton createPageButton(int orientation) { return new PageArrowButton(orientation); } protected void installDefaults() { super.installDefaults(); nextPgButton = createPageButton(SOUTH); prevPgButton = createPageButton(NORTH); scrollbar.add(prevPgButton); scrollbar.add(nextPgButton); } protected void layoutVScrollbar(JScrollBar sb) { Dimension sbSize = sb.getSize(); Insets sbInsets = sb.getInsets(); /* * Width and left edge of the buttons and thumb. */ int itemW = sbSize.width - (sbInsets.left + sbInsets.right); int itemX = sbInsets.left; /* Nominal locations of the buttons, assuming their preferred * size will fit. */ int prevPgButtonH = prevPgButton.getPreferredSize().height; int prevPgButtonY = sbInsets.top; int decrButtonH = decrButton.getPreferredSize().height; int decrButtonY = prevPgButtonY+prevPgButtonH; int incrButtonH = incrButton.getPreferredSize().height; int nextPgButtonH = nextPgButton.getPreferredSize().height; int incrButtonY = sbSize.height - (sbInsets.bottom + incrButtonH+nextPgButtonH); int nextPgButtonY = sbSize.height - (sbInsets.bottom + nextPgButtonH); /* The thumb must fit within the height left over after we * subtract the preferredSize of the buttons and the insets. */ int sbInsetsH = sbInsets.top + sbInsets.bottom; int sbButtonsH = decrButtonH + incrButtonH +prevPgButtonH +nextPgButtonH; float trackH = sbSize.height - (sbInsetsH + sbButtonsH); /* Compute the height and origin of the thumb. The case * where the thumb is at the bottom edge is handled specially * to avoid numerical problems in computing thumbY. Enforce * the thumbs min/max dimensions. If the thumb doesn't * fit in the track (trackH) we'll hide it later. */ float min = sb.getMinimum(); float extent = sb.getVisibleAmount(); float range = sb.getMaximum() - min; float value = sb.getValue(); int thumbH = (range <= 0) ? getMaximumThumbSize().height : (int)(trackH * (extent / range)); thumbH = Math.max(thumbH, getMinimumThumbSize().height); thumbH = Math.min(thumbH, getMaximumThumbSize().height); int thumbY = incrButtonY - thumbH; if (sb.getValue() < (sb.getMaximum() - sb.getVisibleAmount())) { float thumbRange = trackH - thumbH; thumbY = (int)(0.5f + (thumbRange * ((value - min) / (range - extent)))); thumbY += decrButtonY + decrButtonH; } /* If the buttons don't fit, allocate half of the available * space to each and move the lower one (incrButton) down. */ int sbAvailButtonH = (sbSize.height - sbInsetsH); if (sbAvailButtonH < sbButtonsH) { incrButtonH = decrButtonH = sbAvailButtonH / 2; incrButtonY = sbSize.height - (sbInsets.bottom + incrButtonH); } prevPgButton.setBounds(itemX, prevPgButtonY, itemW, prevPgButtonH); decrButton.setBounds(itemX, decrButtonY, itemW, decrButtonH); incrButton.setBounds(itemX, incrButtonY, itemW, incrButtonH); nextPgButton.setBounds(itemX, nextPgButtonY, itemW, nextPgButtonH); /* Update the trackRect field. */ int itrackY = decrButtonY + decrButtonH; int itrackH = incrButtonY - itrackY; trackRect.setBounds(itemX, itrackY, itemW, itrackH); /* If the thumb isn't going to fit, zero it's bounds. Otherwise * make sure it fits between the buttons. Note that setting the * thumbs bounds will cause a repaint. */ if(thumbH >= (int)trackH) { setThumbBounds(0, 0, 0, 0); } else { if ((thumbY + thumbH) > incrButtonY) { thumbY = incrButtonY - thumbH; } if (thumbY < (decrButtonY + decrButtonH)) { thumbY = decrButtonY + decrButtonH + 1; } setThumbBounds(itemX, thumbY, itemW, thumbH); } } protected void installListeners() { super.installListeners(); } protected void uninstallListeners() { super.uninstallListeners(); } public JButton getNextPgButton() { return nextPgButton; } public JButton getDecrButton() { return decrButton; } public JButton getIncrButton() { return incrButton; } public JButton getPrevPgButton() { return prevPgButton; } /** * <p>Title: OpenSwing Framework</p> * <p>Description: Inner class used to render the scrollbar buttons.</p> * @author Mauro Carniel * @version 1.0 */ class PageArrowButton extends MacScrollButton { private Color background = UIManager.getColor("ScrollBar.arrowBackground"); private Color highlight = UIManager.getColor("ScrollBar.arrowHighlight"); private Color shadow = UIManager.getColor("ScrollBar.arrowShadow"); private Color pressedBackground = UIManager.getColor("ScrollBar.pressedArrowBackground"); private Color pressedHighlight = UIManager.getColor("ScrollBar.pressedArrowHighlight"); private Color pressedShadow = UIManager.getColor("ScrollBar.pressedArrowShadow"); private Color arrowColor = UIManager.getColor("ScrollBar.arrowColor"); private int buttonWidth; private final ColorUIResource gray0 = new ColorUIResource(238, 238, 238); private final ColorUIResource gray3 = new ColorUIResource(187, 187, 187); private final ColorUIResource gray6 = new ColorUIResource(136, 136, 136); private final ColorUIResource gray9 = new ColorUIResource(85, 85, 85); public PageArrowButton(int direction) { super(direction,incrButton.getPreferredSize().width); buttonWidth = incrButton.getPreferredSize().width; } public void paint(Graphics g) { if (background==null) background = Color.white; if (highlight==null) highlight = new Color(240,240,240); if (shadow==null) shadow = new Color(20,20,20); if (pressedHighlight==null) pressedHighlight = new Color(200,200,200); if (pressedShadow==null) pressedShadow = new Color(10,10,10); if (arrowColor==null) arrowColor = new Color(1,1,1); ButtonModel buttonmodel = getModel(); boolean flag = buttonmodel.isArmed() && buttonmodel.isPressed(); if(isEnabled()) g.setColor(flag ? pressedBackground : background); else g.setColor(gray0); g.fillRect(0, 0, buttonWidth, buttonWidth); g.setColor(flag ? pressedShadow : highlight); g.drawLine(0, 0, buttonWidth - 2, 0); g.drawLine(0, 0, 0, buttonWidth - 2); g.setColor(flag ? pressedHighlight : shadow); g.drawLine(buttonWidth - 1, 1, buttonWidth - 1, buttonWidth - 1); g.drawLine(1, buttonWidth - 1, buttonWidth - 1, buttonWidth - 1); g.setColor(((Color) (isEnabled() ? arrowColor : ((Color) (gray6))))); int h = -3; switch(getDirection()) { case 1: // '\001' g.drawLine(6, 5+h, 7, 5+h); g.drawLine(5, 6+h, 8, 6+h); g.drawLine(4, 7+h, 9, 7+h); g.drawLine(3, 8+h, 10, 8+h); h = getHeight()-14; g.drawLine(6, 5+h, 7, 5+h); g.drawLine(5, 6+h, 8, 6+h); g.drawLine(4, 7+h, 9, 7+h); g.drawLine(3, 8+h, 10, 8+h); break; case 5: // '\005' g.drawLine(3, 5+h, 10, 5+h); g.drawLine(4, 6+h, 9, 6+h); g.drawLine(5, 7+h, 8, 7+h); g.drawLine(6, 8+h, 7, 8+h); h = getHeight()-14; g.drawLine(3, 5+h, 10, 5+h); g.drawLine(4, 6+h, 9, 6+h); g.drawLine(5, 7+h, 8, 7+h); g.drawLine(6, 8+h, 7, 8+h); break; } } } }
mcarniel/oswing
srclnf/org/openswing/swing/table/client/MacPaginationVerticalScrollBarUI.java
Java
lgpl-2.1
9,721
<?php include_once('./_common.php'); include_once(G5_CAPTCHA_PATH.'/captcha.lib.php'); if ($is_guest) alert_close('회원만 이용하실 수 있습니다.'); if (!$member['mb_open'] && $is_admin != 'super' && $is_admin != 'admin' && $member['mb_id'] != $mb_id) alert_close("자신의 정보를 공개하지 않으면 다른분에게 쪽지를 보낼 수 없습니다. 정보공개 설정은 회원정보수정에서 하실 수 있습니다."); $content = ""; // 탈퇴한 회원에게 쪽지 보낼 수 없음 if ($me_recv_mb_id) { $mb = get_member($me_recv_mb_id); if (!$mb['mb_id']) alert_close('회원정보가 존재하지 않습니다.\\n\\n탈퇴하였을 수 있습니다.'); if (!$mb['mb_open'] && $is_admin != 'super' && $is_admin != 'admin') alert_close('정보공개를 하지 않았습니다.'); // 4.00.15 $row = sql_fetch(" select me_memo from {$g5['memo_table']} where me_id = '{$me_id}' and (me_recv_mb_id = '{$member['mb_id']}' or me_send_mb_id = '{$member['mb_id']}') "); if ($row['me_memo']) { $content = "\n\n\n".' >' ."\n".' >' ."\n".' >'.str_replace("\n", "\n> ", get_text($row['me_memo'], 0)) ."\n".' >' .' >'; } } $g5['title'] = '쪽지 보내기'; include_once(G5_PATH.'/head.sub.php'); $memo_action_url = G5_HTTPS_BBS_URL."/memo_form_update.php"; include_once($member_skin_path.'/memo_form.skin.php'); include_once(G5_PATH.'/tail.sub.php'); ?>
dingdong2310/sir
bbs/memo_form.php
PHP
lgpl-2.1
1,544
package m.c.m.proxyma.rewrite; import java.net.URL; import java.util.logging.Logger; import javax.servlet.http.Cookie; import m.c.m.proxyma.context.ProxyFolderBean; import m.c.m.proxyma.context.ProxymaContext; import m.c.m.proxyma.resource.ProxymaResource; /** * <p> * This Class implements the logic of the Cookies rewriter engine.<br/> * It is used by the plugins that performs Cookie rewriting stuff. * * </p><p> * NOTE: this software is released under GPL License. * See the LICENSE of this distribution for more informations. * </p> * * @author Marco Casavecchia Morganti (marcolinuz) [marcolinuz-at-gmail.com]; * @version $Id: CookieRewriteEngine.java 176 2010-07-03 09:02:14Z marcolinuz $ */ public class CookieRewriteEngine { public CookieRewriteEngine (ProxymaContext context) { //initialize the logger for this class. log = context.getLogger(); urlRewriter = new URLRewriteEngine(context); } /** * Masquerade to the client a cookie that comes froma a remote host by * setting its domain to the domain of proxyma and the path to the path * of the current proxy-folder. * * @param cookie the cookie to masquerade * @param aResource the resource that owns the Cookie */ public void masqueradeCookie(Cookie cookie, ProxymaResource aResource) { //calculate the new values of the Set-Cookie header URL proxymaRootURL = aResource.getProxymaRootURL(); //Calculate the new Cookie Domain cookie.setDomain(proxymaRootURL.getHost()); // calculate new path of the cookie if (cookie.getPath() == null) { cookie.setPath(urlRewriter.masqueradeURL(aResource.getProxyFolder().getDestinationAsURL().getPath(), aResource)); } else { String newPath = urlRewriter.masqueradeURL(cookie.getPath(), aResource); if (newPath.startsWith("/")) { cookie.setPath(newPath); } else { cookie.setPath(urlRewriter.masqueradeURL(aResource.getProxyFolder().getDestinationAsURL().getPath(), aResource)); } } //set the new value for the cookie String newValue = PROXYMA_REWRITTEN_HEADER + cookie.getValue(); cookie.setValue(newValue); log.finer("Masqueraded Cookie, new path=" + cookie.getPath() + "; new value=" + newValue); } /** * Rebuilds the original cookie from a masqueraded one. * @param cookie the cookie to unmasquerade * @return an string array with doamain, path and original value of the cookie. */ public void unmasqueradeCookie (Cookie cookie) { String cookieValue = cookie.getValue(); if (cookieValue.startsWith(PROXYMA_REWRITTEN_HEADER)) { String originalValue = cookieValue.substring(33); cookie.setValue(originalValue); log.finer("Unmasqueraded Cookie original value: " + originalValue); } } /** * The logger for this class */ private Logger log = null; /** * The url rewriter used to rewrite cookie paths */ private URLRewriteEngine urlRewriter = null; /** * The header added to the rewritten cookies that can be recognized by the * preprocessor to restore the original values. */ public static final String PROXYMA_REWRITTEN_HEADER = "#%#PROXYMA-NG_REWRITTEN_COOKIE#%#"; }
dpoldrugo/proxyma
proxyma-core/src/main/java/m/c/m/proxyma/rewrite/CookieRewriteEngine.java
Java
lgpl-2.1
3,420
<?php namespace wcf\system\bbcode; use wcf\system\application\ApplicationHandler; use wcf\system\message\embedded\object\MessageEmbeddedObjectManager; use wcf\system\request\RouteHandler; use wcf\system\WCF; /** * Parses the [quote] bbcode tag. * * @author Marcel Werk * @copyright 2001-2015 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package com.woltlab.wcf * @subpackage system.bbcode * @category Community Framework */ class QuoteBBCode extends AbstractBBCode { /** * @see \wcf\system\bbcode\IBBCode::getParsedTag() */ public function getParsedTag(array $openingTag, $content, array $closingTag, BBCodeParser $parser) { if ($parser->getOutputType() == 'text/html') { $quoteLink = (!empty($openingTag['attributes'][1]) ? $openingTag['attributes'][1] : ''); $externalQuoteLink = (!empty($openingTag['attributes'][1]) ? !ApplicationHandler::getInstance()->isInternalURL($openingTag['attributes'][1]) : false); if (!$externalQuoteLink) { $quoteLink = preg_replace('~^https?://~', RouteHandler::getProtocol(), $quoteLink); } $quoteAuthor = (!empty($openingTag['attributes'][0]) ? $openingTag['attributes'][0] : ''); $quoteAuthorObject = null; if ($quoteAuthor && !$externalQuoteLink) { $quoteAuthorLC = mb_strtolower($quoteAuthor); foreach (MessageEmbeddedObjectManager::getInstance()->getObjects('com.woltlab.wcf.quote') as $user) { if (mb_strtolower($user->username) == $quoteAuthorLC) { $quoteAuthorObject = $user; break; } } } WCF::getTPL()->assign(array( 'content' => $content, 'quoteLink' => $quoteLink, 'quoteAuthor' => $quoteAuthor, 'quoteAuthorObject' => $quoteAuthorObject, 'isExternalQuoteLink' => $externalQuoteLink )); return WCF::getTPL()->fetch('quoteBBCodeTag'); } else if ($parser->getOutputType() == 'text/simplified-html') { return WCF::getLanguage()->getDynamicVariable('wcf.bbcode.quote.text', array('content' => $content, 'cite' => (!empty($openingTag['attributes'][0]) ? $openingTag['attributes'][0] : '')))."\n"; } } }
ramiusGitHub/WCF
wcfsetup/install/files/lib/system/bbcode/QuoteBBCode.class.php
PHP
lgpl-2.1
2,133
<?php // $Id: /cvsroot/tikiwiki/tiki/lib/trackers/index.php,v 1.6 2007-03-06 19:30:25 sylvieg Exp $ // Copyright (c) 2002-2007, Luis Argerich, Garland Foster, Eduardo Polidor, et. al. // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // This redirects to the sites root to prevent directory browsing header ("location: ../index.php"); die; ?>
4thAce/evilhow
lib/trackers/index.php
PHP
lgpl-2.1
470
/** * * $Id$ */ package net.opengis.wfs20.validation; import net.opengis.wfs20.AbstractTransactionActionType; import net.opengis.wfs20.AllSomeType; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.util.FeatureMap; /** * A sample validator interface for {@link net.opengis.wfs20.TransactionType}. * This doesn't really do anything, and it's not a real EMF artifact. * It was generated by the org.eclipse.emf.examples.generator.validator plug-in to illustrate how EMF's code generator can be extended. * This can be disabled with -vmargs -Dorg.eclipse.emf.examples.generator.validator=false. */ public interface TransactionTypeValidator { boolean validate(); boolean validateGroup(FeatureMap value); boolean validateAbstractTransactionActionGroup(FeatureMap value); boolean validateAbstractTransactionAction(EList<AbstractTransactionActionType> value); boolean validateLockId(String value); boolean validateReleaseAction(AllSomeType value); boolean validateSrsName(String value); }
geotools/geotools
modules/ogc/net.opengis.wfs/src/net/opengis/wfs20/validation/TransactionTypeValidator.java
Java
lgpl-2.1
1,029
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtWidgets> #include "addressbook.h" //! [constructor and input fields] AddressBook::AddressBook(QWidget *parent) : QWidget(parent) { QLabel *nameLabel = new QLabel(tr("Name:")); nameLine = new QLineEdit; QLabel *addressLabel = new QLabel(tr("Address:")); addressText = new QTextEdit; //! [constructor and input fields] //! [layout] QGridLayout *mainLayout = new QGridLayout; mainLayout->addWidget(nameLabel, 0, 0); mainLayout->addWidget(nameLine, 0, 1); mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop); mainLayout->addWidget(addressText, 1, 1); //! [layout] //![setting the layout] setLayout(mainLayout); setWindowTitle(tr("Simple Address Book")); } //! [setting the layout]
CodeDJ/qt5-hidpi
qt/qtbase/examples/widgets/tutorials/addressbook/part1/addressbook.cpp
C++
lgpl-2.1
2,740
// Accord Unit Tests // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2015 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace Accord.Tests.Statistics { using Accord.Statistics.Filters; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Data; [TestClass()] public class StratificationFilterTest { private TestContext testContextInstance; public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } [TestMethod()] public void ApplyTest() { DataTable data = new DataTable("Sample data"); data.Columns.Add("x", typeof(double)); data.Columns.Add("Class", typeof(int)); data.Rows.Add(0.21, 0); data.Rows.Add(0.25, 0); data.Rows.Add(0.54, 0); data.Rows.Add(0.19, 1); DataTable expected = new DataTable("Sample data"); expected.Columns.Add("x", typeof(double)); expected.Columns.Add("Class", typeof(int)); expected.Rows.Add(0.21, 0); expected.Rows.Add(0.25, 0); expected.Rows.Add(0.54, 0); expected.Rows.Add(0.19, 1); expected.Rows.Add(0.19, 1); expected.Rows.Add(0.19, 1); DataTable actual; Stratification target = new Stratification("Class"); target.Columns["Class"].Classes = new int[] { 0, 1 }; actual = target.Apply(data); for (int i = 0; i < actual.Rows.Count; i++) { double ex = (double)expected.Rows[i][0]; int ec = (int)expected.Rows[i][1]; double ax = (double)actual.Rows[i][0]; int ac = (int)actual.Rows[i][1]; Assert.AreEqual(ex, ax); Assert.AreEqual(ec, ac); } } } }
NikolasMarkou/Accord-Framework
Unit Tests/Accord.Tests.Statistics/Filters/StratificationFilterTest.cs
C#
lgpl-2.1
2,897
package usp.ime.line.ivprog.model.domain.actions; import usp.ime.line.ivprog.model.components.datafactory.dataobjetcs.Expression; import usp.ime.line.ivprog.model.components.datafactory.dataobjetcs.ReturnStatement; import usp.ime.line.ivprog.model.domain.IVPDomainModel; import ilm.framework.assignment.model.DomainAction; import ilm.framework.domain.DomainModel; public class ReturnSetExpression extends DomainAction { private IVPDomainModel model = null; private ReturnStatement rStatement = null; private Expression returnedExpression = null; private Expression lastReturned = null; public ReturnSetExpression(String name, String description) { super(name, description); } public void setDomainModel(DomainModel m) { model = (IVPDomainModel)model; } protected void executeAction() { lastReturned = model.setReturnExpression(returnedExpression, rStatement, _currentState); } protected void undoAction() { model.setReturnExpression(lastReturned, rStatement, _currentState); } public boolean equals(DomainAction a) { return false; } public ReturnStatement getReturnStatement() { return rStatement; } public void setReturnStatement(ReturnStatement rStatement) { this.rStatement = rStatement; } public Expression getReturnedExpression() { return returnedExpression; } public void setReturnedExpression(Expression returnedExpression) { this.returnedExpression = returnedExpression; } }
Romenig/ivprog2
src/usp/ime/line/ivprog/model/domain/actions/ReturnSetExpression.java
Java
lgpl-2.1
1,489
package org.venice.venicemod.generations; import java.util.Random; import org.venice.venicemod.VeniceMod; import cpw.mods.fml.common.IWorldGenerator; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; public class TitaniumGeneraton extends OreGeneration { public TitaniumGeneraton(){ this.setInBlock( VeniceMod.oreTitanium ); this.setAppearInOverworld( true ); this.setChans( 20 ); this.setMinY( 50 ); this.setMaxY( 100 ); this.setMinVienSize( 6 ); this.setMaxVienSize( 15 ); } }
musdasch/VeniceMod
src/main/java/org/venice/venicemod/generations/TitaniumGeneraton.java
Java
lgpl-2.1
535
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "ParsedSubdomainMeshGenerator.h" #include "Conversion.h" #include "MooseMeshUtils.h" #include "CastUniquePointer.h" #include "libmesh/fparser_ad.hh" #include "libmesh/elem.h" registerMooseObject("MooseApp", ParsedSubdomainMeshGenerator); defineLegacyParams(ParsedSubdomainMeshGenerator); InputParameters ParsedSubdomainMeshGenerator::validParams() { InputParameters params = MeshGenerator::validParams(); params += FunctionParserUtils<false>::validParams(); params.addRequiredParam<MeshGeneratorName>("input", "The mesh we want to modify"); params.addRequiredParam<std::string>("combinatorial_geometry", "Function expression encoding a combinatorial geometry"); params.addRequiredParam<subdomain_id_type>("block_id", "Subdomain id to set for inside of the combinatorial"); params.addParam<SubdomainName>("block_name", "Subdomain name to set for inside of the combinatorial"); params.addParam<std::vector<subdomain_id_type>>( "excluded_subdomain_ids", "A set of subdomain ids that will not changed even if " "they are inside/outside the combinatorial geometry"); params.addParam<std::vector<std::string>>( "constant_names", "Vector of constants used in the parsed function (use this for kB etc.)"); params.addParam<std::vector<std::string>>( "constant_expressions", "Vector of values for the constants in constant_names (can be an FParser expression)"); params.addClassDescription( "Uses a parsed expression (`combinatorial_geometry`) to determine if an " "element (via its centroid) is inside the region defined by the expression and " "assigns a new block ID."); return params; } ParsedSubdomainMeshGenerator::ParsedSubdomainMeshGenerator(const InputParameters & parameters) : MeshGenerator(parameters), FunctionParserUtils<false>(parameters), _input(getMesh("input")), _function(parameters.get<std::string>("combinatorial_geometry")), _block_id(parameters.get<SubdomainID>("block_id")), _excluded_ids(parameters.get<std::vector<SubdomainID>>("excluded_subdomain_ids")) { // base function object _func_F = std::make_shared<SymFunction>(); // set FParser internal feature flags setParserFeatureFlags(_func_F); // add the constant expressions addFParserConstants(_func_F, getParam<std::vector<std::string>>("constant_names"), getParam<std::vector<std::string>>("constant_expressions")); // parse function if (_func_F->Parse(_function, "x,y,z") >= 0) mooseError("Invalid function\n", _function, "\nin ParsedSubdomainMeshModifier ", name(), ".\n", _func_F->ErrorMsg()); _func_params.resize(3); } std::unique_ptr<MeshBase> ParsedSubdomainMeshGenerator::generate() { std::unique_ptr<MeshBase> mesh = std::move(_input); // Loop over the elements for (const auto & elem : mesh->active_element_ptr_range()) { _func_params[0] = elem->centroid()(0); _func_params[1] = elem->centroid()(1); _func_params[2] = elem->centroid()(2); bool contains = evaluate(_func_F); if (contains && std::find(_excluded_ids.begin(), _excluded_ids.end(), elem->subdomain_id()) == _excluded_ids.end()) elem->subdomain_id() = _block_id; } // Assign block name, if provided if (isParamValid("block_name")) mesh->subdomain_name(_block_id) = getParam<SubdomainName>("block_name"); return dynamic_pointer_cast<MeshBase>(mesh); }
nuclear-wizard/moose
framework/src/meshgenerators/ParsedSubdomainMeshGenerator.C
C++
lgpl-2.1
3,959
// // MD2Managed.cs - Message Digest 2 Managed Implementation // // Author: // Sebastien Pouliot (sebastien@ximian.com) // // (C) 2001-2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE 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. // using System; namespace CryptoNet.Security.Cryptography { // References: // a. RFC1319: The MD2 Message-Digest Algorithm // http://www.ietf.org/rfc/rfc1319.txt internal class MD2Managed : MD2 { private byte[] state; private byte[] checksum; private byte[] buffer; private int count; private byte[] x; /// <summary> /// Permutation of 0..255 constructed from the digits of pi. It gives a /// "random" nonlinear byte substitution operation. /// </summary> private static readonly byte[] PI_SUBST = { 41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6, 19, 98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188, 76, 130, 202, 30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24, 138, 23, 229, 18, 190, 78, 196, 214, 218, 158, 222, 73, 160, 251, 245, 142, 187, 47, 238, 122, 169, 104, 121, 145, 21, 178, 7, 63, 148, 194, 16, 137, 11, 34, 95, 33, 128, 127, 93, 154, 90, 144, 50, 39, 53, 62, 204, 231, 191, 247, 151, 3, 255, 25, 48, 179, 72, 165, 181, 209, 215, 94, 146, 42, 172, 86, 170, 198, 79, 184, 56, 210, 150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241, 69, 157, 112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2, 27, 96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15, 85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197, 234, 38, 44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65, 129, 77, 82, 106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123, 8, 12, 189, 177, 74, 120, 136, 149, 139, 227, 99, 232, 109, 233, 203, 213, 254, 59, 0, 29, 57, 242, 239, 183, 14, 102, 88, 208, 228, 166, 119, 114, 248, 235, 117, 75, 10, 49, 68, 80, 180, 143, 237, 31, 26, 219, 153, 141, 51, 159, 17, 131, 20 }; private byte[] Padding (int nLength) { if (nLength > 0) { byte[] padding = new byte [nLength]; for (int i = 0; i < padding.Length; i++) padding[i] = (byte) nLength; return padding; } return null; } //--- constructor ----------------------------------------------------------- public MD2Managed () : base () { // we allocate the context memory state = new byte [16]; checksum = new byte [16]; buffer = new byte [16]; x = new byte [48]; // the initialize our context Initialize (); } public override void Initialize () { count = 0; Array.Clear (state, 0, 16); Array.Clear (checksum, 0, 16); Array.Clear (buffer, 0, 16); // Zeroize sensitive information Array.Clear (x, 0, 48); } protected override void HashCore (byte[] array, int ibStart, int cbSize) { int i; /* Update number of bytes mod 16 */ int index = count; count = (int) (index + cbSize) & 0xf; int partLen = 16 - index; /* Transform as many times as possible. */ if (cbSize >= partLen) { // MD2_memcpy((POINTER)&context->buffer[index], (POINTER)input, partLen); Buffer.BlockCopy (array, ibStart, buffer, index, partLen); // MD2Transform (context->state, context->checksum, context->buffer); MD2Transform (state, checksum, buffer, 0); for (i = partLen; i + 15 < cbSize; i += 16) { // MD2Transform (context->state, context->checksum, &input[i]); MD2Transform (state, checksum, array, i); } index = 0; } else i = 0; /* Buffer remaining input */ // MD2_memcpy((POINTER)&context->buffer[index], (POINTER)&input[i], inputLen-i); Buffer.BlockCopy (array, ibStart + i, buffer, index, (cbSize - i)); } protected override byte[] HashFinal () { // Pad out to multiple of 16. int index = count; int padLen = 16 - index; // is padding needed ? required if length not a multiple of 16. if (padLen > 0) HashCore (Padding (padLen), 0, padLen); // Extend with checksum HashCore (checksum, 0, 16); // Store state in digest byte[] digest = (byte[]) state.Clone (); // Zeroize sensitive information. Initialize (); return digest; } //--- private methods --------------------------------------------------- /// <summary> /// MD2 basic transformation. Transforms state and updates checksum /// based on block. /// </summary> private void MD2Transform (byte[] state, byte[] checksum, byte[] block, int index) { /* Form encryption block from state, block, state ^ block. */ // MD2_memcpy ((POINTER)x, (POINTER)state, 16); Buffer.BlockCopy (state, 0, x, 0, 16); // MD2_memcpy ((POINTER)x+16, (POINTER)block, 16); Buffer.BlockCopy (block, index, x, 16, 16); // for (i = 0; i < 16; i++) x[i+32] = state[i] ^ block[i]; for (int i = 0; i < 16; i++) x [i+32] = (byte) ((byte) state [i] ^ (byte) block [index + i]); /* Encrypt block (18 rounds). */ int t = 0; for (int i = 0; i < 18; i++) { for (int j = 0; j < 48; j++ ) t = x [j] ^= PI_SUBST [t]; t = (t + i) & 0xff; } /* Save new state */ // MD2_memcpy ((POINTER)state, (POINTER)x, 16); Buffer.BlockCopy (x, 0, state, 0, 16); /* Update checksum. */ t = checksum [15]; for (int i = 0; i < 16; i++) t = checksum [i] ^= PI_SUBST [block [index + i] ^ t]; } } }
Reaper38/Crypto.NET
Crypto.Net/SSL/Mono/Mono.Security.Cryptography/MD2Managed.cs
C#
lgpl-2.1
6,457
# JoeTraffic - Web-Log Analysis Application utilizing the JoeAgent Framework. # Copyright (C) 2004 Rhett Garber # 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 from JoeAgent import job, event import db_interface import os, os.path import logging import log_parser LINEINCR = 30 log = logging.getLogger("agent.LogReader") class ReadLogCompleteEvent(event.Event): """Event to indicate the file is completely read. This event will be caught by the FindLogJob that is watching it. The file will continue to be checked for modifications""" pass class ReadLogContinueEvent(event.Event): """Event to indicate we should continue reading the file. Log file processing will be done in chunks so as not to block the agent for too long.""" pass class ReadLogJob(job.Job): def __init__(self, agent_obj, logfile): job.Job.__init__(self, agent_obj) assert os.path.isfile(logfile), "Not a file: %s" % str(logfile) self._log_size = os.stat(logfile).st_size log.debug("Log size is %d" % self._log_size) self._logfile_path = logfile self._logfile_hndl = open(logfile, 'r') self._progress = 0 # Data read from file self._db = db_interface.getDB() def getFilePath(self): return self._logfile_path def getBytesRead(self): return self._progress def getBytesTotal(self): return self._log_size def run(self): evt = ReadLogContinueEvent(self) self.getAgent().addEvent(evt) def notify(self, evt): job.Job.notify(self, evt) if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self: log.debug("Continuing read of file") # Continue to read the log try: self._progress += log_parser.read_log( self._logfile_hndl, self._db, LINEINCR) log.debug("Read %d %% of file (%d / %d)" % (self.getProgress(), self._progress, self._log_size)) except log_parser.EndOfLogException, e: self._progress = self._log_size # Log file is complete, updated the db entry self._mark_complete() # Add an event to notify that the file is complete self._logfile_hndl.close() new_evt = ReadLogCompleteEvent(self) self.getAgent().addEvent(new_evt) except log_parser.InvalidLogException, e: log.warning("Invalid log file: %s" % str(e)) self._logfile_hndl.close() new_evt = ReadLogCompleteEvent(self) self.getAgent().addEvent(new_evt) else: # Add an event to continue reading new_evt = ReadLogContinueEvent(self) self.getAgent().addEvent(new_evt) def _update_db(self): """Update the entry in the database for this logfile""" log.debug("Updating file %s" % self._logfile_path) pass def _mark_invalid(self): """Update the database to indicate that this is not a valid log file""" log.debug("Marking file %s invalid" % self._logfile_path) pass def _mark_complete(self): log.debug("Marking file %s complete" % self._logfile_path) pass def getProgress(self): """Return a percentage complete value""" if self._log_size == 0: return 0 return int((float(self._progress) / self._log_size) * 100)
rhettg/JoeTraffic
LogReader/read_job.py
Python
lgpl-2.1
4,327
/** * DSS - Digital Signature Services * Copyright (C) 2015 European Commission, provided under the CEF programme * * This file is part of the "DSS - Digital Signature Services" project. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package eu.europa.esig.dss.x509.ocsp; import java.util.Date; import java.util.List; import org.bouncycastle.cert.ocsp.BasicOCSPResp; import org.bouncycastle.cert.ocsp.CertificateID; import org.bouncycastle.cert.ocsp.SingleResp; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import eu.europa.esig.dss.DSSRevocationUtils; import eu.europa.esig.dss.utils.Utils; import eu.europa.esig.dss.x509.CertificateToken; import eu.europa.esig.dss.x509.RevocationOrigin; /** * Abstract class that helps to implement an OCSPSource with an already loaded list of BasicOCSPResp * */ @SuppressWarnings("serial") public abstract class OfflineOCSPSource implements OCSPSource { private static final Logger LOG = LoggerFactory.getLogger(OfflineOCSPSource.class); @Override public final OCSPToken getRevocationToken(CertificateToken certificateToken, CertificateToken issuerCertificateToken) { final List<BasicOCSPResp> containedOCSPResponses = getContainedOCSPResponses(); if (Utils.isCollectionEmpty(containedOCSPResponses)) { return null; } if (LOG.isTraceEnabled()) { final String dssIdAsString = certificateToken.getDSSIdAsString(); LOG.trace("--> OfflineOCSPSource queried for " + dssIdAsString + " contains: " + containedOCSPResponses.size() + " element(s)."); } Date bestUpdate = null; BasicOCSPResp bestBasicOCSPResp = null; final CertificateID certId = DSSRevocationUtils.getOCSPCertificateID(certificateToken, issuerCertificateToken); for (final BasicOCSPResp basicOCSPResp : containedOCSPResponses) { for (final SingleResp singleResp : basicOCSPResp.getResponses()) { if (DSSRevocationUtils.matches(certId, singleResp)) { final Date thisUpdate = singleResp.getThisUpdate(); if ((bestUpdate == null) || thisUpdate.after(bestUpdate)) { bestBasicOCSPResp = basicOCSPResp; bestUpdate = thisUpdate; } } } } if (bestBasicOCSPResp != null) { OCSPToken ocspToken = new OCSPToken(); ocspToken.setCertId(certId); ocspToken.setOrigin(RevocationOrigin.SIGNATURE); ocspToken.setBasicOCSPResp(bestBasicOCSPResp); return ocspToken; } return null; } /** * Retrieves the list of {@code BasicOCSPResp} contained in the source. * * @return {@code List} of {@code BasicOCSPResp}s */ public abstract List<BasicOCSPResp> getContainedOCSPResponses(); }
zsoltii/dss
dss-spi/src/main/java/eu/europa/esig/dss/x509/ocsp/OfflineOCSPSource.java
Java
lgpl-2.1
3,289
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2021 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/text/placements/base.hpp> namespace mapnik { text_placements::text_placements() : defaults() {} void text_placements::add_expressions(expression_set& output) const { defaults.add_expressions(output); } text_placement_info::text_placement_info(text_placements const* parent, double scale_factor_) : properties(parent->defaults) , scale_factor(scale_factor_) {} } // namespace mapnik
mapnik/mapnik
src/text/placements/base.cpp
C++
lgpl-2.1
1,428
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.cfg.annotations.reflection; import java.beans.Introspector; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.AssociationOverride; import javax.persistence.AssociationOverrides; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Basic; import javax.persistence.Cacheable; import javax.persistence.CascadeType; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ColumnResult; import javax.persistence.ConstructorResult; import javax.persistence.Convert; import javax.persistence.Converts; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; import javax.persistence.DiscriminatorValue; import javax.persistence.ElementCollection; import javax.persistence.Embeddable; import javax.persistence.Embedded; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.EntityResult; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.ExcludeDefaultListeners; import javax.persistence.ExcludeSuperclassListeners; import javax.persistence.FetchType; import javax.persistence.FieldResult; import javax.persistence.ForeignKey; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.Index; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.JoinTable; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.MapKey; import javax.persistence.MapKeyClass; import javax.persistence.MapKeyColumn; import javax.persistence.MapKeyEnumerated; import javax.persistence.MapKeyJoinColumn; import javax.persistence.MapKeyJoinColumns; import javax.persistence.MapKeyTemporal; import javax.persistence.MappedSuperclass; import javax.persistence.MapsId; import javax.persistence.NamedAttributeNode; import javax.persistence.NamedEntityGraph; import javax.persistence.NamedEntityGraphs; import javax.persistence.NamedNativeQueries; import javax.persistence.NamedNativeQuery; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.NamedStoredProcedureQueries; import javax.persistence.NamedStoredProcedureQuery; import javax.persistence.NamedSubgraph; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.OrderBy; import javax.persistence.OrderColumn; import javax.persistence.ParameterMode; import javax.persistence.PostLoad; import javax.persistence.PostPersist; import javax.persistence.PostRemove; import javax.persistence.PostUpdate; import javax.persistence.PrePersist; import javax.persistence.PreRemove; import javax.persistence.PreUpdate; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.PrimaryKeyJoinColumns; import javax.persistence.QueryHint; import javax.persistence.SecondaryTable; import javax.persistence.SecondaryTables; import javax.persistence.SequenceGenerator; import javax.persistence.SqlResultSetMapping; import javax.persistence.SqlResultSetMappings; import javax.persistence.StoredProcedureParameter; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; import javax.persistence.Version; import org.hibernate.AnnotationException; import org.hibernate.annotations.Any; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.Columns; import org.hibernate.annotations.ManyToAny; import org.hibernate.annotations.common.annotationfactory.AnnotationDescriptor; import org.hibernate.annotations.common.annotationfactory.AnnotationFactory; import org.hibernate.annotations.common.reflection.AnnotationReader; import org.hibernate.annotations.common.reflection.ReflectionUtil; import org.hibernate.boot.registry.classloading.spi.ClassLoadingException; import org.hibernate.boot.spi.ClassLoaderAccess; import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.StringHelper; import org.dom4j.Attribute; import org.dom4j.Element; /** * Encapsulates the overriding of Java annotations from an EJB 3.0 descriptor. * * @author Paolo Perrotta * @author Davide Marchignoli * @author Emmanuel Bernard * @author Hardy Ferentschik */ @SuppressWarnings("unchecked") public class JPAOverriddenAnnotationReader implements AnnotationReader { private static final CoreMessageLogger LOG = CoreLogging.messageLogger( JPAOverriddenAnnotationReader.class ); private static final String SCHEMA_VALIDATION = "Activate schema validation for more information"; private static final String WORD_SEPARATOR = "-"; private static enum PropertyType { PROPERTY, FIELD, METHOD } private static final Map<Class, String> annotationToXml; static { annotationToXml = new HashMap<Class, String>(); annotationToXml.put( Entity.class, "entity" ); annotationToXml.put( MappedSuperclass.class, "mapped-superclass" ); annotationToXml.put( Embeddable.class, "embeddable" ); annotationToXml.put( Table.class, "table" ); annotationToXml.put( SecondaryTable.class, "secondary-table" ); annotationToXml.put( SecondaryTables.class, "secondary-table" ); annotationToXml.put( PrimaryKeyJoinColumn.class, "primary-key-join-column" ); annotationToXml.put( PrimaryKeyJoinColumns.class, "primary-key-join-column" ); annotationToXml.put( IdClass.class, "id-class" ); annotationToXml.put( Inheritance.class, "inheritance" ); annotationToXml.put( DiscriminatorValue.class, "discriminator-value" ); annotationToXml.put( DiscriminatorColumn.class, "discriminator-column" ); annotationToXml.put( SequenceGenerator.class, "sequence-generator" ); annotationToXml.put( TableGenerator.class, "table-generator" ); annotationToXml.put( NamedEntityGraph.class, "named-entity-graph" ); annotationToXml.put( NamedEntityGraphs.class, "named-entity-graph" ); annotationToXml.put( NamedQuery.class, "named-query" ); annotationToXml.put( NamedQueries.class, "named-query" ); annotationToXml.put( NamedNativeQuery.class, "named-native-query" ); annotationToXml.put( NamedNativeQueries.class, "named-native-query" ); annotationToXml.put( NamedStoredProcedureQuery.class, "named-stored-procedure-query" ); annotationToXml.put( NamedStoredProcedureQueries.class, "named-stored-procedure-query" ); annotationToXml.put( SqlResultSetMapping.class, "sql-result-set-mapping" ); annotationToXml.put( SqlResultSetMappings.class, "sql-result-set-mapping" ); annotationToXml.put( ExcludeDefaultListeners.class, "exclude-default-listeners" ); annotationToXml.put( ExcludeSuperclassListeners.class, "exclude-superclass-listeners" ); annotationToXml.put( AccessType.class, "access" ); annotationToXml.put( AttributeOverride.class, "attribute-override" ); annotationToXml.put( AttributeOverrides.class, "attribute-override" ); annotationToXml.put( AttributeOverride.class, "association-override" ); annotationToXml.put( AttributeOverrides.class, "association-override" ); annotationToXml.put( AttributeOverride.class, "map-key-attribute-override" ); annotationToXml.put( AttributeOverrides.class, "map-key-attribute-override" ); annotationToXml.put( Id.class, "id" ); annotationToXml.put( EmbeddedId.class, "embedded-id" ); annotationToXml.put( GeneratedValue.class, "generated-value" ); annotationToXml.put( Column.class, "column" ); annotationToXml.put( Columns.class, "column" ); annotationToXml.put( Temporal.class, "temporal" ); annotationToXml.put( Lob.class, "lob" ); annotationToXml.put( Enumerated.class, "enumerated" ); annotationToXml.put( Version.class, "version" ); annotationToXml.put( Transient.class, "transient" ); annotationToXml.put( Basic.class, "basic" ); annotationToXml.put( Embedded.class, "embedded" ); annotationToXml.put( ManyToOne.class, "many-to-one" ); annotationToXml.put( OneToOne.class, "one-to-one" ); annotationToXml.put( OneToMany.class, "one-to-many" ); annotationToXml.put( ManyToMany.class, "many-to-many" ); annotationToXml.put( Any.class, "any" ); annotationToXml.put( ManyToAny.class, "many-to-any" ); annotationToXml.put( JoinTable.class, "join-table" ); annotationToXml.put( JoinColumn.class, "join-column" ); annotationToXml.put( JoinColumns.class, "join-column" ); annotationToXml.put( MapKey.class, "map-key" ); annotationToXml.put( OrderBy.class, "order-by" ); annotationToXml.put( EntityListeners.class, "entity-listeners" ); annotationToXml.put( PrePersist.class, "pre-persist" ); annotationToXml.put( PreRemove.class, "pre-remove" ); annotationToXml.put( PreUpdate.class, "pre-update" ); annotationToXml.put( PostPersist.class, "post-persist" ); annotationToXml.put( PostRemove.class, "post-remove" ); annotationToXml.put( PostUpdate.class, "post-update" ); annotationToXml.put( PostLoad.class, "post-load" ); annotationToXml.put( CollectionTable.class, "collection-table" ); annotationToXml.put( MapKeyClass.class, "map-key-class" ); annotationToXml.put( MapKeyTemporal.class, "map-key-temporal" ); annotationToXml.put( MapKeyEnumerated.class, "map-key-enumerated" ); annotationToXml.put( MapKeyColumn.class, "map-key-column" ); annotationToXml.put( MapKeyJoinColumn.class, "map-key-join-column" ); annotationToXml.put( MapKeyJoinColumns.class, "map-key-join-column" ); annotationToXml.put( OrderColumn.class, "order-column" ); annotationToXml.put( Cacheable.class, "cacheable" ); annotationToXml.put( Index.class, "index" ); annotationToXml.put( ForeignKey.class, "foreign-key" ); annotationToXml.put( Convert.class, "convert" ); annotationToXml.put( Converts.class, "convert" ); annotationToXml.put( ConstructorResult.class, "constructor-result" ); } private XMLContext xmlContext; private final ClassLoaderAccess classLoaderAccess; private final AnnotatedElement element; private String className; private String propertyName; private PropertyType propertyType; private transient Annotation[] annotations; private transient Map<Class, Annotation> annotationsMap; private transient List<Element> elementsForProperty; private AccessibleObject mirroredAttribute; public JPAOverriddenAnnotationReader(AnnotatedElement el, XMLContext xmlContext, ClassLoaderAccess classLoaderAccess) { this.element = el; this.xmlContext = xmlContext; this.classLoaderAccess = classLoaderAccess; if ( el instanceof Class ) { Class clazz = (Class) el; className = clazz.getName(); } else if ( el instanceof Field ) { Field field = (Field) el; className = field.getDeclaringClass().getName(); propertyName = field.getName(); propertyType = PropertyType.FIELD; String expectedGetter = "get" + Character.toUpperCase( propertyName.charAt( 0 ) ) + propertyName.substring( 1 ); try { mirroredAttribute = field.getDeclaringClass().getDeclaredMethod( expectedGetter ); } catch ( NoSuchMethodException e ) { //no method } } else if ( el instanceof Method ) { Method method = (Method) el; className = method.getDeclaringClass().getName(); propertyName = method.getName(); // YUCK! The null here is the 'boundType', we'd rather get the TypeEnvironment() if ( ReflectionUtil.isProperty( method, null, PersistentAttributeFilter.INSTANCE ) ) { if ( propertyName.startsWith( "get" ) ) { propertyName = Introspector.decapitalize( propertyName.substring( "get".length() ) ); } else if ( propertyName.startsWith( "is" ) ) { propertyName = Introspector.decapitalize( propertyName.substring( "is".length() ) ); } else { throw new RuntimeException( "Method " + propertyName + " is not a property getter" ); } propertyType = PropertyType.PROPERTY; try { mirroredAttribute = method.getDeclaringClass().getDeclaredField( propertyName ); } catch ( NoSuchFieldException e ) { //no method } } else { propertyType = PropertyType.METHOD; } } else { className = null; propertyName = null; } } public <T extends Annotation> T getAnnotation(Class<T> annotationType) { initAnnotations(); return (T) annotationsMap.get( annotationType ); } public <T extends Annotation> boolean isAnnotationPresent(Class<T> annotationType) { initAnnotations(); return annotationsMap.containsKey( annotationType ); } public Annotation[] getAnnotations() { initAnnotations(); return annotations; } /* * The idea is to create annotation proxies for the xml configuration elements. Using this proxy annotations together * with the {@link JPAMetadataProvider} allows to handle xml configuration the same way as annotation configuration. */ private void initAnnotations() { if ( annotations == null ) { XMLContext.Default defaults = xmlContext.getDefault( className ); if ( className != null && propertyName == null ) { //is a class Element tree = xmlContext.getXMLTree( className ); Annotation[] annotations = getPhysicalAnnotations(); List<Annotation> annotationList = new ArrayList<Annotation>( annotations.length + 5 ); annotationsMap = new HashMap<Class, Annotation>( annotations.length + 5 ); for ( Annotation annotation : annotations ) { if ( !annotationToXml.containsKey( annotation.annotationType() ) ) { //unknown annotations are left over annotationList.add( annotation ); } } addIfNotNull( annotationList, getEntity( tree, defaults ) ); addIfNotNull( annotationList, getMappedSuperclass( tree, defaults ) ); addIfNotNull( annotationList, getEmbeddable( tree, defaults ) ); addIfNotNull( annotationList, getTable( tree, defaults ) ); addIfNotNull( annotationList, getSecondaryTables( tree, defaults ) ); addIfNotNull( annotationList, getPrimaryKeyJoinColumns( tree, defaults, true ) ); addIfNotNull( annotationList, getIdClass( tree, defaults ) ); addIfNotNull( annotationList, getCacheable( tree, defaults ) ); addIfNotNull( annotationList, getInheritance( tree, defaults ) ); addIfNotNull( annotationList, getDiscriminatorValue( tree, defaults ) ); addIfNotNull( annotationList, getDiscriminatorColumn( tree, defaults ) ); addIfNotNull( annotationList, getSequenceGenerator( tree, defaults ) ); addIfNotNull( annotationList, getTableGenerator( tree, defaults ) ); addIfNotNull( annotationList, getNamedQueries( tree, defaults ) ); addIfNotNull( annotationList, getNamedNativeQueries( tree, defaults ) ); addIfNotNull( annotationList, getNamedStoredProcedureQueries( tree, defaults ) ); addIfNotNull( annotationList, getNamedEntityGraphs( tree, defaults ) ); addIfNotNull( annotationList, getSqlResultSetMappings( tree, defaults ) ); addIfNotNull( annotationList, getExcludeDefaultListeners( tree, defaults ) ); addIfNotNull( annotationList, getExcludeSuperclassListeners( tree, defaults ) ); addIfNotNull( annotationList, getAccessType( tree, defaults ) ); addIfNotNull( annotationList, getAttributeOverrides( tree, defaults, true ) ); addIfNotNull( annotationList, getAssociationOverrides( tree, defaults, true ) ); addIfNotNull( annotationList, getEntityListeners( tree, defaults ) ); addIfNotNull( annotationList, getConverts( tree, defaults ) ); this.annotations = annotationList.toArray( new Annotation[annotationList.size()] ); for ( Annotation ann : this.annotations ) { annotationsMap.put( ann.annotationType(), ann ); } checkForOrphanProperties( tree ); } else if ( className != null ) { //&& propertyName != null ) { //always true but less confusing Element tree = xmlContext.getXMLTree( className ); Annotation[] annotations = getPhysicalAnnotations(); List<Annotation> annotationList = new ArrayList<Annotation>( annotations.length + 5 ); annotationsMap = new HashMap<Class, Annotation>( annotations.length + 5 ); for ( Annotation annotation : annotations ) { if ( !annotationToXml.containsKey( annotation.annotationType() ) ) { //unknown annotations are left over annotationList.add( annotation ); } } preCalculateElementsForProperty( tree ); Transient transientAnn = getTransient( defaults ); if ( transientAnn != null ) { annotationList.add( transientAnn ); } else { if ( defaults.canUseJavaAnnotations() ) { Annotation annotation = getPhysicalAnnotation( Access.class ); addIfNotNull( annotationList, annotation ); } getId( annotationList, defaults ); getEmbeddedId( annotationList, defaults ); getEmbedded( annotationList, defaults ); getBasic( annotationList, defaults ); getVersion( annotationList, defaults ); getAssociation( ManyToOne.class, annotationList, defaults ); getAssociation( OneToOne.class, annotationList, defaults ); getAssociation( OneToMany.class, annotationList, defaults ); getAssociation( ManyToMany.class, annotationList, defaults ); getAssociation( Any.class, annotationList, defaults ); getAssociation( ManyToAny.class, annotationList, defaults ); getElementCollection( annotationList, defaults ); addIfNotNull( annotationList, getSequenceGenerator( elementsForProperty, defaults ) ); addIfNotNull( annotationList, getTableGenerator( elementsForProperty, defaults ) ); addIfNotNull( annotationList, getConvertsForAttribute( elementsForProperty, defaults ) ); } processEventAnnotations( annotationList, defaults ); //FIXME use annotationsMap rather than annotationList this will be faster since the annotation type is usually known at put() time this.annotations = annotationList.toArray( new Annotation[annotationList.size()] ); for ( Annotation ann : this.annotations ) { annotationsMap.put( ann.annotationType(), ann ); } } else { this.annotations = getPhysicalAnnotations(); annotationsMap = new HashMap<Class, Annotation>( annotations.length + 5 ); for ( Annotation ann : this.annotations ) { annotationsMap.put( ann.annotationType(), ann ); } } } } private Annotation getConvertsForAttribute(List<Element> elementsForProperty, XMLContext.Default defaults) { // NOTE : we use a map here to make sure that an xml and annotation referring to the same attribute // properly overrides. Very sparse map, yes, but easy setup. // todo : revisit this // although bear in mind that this code is no longer used in 5.0... final Map<String,Convert> convertAnnotationsMap = new HashMap<String, Convert>(); for ( Element element : elementsForProperty ) { final boolean isBasic = "basic".equals( element.getName() ); final boolean isEmbedded = "embedded".equals( element.getName() ); // todo : can be collections too final boolean canHaveConverts = isBasic || isEmbedded; if ( !canHaveConverts ) { continue; } final String attributeNamePrefix = isBasic ? null : propertyName; applyXmlDefinedConverts( element, defaults, attributeNamePrefix, convertAnnotationsMap ); } // NOTE : per section 12.2.3.16 of the spec <convert/> is additive, although only if "metadata-complete" is not // specified in the XML if ( defaults.canUseJavaAnnotations() ) { // todo : note sure how to best handle attributeNamePrefix here applyPhysicalConvertAnnotations( propertyName, convertAnnotationsMap ); } if ( !convertAnnotationsMap.isEmpty() ) { final AnnotationDescriptor groupingDescriptor = new AnnotationDescriptor( Converts.class ); groupingDescriptor.setValue( "value", convertAnnotationsMap.values().toArray( new Convert[convertAnnotationsMap.size()]) ); return AnnotationFactory.create( groupingDescriptor ); } return null; } private Converts getConverts(Element tree, XMLContext.Default defaults) { // NOTE : we use a map here to make sure that an xml and annotation referring to the same attribute // properly overrides. Bit sparse, but easy... final Map<String,Convert> convertAnnotationsMap = new HashMap<String, Convert>(); if ( tree != null ) { applyXmlDefinedConverts( tree, defaults, null, convertAnnotationsMap ); } // NOTE : per section 12.2.3.16 of the spec <convert/> is additive, although only if "metadata-complete" is not // specified in the XML if ( defaults.canUseJavaAnnotations() ) { applyPhysicalConvertAnnotations( null, convertAnnotationsMap ); } if ( !convertAnnotationsMap.isEmpty() ) { final AnnotationDescriptor groupingDescriptor = new AnnotationDescriptor( Converts.class ); groupingDescriptor.setValue( "value", convertAnnotationsMap.values().toArray( new Convert[convertAnnotationsMap.size()]) ); return AnnotationFactory.create( groupingDescriptor ); } return null; } private void applyXmlDefinedConverts( Element containingElement, XMLContext.Default defaults, String attributeNamePrefix, Map<String,Convert> convertAnnotationsMap) { final List<Element> convertElements = containingElement.elements( "convert" ); for ( Element convertElement : convertElements ) { final AnnotationDescriptor convertAnnotationDescriptor = new AnnotationDescriptor( Convert.class ); copyStringAttribute( convertAnnotationDescriptor, convertElement, "attribute-name", false ); copyBooleanAttribute( convertAnnotationDescriptor, convertElement, "disable-conversion" ); final Attribute converterClassAttr = convertElement.attribute( "converter" ); if ( converterClassAttr != null ) { final String converterClassName = XMLContext.buildSafeClassName( converterClassAttr.getValue(), defaults ); try { final Class converterClass = classLoaderAccess.classForName( converterClassName ); convertAnnotationDescriptor.setValue( "converter", converterClass ); } catch (ClassLoadingException e) { throw new AnnotationException( "Unable to find specified converter class id-class: " + converterClassName, e ); } } final Convert convertAnnotation = AnnotationFactory.create( convertAnnotationDescriptor ); final String qualifiedAttributeName = qualifyConverterAttributeName( attributeNamePrefix, convertAnnotation.attributeName() ); convertAnnotationsMap.put( qualifiedAttributeName, convertAnnotation ); } } private String qualifyConverterAttributeName(String attributeNamePrefix, String specifiedAttributeName) { String qualifiedAttributeName; if ( StringHelper.isNotEmpty( specifiedAttributeName ) ) { if ( StringHelper.isNotEmpty( attributeNamePrefix ) ) { qualifiedAttributeName = attributeNamePrefix + '.' + specifiedAttributeName; } else { qualifiedAttributeName = specifiedAttributeName; } } else { qualifiedAttributeName = ""; } return qualifiedAttributeName; } private void applyPhysicalConvertAnnotations( String attributeNamePrefix, Map<String, Convert> convertAnnotationsMap) { final Convert physicalAnnotation = getPhysicalAnnotation( Convert.class ); if ( physicalAnnotation != null ) { // only add if no XML element named a converter for this attribute final String qualifiedAttributeName = qualifyConverterAttributeName( attributeNamePrefix, physicalAnnotation.attributeName() ); if ( ! convertAnnotationsMap.containsKey( qualifiedAttributeName ) ) { convertAnnotationsMap.put( qualifiedAttributeName, physicalAnnotation ); } } final Converts physicalGroupingAnnotation = getPhysicalAnnotation( Converts.class ); if ( physicalGroupingAnnotation != null ) { for ( Convert convertAnnotation : physicalGroupingAnnotation.value() ) { // again, only add if no XML element named a converter for this attribute final String qualifiedAttributeName = qualifyConverterAttributeName( attributeNamePrefix, convertAnnotation.attributeName() ); if ( ! convertAnnotationsMap.containsKey( qualifiedAttributeName ) ) { convertAnnotationsMap.put( qualifiedAttributeName, convertAnnotation ); } } } } private void checkForOrphanProperties(Element tree) { Class clazz; try { clazz = classLoaderAccess.classForName( className ); } catch ( ClassLoadingException e ) { return; //a primitive type most likely } Element element = tree != null ? tree.element( "attributes" ) : null; //put entity.attributes elements if ( element != null ) { //precompute the list of properties //TODO is it really useful... Set<String> properties = new HashSet<String>(); for ( Field field : clazz.getFields() ) { properties.add( field.getName() ); } for ( Method method : clazz.getMethods() ) { String name = method.getName(); if ( name.startsWith( "get" ) ) { properties.add( Introspector.decapitalize( name.substring( "get".length() ) ) ); } else if ( name.startsWith( "is" ) ) { properties.add( Introspector.decapitalize( name.substring( "is".length() ) ) ); } } for ( Element subelement : (List<Element>) element.elements() ) { String propertyName = subelement.attributeValue( "name" ); if ( !properties.contains( propertyName ) ) { LOG.propertyNotFound( StringHelper.qualify( className, propertyName ) ); } } } } /** * Adds {@code annotation} to the list (only if it's not null) and then returns it. * * @param annotationList The list of annotations. * @param annotation The annotation to add to the list. * * @return The annotation which was added to the list or {@code null}. */ private Annotation addIfNotNull(List<Annotation> annotationList, Annotation annotation) { if ( annotation != null ) { annotationList.add( annotation ); } return annotation; } //TODO mutualize the next 2 methods private Annotation getTableGenerator(List<Element> elementsForProperty, XMLContext.Default defaults) { for ( Element element : elementsForProperty ) { Element subelement = element != null ? element.element( annotationToXml.get( TableGenerator.class ) ) : null; if ( subelement != null ) { return buildTableGeneratorAnnotation( subelement, defaults ); } } if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) { return getPhysicalAnnotation( TableGenerator.class ); } else { return null; } } private Annotation getSequenceGenerator(List<Element> elementsForProperty, XMLContext.Default defaults) { for ( Element element : elementsForProperty ) { Element subelement = element != null ? element.element( annotationToXml.get( SequenceGenerator.class ) ) : null; if ( subelement != null ) { return buildSequenceGeneratorAnnotation( subelement ); } } if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) { return getPhysicalAnnotation( SequenceGenerator.class ); } else { return null; } } private void processEventAnnotations(List<Annotation> annotationList, XMLContext.Default defaults) { boolean eventElement = false; for ( Element element : elementsForProperty ) { String elementName = element.getName(); if ( "pre-persist".equals( elementName ) ) { AnnotationDescriptor ad = new AnnotationDescriptor( PrePersist.class ); annotationList.add( AnnotationFactory.create( ad ) ); eventElement = true; } else if ( "pre-remove".equals( elementName ) ) { AnnotationDescriptor ad = new AnnotationDescriptor( PreRemove.class ); annotationList.add( AnnotationFactory.create( ad ) ); eventElement = true; } else if ( "pre-update".equals( elementName ) ) { AnnotationDescriptor ad = new AnnotationDescriptor( PreUpdate.class ); annotationList.add( AnnotationFactory.create( ad ) ); eventElement = true; } else if ( "post-persist".equals( elementName ) ) { AnnotationDescriptor ad = new AnnotationDescriptor( PostPersist.class ); annotationList.add( AnnotationFactory.create( ad ) ); eventElement = true; } else if ( "post-remove".equals( elementName ) ) { AnnotationDescriptor ad = new AnnotationDescriptor( PostRemove.class ); annotationList.add( AnnotationFactory.create( ad ) ); eventElement = true; } else if ( "post-update".equals( elementName ) ) { AnnotationDescriptor ad = new AnnotationDescriptor( PostUpdate.class ); annotationList.add( AnnotationFactory.create( ad ) ); eventElement = true; } else if ( "post-load".equals( elementName ) ) { AnnotationDescriptor ad = new AnnotationDescriptor( PostLoad.class ); annotationList.add( AnnotationFactory.create( ad ) ); eventElement = true; } } if ( !eventElement && defaults.canUseJavaAnnotations() ) { Annotation ann = getPhysicalAnnotation( PrePersist.class ); addIfNotNull( annotationList, ann ); ann = getPhysicalAnnotation( PreRemove.class ); addIfNotNull( annotationList, ann ); ann = getPhysicalAnnotation( PreUpdate.class ); addIfNotNull( annotationList, ann ); ann = getPhysicalAnnotation( PostPersist.class ); addIfNotNull( annotationList, ann ); ann = getPhysicalAnnotation( PostRemove.class ); addIfNotNull( annotationList, ann ); ann = getPhysicalAnnotation( PostUpdate.class ); addIfNotNull( annotationList, ann ); ann = getPhysicalAnnotation( PostLoad.class ); addIfNotNull( annotationList, ann ); } } private EntityListeners getEntityListeners(Element tree, XMLContext.Default defaults) { Element element = tree != null ? tree.element( "entity-listeners" ) : null; if ( element != null ) { List<Class> entityListenerClasses = new ArrayList<Class>(); for ( Element subelement : (List<Element>) element.elements( "entity-listener" ) ) { String className = subelement.attributeValue( "class" ); try { entityListenerClasses.add( classLoaderAccess.classForName( XMLContext.buildSafeClassName( className, defaults ) ) ); } catch ( ClassLoadingException e ) { throw new AnnotationException( "Unable to find " + element.getPath() + ".class: " + className, e ); } } AnnotationDescriptor ad = new AnnotationDescriptor( EntityListeners.class ); ad.setValue( "value", entityListenerClasses.toArray( new Class[entityListenerClasses.size()] ) ); return AnnotationFactory.create( ad ); } else if ( defaults.canUseJavaAnnotations() ) { return getPhysicalAnnotation( EntityListeners.class ); } else { return null; } } private JoinTable overridesDefaultsInJoinTable(Annotation annotation, XMLContext.Default defaults) { //no element but might have some default or some annotation boolean defaultToJoinTable = !( isPhysicalAnnotationPresent( JoinColumn.class ) || isPhysicalAnnotationPresent( JoinColumns.class ) ); final Class<? extends Annotation> annotationClass = annotation.annotationType(); defaultToJoinTable = defaultToJoinTable && ( ( annotationClass == ManyToMany.class && StringHelper.isEmpty( ( (ManyToMany) annotation ).mappedBy() ) ) || ( annotationClass == OneToMany.class && StringHelper.isEmpty( ( (OneToMany) annotation ).mappedBy() ) ) || ( annotationClass == ElementCollection.class ) ); final Class<JoinTable> annotationType = JoinTable.class; if ( defaultToJoinTable && ( StringHelper.isNotEmpty( defaults.getCatalog() ) || StringHelper.isNotEmpty( defaults.getSchema() ) ) ) { AnnotationDescriptor ad = new AnnotationDescriptor( annotationType ); if ( defaults.canUseJavaAnnotations() ) { JoinTable table = getPhysicalAnnotation( annotationType ); if ( table != null ) { ad.setValue( "name", table.name() ); ad.setValue( "schema", table.schema() ); ad.setValue( "catalog", table.catalog() ); ad.setValue( "uniqueConstraints", table.uniqueConstraints() ); ad.setValue( "joinColumns", table.joinColumns() ); ad.setValue( "inverseJoinColumns", table.inverseJoinColumns() ); } } if ( StringHelper.isEmpty( (String) ad.valueOf( "schema" ) ) && StringHelper.isNotEmpty( defaults.getSchema() ) ) { ad.setValue( "schema", defaults.getSchema() ); } if ( StringHelper.isEmpty( (String) ad.valueOf( "catalog" ) ) && StringHelper.isNotEmpty( defaults.getCatalog() ) ) { ad.setValue( "catalog", defaults.getCatalog() ); } return AnnotationFactory.create( ad ); } else if ( defaults.canUseJavaAnnotations() ) { return getPhysicalAnnotation( annotationType ); } else { return null; } } private void getJoinTable(List<Annotation> annotationList, Element tree, XMLContext.Default defaults) { addIfNotNull( annotationList, buildJoinTable( tree, defaults ) ); } /* * no partial overriding possible */ private JoinTable buildJoinTable(Element tree, XMLContext.Default defaults) { Element subelement = tree == null ? null : tree.element( "join-table" ); final Class<JoinTable> annotationType = JoinTable.class; if ( subelement == null ) { return null; } //ignore java annotation, an element is defined AnnotationDescriptor annotation = new AnnotationDescriptor( annotationType ); copyStringAttribute( annotation, subelement, "name", false ); copyStringAttribute( annotation, subelement, "catalog", false ); if ( StringHelper.isNotEmpty( defaults.getCatalog() ) && StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) ) ) { annotation.setValue( "catalog", defaults.getCatalog() ); } copyStringAttribute( annotation, subelement, "schema", false ); if ( StringHelper.isNotEmpty( defaults.getSchema() ) && StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) ) ) { annotation.setValue( "schema", defaults.getSchema() ); } buildUniqueConstraints( annotation, subelement ); buildIndex( annotation, subelement ); annotation.setValue( "joinColumns", getJoinColumns( subelement, false ) ); annotation.setValue( "inverseJoinColumns", getJoinColumns( subelement, true ) ); return AnnotationFactory.create( annotation ); } /** * As per section 12.2 of the JPA 2.0 specification, the association * subelements (many-to-one, one-to-many, one-to-one, many-to-many, * element-collection) completely override the mapping for the specified * field or property. Thus, any methods which might in some contexts merge * with annotations must not do so in this context. * * @see #getElementCollection(List, org.hibernate.cfg.annotations.reflection.XMLContext.Default) */ private void getAssociation( Class<? extends Annotation> annotationType, List<Annotation> annotationList, XMLContext.Default defaults ) { String xmlName = annotationToXml.get( annotationType ); for ( Element element : elementsForProperty ) { if ( xmlName.equals( element.getName() ) ) { AnnotationDescriptor ad = new AnnotationDescriptor( annotationType ); addTargetClass( element, ad, "target-entity", defaults ); getFetchType( ad, element ); getCascades( ad, element, defaults ); getJoinTable( annotationList, element, defaults ); buildJoinColumns( annotationList, element ); Annotation annotation = getPrimaryKeyJoinColumns( element, defaults, false ); addIfNotNull( annotationList, annotation ); copyBooleanAttribute( ad, element, "optional" ); copyBooleanAttribute( ad, element, "orphan-removal" ); copyStringAttribute( ad, element, "mapped-by", false ); getOrderBy( annotationList, element ); getMapKey( annotationList, element ); getMapKeyClass( annotationList, element, defaults ); getMapKeyColumn( annotationList, element ); getOrderColumn( annotationList, element ); getMapKeyTemporal( annotationList, element ); getMapKeyEnumerated( annotationList, element ); annotation = getMapKeyAttributeOverrides( element, defaults ); addIfNotNull( annotationList, annotation ); buildMapKeyJoinColumns( annotationList, element ); getAssociationId( annotationList, element ); getMapsId( annotationList, element ); annotationList.add( AnnotationFactory.create( ad ) ); getAccessType( annotationList, element ); } } if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) { Annotation annotation = getPhysicalAnnotation( annotationType ); if ( annotation != null ) { annotationList.add( annotation ); annotation = overridesDefaultsInJoinTable( annotation, defaults ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( JoinColumn.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( JoinColumns.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( PrimaryKeyJoinColumn.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( PrimaryKeyJoinColumns.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( MapKey.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( OrderBy.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AttributeOverride.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AttributeOverrides.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AssociationOverride.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AssociationOverrides.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Lob.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Enumerated.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Temporal.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Column.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Columns.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( MapKeyClass.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( MapKeyTemporal.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( MapKeyEnumerated.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( MapKeyColumn.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( MapKeyJoinColumn.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( MapKeyJoinColumns.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( OrderColumn.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Cascade.class ); addIfNotNull( annotationList, annotation ); } else if ( isPhysicalAnnotationPresent( ElementCollection.class ) ) { //JPA2 annotation = overridesDefaultsInJoinTable( getPhysicalAnnotation( ElementCollection.class ), defaults ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( MapKey.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( OrderBy.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AttributeOverride.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AttributeOverrides.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AssociationOverride.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AssociationOverrides.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Lob.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Enumerated.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Temporal.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Column.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( OrderColumn.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( MapKeyClass.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( MapKeyTemporal.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( MapKeyEnumerated.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( MapKeyColumn.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( MapKeyJoinColumn.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( MapKeyJoinColumns.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( CollectionTable.class ); addIfNotNull( annotationList, annotation ); } } } private void buildMapKeyJoinColumns(List<Annotation> annotationList, Element element) { MapKeyJoinColumn[] joinColumns = getMapKeyJoinColumns( element ); if ( joinColumns.length > 0 ) { AnnotationDescriptor ad = new AnnotationDescriptor( MapKeyJoinColumns.class ); ad.setValue( "value", joinColumns ); annotationList.add( AnnotationFactory.create( ad ) ); } } private MapKeyJoinColumn[] getMapKeyJoinColumns(Element element) { List<Element> subelements = element != null ? element.elements( "map-key-join-column" ) : null; List<MapKeyJoinColumn> joinColumns = new ArrayList<MapKeyJoinColumn>(); if ( subelements != null ) { for ( Element subelement : subelements ) { AnnotationDescriptor column = new AnnotationDescriptor( MapKeyJoinColumn.class ); copyStringAttribute( column, subelement, "name", false ); copyStringAttribute( column, subelement, "referenced-column-name", false ); copyBooleanAttribute( column, subelement, "unique" ); copyBooleanAttribute( column, subelement, "nullable" ); copyBooleanAttribute( column, subelement, "insertable" ); copyBooleanAttribute( column, subelement, "updatable" ); copyStringAttribute( column, subelement, "column-definition", false ); copyStringAttribute( column, subelement, "table", false ); joinColumns.add( (MapKeyJoinColumn) AnnotationFactory.create( column ) ); } } return joinColumns.toArray( new MapKeyJoinColumn[joinColumns.size()] ); } private AttributeOverrides getMapKeyAttributeOverrides(Element tree, XMLContext.Default defaults) { List<AttributeOverride> attributes = buildAttributeOverrides( tree, "map-key-attribute-override" ); return mergeAttributeOverrides( defaults, attributes, false ); } private Cacheable getCacheable(Element element, XMLContext.Default defaults){ if ( element != null ) { String attValue = element.attributeValue( "cacheable" ); if ( attValue != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( Cacheable.class ); ad.setValue( "value", Boolean.valueOf( attValue ) ); return AnnotationFactory.create( ad ); } } if ( defaults.canUseJavaAnnotations() ) { return getPhysicalAnnotation( Cacheable.class ); } else { return null; } } /** * Adds a @MapKeyEnumerated annotation to the specified annotationList if the specified element * contains a map-key-enumerated sub-element. This should only be the case for * element-collection, many-to-many, or one-to-many associations. */ private void getMapKeyEnumerated(List<Annotation> annotationList, Element element) { Element subelement = element != null ? element.element( "map-key-enumerated" ) : null; if ( subelement != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( MapKeyEnumerated.class ); EnumType value = EnumType.valueOf( subelement.getTextTrim() ); ad.setValue( "value", value ); annotationList.add( AnnotationFactory.create( ad ) ); } } /** * Adds a @MapKeyTemporal annotation to the specified annotationList if the specified element * contains a map-key-temporal sub-element. This should only be the case for element-collection, * many-to-many, or one-to-many associations. */ private void getMapKeyTemporal(List<Annotation> annotationList, Element element) { Element subelement = element != null ? element.element( "map-key-temporal" ) : null; if ( subelement != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( MapKeyTemporal.class ); TemporalType value = TemporalType.valueOf( subelement.getTextTrim() ); ad.setValue( "value", value ); annotationList.add( AnnotationFactory.create( ad ) ); } } /** * Adds an @OrderColumn annotation to the specified annotationList if the specified element * contains an order-column sub-element. This should only be the case for element-collection, * many-to-many, or one-to-many associations. */ private void getOrderColumn(List<Annotation> annotationList, Element element) { Element subelement = element != null ? element.element( "order-column" ) : null; if ( subelement != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( OrderColumn.class ); copyStringAttribute( ad, subelement, "name", false ); copyBooleanAttribute( ad, subelement, "nullable" ); copyBooleanAttribute( ad, subelement, "insertable" ); copyBooleanAttribute( ad, subelement, "updatable" ); copyStringAttribute( ad, subelement, "column-definition", false ); annotationList.add( AnnotationFactory.create( ad ) ); } } /** * Adds a @MapsId annotation to the specified annotationList if the specified element has the * maps-id attribute set. This should only be the case for many-to-one or one-to-one * associations. */ private void getMapsId(List<Annotation> annotationList, Element element) { String attrVal = element.attributeValue( "maps-id" ); if ( attrVal != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( MapsId.class ); ad.setValue( "value", attrVal ); annotationList.add( AnnotationFactory.create( ad ) ); } } /** * Adds an @Id annotation to the specified annotationList if the specified element has the id * attribute set to true. This should only be the case for many-to-one or one-to-one * associations. */ private void getAssociationId(List<Annotation> annotationList, Element element) { String attrVal = element.attributeValue( "id" ); if ( "true".equals( attrVal ) ) { AnnotationDescriptor ad = new AnnotationDescriptor( Id.class ); annotationList.add( AnnotationFactory.create( ad ) ); } } private void addTargetClass(Element element, AnnotationDescriptor ad, String nodeName, XMLContext.Default defaults) { String className = element.attributeValue( nodeName ); if ( className != null ) { Class clazz; try { clazz = classLoaderAccess.classForName( XMLContext.buildSafeClassName( className, defaults ) ); } catch ( ClassLoadingException e ) { throw new AnnotationException( "Unable to find " + element.getPath() + " " + nodeName + ": " + className, e ); } ad.setValue( getJavaAttributeNameFromXMLOne( nodeName ), clazz ); } } /** * As per sections 12.2.3.23.9, 12.2.4.8.9 and 12.2.5.3.6 of the JPA 2.0 * specification, the element-collection subelement completely overrides the * mapping for the specified field or property. Thus, any methods which * might in some contexts merge with annotations must not do so in this * context. */ private void getElementCollection(List<Annotation> annotationList, XMLContext.Default defaults) { for ( Element element : elementsForProperty ) { if ( "element-collection".equals( element.getName() ) ) { AnnotationDescriptor ad = new AnnotationDescriptor( ElementCollection.class ); addTargetClass( element, ad, "target-class", defaults ); getFetchType( ad, element ); getOrderBy( annotationList, element ); getOrderColumn( annotationList, element ); getMapKey( annotationList, element ); getMapKeyClass( annotationList, element, defaults ); getMapKeyTemporal( annotationList, element ); getMapKeyEnumerated( annotationList, element ); getMapKeyColumn( annotationList, element ); buildMapKeyJoinColumns( annotationList, element ); Annotation annotation = getColumn( element.element( "column" ), false, element ); addIfNotNull( annotationList, annotation ); getTemporal( annotationList, element ); getEnumerated( annotationList, element ); getLob( annotationList, element ); //Both map-key-attribute-overrides and attribute-overrides //translate into AttributeOverride annotations, which need //need to be wrapped in the same AttributeOverrides annotation. List<AttributeOverride> attributes = new ArrayList<AttributeOverride>(); attributes.addAll( buildAttributeOverrides( element, "map-key-attribute-override" ) ); attributes.addAll( buildAttributeOverrides( element, "attribute-override" ) ); annotation = mergeAttributeOverrides( defaults, attributes, false ); addIfNotNull( annotationList, annotation ); annotation = getAssociationOverrides( element, defaults, false ); addIfNotNull( annotationList, annotation ); getCollectionTable( annotationList, element, defaults ); annotationList.add( AnnotationFactory.create( ad ) ); getAccessType( annotationList, element ); } } } private void getOrderBy(List<Annotation> annotationList, Element element) { Element subelement = element != null ? element.element( "order-by" ) : null; if ( subelement != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( OrderBy.class ); copyStringElement( subelement, ad, "value" ); annotationList.add( AnnotationFactory.create( ad ) ); } } private void getMapKey(List<Annotation> annotationList, Element element) { Element subelement = element != null ? element.element( "map-key" ) : null; if ( subelement != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( MapKey.class ); copyStringAttribute( ad, subelement, "name", false ); annotationList.add( AnnotationFactory.create( ad ) ); } } private void getMapKeyColumn(List<Annotation> annotationList, Element element) { Element subelement = element != null ? element.element( "map-key-column" ) : null; if ( subelement != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( MapKeyColumn.class ); copyStringAttribute( ad, subelement, "name", false ); copyBooleanAttribute( ad, subelement, "unique" ); copyBooleanAttribute( ad, subelement, "nullable" ); copyBooleanAttribute( ad, subelement, "insertable" ); copyBooleanAttribute( ad, subelement, "updatable" ); copyStringAttribute( ad, subelement, "column-definition", false ); copyStringAttribute( ad, subelement, "table", false ); copyIntegerAttribute( ad, subelement, "length" ); copyIntegerAttribute( ad, subelement, "precision" ); copyIntegerAttribute( ad, subelement, "scale" ); annotationList.add( AnnotationFactory.create( ad ) ); } } private void getMapKeyClass(List<Annotation> annotationList, Element element, XMLContext.Default defaults) { String nodeName = "map-key-class"; Element subelement = element != null ? element.element( nodeName ) : null; if ( subelement != null ) { String mapKeyClassName = subelement.attributeValue( "class" ); AnnotationDescriptor ad = new AnnotationDescriptor( MapKeyClass.class ); if ( StringHelper.isNotEmpty( mapKeyClassName ) ) { Class clazz; try { clazz = classLoaderAccess.classForName( XMLContext.buildSafeClassName( mapKeyClassName, defaults ) ); } catch ( ClassLoadingException e ) { throw new AnnotationException( "Unable to find " + element.getPath() + " " + nodeName + ": " + mapKeyClassName, e ); } ad.setValue( "value", clazz ); } annotationList.add( AnnotationFactory.create( ad ) ); } } private void getCollectionTable(List<Annotation> annotationList, Element element, XMLContext.Default defaults) { Element subelement = element != null ? element.element( "collection-table" ) : null; if ( subelement != null ) { AnnotationDescriptor annotation = new AnnotationDescriptor( CollectionTable.class ); copyStringAttribute( annotation, subelement, "name", false ); copyStringAttribute( annotation, subelement, "catalog", false ); if ( StringHelper.isNotEmpty( defaults.getCatalog() ) && StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) ) ) { annotation.setValue( "catalog", defaults.getCatalog() ); } copyStringAttribute( annotation, subelement, "schema", false ); if ( StringHelper.isNotEmpty( defaults.getSchema() ) && StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) ) ) { annotation.setValue( "schema", defaults.getSchema() ); } JoinColumn[] joinColumns = getJoinColumns( subelement, false ); if ( joinColumns.length > 0 ) { annotation.setValue( "joinColumns", joinColumns ); } buildUniqueConstraints( annotation, subelement ); buildIndex( annotation, subelement ); annotationList.add( AnnotationFactory.create( annotation ) ); } } private void buildJoinColumns(List<Annotation> annotationList, Element element) { JoinColumn[] joinColumns = getJoinColumns( element, false ); if ( joinColumns.length > 0 ) { AnnotationDescriptor ad = new AnnotationDescriptor( JoinColumns.class ); ad.setValue( "value", joinColumns ); annotationList.add( AnnotationFactory.create( ad ) ); } } private void getCascades(AnnotationDescriptor ad, Element element, XMLContext.Default defaults) { List<Element> elements = element != null ? element.elements( "cascade" ) : new ArrayList<Element>( 0 ); List<CascadeType> cascades = new ArrayList<CascadeType>(); for ( Element subelement : elements ) { if ( subelement.element( "cascade-all" ) != null ) { cascades.add( CascadeType.ALL ); } if ( subelement.element( "cascade-persist" ) != null ) { cascades.add( CascadeType.PERSIST ); } if ( subelement.element( "cascade-merge" ) != null ) { cascades.add( CascadeType.MERGE ); } if ( subelement.element( "cascade-remove" ) != null ) { cascades.add( CascadeType.REMOVE ); } if ( subelement.element( "cascade-refresh" ) != null ) { cascades.add( CascadeType.REFRESH ); } if ( subelement.element( "cascade-detach" ) != null ) { cascades.add( CascadeType.DETACH ); } } if ( Boolean.TRUE.equals( defaults.getCascadePersist() ) && !cascades.contains( CascadeType.ALL ) && !cascades.contains( CascadeType.PERSIST ) ) { cascades.add( CascadeType.PERSIST ); } if ( cascades.size() > 0 ) { ad.setValue( "cascade", cascades.toArray( new CascadeType[cascades.size()] ) ); } } private void getEmbedded(List<Annotation> annotationList, XMLContext.Default defaults) { for ( Element element : elementsForProperty ) { if ( "embedded".equals( element.getName() ) ) { AnnotationDescriptor ad = new AnnotationDescriptor( Embedded.class ); annotationList.add( AnnotationFactory.create( ad ) ); Annotation annotation = getAttributeOverrides( element, defaults, false ); addIfNotNull( annotationList, annotation ); annotation = getAssociationOverrides( element, defaults, false ); addIfNotNull( annotationList, annotation ); getAccessType( annotationList, element ); } } if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) { Annotation annotation = getPhysicalAnnotation( Embedded.class ); if ( annotation != null ) { annotationList.add( annotation ); annotation = getPhysicalAnnotation( AttributeOverride.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AttributeOverrides.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AssociationOverride.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AssociationOverrides.class ); addIfNotNull( annotationList, annotation ); } } } private Transient getTransient(XMLContext.Default defaults) { for ( Element element : elementsForProperty ) { if ( "transient".equals( element.getName() ) ) { AnnotationDescriptor ad = new AnnotationDescriptor( Transient.class ); return AnnotationFactory.create( ad ); } } if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) { return getPhysicalAnnotation( Transient.class ); } else { return null; } } private void getVersion(List<Annotation> annotationList, XMLContext.Default defaults) { for ( Element element : elementsForProperty ) { if ( "version".equals( element.getName() ) ) { Annotation annotation = buildColumns( element ); addIfNotNull( annotationList, annotation ); getTemporal( annotationList, element ); AnnotationDescriptor basic = new AnnotationDescriptor( Version.class ); annotationList.add( AnnotationFactory.create( basic ) ); getAccessType( annotationList, element ); } } if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) { //we have nothing, so Java annotations might occurs Annotation annotation = getPhysicalAnnotation( Version.class ); if ( annotation != null ) { annotationList.add( annotation ); annotation = getPhysicalAnnotation( Column.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Columns.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Temporal.class ); addIfNotNull( annotationList, annotation ); } } } private void getBasic(List<Annotation> annotationList, XMLContext.Default defaults) { for ( Element element : elementsForProperty ) { if ( "basic".equals( element.getName() ) ) { Annotation annotation = buildColumns( element ); addIfNotNull( annotationList, annotation ); getAccessType( annotationList, element ); getTemporal( annotationList, element ); getLob( annotationList, element ); getEnumerated( annotationList, element ); AnnotationDescriptor basic = new AnnotationDescriptor( Basic.class ); getFetchType( basic, element ); copyBooleanAttribute( basic, element, "optional" ); annotationList.add( AnnotationFactory.create( basic ) ); } } if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) { //no annotation presence constraint, basic is the default Annotation annotation = getPhysicalAnnotation( Basic.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Lob.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Enumerated.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Temporal.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Column.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Columns.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AttributeOverride.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AttributeOverrides.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AssociationOverride.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AssociationOverrides.class ); addIfNotNull( annotationList, annotation ); } } private void getEnumerated(List<Annotation> annotationList, Element element) { Element subElement = element != null ? element.element( "enumerated" ) : null; if ( subElement != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( Enumerated.class ); String enumerated = subElement.getTextTrim(); if ( "ORDINAL".equalsIgnoreCase( enumerated ) ) { ad.setValue( "value", EnumType.ORDINAL ); } else if ( "STRING".equalsIgnoreCase( enumerated ) ) { ad.setValue( "value", EnumType.STRING ); } else if ( StringHelper.isNotEmpty( enumerated ) ) { throw new AnnotationException( "Unknown EnumType: " + enumerated + ". " + SCHEMA_VALIDATION ); } annotationList.add( AnnotationFactory.create( ad ) ); } } private void getLob(List<Annotation> annotationList, Element element) { Element subElement = element != null ? element.element( "lob" ) : null; if ( subElement != null ) { annotationList.add( AnnotationFactory.create( new AnnotationDescriptor( Lob.class ) ) ); } } private void getFetchType(AnnotationDescriptor descriptor, Element element) { String fetchString = element != null ? element.attributeValue( "fetch" ) : null; if ( fetchString != null ) { if ( "eager".equalsIgnoreCase( fetchString ) ) { descriptor.setValue( "fetch", FetchType.EAGER ); } else if ( "lazy".equalsIgnoreCase( fetchString ) ) { descriptor.setValue( "fetch", FetchType.LAZY ); } } } private void getEmbeddedId(List<Annotation> annotationList, XMLContext.Default defaults) { for ( Element element : elementsForProperty ) { if ( "embedded-id".equals( element.getName() ) ) { if ( isProcessingId( defaults ) ) { Annotation annotation = getAttributeOverrides( element, defaults, false ); addIfNotNull( annotationList, annotation ); annotation = getAssociationOverrides( element, defaults, false ); addIfNotNull( annotationList, annotation ); AnnotationDescriptor ad = new AnnotationDescriptor( EmbeddedId.class ); annotationList.add( AnnotationFactory.create( ad ) ); getAccessType( annotationList, element ); } } } if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) { Annotation annotation = getPhysicalAnnotation( EmbeddedId.class ); if ( annotation != null ) { annotationList.add( annotation ); annotation = getPhysicalAnnotation( Column.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Columns.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( GeneratedValue.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Temporal.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( TableGenerator.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( SequenceGenerator.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AttributeOverride.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AttributeOverrides.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AssociationOverride.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AssociationOverrides.class ); addIfNotNull( annotationList, annotation ); } } } private void preCalculateElementsForProperty(Element tree) { elementsForProperty = new ArrayList<Element>(); Element element = tree != null ? tree.element( "attributes" ) : null; //put entity.attributes elements if ( element != null ) { for ( Element subelement : (List<Element>) element.elements() ) { if ( propertyName.equals( subelement.attributeValue( "name" ) ) ) { elementsForProperty.add( subelement ); } } } //add pre-* etc from entity and pure entity listener classes if ( tree != null ) { for ( Element subelement : (List<Element>) tree.elements() ) { if ( propertyName.equals( subelement.attributeValue( "method-name" ) ) ) { elementsForProperty.add( subelement ); } } } } private void getId(List<Annotation> annotationList, XMLContext.Default defaults) { for ( Element element : elementsForProperty ) { if ( "id".equals( element.getName() ) ) { boolean processId = isProcessingId( defaults ); if ( processId ) { Annotation annotation = buildColumns( element ); addIfNotNull( annotationList, annotation ); annotation = buildGeneratedValue( element ); addIfNotNull( annotationList, annotation ); getTemporal( annotationList, element ); //FIXME: fix the priority of xml over java for generator names annotation = getTableGenerator( element, defaults ); addIfNotNull( annotationList, annotation ); annotation = getSequenceGenerator( element, defaults ); addIfNotNull( annotationList, annotation ); AnnotationDescriptor id = new AnnotationDescriptor( Id.class ); annotationList.add( AnnotationFactory.create( id ) ); getAccessType( annotationList, element ); } } } if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) { Annotation annotation = getPhysicalAnnotation( Id.class ); if ( annotation != null ) { annotationList.add( annotation ); annotation = getPhysicalAnnotation( Column.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Columns.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( GeneratedValue.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( Temporal.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( TableGenerator.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( SequenceGenerator.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AttributeOverride.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AttributeOverrides.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AssociationOverride.class ); addIfNotNull( annotationList, annotation ); annotation = getPhysicalAnnotation( AssociationOverrides.class ); addIfNotNull( annotationList, annotation ); } } } private boolean isProcessingId(XMLContext.Default defaults) { boolean isExplicit = defaults.getAccess() != null; boolean correctAccess = ( PropertyType.PROPERTY.equals( propertyType ) && AccessType.PROPERTY.equals( defaults.getAccess() ) ) || ( PropertyType.FIELD.equals( propertyType ) && AccessType.FIELD .equals( defaults.getAccess() ) ); boolean hasId = defaults.canUseJavaAnnotations() && ( isPhysicalAnnotationPresent( Id.class ) || isPhysicalAnnotationPresent( EmbeddedId.class ) ); //if ( properAccessOnMetadataComplete || properOverridingOnMetadataNonComplete ) { boolean mirrorAttributeIsId = defaults.canUseJavaAnnotations() && ( mirroredAttribute != null && ( mirroredAttribute.isAnnotationPresent( Id.class ) || mirroredAttribute.isAnnotationPresent( EmbeddedId.class ) ) ); boolean propertyIsDefault = PropertyType.PROPERTY.equals( propertyType ) && !mirrorAttributeIsId; return correctAccess || ( !isExplicit && hasId ) || ( !isExplicit && propertyIsDefault ); } private Columns buildColumns(Element element) { List<Element> subelements = element.elements( "column" ); List<Column> columns = new ArrayList<Column>( subelements.size() ); for ( Element subelement : subelements ) { columns.add( getColumn( subelement, false, element ) ); } if ( columns.size() > 0 ) { AnnotationDescriptor columnsDescr = new AnnotationDescriptor( Columns.class ); columnsDescr.setValue( "columns", columns.toArray( new Column[columns.size()] ) ); return AnnotationFactory.create( columnsDescr ); } else { return null; } } private GeneratedValue buildGeneratedValue(Element element) { Element subElement = element != null ? element.element( "generated-value" ) : null; if ( subElement != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( GeneratedValue.class ); String strategy = subElement.attributeValue( "strategy" ); if ( "TABLE".equalsIgnoreCase( strategy ) ) { ad.setValue( "strategy", GenerationType.TABLE ); } else if ( "SEQUENCE".equalsIgnoreCase( strategy ) ) { ad.setValue( "strategy", GenerationType.SEQUENCE ); } else if ( "IDENTITY".equalsIgnoreCase( strategy ) ) { ad.setValue( "strategy", GenerationType.IDENTITY ); } else if ( "AUTO".equalsIgnoreCase( strategy ) ) { ad.setValue( "strategy", GenerationType.AUTO ); } else if ( StringHelper.isNotEmpty( strategy ) ) { throw new AnnotationException( "Unknown GenerationType: " + strategy + ". " + SCHEMA_VALIDATION ); } copyStringAttribute( ad, subElement, "generator", false ); return AnnotationFactory.create( ad ); } else { return null; } } private void getTemporal(List<Annotation> annotationList, Element element) { Element subElement = element != null ? element.element( "temporal" ) : null; if ( subElement != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( Temporal.class ); String temporal = subElement.getTextTrim(); if ( "DATE".equalsIgnoreCase( temporal ) ) { ad.setValue( "value", TemporalType.DATE ); } else if ( "TIME".equalsIgnoreCase( temporal ) ) { ad.setValue( "value", TemporalType.TIME ); } else if ( "TIMESTAMP".equalsIgnoreCase( temporal ) ) { ad.setValue( "value", TemporalType.TIMESTAMP ); } else if ( StringHelper.isNotEmpty( temporal ) ) { throw new AnnotationException( "Unknown TemporalType: " + temporal + ". " + SCHEMA_VALIDATION ); } annotationList.add( AnnotationFactory.create( ad ) ); } } private void getAccessType(List<Annotation> annotationList, Element element) { if ( element == null ) { return; } String access = element.attributeValue( "access" ); if ( access != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( Access.class ); AccessType type; try { type = AccessType.valueOf( access ); } catch ( IllegalArgumentException e ) { throw new AnnotationException( access + " is not a valid access type. Check you xml confguration." ); } if ( ( AccessType.PROPERTY.equals( type ) && this.element instanceof Method ) || ( AccessType.FIELD.equals( type ) && this.element instanceof Field ) ) { return; } ad.setValue( "value", type ); annotationList.add( AnnotationFactory.create( ad ) ); } } /** * @param mergeWithAnnotations Whether to use Java annotations for this * element, if present and not disabled by the XMLContext defaults. * In some contexts (such as an element-collection mapping) merging * with annotations is never allowed. */ private AssociationOverrides getAssociationOverrides(Element tree, XMLContext.Default defaults, boolean mergeWithAnnotations) { List<AssociationOverride> attributes = buildAssociationOverrides( tree, defaults ); if ( mergeWithAnnotations && defaults.canUseJavaAnnotations() ) { AssociationOverride annotation = getPhysicalAnnotation( AssociationOverride.class ); addAssociationOverrideIfNeeded( annotation, attributes ); AssociationOverrides annotations = getPhysicalAnnotation( AssociationOverrides.class ); if ( annotations != null ) { for ( AssociationOverride current : annotations.value() ) { addAssociationOverrideIfNeeded( current, attributes ); } } } if ( attributes.size() > 0 ) { AnnotationDescriptor ad = new AnnotationDescriptor( AssociationOverrides.class ); ad.setValue( "value", attributes.toArray( new AssociationOverride[attributes.size()] ) ); return AnnotationFactory.create( ad ); } else { return null; } } private List<AssociationOverride> buildAssociationOverrides(Element element, XMLContext.Default defaults) { List<Element> subelements = element == null ? null : element.elements( "association-override" ); List<AssociationOverride> overrides = new ArrayList<AssociationOverride>(); if ( subelements != null && subelements.size() > 0 ) { for ( Element current : subelements ) { AnnotationDescriptor override = new AnnotationDescriptor( AssociationOverride.class ); copyStringAttribute( override, current, "name", true ); override.setValue( "joinColumns", getJoinColumns( current, false ) ); JoinTable joinTable = buildJoinTable( current, defaults ); if ( joinTable != null ) { override.setValue( "joinTable", joinTable ); } overrides.add( (AssociationOverride) AnnotationFactory.create( override ) ); } } return overrides; } private JoinColumn[] getJoinColumns(Element element, boolean isInverse) { List<Element> subelements = element != null ? element.elements( isInverse ? "inverse-join-column" : "join-column" ) : null; List<JoinColumn> joinColumns = new ArrayList<JoinColumn>(); if ( subelements != null ) { for ( Element subelement : subelements ) { AnnotationDescriptor column = new AnnotationDescriptor( JoinColumn.class ); copyStringAttribute( column, subelement, "name", false ); copyStringAttribute( column, subelement, "referenced-column-name", false ); copyBooleanAttribute( column, subelement, "unique" ); copyBooleanAttribute( column, subelement, "nullable" ); copyBooleanAttribute( column, subelement, "insertable" ); copyBooleanAttribute( column, subelement, "updatable" ); copyStringAttribute( column, subelement, "column-definition", false ); copyStringAttribute( column, subelement, "table", false ); joinColumns.add( (JoinColumn) AnnotationFactory.create( column ) ); } } return joinColumns.toArray( new JoinColumn[joinColumns.size()] ); } private void addAssociationOverrideIfNeeded(AssociationOverride annotation, List<AssociationOverride> overrides) { if ( annotation != null ) { String overrideName = annotation.name(); boolean present = false; for ( AssociationOverride current : overrides ) { if ( current.name().equals( overrideName ) ) { present = true; break; } } if ( !present ) { overrides.add( annotation ); } } } /** * @param mergeWithAnnotations Whether to use Java annotations for this * element, if present and not disabled by the XMLContext defaults. * In some contexts (such as an association mapping) merging with * annotations is never allowed. */ private AttributeOverrides getAttributeOverrides(Element tree, XMLContext.Default defaults, boolean mergeWithAnnotations) { List<AttributeOverride> attributes = buildAttributeOverrides( tree, "attribute-override" ); return mergeAttributeOverrides( defaults, attributes, mergeWithAnnotations ); } /** * @param mergeWithAnnotations Whether to use Java annotations for this * element, if present and not disabled by the XMLContext defaults. * In some contexts (such as an association mapping) merging with * annotations is never allowed. */ private AttributeOverrides mergeAttributeOverrides(XMLContext.Default defaults, List<AttributeOverride> attributes, boolean mergeWithAnnotations) { if ( mergeWithAnnotations && defaults.canUseJavaAnnotations() ) { AttributeOverride annotation = getPhysicalAnnotation( AttributeOverride.class ); addAttributeOverrideIfNeeded( annotation, attributes ); AttributeOverrides annotations = getPhysicalAnnotation( AttributeOverrides.class ); if ( annotations != null ) { for ( AttributeOverride current : annotations.value() ) { addAttributeOverrideIfNeeded( current, attributes ); } } } if ( attributes.size() > 0 ) { AnnotationDescriptor ad = new AnnotationDescriptor( AttributeOverrides.class ); ad.setValue( "value", attributes.toArray( new AttributeOverride[attributes.size()] ) ); return AnnotationFactory.create( ad ); } else { return null; } } private List<AttributeOverride> buildAttributeOverrides(Element element, String nodeName) { List<Element> subelements = element == null ? null : element.elements( nodeName ); return buildAttributeOverrides( subelements, nodeName ); } private List<AttributeOverride> buildAttributeOverrides(List<Element> subelements, String nodeName) { List<AttributeOverride> overrides = new ArrayList<AttributeOverride>(); if ( subelements != null && subelements.size() > 0 ) { for ( Element current : subelements ) { if ( !current.getName().equals( nodeName ) ) { continue; } AnnotationDescriptor override = new AnnotationDescriptor( AttributeOverride.class ); copyStringAttribute( override, current, "name", true ); Element column = current.element( "column" ); override.setValue( "column", getColumn( column, true, current ) ); overrides.add( (AttributeOverride) AnnotationFactory.create( override ) ); } } return overrides; } private Column getColumn(Element element, boolean isMandatory, Element current) { //Element subelement = element != null ? element.element( "column" ) : null; if ( element != null ) { AnnotationDescriptor column = new AnnotationDescriptor( Column.class ); copyStringAttribute( column, element, "name", false ); copyBooleanAttribute( column, element, "unique" ); copyBooleanAttribute( column, element, "nullable" ); copyBooleanAttribute( column, element, "insertable" ); copyBooleanAttribute( column, element, "updatable" ); copyStringAttribute( column, element, "column-definition", false ); copyStringAttribute( column, element, "table", false ); copyIntegerAttribute( column, element, "length" ); copyIntegerAttribute( column, element, "precision" ); copyIntegerAttribute( column, element, "scale" ); return (Column) AnnotationFactory.create( column ); } else { if ( isMandatory ) { throw new AnnotationException( current.getPath() + ".column is mandatory. " + SCHEMA_VALIDATION ); } return null; } } private void addAttributeOverrideIfNeeded(AttributeOverride annotation, List<AttributeOverride> overrides) { if ( annotation != null ) { String overrideName = annotation.name(); boolean present = false; for ( AttributeOverride current : overrides ) { if ( current.name().equals( overrideName ) ) { present = true; break; } } if ( !present ) { overrides.add( annotation ); } } } private Access getAccessType(Element tree, XMLContext.Default defaults) { String access = tree == null ? null : tree.attributeValue( "access" ); if ( access != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( Access.class ); AccessType type; try { type = AccessType.valueOf( access ); } catch ( IllegalArgumentException e ) { throw new AnnotationException( access + " is not a valid access type. Check you xml confguration." ); } ad.setValue( "value", type ); return AnnotationFactory.create( ad ); } else if ( defaults.canUseJavaAnnotations() && isPhysicalAnnotationPresent( Access.class ) ) { return getPhysicalAnnotation( Access.class ); } else if ( defaults.getAccess() != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( Access.class ); ad.setValue( "value", defaults.getAccess() ); return AnnotationFactory.create( ad ); } else { return null; } } private ExcludeSuperclassListeners getExcludeSuperclassListeners(Element tree, XMLContext.Default defaults) { return (ExcludeSuperclassListeners) getMarkerAnnotation( ExcludeSuperclassListeners.class, tree, defaults ); } private ExcludeDefaultListeners getExcludeDefaultListeners(Element tree, XMLContext.Default defaults) { return (ExcludeDefaultListeners) getMarkerAnnotation( ExcludeDefaultListeners.class, tree, defaults ); } private Annotation getMarkerAnnotation( Class<? extends Annotation> clazz, Element element, XMLContext.Default defaults ) { Element subelement = element == null ? null : element.element( annotationToXml.get( clazz ) ); if ( subelement != null ) { return AnnotationFactory.create( new AnnotationDescriptor( clazz ) ); } else if ( defaults.canUseJavaAnnotations() ) { //TODO wonder whether it should be excluded so that user can undone it return getPhysicalAnnotation( clazz ); } else { return null; } } private SqlResultSetMappings getSqlResultSetMappings(Element tree, XMLContext.Default defaults) { List<SqlResultSetMapping> results = buildSqlResultsetMappings( tree, defaults, classLoaderAccess ); if ( defaults.canUseJavaAnnotations() ) { SqlResultSetMapping annotation = getPhysicalAnnotation( SqlResultSetMapping.class ); addSqlResultsetMappingIfNeeded( annotation, results ); SqlResultSetMappings annotations = getPhysicalAnnotation( SqlResultSetMappings.class ); if ( annotations != null ) { for ( SqlResultSetMapping current : annotations.value() ) { addSqlResultsetMappingIfNeeded( current, results ); } } } if ( results.size() > 0 ) { AnnotationDescriptor ad = new AnnotationDescriptor( SqlResultSetMappings.class ); ad.setValue( "value", results.toArray( new SqlResultSetMapping[results.size()] ) ); return AnnotationFactory.create( ad ); } else { return null; } } public static List<NamedEntityGraph> buildNamedEntityGraph( Element element, XMLContext.Default defaults, ClassLoaderAccess classLoaderAccess) { if ( element == null ) { return new ArrayList<NamedEntityGraph>(); } List<NamedEntityGraph> namedEntityGraphList = new ArrayList<NamedEntityGraph>(); List<Element> namedEntityGraphElements = element.elements( "named-entity-graph" ); for ( Element subElement : namedEntityGraphElements ) { AnnotationDescriptor ann = new AnnotationDescriptor( NamedEntityGraph.class ); copyStringAttribute( ann, subElement, "name", false ); copyBooleanAttribute( ann, subElement, "include-all-attributes" ); bindNamedAttributeNodes( subElement, ann ); List<Element> subgraphNodes = subElement.elements( "subgraph" ); bindNamedSubgraph( defaults, ann, subgraphNodes, classLoaderAccess ); List<Element> subclassSubgraphNodes = subElement.elements( "subclass-subgraph" ); bindNamedSubgraph( defaults, ann, subclassSubgraphNodes, classLoaderAccess ); namedEntityGraphList.add( (NamedEntityGraph) AnnotationFactory.create( ann ) ); } //TODO return namedEntityGraphList; } private static void bindNamedSubgraph( XMLContext.Default defaults, AnnotationDescriptor ann, List<Element> subgraphNodes, ClassLoaderAccess classLoaderAccess) { List<NamedSubgraph> annSubgraphNodes = new ArrayList<NamedSubgraph>( ); for(Element subgraphNode : subgraphNodes){ AnnotationDescriptor annSubgraphNode = new AnnotationDescriptor( NamedSubgraph.class ); copyStringAttribute( annSubgraphNode, subgraphNode, "name", true ); String clazzName = subgraphNode.attributeValue( "class" ); Class clazz; try { clazz = classLoaderAccess.classForName( XMLContext.buildSafeClassName( clazzName, defaults ) ); } catch ( ClassLoadingException e ) { throw new AnnotationException( "Unable to find entity-class: " + clazzName, e ); } annSubgraphNode.setValue( "type", clazz ); bindNamedAttributeNodes(subgraphNode, annSubgraphNode); annSubgraphNodes.add( (NamedSubgraph) AnnotationFactory.create( annSubgraphNode ) ); } ann.setValue( "subgraphs", annSubgraphNodes.toArray( new NamedSubgraph[annSubgraphNodes.size()] ) ); } private static void bindNamedAttributeNodes(Element subElement, AnnotationDescriptor ann) { List<Element> namedAttributeNodes = subElement.elements("named-attribute-node"); List<NamedAttributeNode> annNamedAttributeNodes = new ArrayList<NamedAttributeNode>( ); for(Element namedAttributeNode : namedAttributeNodes){ AnnotationDescriptor annNamedAttributeNode = new AnnotationDescriptor( NamedAttributeNode.class ); copyStringAttribute( annNamedAttributeNode, namedAttributeNode, "value", "name", true ); copyStringAttribute( annNamedAttributeNode, namedAttributeNode, "subgraph", false ); copyStringAttribute( annNamedAttributeNode, namedAttributeNode, "key-subgraph", false ); annNamedAttributeNodes.add( (NamedAttributeNode) AnnotationFactory.create( annNamedAttributeNode ) ); } ann.setValue( "attributeNodes", annNamedAttributeNodes.toArray( new NamedAttributeNode[annNamedAttributeNodes.size()] ) ); } public static List<NamedStoredProcedureQuery> buildNamedStoreProcedureQueries( Element element, XMLContext.Default defaults, ClassLoaderAccess classLoaderAccess) { if ( element == null ) { return new ArrayList<NamedStoredProcedureQuery>(); } List namedStoredProcedureElements = element.elements( "named-stored-procedure-query" ); List<NamedStoredProcedureQuery> namedStoredProcedureQueries = new ArrayList<NamedStoredProcedureQuery>(); for ( Object obj : namedStoredProcedureElements ) { Element subElement = (Element) obj; AnnotationDescriptor ann = new AnnotationDescriptor( NamedStoredProcedureQuery.class ); copyStringAttribute( ann, subElement, "name", true ); copyStringAttribute( ann, subElement, "procedure-name", true ); List<Element> elements = subElement.elements( "parameter" ); List<StoredProcedureParameter> storedProcedureParameters = new ArrayList<StoredProcedureParameter>(); for ( Element parameterElement : elements ) { AnnotationDescriptor parameterDescriptor = new AnnotationDescriptor( StoredProcedureParameter.class ); copyStringAttribute( parameterDescriptor, parameterElement, "name", false ); String modeValue = parameterElement.attributeValue( "mode" ); if ( modeValue == null ) { parameterDescriptor.setValue( "mode", ParameterMode.IN ); } else { parameterDescriptor.setValue( "mode", ParameterMode.valueOf( modeValue.toUpperCase(Locale.ROOT) ) ); } String clazzName = parameterElement.attributeValue( "class" ); Class clazz; try { clazz = classLoaderAccess.classForName( XMLContext.buildSafeClassName( clazzName, defaults ) ); } catch ( ClassLoadingException e ) { throw new AnnotationException( "Unable to find entity-class: " + clazzName, e ); } parameterDescriptor.setValue( "type", clazz ); storedProcedureParameters.add( (StoredProcedureParameter) AnnotationFactory.create( parameterDescriptor ) ); } ann.setValue( "parameters", storedProcedureParameters.toArray( new StoredProcedureParameter[storedProcedureParameters.size()] ) ); elements = subElement.elements( "result-class" ); List<Class> returnClasses = new ArrayList<Class>(); for ( Element classElement : elements ) { String clazzName = classElement.getTextTrim(); Class clazz; try { clazz = classLoaderAccess.classForName( XMLContext.buildSafeClassName( clazzName, defaults ) ); } catch ( ClassLoadingException e ) { throw new AnnotationException( "Unable to find entity-class: " + clazzName, e ); } returnClasses.add( clazz ); } ann.setValue( "resultClasses", returnClasses.toArray( new Class[returnClasses.size()] ) ); elements = subElement.elements( "result-set-mapping" ); List<String> resultSetMappings = new ArrayList<String>(); for ( Element resultSetMappingElement : elements ) { resultSetMappings.add( resultSetMappingElement.getTextTrim() ); } ann.setValue( "resultSetMappings", resultSetMappings.toArray( new String[resultSetMappings.size()] ) ); elements = subElement.elements( "hint" ); buildQueryHints( elements, ann ); namedStoredProcedureQueries.add( (NamedStoredProcedureQuery) AnnotationFactory.create( ann ) ); } return namedStoredProcedureQueries; } public static List<SqlResultSetMapping> buildSqlResultsetMappings( Element element, XMLContext.Default defaults, ClassLoaderAccess classLoaderAccess) { final List<SqlResultSetMapping> builtResultSetMappings = new ArrayList<SqlResultSetMapping>(); if ( element == null ) { return builtResultSetMappings; } // iterate over each <sql-result-set-mapping/> element for ( Object resultSetMappingElementObject : element.elements( "sql-result-set-mapping" ) ) { final Element resultSetMappingElement = (Element) resultSetMappingElementObject; final AnnotationDescriptor resultSetMappingAnnotation = new AnnotationDescriptor( SqlResultSetMapping.class ); copyStringAttribute( resultSetMappingAnnotation, resultSetMappingElement, "name", true ); // iterate over the <sql-result-set-mapping/> sub-elements, which should include: // * <entity-result/> // * <column-result/> // * <constructor-result/> List<EntityResult> entityResultAnnotations = null; List<ColumnResult> columnResultAnnotations = null; List<ConstructorResult> constructorResultAnnotations = null; for ( Object resultElementObject : resultSetMappingElement.elements() ) { final Element resultElement = (Element) resultElementObject; if ( "entity-result".equals( resultElement.getName() ) ) { if ( entityResultAnnotations == null ) { entityResultAnnotations = new ArrayList<EntityResult>(); } // process the <entity-result/> entityResultAnnotations.add( buildEntityResult( resultElement, defaults, classLoaderAccess ) ); } else if ( "column-result".equals( resultElement.getName() ) ) { if ( columnResultAnnotations == null ) { columnResultAnnotations = new ArrayList<ColumnResult>(); } columnResultAnnotations.add( buildColumnResult( resultElement, defaults, classLoaderAccess ) ); } else if ( "constructor-result".equals( resultElement.getName() ) ) { if ( constructorResultAnnotations == null ) { constructorResultAnnotations = new ArrayList<ConstructorResult>(); } constructorResultAnnotations.add( buildConstructorResult( resultElement, defaults, classLoaderAccess ) ); } else { // most likely the <result-class/> this code used to handle. I have left the code here, // but commented it out for now. I'll just log a warning for now. LOG.debug( "Encountered unrecognized sql-result-set-mapping sub-element : " + resultElement.getName() ); // String clazzName = subelement.attributeValue( "result-class" ); // if ( StringHelper.isNotEmpty( clazzName ) ) { // Class clazz; // try { // clazz = ReflectHelper.classForName( // XMLContext.buildSafeClassName( clazzName, defaults ), // JPAOverriddenAnnotationReader.class // ); // } // catch ( ClassNotFoundException e ) { // throw new AnnotationException( "Unable to find entity-class: " + clazzName, e ); // } // ann.setValue( "resultClass", clazz ); // } } } if ( entityResultAnnotations != null && !entityResultAnnotations.isEmpty() ) { resultSetMappingAnnotation.setValue( "entities", entityResultAnnotations.toArray( new EntityResult[entityResultAnnotations.size()] ) ); } if ( columnResultAnnotations != null && !columnResultAnnotations.isEmpty() ) { resultSetMappingAnnotation.setValue( "columns", columnResultAnnotations.toArray( new ColumnResult[columnResultAnnotations.size()] ) ); } if ( constructorResultAnnotations != null && !constructorResultAnnotations.isEmpty() ) { resultSetMappingAnnotation.setValue( "classes", constructorResultAnnotations.toArray( new ConstructorResult[constructorResultAnnotations.size()] ) ); } // this was part of the old code too, but could never figure out what it is supposed to do... // copyStringAttribute( ann, subelement, "result-set-mapping", false ); builtResultSetMappings.add( (SqlResultSetMapping) AnnotationFactory.create( resultSetMappingAnnotation ) ); } return builtResultSetMappings; } private static EntityResult buildEntityResult( Element entityResultElement, XMLContext.Default defaults, ClassLoaderAccess classLoaderAccess) { final AnnotationDescriptor entityResultDescriptor = new AnnotationDescriptor( EntityResult.class ); final Class entityClass = resolveClassReference( entityResultElement.attributeValue( "entity-class" ), defaults, classLoaderAccess ); entityResultDescriptor.setValue( "entityClass", entityClass ); copyStringAttribute( entityResultDescriptor, entityResultElement, "discriminator-column", false ); // process the <field-result/> sub-elements List<FieldResult> fieldResultAnnotations = new ArrayList<FieldResult>(); for ( Element fieldResult : (List<Element>) entityResultElement.elements( "field-result" ) ) { AnnotationDescriptor fieldResultDescriptor = new AnnotationDescriptor( FieldResult.class ); copyStringAttribute( fieldResultDescriptor, fieldResult, "name", true ); copyStringAttribute( fieldResultDescriptor, fieldResult, "column", true ); fieldResultAnnotations.add( (FieldResult) AnnotationFactory.create( fieldResultDescriptor ) ); } entityResultDescriptor.setValue( "fields", fieldResultAnnotations.toArray( new FieldResult[fieldResultAnnotations.size()] ) ); return AnnotationFactory.create( entityResultDescriptor ); } private static Class resolveClassReference( String className, XMLContext.Default defaults, ClassLoaderAccess classLoaderAccess) { if ( className == null ) { throw new AnnotationException( "<entity-result> without entity-class. " + SCHEMA_VALIDATION ); } try { return classLoaderAccess.classForName( XMLContext.buildSafeClassName( className, defaults ) ); } catch ( ClassLoadingException e ) { throw new AnnotationException( "Unable to find specified class: " + className, e ); } } private static ColumnResult buildColumnResult( Element columnResultElement, XMLContext.Default defaults, ClassLoaderAccess classLoaderAccess) { // AnnotationDescriptor columnResultDescriptor = new AnnotationDescriptor( ColumnResult.class ); // copyStringAttribute( columnResultDescriptor, columnResultElement, "name", true ); // return AnnotationFactory.create( columnResultDescriptor ); AnnotationDescriptor columnResultDescriptor = new AnnotationDescriptor( ColumnResult.class ); copyStringAttribute( columnResultDescriptor, columnResultElement, "name", true ); final String columnTypeName = columnResultElement.attributeValue( "class" ); if ( StringHelper.isNotEmpty( columnTypeName ) ) { columnResultDescriptor.setValue( "type", resolveClassReference( columnTypeName, defaults, classLoaderAccess ) ); } return AnnotationFactory.create( columnResultDescriptor ); } private static ConstructorResult buildConstructorResult( Element constructorResultElement, XMLContext.Default defaults, ClassLoaderAccess classLoaderAccess) { AnnotationDescriptor constructorResultDescriptor = new AnnotationDescriptor( ConstructorResult.class ); final Class entityClass = resolveClassReference( constructorResultElement.attributeValue( "target-class" ), defaults, classLoaderAccess ); constructorResultDescriptor.setValue( "targetClass", entityClass ); List<ColumnResult> columnResultAnnotations = new ArrayList<ColumnResult>(); for ( Element columnResultElement : (List<Element>) constructorResultElement.elements( "column" ) ) { columnResultAnnotations.add( buildColumnResult( columnResultElement, defaults, classLoaderAccess ) ); } constructorResultDescriptor.setValue( "columns", columnResultAnnotations.toArray( new ColumnResult[ columnResultAnnotations.size() ] ) ); return AnnotationFactory.create( constructorResultDescriptor ); } private void addSqlResultsetMappingIfNeeded(SqlResultSetMapping annotation, List<SqlResultSetMapping> resultsets) { if ( annotation != null ) { String resultsetName = annotation.name(); boolean present = false; for ( SqlResultSetMapping current : resultsets ) { if ( current.name().equals( resultsetName ) ) { present = true; break; } } if ( !present ) { resultsets.add( annotation ); } } } private NamedQueries getNamedQueries(Element tree, XMLContext.Default defaults) { //TODO avoid the Proxy Creation (@NamedQueries) when possible List<NamedQuery> queries = (List<NamedQuery>) buildNamedQueries( tree, false, defaults, classLoaderAccess ); if ( defaults.canUseJavaAnnotations() ) { NamedQuery annotation = getPhysicalAnnotation( NamedQuery.class ); addNamedQueryIfNeeded( annotation, queries ); NamedQueries annotations = getPhysicalAnnotation( NamedQueries.class ); if ( annotations != null ) { for ( NamedQuery current : annotations.value() ) { addNamedQueryIfNeeded( current, queries ); } } } if ( queries.size() > 0 ) { AnnotationDescriptor ad = new AnnotationDescriptor( NamedQueries.class ); ad.setValue( "value", queries.toArray( new NamedQuery[queries.size()] ) ); return AnnotationFactory.create( ad ); } else { return null; } } private void addNamedQueryIfNeeded(NamedQuery annotation, List<NamedQuery> queries) { if ( annotation != null ) { String queryName = annotation.name(); boolean present = false; for ( NamedQuery current : queries ) { if ( current.name().equals( queryName ) ) { present = true; break; } } if ( !present ) { queries.add( annotation ); } } } private NamedEntityGraphs getNamedEntityGraphs(Element tree, XMLContext.Default defaults) { List<NamedEntityGraph> queries = buildNamedEntityGraph( tree, defaults, classLoaderAccess ); if ( defaults.canUseJavaAnnotations() ) { NamedEntityGraph annotation = getPhysicalAnnotation( NamedEntityGraph.class ); addNamedEntityGraphIfNeeded( annotation, queries ); NamedEntityGraphs annotations = getPhysicalAnnotation( NamedEntityGraphs.class ); if ( annotations != null ) { for ( NamedEntityGraph current : annotations.value() ) { addNamedEntityGraphIfNeeded( current, queries ); } } } if ( queries.size() > 0 ) { AnnotationDescriptor ad = new AnnotationDescriptor( NamedEntityGraphs.class ); ad.setValue( "value", queries.toArray( new NamedEntityGraph[queries.size()] ) ); return AnnotationFactory.create( ad ); } else { return null; } } private void addNamedEntityGraphIfNeeded(NamedEntityGraph annotation, List<NamedEntityGraph> queries) { if ( annotation != null ) { String queryName = annotation.name(); boolean present = false; for ( NamedEntityGraph current : queries ) { if ( current.name().equals( queryName ) ) { present = true; break; } } if ( !present ) { queries.add( annotation ); } } } private NamedStoredProcedureQueries getNamedStoredProcedureQueries(Element tree, XMLContext.Default defaults) { List<NamedStoredProcedureQuery> queries = buildNamedStoreProcedureQueries( tree, defaults, classLoaderAccess ); if ( defaults.canUseJavaAnnotations() ) { NamedStoredProcedureQuery annotation = getPhysicalAnnotation( NamedStoredProcedureQuery.class ); addNamedStoredProcedureQueryIfNeeded( annotation, queries ); NamedStoredProcedureQueries annotations = getPhysicalAnnotation( NamedStoredProcedureQueries.class ); if ( annotations != null ) { for ( NamedStoredProcedureQuery current : annotations.value() ) { addNamedStoredProcedureQueryIfNeeded( current, queries ); } } } if ( queries.size() > 0 ) { AnnotationDescriptor ad = new AnnotationDescriptor( NamedStoredProcedureQueries.class ); ad.setValue( "value", queries.toArray( new NamedStoredProcedureQuery[queries.size()] ) ); return AnnotationFactory.create( ad ); } else { return null; } } private void addNamedStoredProcedureQueryIfNeeded(NamedStoredProcedureQuery annotation, List<NamedStoredProcedureQuery> queries) { if ( annotation != null ) { String queryName = annotation.name(); boolean present = false; for ( NamedStoredProcedureQuery current : queries ) { if ( current.name().equals( queryName ) ) { present = true; break; } } if ( !present ) { queries.add( annotation ); } } } private NamedNativeQueries getNamedNativeQueries( Element tree, XMLContext.Default defaults) { List<NamedNativeQuery> queries = (List<NamedNativeQuery>) buildNamedQueries( tree, true, defaults, classLoaderAccess ); if ( defaults.canUseJavaAnnotations() ) { NamedNativeQuery annotation = getPhysicalAnnotation( NamedNativeQuery.class ); addNamedNativeQueryIfNeeded( annotation, queries ); NamedNativeQueries annotations = getPhysicalAnnotation( NamedNativeQueries.class ); if ( annotations != null ) { for ( NamedNativeQuery current : annotations.value() ) { addNamedNativeQueryIfNeeded( current, queries ); } } } if ( queries.size() > 0 ) { AnnotationDescriptor ad = new AnnotationDescriptor( NamedNativeQueries.class ); ad.setValue( "value", queries.toArray( new NamedNativeQuery[queries.size()] ) ); return AnnotationFactory.create( ad ); } else { return null; } } private void addNamedNativeQueryIfNeeded(NamedNativeQuery annotation, List<NamedNativeQuery> queries) { if ( annotation != null ) { String queryName = annotation.name(); boolean present = false; for ( NamedNativeQuery current : queries ) { if ( current.name().equals( queryName ) ) { present = true; break; } } if ( !present ) { queries.add( annotation ); } } } private static void buildQueryHints(List<Element> elements, AnnotationDescriptor ann){ List<QueryHint> queryHints = new ArrayList<QueryHint>( elements.size() ); for ( Element hint : elements ) { AnnotationDescriptor hintDescriptor = new AnnotationDescriptor( QueryHint.class ); String value = hint.attributeValue( "name" ); if ( value == null ) { throw new AnnotationException( "<hint> without name. " + SCHEMA_VALIDATION ); } hintDescriptor.setValue( "name", value ); value = hint.attributeValue( "value" ); if ( value == null ) { throw new AnnotationException( "<hint> without value. " + SCHEMA_VALIDATION ); } hintDescriptor.setValue( "value", value ); queryHints.add( (QueryHint) AnnotationFactory.create( hintDescriptor ) ); } ann.setValue( "hints", queryHints.toArray( new QueryHint[queryHints.size()] ) ); } public static List buildNamedQueries( Element element, boolean isNative, XMLContext.Default defaults, ClassLoaderAccess classLoaderAccess) { if ( element == null ) { return new ArrayList(); } List namedQueryElementList = isNative ? element.elements( "named-native-query" ) : element.elements( "named-query" ); List namedQueries = new ArrayList(); for ( Object aNamedQueryElementList : namedQueryElementList ) { Element subelement = (Element) aNamedQueryElementList; AnnotationDescriptor ann = new AnnotationDescriptor( isNative ? NamedNativeQuery.class : NamedQuery.class ); copyStringAttribute( ann, subelement, "name", false ); Element queryElt = subelement.element( "query" ); if ( queryElt == null ) { throw new AnnotationException( "No <query> element found." + SCHEMA_VALIDATION ); } copyStringElement( queryElt, ann, "query" ); List<Element> elements = subelement.elements( "hint" ); buildQueryHints( elements, ann ); String clazzName = subelement.attributeValue( "result-class" ); if ( StringHelper.isNotEmpty( clazzName ) ) { Class clazz; try { clazz = classLoaderAccess.classForName( XMLContext.buildSafeClassName( clazzName, defaults ) ); } catch (ClassLoadingException e) { throw new AnnotationException( "Unable to find entity-class: " + clazzName, e ); } ann.setValue( "resultClass", clazz ); } copyStringAttribute( ann, subelement, "result-set-mapping", false ); namedQueries.add( AnnotationFactory.create( ann ) ); } return namedQueries; } private TableGenerator getTableGenerator(Element tree, XMLContext.Default defaults) { Element element = tree != null ? tree.element( annotationToXml.get( TableGenerator.class ) ) : null; if ( element != null ) { return buildTableGeneratorAnnotation( element, defaults ); } else if ( defaults.canUseJavaAnnotations() && isPhysicalAnnotationPresent( TableGenerator.class ) ) { TableGenerator tableAnn = getPhysicalAnnotation( TableGenerator.class ); if ( StringHelper.isNotEmpty( defaults.getSchema() ) || StringHelper.isNotEmpty( defaults.getCatalog() ) ) { AnnotationDescriptor annotation = new AnnotationDescriptor( TableGenerator.class ); annotation.setValue( "name", tableAnn.name() ); annotation.setValue( "table", tableAnn.table() ); annotation.setValue( "catalog", tableAnn.table() ); if ( StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) ) && StringHelper.isNotEmpty( defaults.getCatalog() ) ) { annotation.setValue( "catalog", defaults.getCatalog() ); } annotation.setValue( "schema", tableAnn.table() ); if ( StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) ) && StringHelper.isNotEmpty( defaults.getSchema() ) ) { annotation.setValue( "catalog", defaults.getSchema() ); } annotation.setValue( "pkColumnName", tableAnn.pkColumnName() ); annotation.setValue( "valueColumnName", tableAnn.valueColumnName() ); annotation.setValue( "pkColumnValue", tableAnn.pkColumnValue() ); annotation.setValue( "initialValue", tableAnn.initialValue() ); annotation.setValue( "allocationSize", tableAnn.allocationSize() ); annotation.setValue( "uniqueConstraints", tableAnn.uniqueConstraints() ); return AnnotationFactory.create( annotation ); } else { return tableAnn; } } else { return null; } } public static TableGenerator buildTableGeneratorAnnotation(Element element, XMLContext.Default defaults) { AnnotationDescriptor ad = new AnnotationDescriptor( TableGenerator.class ); copyStringAttribute( ad, element, "name", false ); copyStringAttribute( ad, element, "table", false ); copyStringAttribute( ad, element, "catalog", false ); copyStringAttribute( ad, element, "schema", false ); copyStringAttribute( ad, element, "pk-column-name", false ); copyStringAttribute( ad, element, "value-column-name", false ); copyStringAttribute( ad, element, "pk-column-value", false ); copyIntegerAttribute( ad, element, "initial-value" ); copyIntegerAttribute( ad, element, "allocation-size" ); buildUniqueConstraints( ad, element ); if ( StringHelper.isEmpty( (String) ad.valueOf( "schema" ) ) && StringHelper.isNotEmpty( defaults.getSchema() ) ) { ad.setValue( "schema", defaults.getSchema() ); } if ( StringHelper.isEmpty( (String) ad.valueOf( "catalog" ) ) && StringHelper.isNotEmpty( defaults.getCatalog() ) ) { ad.setValue( "catalog", defaults.getCatalog() ); } return AnnotationFactory.create( ad ); } private SequenceGenerator getSequenceGenerator(Element tree, XMLContext.Default defaults) { Element element = tree != null ? tree.element( annotationToXml.get( SequenceGenerator.class ) ) : null; if ( element != null ) { return buildSequenceGeneratorAnnotation( element ); } else if ( defaults.canUseJavaAnnotations() ) { return getPhysicalAnnotation( SequenceGenerator.class ); } else { return null; } } public static SequenceGenerator buildSequenceGeneratorAnnotation(Element element) { if ( element != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( SequenceGenerator.class ); copyStringAttribute( ad, element, "name", false ); copyStringAttribute( ad, element, "sequence-name", false ); copyIntegerAttribute( ad, element, "initial-value" ); copyIntegerAttribute( ad, element, "allocation-size" ); return AnnotationFactory.create( ad ); } else { return null; } } private DiscriminatorColumn getDiscriminatorColumn(Element tree, XMLContext.Default defaults) { Element element = tree != null ? tree.element( "discriminator-column" ) : null; if ( element != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( DiscriminatorColumn.class ); copyStringAttribute( ad, element, "name", false ); copyStringAttribute( ad, element, "column-definition", false ); String value = element.attributeValue( "discriminator-type" ); DiscriminatorType type = DiscriminatorType.STRING; if ( value != null ) { if ( "STRING".equals( value ) ) { type = DiscriminatorType.STRING; } else if ( "CHAR".equals( value ) ) { type = DiscriminatorType.CHAR; } else if ( "INTEGER".equals( value ) ) { type = DiscriminatorType.INTEGER; } else { throw new AnnotationException( "Unknown DiscrimiatorType in XML: " + value + " (" + SCHEMA_VALIDATION + ")" ); } } ad.setValue( "discriminatorType", type ); copyIntegerAttribute( ad, element, "length" ); return AnnotationFactory.create( ad ); } else if ( defaults.canUseJavaAnnotations() ) { return getPhysicalAnnotation( DiscriminatorColumn.class ); } else { return null; } } private DiscriminatorValue getDiscriminatorValue(Element tree, XMLContext.Default defaults) { Element element = tree != null ? tree.element( "discriminator-value" ) : null; if ( element != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( DiscriminatorValue.class ); copyStringElement( element, ad, "value" ); return AnnotationFactory.create( ad ); } else if ( defaults.canUseJavaAnnotations() ) { return getPhysicalAnnotation( DiscriminatorValue.class ); } else { return null; } } private Inheritance getInheritance(Element tree, XMLContext.Default defaults) { Element element = tree != null ? tree.element( "inheritance" ) : null; if ( element != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( Inheritance.class ); Attribute attr = element.attribute( "strategy" ); InheritanceType strategy = InheritanceType.SINGLE_TABLE; if ( attr != null ) { String value = attr.getValue(); if ( "SINGLE_TABLE".equals( value ) ) { strategy = InheritanceType.SINGLE_TABLE; } else if ( "JOINED".equals( value ) ) { strategy = InheritanceType.JOINED; } else if ( "TABLE_PER_CLASS".equals( value ) ) { strategy = InheritanceType.TABLE_PER_CLASS; } else { throw new AnnotationException( "Unknown InheritanceType in XML: " + value + " (" + SCHEMA_VALIDATION + ")" ); } } ad.setValue( "strategy", strategy ); return AnnotationFactory.create( ad ); } else if ( defaults.canUseJavaAnnotations() ) { return getPhysicalAnnotation( Inheritance.class ); } else { return null; } } private IdClass getIdClass(Element tree, XMLContext.Default defaults) { Element element = tree == null ? null : tree.element( "id-class" ); if ( element != null ) { Attribute attr = element.attribute( "class" ); if ( attr != null ) { AnnotationDescriptor ad = new AnnotationDescriptor( IdClass.class ); Class clazz; try { clazz = classLoaderAccess.classForName( XMLContext.buildSafeClassName( attr.getValue(), defaults ) ); } catch ( ClassLoadingException e ) { throw new AnnotationException( "Unable to find id-class: " + attr.getValue(), e ); } ad.setValue( "value", clazz ); return AnnotationFactory.create( ad ); } else { throw new AnnotationException( "id-class without class. " + SCHEMA_VALIDATION ); } } else if ( defaults.canUseJavaAnnotations() ) { return getPhysicalAnnotation( IdClass.class ); } else { return null; } } /** * @param mergeWithAnnotations Whether to use Java annotations for this * element, if present and not disabled by the XMLContext defaults. * In some contexts (such as an association mapping) merging with * annotations is never allowed. */ private PrimaryKeyJoinColumns getPrimaryKeyJoinColumns(Element element, XMLContext.Default defaults, boolean mergeWithAnnotations) { PrimaryKeyJoinColumn[] columns = buildPrimaryKeyJoinColumns( element ); if ( mergeWithAnnotations ) { if ( columns.length == 0 && defaults.canUseJavaAnnotations() ) { PrimaryKeyJoinColumn annotation = getPhysicalAnnotation( PrimaryKeyJoinColumn.class ); if ( annotation != null ) { columns = new PrimaryKeyJoinColumn[] { annotation }; } else { PrimaryKeyJoinColumns annotations = getPhysicalAnnotation( PrimaryKeyJoinColumns.class ); columns = annotations != null ? annotations.value() : columns; } } } if ( columns.length > 0 ) { AnnotationDescriptor ad = new AnnotationDescriptor( PrimaryKeyJoinColumns.class ); ad.setValue( "value", columns ); return AnnotationFactory.create( ad ); } else { return null; } } private Entity getEntity(Element tree, XMLContext.Default defaults) { if ( tree == null ) { return defaults.canUseJavaAnnotations() ? getPhysicalAnnotation( Entity.class ) : null; } else { if ( "entity".equals( tree.getName() ) ) { AnnotationDescriptor entity = new AnnotationDescriptor( Entity.class ); copyStringAttribute( entity, tree, "name", false ); if ( defaults.canUseJavaAnnotations() && StringHelper.isEmpty( (String) entity.valueOf( "name" ) ) ) { Entity javaAnn = getPhysicalAnnotation( Entity.class ); if ( javaAnn != null ) { entity.setValue( "name", javaAnn.name() ); } } return AnnotationFactory.create( entity ); } else { return null; //this is not an entity } } } private MappedSuperclass getMappedSuperclass(Element tree, XMLContext.Default defaults) { if ( tree == null ) { return defaults.canUseJavaAnnotations() ? getPhysicalAnnotation( MappedSuperclass.class ) : null; } else { if ( "mapped-superclass".equals( tree.getName() ) ) { AnnotationDescriptor entity = new AnnotationDescriptor( MappedSuperclass.class ); return AnnotationFactory.create( entity ); } else { return null; //this is not an entity } } } private Embeddable getEmbeddable(Element tree, XMLContext.Default defaults) { if ( tree == null ) { return defaults.canUseJavaAnnotations() ? getPhysicalAnnotation( Embeddable.class ) : null; } else { if ( "embeddable".equals( tree.getName() ) ) { AnnotationDescriptor entity = new AnnotationDescriptor( Embeddable.class ); return AnnotationFactory.create( entity ); } else { return null; //this is not an entity } } } private Table getTable(Element tree, XMLContext.Default defaults) { Element subelement = tree == null ? null : tree.element( "table" ); if ( subelement == null ) { //no element but might have some default or some annotation if ( StringHelper.isNotEmpty( defaults.getCatalog() ) || StringHelper.isNotEmpty( defaults.getSchema() ) ) { AnnotationDescriptor annotation = new AnnotationDescriptor( Table.class ); if ( defaults.canUseJavaAnnotations() ) { Table table = getPhysicalAnnotation( Table.class ); if ( table != null ) { annotation.setValue( "name", table.name() ); annotation.setValue( "schema", table.schema() ); annotation.setValue( "catalog", table.catalog() ); annotation.setValue( "uniqueConstraints", table.uniqueConstraints() ); annotation.setValue( "indexes", table.indexes() ); } } if ( StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) ) && StringHelper.isNotEmpty( defaults.getSchema() ) ) { annotation.setValue( "schema", defaults.getSchema() ); } if ( StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) ) && StringHelper.isNotEmpty( defaults.getCatalog() ) ) { annotation.setValue( "catalog", defaults.getCatalog() ); } return AnnotationFactory.create( annotation ); } else if ( defaults.canUseJavaAnnotations() ) { return getPhysicalAnnotation( Table.class ); } else { return null; } } else { //ignore java annotation, an element is defined AnnotationDescriptor annotation = new AnnotationDescriptor( Table.class ); copyStringAttribute( annotation, subelement, "name", false ); copyStringAttribute( annotation, subelement, "catalog", false ); if ( StringHelper.isNotEmpty( defaults.getCatalog() ) && StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) ) ) { annotation.setValue( "catalog", defaults.getCatalog() ); } copyStringAttribute( annotation, subelement, "schema", false ); if ( StringHelper.isNotEmpty( defaults.getSchema() ) && StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) ) ) { annotation.setValue( "schema", defaults.getSchema() ); } buildUniqueConstraints( annotation, subelement ); buildIndex( annotation, subelement ); return AnnotationFactory.create( annotation ); } } private SecondaryTables getSecondaryTables(Element tree, XMLContext.Default defaults) { List<Element> elements = tree == null ? new ArrayList<Element>() : (List<Element>) tree.elements( "secondary-table" ); List<SecondaryTable> secondaryTables = new ArrayList<SecondaryTable>( 3 ); for ( Element element : elements ) { AnnotationDescriptor annotation = new AnnotationDescriptor( SecondaryTable.class ); copyStringAttribute( annotation, element, "name", false ); copyStringAttribute( annotation, element, "catalog", false ); if ( StringHelper.isNotEmpty( defaults.getCatalog() ) && StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) ) ) { annotation.setValue( "catalog", defaults.getCatalog() ); } copyStringAttribute( annotation, element, "schema", false ); if ( StringHelper.isNotEmpty( defaults.getSchema() ) && StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) ) ) { annotation.setValue( "schema", defaults.getSchema() ); } buildUniqueConstraints( annotation, element ); buildIndex( annotation, element ); annotation.setValue( "pkJoinColumns", buildPrimaryKeyJoinColumns( element ) ); secondaryTables.add( (SecondaryTable) AnnotationFactory.create( annotation ) ); } /* * You can't have both secondary table in XML and Java, * since there would be no way to "remove" a secondary table */ if ( secondaryTables.size() == 0 && defaults.canUseJavaAnnotations() ) { SecondaryTable secTableAnn = getPhysicalAnnotation( SecondaryTable.class ); overridesDefaultInSecondaryTable( secTableAnn, defaults, secondaryTables ); SecondaryTables secTablesAnn = getPhysicalAnnotation( SecondaryTables.class ); if ( secTablesAnn != null ) { for ( SecondaryTable table : secTablesAnn.value() ) { overridesDefaultInSecondaryTable( table, defaults, secondaryTables ); } } } if ( secondaryTables.size() > 0 ) { AnnotationDescriptor descriptor = new AnnotationDescriptor( SecondaryTables.class ); descriptor.setValue( "value", secondaryTables.toArray( new SecondaryTable[secondaryTables.size()] ) ); return AnnotationFactory.create( descriptor ); } else { return null; } } private void overridesDefaultInSecondaryTable( SecondaryTable secTableAnn, XMLContext.Default defaults, List<SecondaryTable> secondaryTables ) { if ( secTableAnn != null ) { //handle default values if ( StringHelper.isNotEmpty( defaults.getCatalog() ) || StringHelper.isNotEmpty( defaults.getSchema() ) ) { AnnotationDescriptor annotation = new AnnotationDescriptor( SecondaryTable.class ); annotation.setValue( "name", secTableAnn.name() ); annotation.setValue( "schema", secTableAnn.schema() ); annotation.setValue( "catalog", secTableAnn.catalog() ); annotation.setValue( "uniqueConstraints", secTableAnn.uniqueConstraints() ); annotation.setValue( "pkJoinColumns", secTableAnn.pkJoinColumns() ); if ( StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) ) && StringHelper.isNotEmpty( defaults.getSchema() ) ) { annotation.setValue( "schema", defaults.getSchema() ); } if ( StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) ) && StringHelper.isNotEmpty( defaults.getCatalog() ) ) { annotation.setValue( "catalog", defaults.getCatalog() ); } secondaryTables.add( (SecondaryTable) AnnotationFactory.create( annotation ) ); } else { secondaryTables.add( secTableAnn ); } } } private static void buildIndex(AnnotationDescriptor annotation, Element element){ List indexElementList = element.elements( "index" ); Index[] indexes = new Index[indexElementList.size()]; for(int i=0;i<indexElementList.size();i++){ Element subelement = (Element)indexElementList.get( i ); AnnotationDescriptor indexAnn = new AnnotationDescriptor( Index.class ); copyStringAttribute( indexAnn, subelement, "name", false ); copyStringAttribute( indexAnn, subelement, "column-list", true ); copyBooleanAttribute( indexAnn, subelement, "unique" ); indexes[i] = AnnotationFactory.create( indexAnn ); } annotation.setValue( "indexes", indexes ); } private static void buildUniqueConstraints(AnnotationDescriptor annotation, Element element) { List uniqueConstraintElementList = element.elements( "unique-constraint" ); UniqueConstraint[] uniqueConstraints = new UniqueConstraint[uniqueConstraintElementList.size()]; int ucIndex = 0; Iterator ucIt = uniqueConstraintElementList.listIterator(); while ( ucIt.hasNext() ) { Element subelement = (Element) ucIt.next(); List<Element> columnNamesElements = subelement.elements( "column-name" ); String[] columnNames = new String[columnNamesElements.size()]; int columnNameIndex = 0; Iterator it = columnNamesElements.listIterator(); while ( it.hasNext() ) { Element columnNameElt = (Element) it.next(); columnNames[columnNameIndex++] = columnNameElt.getTextTrim(); } AnnotationDescriptor ucAnn = new AnnotationDescriptor( UniqueConstraint.class ); copyStringAttribute( ucAnn, subelement, "name", false ); ucAnn.setValue( "columnNames", columnNames ); uniqueConstraints[ucIndex++] = AnnotationFactory.create( ucAnn ); } annotation.setValue( "uniqueConstraints", uniqueConstraints ); } private PrimaryKeyJoinColumn[] buildPrimaryKeyJoinColumns(Element element) { if ( element == null ) { return new PrimaryKeyJoinColumn[] { }; } List pkJoinColumnElementList = element.elements( "primary-key-join-column" ); PrimaryKeyJoinColumn[] pkJoinColumns = new PrimaryKeyJoinColumn[pkJoinColumnElementList.size()]; int index = 0; Iterator pkIt = pkJoinColumnElementList.listIterator(); while ( pkIt.hasNext() ) { Element subelement = (Element) pkIt.next(); AnnotationDescriptor pkAnn = new AnnotationDescriptor( PrimaryKeyJoinColumn.class ); copyStringAttribute( pkAnn, subelement, "name", false ); copyStringAttribute( pkAnn, subelement, "referenced-column-name", false ); copyStringAttribute( pkAnn, subelement, "column-definition", false ); pkJoinColumns[index++] = AnnotationFactory.create( pkAnn ); } return pkJoinColumns; } /** * Copy a string attribute from an XML element to an annotation descriptor. The name of the annotation attribute is * computed from the name of the XML attribute by {@link #getJavaAttributeNameFromXMLOne(String)}. * * @param annotation annotation descriptor where to copy to the attribute. * @param element XML element from where to copy the attribute. * @param attributeName name of the XML attribute to copy. * @param mandatory whether the attribute is mandatory. */ private static void copyStringAttribute( final AnnotationDescriptor annotation, final Element element, final String attributeName, final boolean mandatory) { copyStringAttribute( annotation, element, getJavaAttributeNameFromXMLOne( attributeName ), attributeName, mandatory ); } /** * Copy a string attribute from an XML element to an annotation descriptor. The name of the annotation attribute is * explicitely given. * * @param annotation annotation where to copy to the attribute. * @param element XML element from where to copy the attribute. * @param annotationAttributeName name of the annotation attribute where to copy. * @param attributeName name of the XML attribute to copy. * @param mandatory whether the attribute is mandatory. */ private static void copyStringAttribute( final AnnotationDescriptor annotation, final Element element, final String annotationAttributeName, final String attributeName, boolean mandatory) { String attribute = element.attributeValue( attributeName ); if ( attribute != null ) { annotation.setValue( annotationAttributeName, attribute ); } else { if ( mandatory ) { throw new AnnotationException( element.getName() + "." + attributeName + " is mandatory in XML overriding. " + SCHEMA_VALIDATION ); } } } private static void copyIntegerAttribute(AnnotationDescriptor annotation, Element element, String attributeName) { String attribute = element.attributeValue( attributeName ); if ( attribute != null ) { String annotationAttributeName = getJavaAttributeNameFromXMLOne( attributeName ); annotation.setValue( annotationAttributeName, attribute ); try { int length = Integer.parseInt( attribute ); annotation.setValue( annotationAttributeName, length ); } catch ( NumberFormatException e ) { throw new AnnotationException( element.getPath() + attributeName + " not parseable: " + attribute + " (" + SCHEMA_VALIDATION + ")" ); } } } private static String getJavaAttributeNameFromXMLOne(String attributeName) { StringBuilder annotationAttributeName = new StringBuilder( attributeName ); int index = annotationAttributeName.indexOf( WORD_SEPARATOR ); while ( index != -1 ) { annotationAttributeName.deleteCharAt( index ); annotationAttributeName.setCharAt( index, Character.toUpperCase( annotationAttributeName.charAt( index ) ) ); index = annotationAttributeName.indexOf( WORD_SEPARATOR ); } return annotationAttributeName.toString(); } private static void copyStringElement(Element element, AnnotationDescriptor ad, String annotationAttribute) { String discr = element.getTextTrim(); ad.setValue( annotationAttribute, discr ); } private static void copyBooleanAttribute(AnnotationDescriptor descriptor, Element element, String attribute) { String attributeValue = element.attributeValue( attribute ); if ( StringHelper.isNotEmpty( attributeValue ) ) { String javaAttribute = getJavaAttributeNameFromXMLOne( attribute ); descriptor.setValue( javaAttribute, Boolean.parseBoolean( attributeValue ) ); } } private <T extends Annotation> T getPhysicalAnnotation(Class<T> annotationType) { return element.getAnnotation( annotationType ); } private <T extends Annotation> boolean isPhysicalAnnotationPresent(Class<T> annotationType) { return element.isAnnotationPresent( annotationType ); } private Annotation[] getPhysicalAnnotations() { return element.getAnnotations(); } }
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/main/java/org/hibernate/cfg/annotations/reflection/JPAOverriddenAnnotationReader.java
Java
lgpl-2.1
128,122
<?php class Response extends Component { protected $status = 200; protected $headers = array(); protected $rawHeaders = array(); protected $compression = false; protected $body = ''; public $isRedirect = false; public $isError = false; public $isException = false; public function __construct() { $this->compression = (@strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false/* && !Php2Go::app()->getRequest()->isAjax()*/); $this->setContentType('text/html; charset=' . Php2Go::app()->getCharset()); } public function getHeaders() { return $this->headers; } public function getRawHeaders() { return $this->rawHeaders; } public function addHeader($name, $value, $replace=true) { $this->canSendHeaders(true); $name = $this->normalizeHeader($name); $value = (string)$value; if ($replace) { foreach ($this->headers as $key => $header) { if ($header['name'] == $name) unset($this->headers[$key]); } } $this->headers[] = array( 'name' => $name, 'value' => $value, 'replace' => $replace ); return $this; } public function setRawHeader($header) { $this->canSendHeaders(true); if (stripos(trim($header), 'location:') === 0) $this->isRedirect = true; $this->rawHeaders[] = (string)$value; return $this; } public function clearHeader($name) { if (!empty($this->headers)) { foreach ($this->headers as $key => $header) { if ($header['name'] == $key) unset($this->headers[$key]); } } return $this; } public function clearRawHeader($name) { if (!empty($this->rawHeaders)) { $key = array_search($name, $this->rawHeaders); if ($key !== false) unset($this->rawHeaders[$key]); } return $this; } public function clearHeaders() { $this->headers = array(); return $this; } public function clearRawHeaders() { $this->rawHeaders = array(); return $this; } public function getCompression() { return $this->compression; } public function setCompression($compression) { $this->compression = !!$compression; return $this; } public function addCookie(Cookie $cookie) { setcookie($cookie->name, $cookie->value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly); } public function removeCookie(Cookie $cookie) { setcookie($cookie->name, null, 0, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly); } public function canSendHeaders($throw=false) { $sent = headers_sent($file, $line); if ($sent && $throw) throw new Exception(__(PHP2GO_LANG_DOMAIN, 'Headers already sent in %s, line %s', array($file, $line))); return !$sent; } public function sendHeaders() { if (!empty($this->rawHeaders) || !empty($this->headers) || $this->status == 200) $this->canSendHeaders(true); elseif ($this->status == 200) return; $statusSent = false; foreach ($this->rawHeaders as $header) { if (!$statusSent && $this->status) { header($header, true, $this->status); $statusSent = true; } else { header($header); } } foreach ($this->headers as $header) { if (!$statusSent && $this->status) { header($header['name'] . ': ' . $header['value'], $header['replace'], $this->status); $statusSent = true; } else { header($header['name'] . ': ' . $header['value'], $header['replace']); } } if (!$statusSent) header('HTTP/1.1 ' . $this->status, true, $this->status); return $this; } public function getStatus() { return $this->status; } public function setStatus($code) { if (!is_int($code) || (100 > $code) || (599 < $code)) throw new InvalidArgumentException(__(PHP2GO_LANG_DOMAIN, 'Invalid HTTP response code.')); $this->isRedirect = ($code >= 300 && $code <= 307); $this->status = $code; return $this; } public function getContentType($contentType) { foreach ($this->headers as $header) { if ($header['name'] == 'Content-Type') return $header['value']; } foreach ($this->rawHeaders as $header) { if (stripos(trim($header), 'content-type:') === 0) return trim(substr(trim($header), strlen('content-type:'))); } return null; } public function setContentType($contentType) { $this->addHeader('Content-Type', $contentType); return $this; } public function redirect($url, $status=302) { $this->addHeader('Location', $url, true); $this->setStatus($status); $this->sendHeaders(); Php2Go::app()->stop(); } public function getBody() { ob_start(); $this->sendBody(); return ob_get_clean(); } public function setBody($content) { $this->body = $content; return $this; } public function appendBody($content) { $this->body .= $content; return $this; } public function clearBody() { $this->body = ''; return $this; } public function sendBody() { if ($this->compression) { $body = preg_replace( array( '/(\x20{2,})/', // extra-white spaces '/\t/', // tab '/\n\r/' // blank lines ), array(' ', '', ''), $this->body ); echo gzencode($this->body, 9); } else { echo $this->body; } } public function sendResponse() { if ($this->compression) $this->addHeader('Content-Encoding', 'gzip', true); $this->sendHeaders(); if (!$this->isRedirect) $this->sendBody(); } public function __toString() { ob_start(); $this->sendResponse(); return ob_get_clean(); } protected function normalizeHeader($name) { $filtered = str_replace(array('-', '_'), ' ', (string)$name); $filtered = ucwords(strtolower($filtered)); $filtered = str_replace(' ', '-', $filtered); return $filtered; } }
marcospont/php2go
php2go/web/Response.php
PHP
lgpl-2.1
5,692
package com.gromstudio.treckar.model; import java.net.URL; public class WorldMapArea { URL mBitmapUrl; }
jeromeOrfila/treckar
src/com/gromstudio/treckar/model/WorldMapArea.java
Java
lgpl-2.1
114
<?php // $Header: /cvsroot/tikiwiki/tiki/img/trackers/index.php,v 1.1.2.2 2007/03/02 12:10:41 luciash Exp $ // Copyright (c) 2002-2007, Luis Argerich, Garland Foster, Eduardo Polidor, et. al. // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // This redirects to the sites root to prevent directory browsing header("location: ../../tiki-index.php"); die; ?>
marcelosoaressouza/estudiolivre
img/trackers/index.php
PHP
lgpl-2.1
485
/******************************************************************************* * Copyright (c) 2012 Eric Bodden. * Copyright (c) 2013 Tata Consultancy Services & Ecole Polytechnique de Montreal * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * Eric Bodden - initial API and implementation * Marc-Andre Laverdiere-Papineau - Fixed race condition * Steven Arzt - Created FastSolver implementation ******************************************************************************/ package soot.jimple.infoflow.solver.fastSolver; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.cache.CacheBuilder; import heros.DontSynchronize; import heros.FlowFunction; import heros.FlowFunctionCache; import heros.FlowFunctions; import heros.IFDSTabulationProblem; import heros.SynchronizedBy; import heros.ZeroedFlowFunctions; import heros.solver.Pair; import heros.solver.PathEdge; import soot.SootMethod; import soot.Unit; import soot.jimple.infoflow.collect.ConcurrentHashSet; import soot.jimple.infoflow.collect.MyConcurrentHashMap; import soot.jimple.infoflow.memory.IMemoryBoundedSolver; import soot.jimple.infoflow.solver.executors.InterruptableExecutor; import soot.jimple.infoflow.solver.executors.SetPoolExecutor; import soot.jimple.infoflow.solver.memory.IMemoryManager; import soot.jimple.toolkits.ide.icfg.BiDiInterproceduralCFG; /** * A solver for an {@link IFDSTabulationProblem}. This solver is not based on the IDESolver * implementation in Heros for performance reasons. * * @param <N> The type of nodes in the interprocedural control-flow graph. Typically {@link Unit}. * @param <D> The type of data-flow facts to be computed by the tabulation problem. * @param <I> The type of inter-procedural control-flow graph being used. * @see IFDSTabulationProblem */ public class IFDSSolver<N,D extends FastSolverLinkedNode<D, N>,I extends BiDiInterproceduralCFG<N, SootMethod>> implements IMemoryBoundedSolver { public static CacheBuilder<Object, Object> DEFAULT_CACHE_BUILDER = CacheBuilder.newBuilder().concurrencyLevel (Runtime.getRuntime().availableProcessors()).initialCapacity(10000).softValues(); protected static final Logger logger = LoggerFactory.getLogger(IFDSSolver.class); //enable with -Dorg.slf4j.simpleLogger.defaultLogLevel=trace public static final boolean DEBUG = logger.isDebugEnabled(); protected InterruptableExecutor executor; @DontSynchronize("only used by single thread") protected int numThreads; @SynchronizedBy("thread safe data structure, consistent locking when used") protected MyConcurrentHashMap<PathEdge<N, D>,D> jumpFunctions = new MyConcurrentHashMap<PathEdge<N,D>, D>(); @SynchronizedBy("thread safe data structure, only modified internally") protected final I icfg; //stores summaries that were queried before they were computed //see CC 2010 paper by Naeem, Lhotak and Rodriguez @SynchronizedBy("consistent lock on 'incoming'") protected final MyConcurrentHashMap<Pair<SootMethod,D>,Set<Pair<N,D>>> endSummary = new MyConcurrentHashMap<Pair<SootMethod,D>, Set<Pair<N,D>>>(); //edges going along calls //see CC 2010 paper by Naeem, Lhotak and Rodriguez @SynchronizedBy("consistent lock on field") protected final MyConcurrentHashMap<Pair<SootMethod,D>,MyConcurrentHashMap<N,Map<D, D>>> incoming = new MyConcurrentHashMap<Pair<SootMethod,D>,MyConcurrentHashMap<N,Map<D, D>>>(); @DontSynchronize("stateless") protected final FlowFunctions<N, D, SootMethod> flowFunctions; @DontSynchronize("only used by single thread") protected final Map<N,Set<D>> initialSeeds; @DontSynchronize("benign races") public long propagationCount; @DontSynchronize("stateless") protected final D zeroValue; @DontSynchronize("readOnly") protected final FlowFunctionCache<N,D,SootMethod> ffCache; @DontSynchronize("readOnly") protected final boolean followReturnsPastSeeds; @DontSynchronize("readOnly") protected boolean setJumpPredecessors = false; @DontSynchronize("readOnly") private boolean enableMergePointChecking = false; @DontSynchronize("readOnly") private boolean singleJoinPointAbstraction = false; @DontSynchronize("readOnly") protected IMemoryManager<D, N> memoryManager = null; protected boolean solverId; private Set<IMemoryBoundedSolverStatusNotification> notificationListeners = new HashSet<>(); private boolean killFlag = false; /** * Creates a solver for the given problem, which caches flow functions and edge functions. * The solver must then be started by calling {@link #solve()}. */ public IFDSSolver(IFDSTabulationProblem<N,D,SootMethod,I> tabulationProblem) { this(tabulationProblem, DEFAULT_CACHE_BUILDER); } /** * Creates a solver for the given problem, constructing caches with the * given {@link CacheBuilder}. The solver must then be started by calling * {@link #solve()}. * @param tabulationProblem The tabulation problem to solve * @param flowFunctionCacheBuilder A valid {@link CacheBuilder} or * <code>null</code> if no caching is to be used for flow functions. */ public IFDSSolver(IFDSTabulationProblem<N,D,SootMethod,I> tabulationProblem, @SuppressWarnings("rawtypes") CacheBuilder flowFunctionCacheBuilder) { if(logger.isDebugEnabled()) flowFunctionCacheBuilder = flowFunctionCacheBuilder.recordStats(); this.zeroValue = tabulationProblem.zeroValue(); this.icfg = tabulationProblem.interproceduralCFG(); FlowFunctions<N, D, SootMethod> flowFunctions = tabulationProblem.autoAddZero() ? new ZeroedFlowFunctions<N,D,SootMethod>(tabulationProblem.flowFunctions(), zeroValue) : tabulationProblem.flowFunctions(); if(flowFunctionCacheBuilder!=null) { ffCache = new FlowFunctionCache<N,D,SootMethod>(flowFunctions, flowFunctionCacheBuilder); flowFunctions = ffCache; } else { ffCache = null; } this.flowFunctions = flowFunctions; this.initialSeeds = tabulationProblem.initialSeeds(); this.followReturnsPastSeeds = tabulationProblem.followReturnsPastSeeds(); this.numThreads = Math.max(1,tabulationProblem.numThreads()); this.executor = getExecutor(); } public void setSolverId(boolean solverId) { this.solverId = solverId; } /** * Runs the solver on the configured problem. This can take some time. */ public void solve() { // Notify the listeners that the solver has been started for (IMemoryBoundedSolverStatusNotification listener : notificationListeners) listener.notifySolverStarted(this); submitInitialSeeds(); awaitCompletionComputeValuesAndShutdown(); // Notify the listeners that the solver has been terminated for (IMemoryBoundedSolverStatusNotification listener : notificationListeners) listener.notifySolverTerminated(this); } /** * Schedules the processing of initial seeds, initiating the analysis. * Clients should only call this methods if performing synchronization on * their own. Normally, {@link #solve()} should be called instead. */ protected void submitInitialSeeds() { for(Entry<N, Set<D>> seed: initialSeeds.entrySet()) { N startPoint = seed.getKey(); for(D val: seed.getValue()) propagate(zeroValue, startPoint, val, null, false); addFunction(new PathEdge<N, D>(zeroValue, startPoint, zeroValue)); } } /** * Awaits the completion of the exploded super graph. When complete, computes result values, * shuts down the executor and returns. */ protected void awaitCompletionComputeValuesAndShutdown() { { //run executor and await termination of tasks runExecutorAndAwaitCompletion(); } if(logger.isDebugEnabled()) printStats(); //ask executor to shut down; //this will cause new submissions to the executor to be rejected, //but at this point all tasks should have completed anyway executor.shutdown(); // Wait for the executor to be really gone while (!executor.isTerminated()) { try { Thread.sleep(100); } catch (InterruptedException e) { // silently ignore the exception, it's not an issue if the // thread gets aborted } } } /** * Runs execution, re-throwing exceptions that might be thrown during its execution. */ private void runExecutorAndAwaitCompletion() { try { executor.awaitCompletion(); } catch (InterruptedException e) { e.printStackTrace(); } Throwable exception = executor.getException(); if(exception!=null) { throw new RuntimeException("There were exceptions during IFDS analysis. Exiting.",exception); } } /** * Dispatch the processing of a given edge. It may be executed in a different thread. * @param edge the edge to process */ protected void scheduleEdgeProcessing(PathEdge<N,D> edge){ // If the executor has been killed, there is little point // in submitting new tasks if (killFlag || executor.isTerminating() || executor.isTerminated()) return; executor.execute(new PathEdgeProcessingTask(edge, solverId)); propagationCount++; } /** * Lines 13-20 of the algorithm; processing a call site in the caller's context. * * For each possible callee, registers incoming call edges. * Also propagates call-to-return flows and summarized callee flows within the caller. * * @param edge an edge whose target node resembles a method call */ private void processCall(PathEdge<N,D> edge) { final D d1 = edge.factAtSource(); final N n = edge.getTarget(); // a call node; line 14... final D d2 = edge.factAtTarget(); assert d2 != null; Collection<N> returnSiteNs = icfg.getReturnSitesOfCallAt(n); //for each possible callee Collection<SootMethod> callees = icfg.getCalleesOfCallAt(n); for(SootMethod sCalledProcN: callees) { //still line 14 // Early termination check if (killFlag) return; //compute the call-flow function FlowFunction<D> function = flowFunctions.getCallFlowFunction(n, sCalledProcN); Set<D> res = computeCallFlowFunction(function, d1, d2); Collection<N> startPointsOf = icfg.getStartPointsOf(sCalledProcN); //for each result node of the call-flow function for(D d3: res) { if (memoryManager != null) d3 = memoryManager.handleGeneratedMemoryObject(d2, d3); if (d3 == null) continue; //for each callee's start point(s) for(N sP: startPointsOf) { //create initial self-loop propagate(d3, sP, d3, n, false, true); //line 15 } //register the fact that <sp,d3> has an incoming edge from <n,d2> //line 15.1 of Naeem/Lhotak/Rodriguez if (!addIncoming(sCalledProcN,d3,n,d1,d2)) continue; //line 15.2 Set<Pair<N, D>> endSumm = endSummary(sCalledProcN, d3); //still line 15.2 of Naeem/Lhotak/Rodriguez //for each already-queried exit value <eP,d4> reachable from <sP,d3>, //create new caller-side jump functions to the return sites //because we have observed a potentially new incoming edge into <sP,d3> if (endSumm != null && !endSumm.isEmpty()) for(Pair<N, D> entry: endSumm) { N eP = entry.getO1(); D d4 = entry.getO2(); //for each return site for(N retSiteN: returnSiteNs) { //compute return-flow function FlowFunction<D> retFunction = flowFunctions.getReturnFlowFunction(n, sCalledProcN, eP, retSiteN); //for each target value of the function for(D d5: computeReturnFlowFunction(retFunction, d3, d4, n, Collections.singleton(d1))) { if (memoryManager != null) d5 = memoryManager.handleGeneratedMemoryObject(d4, d5); // If we have not changed anything in the callee, we do not need the facts // from there. Even if we change something: If we don't need the concrete // path, we can skip the callee in the predecessor chain D d5p = d5; if (d5.equals(d2)) d5p = d2; else if (setJumpPredecessors && d5p != d2) { d5p = d5p.clone(); d5p.setPredecessor(d2); } propagate(d1, retSiteN, d5p, n, false, true); } } } } } //line 17-19 of Naeem/Lhotak/Rodriguez //process intra-procedural flows along call-to-return flow functions for (N returnSiteN : returnSiteNs) { FlowFunction<D> callToReturnFlowFunction = flowFunctions.getCallToReturnFlowFunction(n, returnSiteN); for(D d3: computeCallToReturnFlowFunction(callToReturnFlowFunction, d1, d2)) { if (memoryManager != null) d3 = memoryManager.handleGeneratedMemoryObject(d2, d3); if (d3 != null) propagate(d1, returnSiteN, d3, n, false); } } } /** * Computes the call flow function for the given call-site abstraction * @param callFlowFunction The call flow function to compute * @param d1 The abstraction at the current method's start node. * @param d2 The abstraction at the call site * @return The set of caller-side abstractions at the callee's start node */ protected Set<D> computeCallFlowFunction (FlowFunction<D> callFlowFunction, D d1, D d2) { return callFlowFunction.computeTargets(d2); } /** * Computes the call-to-return flow function for the given call-site * abstraction * @param callToReturnFlowFunction The call-to-return flow function to * compute * @param d1 The abstraction at the current method's start node. * @param d2 The abstraction at the call site * @return The set of caller-side abstractions at the return site */ protected Set<D> computeCallToReturnFlowFunction (FlowFunction<D> callToReturnFlowFunction, D d1, D d2) { return callToReturnFlowFunction.computeTargets(d2); } /** * Lines 21-32 of the algorithm. * * Stores callee-side summaries. * Also, at the side of the caller, propagates intra-procedural flows to return sites * using those newly computed summaries. * * @param edge an edge whose target node resembles a method exits */ protected void processExit(PathEdge<N,D> edge) { final N n = edge.getTarget(); // an exit node; line 21... SootMethod methodThatNeedsSummary = icfg.getMethodOf(n); final D d1 = edge.factAtSource(); final D d2 = edge.factAtTarget(); //for each of the method's start points, determine incoming calls //line 21.1 of Naeem/Lhotak/Rodriguez //register end-summary if (!addEndSummary(methodThatNeedsSummary, d1, n, d2)) return; Map<N,Map<D, D>> inc = incoming(d1, methodThatNeedsSummary); //for each incoming call edge already processed //(see processCall(..)) if (inc != null) for (Entry<N,Map<D, D>> entry: inc.entrySet()) { // Early termination check if (killFlag) return; //line 22 N c = entry.getKey(); Set<D> callerSideDs = entry.getValue().keySet(); //for each return site for(N retSiteC: icfg.getReturnSitesOfCallAt(c)) { //compute return-flow function FlowFunction<D> retFunction = flowFunctions.getReturnFlowFunction(c, methodThatNeedsSummary,n,retSiteC); Set<D> targets = computeReturnFlowFunction(retFunction, d1, d2, c, callerSideDs); //for each incoming-call value for(Entry<D, D> d1d2entry : entry.getValue().entrySet()) { final D d4 = d1d2entry.getKey(); final D predVal = d1d2entry.getValue(); for(D d5: targets) { if (memoryManager != null) d5 = memoryManager.handleGeneratedMemoryObject(d2, d5); if (d5 == null) continue; // If we have not changed anything in the callee, we do not need the facts // from there. Even if we change something: If we don't need the concrete // path, we can skip the callee in the predecessor chain D d5p = d5; if (d5.equals(predVal)) d5p = predVal; else if (setJumpPredecessors && d5p != predVal) { d5p = d5p.clone(); d5p.setPredecessor(predVal); } propagate(d4, retSiteC, d5p, c, false, true); } } } } //handling for unbalanced problems where we return out of a method with a fact for which we have no incoming flow //note: we propagate that way only values that originate from ZERO, as conditionally generated values should only //be propagated into callers that have an incoming edge for this condition if(followReturnsPastSeeds && d1 == zeroValue && (inc == null || inc.isEmpty())) { Collection<N> callers = icfg.getCallersOf(methodThatNeedsSummary); for(N c: callers) { SootMethod callerMethod = icfg.getMethodOf(c); for(N retSiteC: icfg.getReturnSitesOfCallAt(c)) { FlowFunction<D> retFunction = flowFunctions.getReturnFlowFunction(c, methodThatNeedsSummary,n,retSiteC); Set<D> targets = computeReturnFlowFunction(retFunction, d1, d2, c, Collections.singleton(zeroValue)); for(D d5: targets) { if (memoryManager != null) d5 = memoryManager.handleGeneratedMemoryObject(d2, d5); if (d5 != null) propagate(zeroValue, retSiteC, d5, c, true, callerMethod == methodThatNeedsSummary); } } } //in cases where there are no callers, the return statement would normally not be processed at all; //this might be undesirable if the flow function has a side effect such as registering a taint; //instead we thus call the return flow function will a null caller if(callers.isEmpty()) { FlowFunction<D> retFunction = flowFunctions.getReturnFlowFunction(null, methodThatNeedsSummary,n,null); retFunction.computeTargets(d2); } } } /** * Computes the return flow function for the given set of caller-side * abstractions. * @param retFunction The return flow function to compute * @param d1 The abstraction at the beginning of the callee * @param d2 The abstraction at the exit node in the callee * @param callSite The call site * @param callerSideDs The abstractions at the call site * @return The set of caller-side abstractions at the return site */ protected Set<D> computeReturnFlowFunction (FlowFunction<D> retFunction, D d1, D d2, N callSite, Collection<D> callerSideDs) { return retFunction.computeTargets(d2); } /** * Lines 33-37 of the algorithm. * Simply propagate normal, intra-procedural flows. * @param edge */ private void processNormalFlow(PathEdge<N,D> edge) { final D d1 = edge.factAtSource(); final N n = edge.getTarget(); final D d2 = edge.factAtTarget(); for (N m : icfg.getSuccsOf(n)) { // Early termination check if (killFlag) return; // Compute the flow function FlowFunction<D> flowFunction = flowFunctions.getNormalFlowFunction(n,m); Set<D> res = computeNormalFlowFunction(flowFunction, d1, d2); for (D d3 : res) { if (memoryManager != null && d2 != d3) d3 = memoryManager.handleGeneratedMemoryObject(d2, d3); if (d3 != null) propagate(d1, m, d3, null, false); } } } /** * Computes the normal flow function for the given set of start and end * abstractions. * @param flowFunction The normal flow function to compute * @param d1 The abstraction at the method's start node * @param d2 The abstraction at the current node * @return The set of abstractions at the successor node */ protected Set<D> computeNormalFlowFunction (FlowFunction<D> flowFunction, D d1, D d2) { return flowFunction.computeTargets(d2); } /** * Propagates the flow further down the exploded super graph. * @param sourceVal the source value of the propagated summary edge * @param target the target statement * @param targetVal the target value at the target statement * @param relatedCallSite for call and return flows the related call statement, <code>null</code> otherwise * (this value is not used within this implementation but may be useful for subclasses of {@link IFDSSolver}) * @param isUnbalancedReturn <code>true</code> if this edge is propagating an unbalanced return * (this value is not used within this implementation but may be useful for subclasses of {@link IFDSSolver}) */ protected void propagate(D sourceVal, N target, D targetVal, /* deliberately exposed to clients */ N relatedCallSite, /* deliberately exposed to clients */ boolean isUnbalancedReturn) { propagate(sourceVal, target, targetVal, relatedCallSite, isUnbalancedReturn, false); } /** * Propagates the flow further down the exploded super graph. * @param sourceVal the source value of the propagated summary edge * @param target the target statement * @param targetVal the target value at the target statement * @param relatedCallSite for call and return flows the related call statement, <code>null</code> otherwise * (this value is not used within this implementation but may be useful for subclasses of {@link IFDSSolver}) * @param isUnbalancedReturn <code>true</code> if this edge is propagating an unbalanced return * (this value is not used within this implementation but may be useful for subclasses of {@link IFDSSolver}) * @param forceRegister True if the jump function must always be registered with jumpFn . * This can happen when externally injecting edges that don't come out of this * solver. */ protected void propagate(D sourceVal, N target, D targetVal, /* deliberately exposed to clients */ N relatedCallSite, /* deliberately exposed to clients */ boolean isUnbalancedReturn, boolean forceRegister) { // Let the memory manager run if (memoryManager != null) { sourceVal = memoryManager.handleMemoryObject(sourceVal); targetVal = memoryManager.handleMemoryObject(targetVal); if (sourceVal == null || targetVal == null) return; } final PathEdge<N,D> edge = new PathEdge<N,D>(sourceVal, target, targetVal); final D existingVal = (forceRegister || !enableMergePointChecking || isMergePoint(target)) ? addFunction(edge) : null; if (existingVal != null) { if (existingVal != targetVal) { // Check whether we need to retain this abstraction boolean isEssential; if (memoryManager == null) isEssential = relatedCallSite != null && icfg.isCallStmt(relatedCallSite); else isEssential = memoryManager.isEssentialJoinPoint(targetVal, relatedCallSite); if (!singleJoinPointAbstraction || isEssential) existingVal.addNeighbor(targetVal); } } else { // If this is an inactive abstraction and we have already processed // its active counterpart, we can skip this one D activeVal = targetVal.getActiveCopy(); if (activeVal != targetVal) { PathEdge<N, D> activeEdge = new PathEdge<>(sourceVal, target, activeVal); if (jumpFunctions.containsKey(activeEdge)) return; } scheduleEdgeProcessing(edge); } } /** * Records a jump function. The source statement is implicit. * @see PathEdge */ public D addFunction(PathEdge<N, D> edge) { return jumpFunctions.putIfAbsent(edge, edge.factAtTarget()); } /** * Gets whether the given unit is a merge point in the ICFG * @param target The unit to check * @return True if the given unit is a merge point in the ICFG, otherwise * false */ private boolean isMergePoint(N target) { // Check whether there is more than one possibility to reach this unit List<N> preds = icfg.getPredsOf(target); int size = preds.size(); if (size > 1) if (!icfg.getEndPointsOf(icfg.getMethodOf(target)).contains(target)) return true; // Special case: If this is the first unit in the method, there is an // implicit second way (through method call) if (size == 1) { if (icfg.getStartPointsOf(icfg.getMethodOf(target)).contains(target)) if (!icfg.getEndPointsOf(icfg.getMethodOf(target)).contains(target)) return true; } return false; } protected Set<Pair<N, D>> endSummary(SootMethod m, D d3) { Set<Pair<N, D>> map = endSummary.get(new Pair<SootMethod, D>(m, d3)); return map; } private boolean addEndSummary(SootMethod m, D d1, N eP, D d2) { if (d1 == zeroValue) return true; Set<Pair<N, D>> summaries = endSummary.putIfAbsentElseGet (new Pair<SootMethod, D>(m, d1), new ConcurrentHashSet<Pair<N, D>>()); return summaries.add(new Pair<N, D>(eP, d2)); } protected Map<N, Map<D, D>> incoming(D d1, SootMethod m) { Map<N, Map<D, D>> map = incoming.get(new Pair<SootMethod, D>(m, d1)); return map; } protected boolean addIncoming(SootMethod m, D d3, N n, D d1, D d2) { MyConcurrentHashMap<N, Map<D, D>> summaries = incoming.putIfAbsentElseGet (new Pair<SootMethod, D>(m, d3), new MyConcurrentHashMap<N, Map<D, D>>()); Map<D, D> set = summaries.putIfAbsentElseGet(n, new ConcurrentHashMap<D, D>()); return set.put(d1, d2) == null; } /** * Factory method for this solver's thread-pool executor. */ protected InterruptableExecutor getExecutor() { return new SetPoolExecutor(1, this.numThreads, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); } /** * Returns a String used to identify the output of this solver in debug mode. * Subclasses can overwrite this string to distinguish the output from different solvers. */ protected String getDebugName() { return "FAST IFDS SOLVER"; } public void printStats() { if(logger.isDebugEnabled()) { if(ffCache!=null) ffCache.printStats(); } else { logger.info("No statistics were collected, as DEBUG is disabled."); } } private class PathEdgeProcessingTask implements Runnable { private final PathEdge<N,D> edge; private final boolean solverId; public PathEdgeProcessingTask(PathEdge<N,D> edge, boolean solverId) { this.edge = edge; this.solverId = solverId; } public void run() { if(icfg.isCallStmt(edge.getTarget())) { processCall(edge); } else { //note that some statements, such as "throw" may be //both an exit statement and a "normal" statement if(icfg.isExitStmt(edge.getTarget())) processExit(edge); if(!icfg.getSuccsOf(edge.getTarget()).isEmpty()) processNormalFlow(edge); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((edge == null) ? 0 : edge.hashCode()); result = prime * result + (solverId ? 1231 : 1237); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PathEdgeProcessingTask other = (PathEdgeProcessingTask) obj; if (edge == null) { if (other.edge != null) return false; } else if (!edge.equals(other.edge)) return false; if (solverId != other.solverId) return false; return true; } } /** * Sets whether abstractions on method returns shall be connected to the * respective call abstractions to shortcut paths. * @param setJumpPredecessors True if return abstractions shall be connected * to call abstractions as predecessors, otherwise false. */ public void setJumpPredecessors(boolean setJumpPredecessors) { this.setJumpPredecessors = setJumpPredecessors; } /** * Sets whether only abstractions at merge points shall be recorded to jumpFn. * @param enableMergePointChecking True if only abstractions at merge points * shall be recorded to jumpFn, otherwise false. */ public void setEnableMergePointChecking(boolean enableMergePointChecking) { this.enableMergePointChecking = enableMergePointChecking; } /** * Sets whether only a single abstraction shall be recorded per join point. * In other words, enabling this option disables the recording of neighbors. * @param singleJoinPointAbstraction True to only record a single abstraction * per join point, false to record all incoming neighbors */ public void setSingleJoinPointAbstraction(boolean singleJoinPointAbstraction) { this.singleJoinPointAbstraction = singleJoinPointAbstraction; } /** * Sets the memory manager that shall be used to manage the abstractions * @param memoryManager The memory manager that shall be used to manage the * abstractions */ public void setMemoryManager(IMemoryManager<D, N> memoryManager) { this.memoryManager = memoryManager; } /** * Gets the memory manager used by this solver to reduce memory consumption * @return The memory manager registered with this solver */ public IMemoryManager<D, N> getMemoryManager() { return this.memoryManager; } @Override public void forceTerminate() { this.killFlag = true; this.executor.interrupt(); this.executor.shutdown(); } @Override public boolean isTerminated() { return killFlag || this.executor.isFinished(); } @Override public boolean isKilled() { return killFlag; } @Override public void reset() { this.killFlag = false; } @Override public void addStatusListener(IMemoryBoundedSolverStatusNotification listener) { this.notificationListeners.add(listener); } }
secure-software-engineering/soot-infoflow
src/soot/jimple/infoflow/solver/fastSolver/IFDSSolver.java
Java
lgpl-2.1
29,328
/* $Id$ * $Revision$ * $Date$ * $Author$ * * The Netarchive Suite - Software to harvest and preserve websites * Copyright 2004-2012 The Royal Danish Library, the Danish State and * University Library, the National Library of France and the Austrian * National Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package dk.netarkivet.harvester.indexserver.distribute; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import junit.framework.TestCase; import dk.netarkivet.common.distribute.ChannelID; import dk.netarkivet.common.distribute.JMSConnectionFactory; import dk.netarkivet.common.distribute.JMSConnectionMockupMQ; import dk.netarkivet.common.distribute.RemoteFile; import dk.netarkivet.common.distribute.indexserver.RequestType; import dk.netarkivet.common.exceptions.ArgumentNotValid; import dk.netarkivet.common.utils.FileUtils; import dk.netarkivet.harvester.indexserver.FileBasedCache; import dk.netarkivet.harvester.indexserver.MockupMultiFileBasedCache; import dk.netarkivet.harvester.indexserver.distribute.IndexRequestMessage; import dk.netarkivet.harvester.indexserver.distribute.IndexRequestServer; import dk.netarkivet.testutils.ClassAsserts; import dk.netarkivet.testutils.GenericMessageListener; import dk.netarkivet.testutils.preconfigured.*; public class IndexRequestServerTester extends TestCase { private static final Set<Long> JOB_SET = new HashSet<Long>(Arrays.asList( new Long[]{2L, 4L, 8L, 16L, 32L})); private static final Set<Long> JOB_SET2 = new HashSet<Long>(Arrays.asList( new Long[]{1L, 3L, 7L, 15L, 31L})); IndexRequestServer server; private UseTestRemoteFile ulrf = new UseTestRemoteFile(); private PreventSystemExit pse = new PreventSystemExit(); private PreserveStdStreams pss = new PreserveStdStreams(); private MoveTestFiles mtf = new MoveTestFiles(TestInfo.ORIGINALS_DIR, TestInfo.WORKING_DIR); private MockupJMS mjms = new MockupJMS(); private MockupMultiFileBasedCache mmfbc = new MockupMultiFileBasedCache(); ReloadSettings rs = new ReloadSettings(); public void setUp() { rs.setUp(); ulrf.setUp(); mjms.setUp(); mtf.setUp(); pss.setUp(); pse.setUp(); mmfbc.setUp(); } public void tearDown() { if (server != null) { server.close(); } mmfbc.tearDown(); pse.tearDown(); pss.tearDown(); mtf.tearDown(); mjms.tearDown(); ulrf.tearDown(); rs.tearDown(); } /** * Verify that factory method - does not throw exception - returns non-null * value. */ public void testGetInstance() { assertNotNull("Factory method should return non-null object", IndexRequestServer.getInstance()); server = ClassAsserts.assertSingleton(IndexRequestServer.class); } /** * Verify that visit() - throws exception on null message or message that is * not ok - returns a non-ok message if handler fails with exception or no * handler registered */ public void testVisitFailures() throws InterruptedException { server = IndexRequestServer.getInstance(); mmfbc.setMode(MockupMultiFileBasedCache.Mode.FAILING); server.setHandler(RequestType.CDX, mmfbc); server.start(); try { server.visit((IndexRequestMessage) null); fail("Should throw ArgumentNotValid on null"); } catch (ArgumentNotValid e) { //expected } IndexRequestMessage irMsg = new IndexRequestMessage( RequestType.CDX, JOB_SET, null); JMSConnectionMockupMQ.updateMsgID(irMsg, "irMsg1"); GenericMessageListener listener = new GenericMessageListener(); JMSConnectionMockupMQ conn = (JMSConnectionMockupMQ) JMSConnectionFactory.getInstance(); conn.setListener(irMsg.getReplyTo(), listener); server.visit(irMsg); conn.waitForConcurrentTasksToFinish(); //Give a little time to reply Thread.sleep(200); conn.waitForConcurrentTasksToFinish(); assertEquals("Should have received reply", 1, listener.messagesReceived.size()); assertTrue("Should be the right type", listener.messagesReceived.get(0) instanceof IndexRequestMessage); IndexRequestMessage msg = (IndexRequestMessage) listener.messagesReceived.get(0); assertEquals("Should be the right message", irMsg.getID(), msg.getID()); assertFalse("Should not be OK", msg.isOk()); irMsg = new IndexRequestMessage(RequestType.DEDUP_CRAWL_LOG, JOB_SET, null); JMSConnectionMockupMQ.updateMsgID(irMsg, "irMsg2"); server.visit(irMsg); conn.waitForConcurrentTasksToFinish(); //Give a little time to reply Thread.sleep(200); conn.waitForConcurrentTasksToFinish(); assertEquals("Should have received reply", 2, listener.messagesReceived.size()); assertTrue("Should be the right type", listener.messagesReceived.get(1) instanceof IndexRequestMessage); msg = (IndexRequestMessage) listener.messagesReceived.get(1); assertEquals("Should be the right message", irMsg.getID(), msg.getID()); assertFalse("Should not be OK", msg.isOk()); irMsg = new IndexRequestMessage(RequestType.DEDUP_CRAWL_LOG, JOB_SET, null); JMSConnectionMockupMQ.updateMsgID(irMsg, "irMsg3"); } /** * Verify that visit() - extracts correct info from message - calls the * appropriate handler - encodes the return value appropriately - sends * message back as reply */ public void testVisitNormal() throws IOException, InterruptedException { for (RequestType t : RequestType.values()) { subtestVisitNormal(t); } } private void subtestVisitNormal(RequestType t) throws IOException, InterruptedException { //Start server and set a handler mmfbc.tearDown(); mmfbc.setUp(); mmfbc.setMode(MockupMultiFileBasedCache.Mode.REPLYING); server = IndexRequestServer.getInstance(); server.setHandler(t, mmfbc); server.start(); //A message to visit with IndexRequestMessage irm = new IndexRequestMessage(t, JOB_SET, null); JMSConnectionMockupMQ.updateMsgID(irm, "irm-1"); //Listen for replies GenericMessageListener listener = new GenericMessageListener(); JMSConnectionMockupMQ conn = (JMSConnectionMockupMQ) JMSConnectionFactory.getInstance(); ChannelID channelID = irm.getReplyTo(); conn.setListener(channelID, listener); //Execute visit server.visit(irm); conn.waitForConcurrentTasksToFinish(); //Give a little time to reply Thread.sleep(200); conn.waitForConcurrentTasksToFinish(); assertHandlerCalledWithParameter(mmfbc); //Check reply is sent assertEquals("Should have received reply", 1, listener.messagesReceived.size()); assertTrue("Should be the right type", listener.messagesReceived.get(0) instanceof IndexRequestMessage); IndexRequestMessage msg = (IndexRequestMessage) listener.messagesReceived.get(0); assertEquals("Should be the right message", irm.getID(), msg.getID()); assertTrue("Should be OK", msg.isOk()); //Check contents of file replied File extractFile = File.createTempFile("extr", "act", TestInfo.WORKING_DIR); assertFalse("Message should not indicate directory", msg.isIndexIsStoredInDirectory()); RemoteFile resultFile = msg.getResultFile(); resultFile.copyTo(extractFile); // Order in the JOB_SET and the extract file can't be guaranteed // So we are comparing between the contents of the two sets, not // the order, which is dubious in relation to sets anyway. Set<Long> longFromExtractFile = new HashSet<Long>(); FileInputStream fis = new FileInputStream(extractFile); try { for (int i = 0; i < JOB_SET.size(); i++) { longFromExtractFile.add(Long.valueOf(fis.read())); } assertEquals("End of file expected after this", -1, fis.read()); } catch (IOException e) { fail("Exception thrown: " + e); } finally { if (fis != null) { fis.close(); } } assertTrue( "JOBSET, and the contents of extractfile should be identical", longFromExtractFile.containsAll(JOB_SET)); FileUtils.remove(mmfbc.getCacheFile(JOB_SET)); conn.removeListener(channelID, listener); } /** * Verify that a message sent to the index server queue is dispatched to the * appropriate handler if non-null and ok. Verify that no call is made if * message is null or not ok. */ public void testIndexServerListener() throws InterruptedException { //Start server and set a handler server = IndexRequestServer.getInstance(); server.setHandler(RequestType.CDX, mmfbc); server.start(); Thread.sleep(200); // necessary for the unittest to pass //Send OK message IndexRequestMessage irm = new IndexRequestMessage(RequestType.CDX, JOB_SET, null); JMSConnectionMockupMQ.updateMsgID(irm, "ID-0"); JMSConnectionMockupMQ conn = (JMSConnectionMockupMQ) JMSConnectionFactory.getInstance(); conn.send(irm); conn.waitForConcurrentTasksToFinish(); //Give a little time to reply Thread.sleep(200); conn.waitForConcurrentTasksToFinish(); assertHandlerCalledWithParameter(mmfbc); //Send not-OK message irm = new IndexRequestMessage(RequestType.CDX, JOB_SET, null); JMSConnectionMockupMQ.updateMsgID(irm, "ID-1"); irm.setNotOk("Not OK"); conn.send(irm); conn.waitForConcurrentTasksToFinish(); //Give a little time to reply Thread.sleep(200); conn.waitForConcurrentTasksToFinish(); //Check handler is NOT called assertEquals("Should NOT have called handler again", 1, mmfbc.cacheCalled); } /** * Verify that - setHandler() throws exception on null values - calling * setHandler twice on same type replaces first handler */ public void testSetHandler() throws InterruptedException { server = IndexRequestServer.getInstance(); try { server.setHandler(RequestType.CDX, (FileBasedCache<Set<Long>>)null); fail("should have thrown exception on null value."); } catch (ArgumentNotValid e) { //expected } server = IndexRequestServer.getInstance(); try { server.setHandler(null, mmfbc); fail("should have thrown exception on null value."); } catch (ArgumentNotValid e) { //expected } //Start server and set a handler server = IndexRequestServer.getInstance(); server.setHandler(RequestType.CDX, mmfbc); //A message to visit with IndexRequestMessage irm = new IndexRequestMessage(RequestType.CDX, JOB_SET, null); JMSConnectionMockupMQ.updateMsgID(irm, "dummyID"); //Execute visit server.visit(irm); JMSConnectionMockupMQ conn = (JMSConnectionMockupMQ) JMSConnectionFactory.getInstance(); conn.waitForConcurrentTasksToFinish(); //Give a little time to reply Thread.sleep(200); conn.waitForConcurrentTasksToFinish(); assertHandlerCalledWithParameter(mmfbc); //Set new handler MockupMultiFileBasedCache mjic2 = new MockupMultiFileBasedCache(); mjic2.setUp(); server.setHandler(RequestType.CDX, mjic2); //Execute new visit irm = new IndexRequestMessage(RequestType.CDX, JOB_SET, null); JMSConnectionMockupMQ.updateMsgID(irm, "dummyID"); server.visit(irm); conn.waitForConcurrentTasksToFinish(); //Give a little time to reply Thread.sleep(200); conn.waitForConcurrentTasksToFinish(); //Check the first handler is not called again assertEquals("Handler should NOT be called", 1, mmfbc.cacheCalled); assertHandlerCalledWithParameter(mjic2); mjic2.tearDown(); } public void testUnblocking() throws InterruptedException { mmfbc.setMode(MockupMultiFileBasedCache.Mode.WAITING); server = IndexRequestServer.getInstance(); server.setHandler(RequestType.CDX, mmfbc); server.start(); Thread.sleep(200); // necessary for the unittest to pass //A message to visit with IndexRequestMessage irm = new IndexRequestMessage(RequestType.CDX, JOB_SET, null); //Another message to visit with IndexRequestMessage irm2 = new IndexRequestMessage(RequestType.CDX, JOB_SET2, null); //Listen for replies GenericMessageListener listener = new GenericMessageListener(); JMSConnectionMockupMQ conn = (JMSConnectionMockupMQ) JMSConnectionFactory.getInstance(); conn.setListener(irm.getReplyTo(), listener); //Send both messages conn.send(irm); conn.send(irm2); conn.waitForConcurrentTasksToFinish(); //Give a little time to reply Thread.sleep(200); conn.waitForConcurrentTasksToFinish(); assertEquals("Should have replies from both messages", 2, listener.messagesReceived.size()); //Now, we test that the threads have actually run simultaneously, and //have awaken each other; not just timed out. assertTrue("Threads should have been woken up", mmfbc.woken); } private void assertHandlerCalledWithParameter( MockupMultiFileBasedCache mjic) { //Check the handler is called assertEquals("Handler should be called", 1, mjic.cacheCalled); assertEquals("Handler should be called with right parameter", JOB_SET, mjic.cacheParameter); } }
netarchivesuite/netarchivesuite-svngit-migration
tests/dk/netarkivet/harvester/indexserver/distribute/IndexRequestServerTester.java
Java
lgpl-2.1
15,783
<?php /* | Author: Jean SUZINEAU <Jean.Suzineau@wanadoo.fr> | partly as freelance: http://www.mars42.com | and partly as employee : http://www.batpro.com | Contact: gilles.doutre@batpro.com | | Copyright 2014 Jean SUZINEAU - MARS42 | Copyright 2014 Cabinet Gilles DOUTRE - BATPRO | | This program is free software: you can redistribute it and/or modify | it under the terms of the GNU Lesser General Public License as published by | the Free Software Foundation, either version 3 of the License, or | (at your option) any later version. | | This program is distributed in the hope that it will be useful, | but WITHOUT ANY WARRANTY; without even the implied warranty of | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | GNU Lesser General Public License for more details. | | You should have received a copy of the GNU Lesser General Public License | along with this program. If not, see <http://www.gnu.org/licenses/>. | | | */ require_once dirname(__FILE__).'/modeles/rTULEAP_Project.class.php'; class tTULEAP_Project extends Doctrine_Table { } ?>
jsuzineau/pascal_o_r_mapping
jsWorks/Generateur_de_code/Source/PHP/tTULEAP_Project.class.php
PHP
lgpl-2.1
2,017
package org.cacheonix.impl.net.cluster; import java.util.List; import java.util.Set; import org.cacheonix.impl.net.ClusterNodeAddress; import org.cacheonix.impl.net.processor.ReceiverAddress; import org.cacheonix.impl.net.processor.UUID; import org.cacheonix.impl.net.serializer.Wireable; /** * Marker list. * <p/> * * @author <a href="mailto:simeshev@cacheonix.org">Slava Imeshev</a> */ public interface ClusterView extends Wireable { void setOwner(ClusterNodeAddress owner); boolean isRepresentative(); ClusterNodeAddress getNextElement(); int getSize(); boolean remove(ClusterNodeAddress clusterNodeAddress); void insert(ClusterNodeAddress predecessor, final ClusterNodeAddress address); /** * @return representative. */ ClusterNodeAddress getRepresentative(); /** * @param elementAfter existing element after that to return a element * @throws IllegalStateException if the element is not in the list */ ClusterNodeAddress getNextElement(ClusterNodeAddress elementAfter) throws IllegalStateException; /** * Returns <code>true</code> if this marker list has a majority over te other list that we have common a ancestor * with. In other words, we and the another list a parts of some previous list. * * @param previousView * @return <code>true</code> if this marker list has a majority over other list. */ boolean hasMajorityOver(ClusterView previousView); /** * Returns a copy of the process list. * * @return a copy of the process list. */ List<ClusterNodeAddress> getClusterNodeList(); /** * {@inheritDoc} */ ClusterView copy(); /** * Returns this cluster's unique ID. * * @return this cluster's unique ID. */ UUID getClusterUUID(); /** * Returns <code>true</code> if the cluster view contains active node. * * @param address ClusterNodeAddress to check. * @return <code>true</code> if the cluster view contains active node. */ boolean contains(ClusterNodeAddress address); /** * Returns <code>true</code> if the cluster view contains active node. * * @param address ClusterNodeAddress to check. * @return <code>true</code> if the cluster view contains active node. */ boolean contains(ReceiverAddress address); /** * Calculates a collection of members that have left as compared to the previous view. * * @param previousClusterView previous cluster view * @return a collection of members that have left as compared to this previous view. */ Set<ClusterNodeAddress> calculateNodesLeft(ClusterView previousClusterView); /** * Calculates a collection of members that have joined as compared to the previous view. * * @param previousClusterView previous cluster view * @return a collection of members that have joined as compared to this previous view. */ Set<ClusterNodeAddress> calculateNodesJoined(ClusterView previousClusterView); ClusterNodeAddress getNextElement(ReceiverAddress elementAfter); ClusterNodeAddress greatestMember(); }
cacheonix/cacheonix-core
src/org/cacheonix/impl/net/cluster/ClusterView.java
Java
lgpl-2.1
3,125
/* * Copyright (C) 2003-2005 Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <tnt/contenttype.h> #include <tnt/util.h> #include <iostream> #include <sstream> #include <stdexcept> #include <ctype.h> #include <algorithm> #include <cxxtools/log.h> log_define("tntnet.contenttype") namespace tnt { Contenttype::Contenttype(const std::string& ct) { log_debug("Contenttype <= " << ct); std::istringstream in(ct); in >> *this; if (!in) { std::ostringstream msg; msg << "error 1 parsing content-type-header at " << in.tellg() << ": " << ct; throwRuntimeError(msg.str()); } if (in.get() != std::ios::traits_type::eof()) { std::ostringstream msg; msg << "error 2 parsing content-type-header at " << in.tellg() << ": " << ct; throwRuntimeError(msg.str()); } } Contenttype::return_type Contenttype::onType( const std::string& t, const std::string& s) { log_debug("Contenttype::onType " << t << ", " << s); if (s.empty()) return FAIL; type = t; subtype = s; std::transform(type.begin(), type.end(), type.begin(), ::tolower); std::transform(subtype.begin(), subtype.end(), subtype.begin(), ::tolower); return OK; } Contenttype::return_type Contenttype::onParameter( const std::string& attribute, const std::string& value) { log_debug("Contenttype::onParameter " << attribute << ", " << value); std::string att = attribute; std::transform(att.begin(), att.end(), att.begin(), ::tolower); parameter.insert(parameter_type::value_type(att, value)); if (attribute == "boundary") boundary = value; return OK; } }
deniskin82/tntnet
framework/common/contenttype.cpp
C++
lgpl-2.1
3,043
#include <algorithm> #include <sstream> #include <math.h> #include "device_ds.h" #include "device_ds_stream.h" #include "device_ds_buffer.h" #include "debug.h" #include "utility.h" namespace audiere { static const int DEFAULT_BUFFER_LENGTH = 1000; // one second DSAudioDevice* DSAudioDevice::create(const ParameterList& parameters) { ADR_GUARD("DSAudioDevice::create"); // parse parameters int stream_buffer_length = parameters.getInt("buffer", 0); if (stream_buffer_length <= 0) { stream_buffer_length = DEFAULT_BUFFER_LENGTH; } int min_buffer_length = parameters.getInt("min_buffer_size", 0); min_buffer_length = std::max(1, min_buffer_length); bool global_focus = parameters.getBoolean("global", true); // initialize COM HRESULT rv = CoInitialize(NULL); if (FAILED(rv)) { return 0; } ADR_LOG("COM initialized properly"); // register anonymous window class // don't worry about failure, if it fails, the window creation will fail WNDCLASSA wc; wc.style = 0; wc.lpfnWndProc = DefWindowProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = GetModuleHandle(NULL); wc.hIcon = NULL; wc.hCursor = NULL; wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = "AudiereHiddenWindow"; RegisterClassA(&wc); // create anonymous window HWND anonymous_window = CreateWindowA( "AudiereHiddenWindow", "", WS_POPUP, 0, 0, 0, 0, NULL, NULL, GetModuleHandle(NULL), NULL); if (!anonymous_window) { return NULL; } ADR_LOG("Anonymous window created successfully"); // create the DirectSound object IDirectSound* direct_sound; rv = CoCreateInstance( CLSID_DirectSound, NULL, CLSCTX_INPROC_SERVER, IID_IDirectSound, (void**)&direct_sound); if (FAILED(rv) || !direct_sound) { DestroyWindow(anonymous_window); return 0; } ADR_LOG("Created DS object"); LPGUID guid = NULL; GUID stack_guid; // so we can point 'guid' to an object that won't be destroyed std::string guid_string = parameters.getValue("device_guid", ""); if (!guid_string.empty()) { if (UuidFromStringA((unsigned char*)guid_string.c_str(), &stack_guid) == RPC_S_OK) { guid = &stack_guid; } } // initialize the DirectSound device rv = direct_sound->Initialize(guid); if (FAILED(rv)) { DestroyWindow(anonymous_window); direct_sound->Release(); return 0; } ADR_LOG("Initialized DS object"); // set the cooperative level rv = direct_sound->SetCooperativeLevel(anonymous_window, DSSCL_NORMAL); if (FAILED(rv)) { DestroyWindow(anonymous_window); direct_sound->Release(); return 0; } ADR_LOG("Set cooperative level"); return new DSAudioDevice( global_focus, stream_buffer_length, min_buffer_length, anonymous_window, direct_sound); } DSAudioDevice::DSAudioDevice( bool global_focus, int stream_buffer_length, int min_buffer_length, HWND anonymous_window, IDirectSound* direct_sound) { m_global_focus = global_focus; m_buffer_length = stream_buffer_length; m_min_buffer_length = min_buffer_length; m_anonymous_window = anonymous_window; m_direct_sound = direct_sound; } DSAudioDevice::~DSAudioDevice() { ADR_ASSERT(m_open_streams.empty(), "DirectSound device should not die with open streams"); ADR_ASSERT(m_open_buffers.empty(), "DirectSound device should not die with open buffers"); // shut down DirectSound if (m_direct_sound) { m_direct_sound->Release(); m_direct_sound = NULL; } // if the anonymous window is open, close it if (m_anonymous_window) { DestroyWindow(m_anonymous_window); m_anonymous_window = NULL; } CoUninitialize(); } void DSAudioDevice::update() { ADR_GUARD("DSAudioDevice::update"); { /* Put the critical section in its own scope so we don't hold the lock while sleeping. --MattC */ SYNCHRONIZED(this); // enumerate all open streams StreamList::iterator i = m_open_streams.begin(); while (i != m_open_streams.end()) { DSOutputStream* s = *i++; s->update(); } // enumerate all open buffers BufferList::iterator j = m_open_buffers.begin(); while (j != m_open_buffers.end()) { DSOutputBuffer* b = *j++; b->update(); } } Sleep(50); } OutputStream* DSAudioDevice::openStream(SampleSource* source) { if (!source) { return 0; } ADR_GUARD("DSAudioDevice::openStream"); int channel_count, sample_rate; SampleFormat sample_format; source->getFormat(channel_count, sample_rate, sample_format); const int frame_size = channel_count * GetSampleSize(sample_format); // calculate an ideal buffer size const int buffer_length = sample_rate * m_buffer_length / 1000; // define the wave format WAVEFORMATEX wfx; memset(&wfx, 0, sizeof(wfx)); wfx.wFormatTag = WAVE_FORMAT_PCM; wfx.nChannels = channel_count; wfx.nSamplesPerSec = sample_rate; wfx.nAvgBytesPerSec = sample_rate * frame_size; wfx.nBlockAlign = frame_size; wfx.wBitsPerSample = GetSampleSize(sample_format) * 8; wfx.cbSize = sizeof(wfx); DSBUFFERDESC dsbd; memset(&dsbd, 0, sizeof(dsbd)); dsbd.dwSize = sizeof(dsbd); dsbd.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY; if (m_global_focus) { dsbd.dwFlags |= DSBCAPS_GLOBALFOCUS; } dsbd.dwBufferBytes = frame_size * buffer_length; dsbd.lpwfxFormat = &wfx; // create the DirectSound buffer IDirectSoundBuffer* buffer; HRESULT result = m_direct_sound->CreateSoundBuffer(&dsbd, &buffer, NULL); if (FAILED(result) || !buffer) { return 0; } ADR_LOG("CreateSoundBuffer succeeded"); // now create the output stream DSOutputStream* stream = new DSOutputStream( this, buffer, buffer_length, source); // add it the list of streams and return SYNCHRONIZED(this); m_open_streams.push_back(stream); return stream; } OutputStream* DSAudioDevice::openBuffer( void* samples, int frame_count, int channel_count, int sample_rate, SampleFormat sample_format) { ADR_GUARD("DSAudioDevice::openBuffer"); const int frame_size = channel_count * GetSampleSize(sample_format); WAVEFORMATEX wfx; memset(&wfx, 0, sizeof(wfx)); wfx.wFormatTag = WAVE_FORMAT_PCM; wfx.nChannels = channel_count; wfx.nSamplesPerSec = sample_rate; wfx.nAvgBytesPerSec = sample_rate * frame_size; wfx.nBlockAlign = frame_size; wfx.wBitsPerSample = GetSampleSize(sample_format) * 8; wfx.cbSize = sizeof(wfx); DSBUFFERDESC dsbd; memset(&dsbd, 0, sizeof(dsbd)); dsbd.dwSize = sizeof(dsbd); dsbd.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY | DSBCAPS_STATIC | DSBCAPS_CTRLPOSITIONNOTIFY; if (m_global_focus) { dsbd.dwFlags |= DSBCAPS_GLOBALFOCUS; } const int buffer_frame_count = std::max(m_min_buffer_length, frame_count); const int buffer_size = buffer_frame_count * frame_size; dsbd.dwBufferBytes = buffer_size; dsbd.lpwfxFormat = &wfx; // create the DS buffer IDirectSoundBuffer* buffer; HRESULT result = m_direct_sound->CreateSoundBuffer( &dsbd, &buffer, NULL); if (FAILED(result) || !buffer) { return 0; } ADR_IF_DEBUG { DSBCAPS caps; caps.dwSize = sizeof(caps); result = buffer->GetCaps(&caps); if (FAILED(result)) { buffer->Release(); return 0; } else { std::ostringstream ss; ss << "actual buffer size: " << caps.dwBufferBytes << std::endl << "buffer_size: " << buffer_size; ADR_LOG(ss.str().c_str()); } } void* data; DWORD data_size; result = buffer->Lock(0, buffer_size, &data, &data_size, 0, 0, 0); if (FAILED(result)) { buffer->Release(); return 0; } ADR_IF_DEBUG { std::ostringstream ss; ss << "buffer size: " << buffer_size << std::endl << "data size: " << data_size << std::endl << "frame count: " << frame_count; ADR_LOG(ss.str().c_str()); } const int actual_size = frame_count * frame_size; memcpy(data, samples, actual_size); memset((u8*)data + actual_size, 0, buffer_size - actual_size); buffer->Unlock(data, data_size, 0, 0); DSOutputBuffer* b = new DSOutputBuffer( this, buffer, buffer_frame_count, frame_size); SYNCHRONIZED(this); m_open_buffers.push_back(b); return b; } const char* ADR_CALL DSAudioDevice::getName() { return "directsound"; } void DSAudioDevice::removeStream(DSOutputStream* stream) { SYNCHRONIZED(this); m_open_streams.remove(stream); } void DSAudioDevice::removeBuffer(DSOutputBuffer* buffer) { SYNCHRONIZED(this); m_open_buffers.remove(buffer); } int DSAudioDevice::Volume_AudiereToDirectSound(float volume) { if (volume == 0) { return -10000; } else { double attenuate = 1000 * log(1 / volume); return int(-attenuate); } } int DSAudioDevice::Pan_AudiereToDirectSound(float pan) { if (pan < 0) { return -Pan_AudiereToDirectSound(-pan); } else { return -Volume_AudiereToDirectSound(1 - pan); } } }
nabijaczleweli/audiere
src/device_ds.cpp
C++
lgpl-2.1
9,780
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qcoreapplication.h> #include <qdir.h> QT_BEGIN_NAMESPACE static bool launchWebBrowser(const QUrl &url) { Q_UNUSED(url); qWarning("QDesktopServices::launchWebBrowser not implemented"); return false; } static bool openDocument(const QUrl &file) { Q_UNUSED(file); qWarning("QDesktopServices::openDocument not implemented"); return false; } QString QDesktopServices::storageLocation(StandardLocation type) { if (type == DataLocation) { QString qwsDataHome = QLatin1String(qgetenv("QWS_DATA_HOME")); if (qwsDataHome.isEmpty()) qwsDataHome = QDir::homePath() + QLatin1String("/.qws/share"); qwsDataHome += QLatin1String("/data/") + QCoreApplication::organizationName() + QLatin1Char('/') + QCoreApplication::applicationName(); return qwsDataHome; } if (type == QDesktopServices::CacheLocation) { QString qwsCacheHome = QLatin1String(qgetenv("QWS_CACHE_HOME")); if (qwsCacheHome.isEmpty()) qwsCacheHome = QDir::homePath() + QLatin1String("/.qws/cache/"); qwsCacheHome += QCoreApplication::organizationName() + QLatin1Char('/') + QCoreApplication::applicationName(); return qwsCacheHome; } qWarning("QDesktopServices::storageLocation %d not implemented", type); return QString(); } QString QDesktopServices::displayName(StandardLocation type) { Q_UNUSED(type); qWarning("QDesktopServices::displayName not implemented"); return QString(); } QT_END_NAMESPACE
radekp/qt
src/gui/util/qdesktopservices_qws.cpp
C++
lgpl-2.1
3,069
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2021 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/util/geometry_to_geojson.hpp> #include <mapnik/json/geometry_generator_grammar.hpp> namespace mapnik { namespace util { bool to_geojson(std::string& json, mapnik::geometry::geometry<double> const& geom) { using sink_type = std::back_insert_iterator<std::string>; static const mapnik::json::geometry_generator_grammar<sink_type, mapnik::geometry::geometry<double>> grammar; sink_type sink(json); return boost::spirit::karma::generate(sink, grammar, geom); } } // namespace util } // namespace mapnik
mapnik/mapnik
src/json/mapnik_geometry_to_geojson.cpp
C++
lgpl-2.1
1,544
/** * * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. * * 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, see <http://www.gnu.org/licenses/>. * **/ /** * Implements the CFML Function replacenocase */ package lucee.runtime.functions.string; import lucee.commons.lang.StringUtil; import lucee.runtime.PageContext; import lucee.runtime.exp.FunctionException; import lucee.runtime.exp.PageException; import lucee.runtime.ext.function.BIF; import lucee.runtime.op.Caster; import lucee.runtime.op.Decision; public final class ReplaceNoCase extends BIF { private static final long serialVersionUID = 4991516019845001690L; public static String call(PageContext pc, String str, String sub1, String sub2) throws FunctionException { return _call(pc, str, sub1, sub2, true); } public static String call(PageContext pc, String str, String sub1, String sub2, String scope) throws FunctionException { return _call(pc, str, sub1, sub2, !scope.equalsIgnoreCase("all")); } public static String call(PageContext pc, String input, Object find, String repl, String scope) throws PageException { return _call(pc, input, find, repl, !scope.equalsIgnoreCase("all")); } public static String call(PageContext pc, String input, Object find, String repl) throws PageException { return _call(pc, input, find, repl, true); } private static String _call(PageContext pc, String str, String sub1, String sub2, boolean onlyFirst) throws FunctionException { if (StringUtil.isEmpty(sub1)) throw new FunctionException(pc, "ReplaceNoCase", 2, "sub1", "The string length must be greater than 0"); return StringUtil.replace(str, sub1, sub2, onlyFirst, true); } private static String _call(PageContext pc, String input, Object find, String repl, boolean onlyFirst) throws PageException { if (!Decision.isSimpleValue(find)) throw new FunctionException(pc, "ReplaceNoCase", 2, "sub1", "When passing three parameters or more, the second parameter must be a String."); return _call(pc, input, Caster.toString(find), repl, onlyFirst); } public static String call(PageContext pc, String input, Object struct) throws PageException { if (!Decision.isStruct(struct)) throw new FunctionException(pc, "ReplaceNoCase", 2, "sub1", "When passing only two parameters, the second parameter must be a Struct."); return StringUtil.replaceStruct(input, Caster.toStruct(struct), true); } @Override public Object invoke(PageContext pc, Object[] args) throws PageException { if (args.length == 2) return call(pc, Caster.toString(args[0]), args[1]); if (args.length == 3) return call(pc, Caster.toString(args[0]), args[1], Caster.toString(args[2])); if (args.length == 4) return call(pc, Caster.toString(args[0]), args[1], Caster.toString(args[2]), Caster.toString(args[3])); throw new FunctionException(pc, "Replace", 2, 4, args.length); } }
lucee/Lucee
core/src/main/java/lucee/runtime/functions/string/ReplaceNoCase.java
Java
lgpl-2.1
3,453
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.service.protocol.event; import java.util.*; import net.java.sip.communicator.service.protocol.*; /** * <tt>WhiteboardParticipantEvent</tt>s indicate that a participant in a * whiteboard session has either left or entered the session. * * @author Julien Waechter * @author Emil Ivov */ public class WhiteboardParticipantEvent extends EventObject { /** * Serial version UID. */ private static final long serialVersionUID = 0L; /** * An event id value indicating that this event is about the fact that * the source whiteboard participant has joined the source whiteboard. */ public static final int WHITEBOARD_PARTICIPANT_ADDED = 1; /** * An event id value indicating that this event is about the fact that * the source whiteboard participant has left the source whiteboard. */ public static final int WHITEBOARD_PARTICIPANT_REMOVED = 2; /** * The id indicating the type of this event. */ private int eventID = -1; /** * The whiteboard session participant that this event is about. */ private WhiteboardParticipant sourceWhiteboardParticipant = null; /** * Creates a whiteboard participant event instance indicating that * an event with id <tt>eventID</tt> has happened * to <tt>sourceWhiteboardParticipant</tt> in <tt>sourceWhiteboard</tt> * * @param sourceWhiteboardParticipant the whiteboard participant that this * event is about. * @param source the whiteboard that the source whiteboard participant is * associated with. * @param eventID one of the WHITEBOARD_PARTICIPANT_XXX member ints * indicating the type of this event. */ public WhiteboardParticipantEvent( WhiteboardSession source, WhiteboardParticipant sourceWhiteboardParticipant, int eventID) { super(source); this.sourceWhiteboardParticipant = sourceWhiteboardParticipant; this.eventID = eventID; } /** * Returnst one of the WHITEBOARD_PARTICIPANT_XXX member ints indicating * the type of this event. * @return one of the WHITEBOARD_PARTICIPANT_XXX member ints indicating * the type of this event. */ public int getEventID() { return this.eventID; } /** * Returns the whiteboard session that produced this event. * * @return a reference to the <tt>WhiteboardSession</tt> that produced this * event. */ public WhiteboardSession getSourceWhiteboard() { return (WhiteboardSession)getSource(); } /** * Returns the whiteboard participant that this event is about. * * @return a reference to the <tt>WhiteboardParticipant</tt> instance that * triggered this event. */ public WhiteboardParticipant getSourceWhiteboardParticipant() { return sourceWhiteboardParticipant; } /** * Returns a String representation of this * <tt>WhiteboardParticipantEvent</tt>. * * @return a String representation of this * <tt>WhiteboardParticipantEvent</tt>. */ public String toString() { return "WhiteboardParticipantEvent: ID=" + getEventID() + " source participant=" + getSourceWhiteboardParticipant() + " source whiteboard=" + getSourceWhiteboard(); } }
zhaozw/android-1
src/net/java/sip/communicator/service/protocol/event/WhiteboardParticipantEvent.java
Java
lgpl-2.1
3,611
//$Id: SessionFactoryImplementor.java 8754 2005-12-05 23:36:59Z steveebersole $ package org.hibernate.engine; import java.util.Map; import java.util.Set; import java.sql.Connection; import javax.transaction.TransactionManager; import org.hibernate.HibernateException; import org.hibernate.Interceptor; import org.hibernate.MappingException; import org.hibernate.SessionFactory; import org.hibernate.ConnectionReleaseMode; import org.hibernate.engine.query.QueryPlanCache; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.cache.Cache; import org.hibernate.cache.QueryCache; import org.hibernate.cache.UpdateTimestampsCache; import org.hibernate.cfg.Settings; import org.hibernate.connection.ConnectionProvider; import org.hibernate.dialect.Dialect; import org.hibernate.exception.SQLExceptionConverter; import org.hibernate.id.IdentifierGenerator; import org.hibernate.stat.StatisticsImplementor; import org.hibernate.type.Type; /** * Defines the internal contract between the <tt>SessionFactory</tt> and other parts of * Hibernate such as implementors of <tt>Type</tt>. * * @see org.hibernate.SessionFactory * @see org.hibernate.impl.SessionFactoryImpl * @author Gavin King */ public interface SessionFactoryImplementor extends Mapping, SessionFactory { /** * Get the persister for the named entity */ public EntityPersister getEntityPersister(String entityName) throws MappingException; /** * Get the persister object for a collection role */ public CollectionPersister getCollectionPersister(String role) throws MappingException; /** * Get the SQL <tt>Dialect</tt> */ public Dialect getDialect(); public Interceptor getInterceptor(); public QueryPlanCache getQueryPlanCache(); /** * Get the return types of a query */ public Type[] getReturnTypes(String queryString) throws HibernateException; /** * Get the return aliases of a query */ public String[] getReturnAliases(String queryString) throws HibernateException; /** * Get the connection provider */ public ConnectionProvider getConnectionProvider(); /** * Get the names of all persistent classes that implement/extend the given interface/class */ public String[] getImplementors(String className) throws MappingException; /** * Get a class name, using query language imports */ public String getImportedClassName(String name); /** * Get the JTA transaction manager */ public TransactionManager getTransactionManager(); /** * Get the default query cache */ public QueryCache getQueryCache(); /** * Get a particular named query cache, or the default cache * @param regionName the name of the cache region, or null for the default query cache * @return the existing cache, or a newly created cache if none by that region name */ public QueryCache getQueryCache(String regionName) throws HibernateException; /** * Get the cache of table update timestamps */ public UpdateTimestampsCache getUpdateTimestampsCache(); /** * Statistics SPI */ public StatisticsImplementor getStatisticsImplementor(); public NamedQueryDefinition getNamedQuery(String queryName); public NamedSQLQueryDefinition getNamedSQLQuery(String queryName); public ResultSetMappingDefinition getResultSetMapping(String name); /** * Get the identifier generator for the hierarchy */ public IdentifierGenerator getIdentifierGenerator(String rootEntityName); /** * Get a named second-level cache region */ public Cache getSecondLevelCacheRegion(String regionName); public Map getAllSecondLevelCacheRegions(); /** * Retrieves the SQLExceptionConverter in effect for this SessionFactory. * * @return The SQLExceptionConverter for this SessionFactory. */ public SQLExceptionConverter getSQLExceptionConverter(); public Settings getSettings(); /** * Get a nontransactional "current" session for Hibernate EntityManager */ public org.hibernate.classic.Session openTemporarySession() throws HibernateException; /** * Open a session conforming to the given parameters. Used mainly by * {@link org.hibernate.context.JTASessionContext} for current session processing. * * @param connection The external jdbc connection to use, if one (i.e., optional). * @param flushBeforeCompletionEnabled Should the session be auto-flushed * prior to transaction completion? * @param autoCloseSessionEnabled Should the session be auto-closed after * transaction completion? * @param connectionReleaseMode The release mode for managed jdbc connections. * @return An appropriate session. * @throws HibernateException */ public org.hibernate.classic.Session openSession( final Connection connection, final boolean flushBeforeCompletionEnabled, final boolean autoCloseSessionEnabled, final ConnectionReleaseMode connectionReleaseMode) throws HibernateException; /** * Retrieves a set of all the collection roles in which the given entity * is a participant, as either an index or an element. * * @param entityName The entity name for which to get the collection roles. * @return set of all the collection roles in which the given entityName participates. */ public Set getCollectionRolesByEntityParticipant(String entityName); }
raedle/univis
lib/hibernate-3.1.3/src/org/hibernate/engine/SessionFactoryImplementor.java
Java
lgpl-2.1
5,315
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.spatial.dialect.h2geodb; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import org.geolatte.geom.Geometry; import org.hibernate.type.descriptor.ValueBinder; import org.hibernate.type.descriptor.ValueExtractor; import org.hibernate.type.descriptor.WrapperOptions; import org.hibernate.type.descriptor.java.JavaTypeDescriptor; import org.hibernate.type.descriptor.sql.BasicBinder; import org.hibernate.type.descriptor.sql.BasicExtractor; import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; /** * Descriptor for GeoDB Geometries. * * @author Karel Maesen, Geovise BVBA */ public class GeoDBGeometryTypeDescriptor implements SqlTypeDescriptor { /** * An instance of this Descriptor */ public static final GeoDBGeometryTypeDescriptor INSTANCE = new GeoDBGeometryTypeDescriptor(); @Override public int getSqlType() { return Types.ARRAY; } @Override public boolean canBeRemapped() { return false; } @Override public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) { return new BasicBinder<X>( javaTypeDescriptor, this ) { @Override protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException { final Geometry geometry = getJavaDescriptor().unwrap( value, Geometry.class, options ); st.setBytes( index, GeoDbWkb.to( geometry ) ); } @Override protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) throws SQLException { final Geometry geometry = getJavaDescriptor().unwrap( value, Geometry.class, options ); st.setBytes( name, GeoDbWkb.to( geometry ) ); } }; } @Override public <X> ValueExtractor<X> getExtractor(final JavaTypeDescriptor<X> javaTypeDescriptor) { return new BasicExtractor<X>( javaTypeDescriptor, this ) { @Override protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException { return getJavaDescriptor().wrap( GeoDbWkb.from( rs.getObject( name ) ), options ); } @Override protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException { return getJavaDescriptor().wrap( GeoDbWkb.from( statement.getObject( index ) ), options ); } @Override protected X doExtract(CallableStatement statement, String name, WrapperOptions options) throws SQLException { return getJavaDescriptor().wrap( GeoDbWkb.from( statement.getObject( name ) ), options ); } }; } }
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-spatial/src/main/java/org/hibernate/spatial/dialect/h2geodb/GeoDBGeometryTypeDescriptor.java
Java
lgpl-2.1
2,853
/* * i6engine * Copyright (2016) Daniel Bonrath, Michael Baer, All rights reserved. * * This file is part of i6engine; i6engine is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "i6engine/api/components/MoverInterpolateComponent.h" #include "i6engine/utils/Exceptions.h" #include "i6engine/math/i6eMath.h" #include "i6engine/core/configs/SubsystemConfig.h" #include "i6engine/configs/NetworkChannels.h" #include "i6engine/api/EngineController.h" #include "i6engine/api/FrontendMessageTypes.h" #include "i6engine/api/components/PhysicalStateComponent.h" #include "i6engine/api/configs/ComponentConfig.h" #include "i6engine/api/facades/NetworkFacade.h" #include "i6engine/api/facades/ObjectFacade.h" #include "i6engine/api/objects/GameObject.h" namespace i6e { namespace api { MoverInterpolateComponent::MoverInterpolateComponent(const int64_t id, const attributeMap & params) : MoverComponent(id, params), _keyFrames(), _mode(), _openTime(2), _way(), _totalDistance(0), _currentDist(0), _currentFrame(0), _direction(true), _lock() { _objComponentID = components::MoverInterpolateComponent; loadParams(params); } MoverInterpolateComponent::~MoverInterpolateComponent() { } void MoverInterpolateComponent::addKeyFrame(const Vec3 & position, const Quaternion & rotation) { boost::mutex::scoped_lock l(_lock); _keyFrames.push_back(keyFrame(position, rotation)); } void MoverInterpolateComponent::removeKeyFrame(const uint32_t id) { boost::mutex::scoped_lock l(_lock); _keyFrames.erase(_keyFrames.begin() + int(id)); } void MoverInterpolateComponent::start(Vec3 & startPos) { boost::mutex::scoped_lock l(_lock); _started = true; _moving = true; _currentFrame = 0; _totalDistance = 0; if (_positioning == Positioning::POSITIONING_RELATIVE) { // for absolute, startPos will be ignored because it doesn't make any sense _realStartPos = startPos; } _startTime = EngineController::GetSingleton().getCurrentTime(); if (_keyFrames.size() <= 1) { ISIXE_THROW_FAILURE("MoverComponent", "You need at least two keyFrames."); return; } if (_keyFrames.size() > 0) { if (_positioning == Positioning::POSITIONING_ABSOLUTE) { // for absolute, startPos ist first key frame _realStartPos = _keyFrames[0].first; } if (_direction) { for (size_t i = 0; i < _keyFrames.size() - 1; ++i) { _totalDistance += (_keyFrames[i + 1].first - _keyFrames[i].first).length(); } } else { for (size_t i = _keyFrames.size(); i > 0; --i) { _totalDistance += (_keyFrames[i].first - _keyFrames[i - 1].first).length(); } } } auto psc = _psc.get(); if (_way == Way::LINEAR) { if (_positioning == Positioning::POSITIONING_ABSOLUTE) { psc->setPosition(_realStartPos, 2); } if (_direction) { _lastPos = _keyFrames[0].first; } else { _lastPos = _keyFrames.back().first; } } else if (_way == Way::BEZIER) { if (_positioning == Positioning::POSITIONING_ABSOLUTE) { psc->setPosition(_realStartPos, 2); } if (_direction) { _lastPos = _keyFrames[0].first; } else { _lastPos = _keyFrames.back().first; } } else { ISIXE_THROW_FAILURE("MoverComponent", "Unknown way."); } // resync GOPtr go = getOwnerGO(); if (go != nullptr && go->getGOC(components::NetworkSenderComponent) != nullptr) { attributeMap am = synchronize(); GameMessage::Ptr msg = boost::make_shared<GameMessage>(messages::ComponentMessageType, components::ComMoverResync, core::Method::Update, new components::Component_MoverResync_Update(go->getID(), _id, am), core::Subsystem::Object); EngineController::GetSingletonPtr()->getNetworkFacade()->publish(OBJECT_CHANNEL, msg); } } void MoverInterpolateComponent::getNewPosition(const uint64_t t, Vec3 & newPos, Quaternion & newRot) { uint64_t timeElapsed = t; boost::mutex::scoped_lock l(_lock); double tt = 0; if (_mode == Mode::NSTATE_LOOP) { timeElapsed %= _duration; tt = double(timeElapsed) / _duration; } else if (_mode == Mode::TWOSTATE_TOGGLE) { timeElapsed %= (2 * _duration); tt = 1 - double(timeElapsed - _duration) / _duration; } else if (_mode == Mode::TWOSTATE_OPENTIME) { timeElapsed %= (2 * _duration + _openTime); if (timeElapsed < _duration) { tt = double(timeElapsed) / _duration; } else if (timeElapsed < _duration + _openTime) { tt = 1; } else { tt = 1 - double(timeElapsed - _duration - _openTime) / _duration; } } else if (_mode == Mode::ONCE) { timeElapsed %= _duration; tt = double(timeElapsed) / _duration; if (t > _duration) { stop(); return; } } switch (_way) { case Way::LINEAR: { // TODO (Michael): optimierung, dass nicht immer soviel gerechnet werden muss. vllt etwas precalc? oder distanzvektoren zusaetlzlich speichern? // gesamtstrecke nach dieser Zeit double traveled = _totalDistance * tt; // zwischen diesen 2 Frames ist normalerweise der Punkt keyFrame last; keyFrame next; if (_direction) { last = _keyFrames[_currentFrame]; next = _keyFrames[(_currentFrame + 1) % _keyFrames.size()]; } else { last = _keyFrames[_currentFrame]; if (_currentFrame == 0) { next = _keyFrames.back(); } else { next = _keyFrames[(_currentFrame - 1)]; } } // this part of the distance between these two frames should be traveled double part = (traveled - _currentDist) / (next.first - last.first).length(); if (_currentDist > traveled) { _currentFrame = 0; _currentDist = 0; part = (traveled - _currentDist) / (next.first - last.first).length(); if (_direction) { last = _keyFrames[0]; next = _keyFrames[1]; } else { last = _keyFrames.back(); next = _keyFrames[_keyFrames.size() - 2]; } } // point is further than next frame while (part >= 1) { // go to next frames if (_direction) { _currentFrame++; _currentFrame %= _keyFrames.size(); _currentDist += (next.first - last.first).length(); last = next; next = _keyFrames[(_currentFrame + 1) % _keyFrames.size()]; } else { _currentFrame--; if (_currentFrame == UINT32_MAX) { _currentFrame = _keyFrames.size() - 1; } _currentDist += (next.first - last.first).length(); last = next; if (_currentFrame == 0) { next = _keyFrames.back(); } else { next = _keyFrames[(_currentFrame - 1)]; } } part = (traveled - _currentDist) / (next.first - last.first).length(); } // calc actual Position newPos = last.first + (next.first - last.first) * part; // calc actual rotation double omega = acos(dotProduct(last.second, next.second)); newRot = (last.second * sin((1 - part) * omega) + next.second * sin(part * omega)) / sin(omega); break; } case Way::BEZIER: { double fak1 = 1, fak2 = 1; uint32_t n = uint32_t(_keyFrames.size()); for (uint32_t i = 0; i < n; i++) { fak1 *= (1 - tt); } for (uint32_t i = 0; i < n + 1; ++i) { newPos += _keyFrames[i % n].first * fak1 * fak2 * double(math::binom(n, i)); fak1 /= (1 - tt); fak2 *= tt; } break; } default: { ISIXE_THROW_FAILURE("MoverLinearComponent", "Invalid way."); return; } } /* switch _way */ } void MoverInterpolateComponent::News(const GameMessage::Ptr & msg) { uint16_t type = msg->getSubtype(); if (type == api::components::ComMoverResync) { attributeMap am = static_cast<components::Component_MoverResync_Update *>(msg->getContent())->attMap; stop(); { boost::mutex::scoped_lock l(_lock); _keyFrames.clear(); } loadParams(am); Vec3 x(am, "realCenterPos"); start(x); } else { Component::News(msg); } } void MoverInterpolateComponent::loadParams(const attributeMap & params) { MoverComponent::loadParams(params); parseAttribute<true>(params, "mode", _mode); parseAttribute<true>(params, "way", _way); parseAttribute<true>(params, "direction", _direction); if (_mode == Mode::TWOSTATE_OPENTIME) { parseAttribute<true>(params, "openTime", _openTime); } uint32_t frames; parseAttribute<true>(params, "keyframes", frames); for (uint32_t i = 0; i < frames; ++i) { Vec3 pos; Quaternion rot; parseAttribute<true>(params, std::string("keyframe_") + std::to_string(i) + "_pos", pos); parseAttribute<true>(params, std::string("keyframe_") + std::to_string(i) + "_rot", rot); addKeyFrame(pos, rot); } if (_direction) { _lastPos = _keyFrames[0].first; } else { _lastPos = _keyFrames.back().first; } } attributeMap MoverInterpolateComponent::synchronize() const { attributeMap params = MoverComponent::synchronize(); // general attributes writeAttribute(params, "mode", _mode); writeAttribute(params, "way", _way); writeAttribute(params, "direction", _direction); writeAttribute(params, "keyframes", _keyFrames.size()); for (size_t i = 0; i < _keyFrames.size(); ++i) { writeAttribute(params, std::string("keyframe_") + std::to_string(i) + "_pos", _keyFrames[i].first); writeAttribute(params, std::string("keyframe_") + std::to_string(i) + "_rot", _keyFrames[i].second); } return params; } void MoverInterpolateComponent::reset() { boost::mutex::scoped_lock l(_lock); _currentFrame = 0; _totalDistance = 0; if (_keyFrames.size() <= 1) { ISIXE_THROW_FAILURE("MoverComponent", "You need at least two keyFrames."); return; } auto psc = _psc.get(); if (_way == Way::LINEAR) { psc->setPosition(_realStartPos, 1); _lastPos = _keyFrames[0].first; } else if (_way == Way::BEZIER) { psc->setPosition(_realStartPos, 1); _lastPos = _keyFrames[0].first; } else { ISIXE_THROW_FAILURE("MoverComponent", "Unknown way."); } } std::vector<componentOptions> MoverInterpolateComponent::getComponentOptions() { std::vector<componentOptions> result = MoverComponent::getComponentOptions(); result.push_back(std::make_tuple(AccessState::READWRITE, "Mode", [this]() { return boost::lexical_cast<std::string>(uint16_t(_mode)); }, [this](std::string s) { _mode = Mode(boost::lexical_cast<uint16_t>(s)); return true; }, "MoverInterpolateMode")); result.push_back(std::make_tuple(AccessState::READWRITE, "Way", [this]() { return boost::lexical_cast<std::string>(uint16_t(_way)); }, [this](std::string s) { _way = Way(boost::lexical_cast<uint16_t>(s)); return true; }, "MoverInterpolateWay")); result.push_back(std::make_tuple(AccessState::READONLY, "Num. Keyframes", [this]() { return boost::lexical_cast<std::string>(_keyFrames.size()); }, boost::function<bool(std::string)>(), "Integer")); return result; } } /* namespace api */ } /* namespace i6e */
ClockworkOrigins/i6engine
libs/i6engine-modules/src/api/components/MoverInterpolateComponent.cpp
C++
lgpl-2.1
11,390
///////////////////////////////////////////////////////////////////////// // // © University of Southampton IT Innovation Centre, 2013 // // Copyright in this software belongs to University of Southampton // IT Innovation Centre of Gamma House, Enterprise Road, // Chilworth Science Park, Southampton, SO16 7NS, UK. // // This software may not be used, sold, licensed, transferred, copied // or reproduced in whole or in part in any manner or form or in or // on any media by any person other than in accordance with the terms // of the Licence Agreement supplied with the software, or otherwise // without the prior written consent of the copyright owners. // // This software is distributed WITHOUT ANY WARRANTY, without even the // implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE, except where stated in the Licence Agreement supplied with // the software. // // Created By : Simon Crowle // Created Date : 15-May-2013 // Created for Project : EXPERIMEDIA // ///////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "AMQPConnectionFactory.h" #include "AMQPBasicChannel.h" #include "AMQPBasicSubscriptionService.h" #include <boost/asio.hpp> #include <boost/regex.hpp> #include <exception> using namespace AmqpClient; using namespace std; using namespace boost; using namespace boost::asio; namespace ecc_amqpAPI_impl { AMQPConnectionFactory::AMQPConnectionFactory() : userName( L"guest" ), userPass( L"guest" ), amqpHostIP( L"127.0.0.1" ), amqpPortNumber(5672), connectionEstablished( false ) { } AMQPConnectionFactory::~AMQPConnectionFactory() { } bool AMQPConnectionFactory::setAMQPHostIPAddress( const String& addr ) { bool ipSuccess = false; string source = toNarrow( addr ); smatch matcher; regex ipPattern( "\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" ); if ( regex_search( source, matcher, ipPattern ) ) { amqpHostIP = addr; ipSuccess = true; } else throw L"Failed to parse IP address"; return ipSuccess; } void AMQPConnectionFactory::closeDownConnection() { // Close down the subscription service... amqpSubscriptionService.stopService(); connectionEstablished = false; } bool AMQPConnectionFactory::setAMQPHostPort( const int port ) { if ( port < 1 ) return false; amqpPortNumber = port; return true; } void AMQPConnectionFactory::setRabbitUserLogin( const String& name, const String& password ) { if ( !name.empty() && !password.empty() ) { userName = name; userPass = password; } } wstring AMQPConnectionFactory::getLocalIP() { wstring localIPValue = L"unknown"; io_service io_service; ip::tcp::socket socket( io_service ); string ipVal = socket.remote_endpoint().address().to_string(); if ( !ipVal.empty() ) localIPValue = toWide( ipVal ); return localIPValue; } void AMQPConnectionFactory::connectToAMQPHost() { // Safety first if ( amqpHostIP.empty() ) throw L"AMQP Host IP not correct"; // Try a throw-away connection connectionEstablished = false; if ( createChannelImpl() ) connectionEstablished = true; if ( !connectionEstablished ) throw L"Could not connect to AMQP host"; } /* void AMQPConnectionFactory::connectToAMQPSSLHost() { } void AMQPConnectionFactory::connectToVerifiedAMQPHost( InputStream keystore, String password ) { } */ bool AMQPConnectionFactory::isConnectionValid() { return connectionEstablished; } AMQPBasicChannel::ptr_t AMQPConnectionFactory::createNewChannel() { AMQPBasicChannel::ptr_t newChannel; if ( connectionEstablished ) { Channel::ptr_t channelImpl = createChannelImpl(); // If implementation is OK, encapsulate it if ( channelImpl ) newChannel = AMQPBasicChannel::ptr_t( new AMQPBasicChannel(channelImpl) ); else connectionEstablished = false; // Indicate we don't have the ability to connect } return newChannel; } AMQPBasicSubscriptionService::ptr_t AMQPConnectionFactory::getSubscriptionService() { return AMQPBasicSubscriptionService::ptr_t( &amqpSubscriptionService ); } // Private methods ----------------------------------------------------------- Channel::ptr_t AMQPConnectionFactory::createChannelImpl() { Channel::ptr_t channelImpl; if ( !amqpHostIP.empty() ) { string ip = toNarrow( amqpHostIP ); channelImpl = Channel::Create( ip, amqpPortNumber, toNarrow( userName ), toNarrow( userPass ) ); } return channelImpl; } }
it-innovation/EXPERImonitor
extensions/cppClientAPI/amqpAPI/amqp-Impl/amqp/AMQPConnectionFactory.cpp
C++
lgpl-2.1
4,866
// -------------------------------------------------------------------------------------------------------------------- // Copyright (c) 2009-2010 Esben Carlsen // Forked Copyright (c) 2011-2017 Jaben Cargman and CaptiveAire Systems // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Web; using DynamicImageHandler.Properties; using DynamicImageHandler.Utils; namespace DynamicImageHandler.ImageParameters { public class HiddenImageParameters : SimpleImageParameters { private static readonly Lazy<ISymCryptKey> _currentKey = new Lazy<ISymCryptKey>(() => new SymCryptKey(Settings.Default.ImageParameterKey)); /// <exception cref="MemberAccessException" accessor="get">The <see cref="T:System.Lazy`1" /> instance is initialized to use the default constructor of the type that is being lazily initialized, and permissions to access the constructor are missing.</exception> protected static ISymCryptKey CurrentCryptKey => _currentKey.Value; /// <exception cref="CryptographicException">The value of the <see cref="P:System.Security.Cryptography.SymmetricAlgorithm.Mode" /> parameter is not <see cref="F:System.Security.Cryptography.CipherMode.ECB" />, <see cref="F:System.Security.Cryptography.CipherMode.CBC" />, or <see cref="F:System.Security.Cryptography.CipherMode.CFB" />.</exception> public static string GetImageClassUrl(string parameters) { var paramClass = new HiddenImageParameters(); paramClass.Parameters.AddRange(parameters.ParseParametersAsKeyValuePairs()); // get the encoded parameters string encodedParams = paramClass.CreateEncodedParameterString(); // url encode and return... return $"id={HttpUtility.UrlEncode(encodedParams)}"; } /// <exception cref="CryptographicException">The value of the <see cref="P:System.Security.Cryptography.SymmetricAlgorithm.Mode" /> parameter is not <see cref="F:System.Security.Cryptography.CipherMode.ECB" />, <see cref="F:System.Security.Cryptography.CipherMode.CBC" />, or <see cref="F:System.Security.Cryptography.CipherMode.CFB" />.</exception> public override void AppendRawParameters(IEnumerable<KeyValuePair<string, string>> values) { if (values == null) { throw new ArgumentNullException("values"); } var kv = values.FirstOrDefault(s => s.Key == "id"); if (kv.IsDefault() || string.IsNullOrWhiteSpace(kv.Value)) { return; } this.LoadEncodedParameterString(kv.Value); } /// <exception cref="CryptographicException">The value of the <see cref="P:System.Security.Cryptography.SymmetricAlgorithm.Mode" /> parameter is not <see cref="F:System.Security.Cryptography.CipherMode.ECB" />, <see cref="F:System.Security.Cryptography.CipherMode.CBC" />, or <see cref="F:System.Security.Cryptography.CipherMode.CFB" />.</exception> public virtual string CreateEncodedParameterString() { return SymCrypt.Encrypt(this.ParametersAsString(), CurrentCryptKey); } /// <exception cref="CryptographicException">The value of the <see cref="P:System.Security.Cryptography.SymmetricAlgorithm.Mode" /> parameter is not <see cref="F:System.Security.Cryptography.CipherMode.ECB" />, <see cref="F:System.Security.Cryptography.CipherMode.CBC" />, or <see cref="F:System.Security.Cryptography.CipherMode.CFB" />.</exception> protected virtual void LoadEncodedParameterString(string paramString) { string decrypted = SymCrypt.Decrypt(paramString, CurrentCryptKey); this.Parameters.AddRange(decrypted.ParseParametersAsKeyValuePairs()); } } }
CaptiveAire/Dynamic-Image-Handler
DynamicImageHandler/ImageParameters/HiddenImageParameters.cs
C#
lgpl-2.1
4,725
@app.route('/job/<name>') def results(name): job = saliweb.frontend.get_completed_job(name, flask.request.args.get('passwd')) # Determine whether the job completed successfully if os.path.exists(job.get_path('output.pdb')): template = 'results_ok.html' else: template = 'results_failed.html' return saliweb.frontend.render_results_template(template, job=job)
salilab/saliweb
examples/frontend-results.py
Python
lgpl-2.1
440
/* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. You should have received * a copy of the GNU Lesser General Public License along with this library; * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA. */ import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.TargetDataLine; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import org.ccnx.ccn.io.content.ContentEncodingException; import org.ccnx.ccn.protocol.MalformedContentNameStringException; /** * front-end(UI) * GUI for communicate user */ public class CCNVoice extends JFrame implements CCNServiceCallback { private static final long serialVersionUID = -328096355073388654L; public ByteArrayOutputStream out; private static CCNService ccnService = null; public String ChattingRoomName = "ccnx:/"; private boolean isRecorded = false; private boolean isPlayed = false; private String AudioData = null; private AudioFormat format = getFormat(); private String charsetName = "UTF-16"; private int BufferSize = 1024; private DataLine.Info TargetInfo; private static TargetDataLine m_TargetDataLine; // swing based GUI component // based panel private JPanel ConfigPanel = new JPanel(new FlowLayout()); // Forr // congifuring // room name private JPanel ChattingPanel = new JPanel(new BorderLayout()); // For // Message // List private JPanel ControlPanel = new JPanel(new GridLayout(0, 3)); // For // record, // play, // send Btn private JTextField InputRoomName = new JTextField(15); // button image icon private URL imageURL = getClass().getResource("/img/KHU.jpeg"); private URL recordURL = getClass().getResource("/img/record.png"); private URL playURL = getClass().getResource("/img/play.png"); private URL stopURL = getClass().getResource("/img/stop.png"); public ImageIcon imageIcon; private ImageIcon recordIcon; private ImageIcon playIcon; private ImageIcon stopIcon; private JButton okBtn; private JButton recordBtn; private JButton playBtn; private JButton sendBtn; private JTextArea MessageArea = null; // constructor of CCNVoice object public CCNVoice() throws MalformedContentNameStringException { ccnService = new CCNService(this); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { stop(); } }); // the window size of application // window size : maximize or customize your device this.setExtendedState(JFrame.MAXIMIZED_BOTH); setVisible(true); setTitle("[CCN Voice]"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); imageIcon = new ImageIcon(imageURL); recordIcon = new ImageIcon(recordURL); stopIcon = new ImageIcon(stopURL); playIcon = new ImageIcon(playURL); okBtn = new JButton("OK"); sendBtn = new JButton(" Send "); recordBtn = new JButton(recordIcon); playBtn = new JButton(playIcon); MessageArea = new JTextArea(); // add each components JLabel icon = new JLabel(imageIcon); JLabel RoomInfo = new JLabel("Room Name"); ConfigPanel.setBackground(Color.WHITE); ConfigPanel.add(RoomInfo); ConfigPanel.add(InputRoomName); ConfigPanel.add(okBtn); ConfigPanel.add(icon); ConfigPanel.setVisible(true); getContentPane().add(ConfigPanel); // button listener okBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ChattingRoomName += InputRoomName.getText(); if (ChattingRoomName != "ccnx:/") { // When RoomName is normal } else { // When RoomName is abnormal ChattingRoomName = "DefaultRoomName"; } try { ccnService.setNamespace(ChattingRoomName); } catch (MalformedContentNameStringException e1) { e1.printStackTrace(); } getContentPane().removeAll(); getContentPane().add(ChattingPanel); revalidate(); repaint(); // start CCN based networking service(back-end) ccnService.start(); } }); recordBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (isRecorded) { // recordBtn.setText("Record"); recordBtn.setIcon(recordIcon); isRecorded = false; } else { recordAudio(); // recordBtn.setText(" Stop "); recordBtn.setIcon(stopIcon); } } }); sendBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sendAudioData(); } }); playBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(isPlayed) { // playBtn.setText("Play"); playBtn.setIcon(playIcon); isPlayed = false; } else { playAudio(); // playBtn.setText("Stop"); playBtn.setIcon(stopIcon); } } }); MessageArea.setBackground(Color.LIGHT_GRAY); MessageArea.setEditable(false); MessageArea.setLineWrap(true); // set GUI panel ControlPanel.setPreferredSize(new Dimension(50,100)); ControlPanel.add(recordBtn); ControlPanel.add(playBtn); ControlPanel.add(sendBtn); ChattingPanel.add(new JScrollPane(MessageArea), BorderLayout.CENTER); ChattingPanel.add(ControlPanel, BorderLayout.SOUTH); revalidate(); repaint(); setVisible(true); TargetInfo = new DataLine.Info(TargetDataLine.class, format); try { m_TargetDataLine = (TargetDataLine) AudioSystem.getLine(TargetInfo); } catch (LineUnavailableException e1) { e1.printStackTrace(); } } // stop the application protected void stop() { try { ccnService.shutdown(); } catch (IOException e) { e.printStackTrace(); } } // record a audio data(PCM) private void recordAudio() { try { m_TargetDataLine.open(format); m_TargetDataLine.start(); Runnable runner = new Runnable() { byte buffer[] = new byte[BufferSize]; public void run() { out = new ByteArrayOutputStream(); isRecorded = true; try { while (isRecorded) { int count = m_TargetDataLine.read(buffer, 0, buffer.length); if(count > 0) { out.write(buffer, 0, count); } } AudioData = new String(out.toByteArray(), charsetName); out.close(); m_TargetDataLine.close(); } catch (IOException e) { System.err.println("I/O problems: " + e); } } }; Thread captureThread = new Thread(runner); captureThread.start(); } catch (LineUnavailableException e) { System.err.println("Line unavailable: " + e); } } // play a audio data(received audio and sended audio) private void playAudio() { try { byte[] audio = null; isPlayed = true; try { audio = AudioData.getBytes(charsetName); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } InputStream input = new ByteArrayInputStream(audio); final AudioInputStream ais = new AudioInputStream(input, format, audio.length / format.getFrameSize()); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); final SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); line.open(format); line.start(); Runnable runner = new Runnable() { byte buffer[] = new byte[BufferSize]; public void run() { try { int count; while ((count = ais.read(buffer, 0, buffer.length)) != -1) { if (count > 0) { line.write(buffer, 0, count); } } line.drain(); line.close(); setPlayBtnText(); } catch (IOException e) { System.err.println("I/O problems: " + e); } } }; Thread playThread = new Thread(runner); playThread.start(); } catch (LineUnavailableException e) { System.err.println("Line unavailable: " + e); } } // play the parameter data public void playAudio(byte[] data) { try { InputStream input = new ByteArrayInputStream(data); final AudioFormat format = getFormat(); final AudioInputStream ais = new AudioInputStream(input, format, data.length / format.getFrameSize()); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); final SourceDataLine line = (SourceDataLine) AudioSystem .getLine(info); line.open(format); line.start(); Runnable runner = new Runnable() { byte buffer[] = new byte[BufferSize]; public void run() { try { int count; while ((count = ais.read(buffer, 0, buffer.length)) != -1) { if (count > 0) { line.write(buffer, 0, count); } } line.drain(); line.close(); } catch (IOException e) { System.err.println("I/O problems: " + e); } } }; Thread playThread = new Thread(runner); playThread.start(); } catch (LineUnavailableException e) { System.err.println("Line unavailable: " + e); } } // send the audio data to back-end(network service part) private void sendAudioData() { try { ccnService.sendMessage(AudioData); } catch (ContentEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Send data to ccn, excepting audio data for example, session info, meta * data * * @param payload */ public void sendData(byte[] payload) { // TODO send data excepting audio } // information about recording audio private AudioFormat getFormat() { float sampleRate = 8000; int sampleSizeInBits = 8; int channels = 1; boolean signed = true; boolean bigEndian = false; return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian); } public static void main(String[] args) { try { System.out.println("[CCNVoice]main"); new CCNVoice(); } catch (MalformedContentNameStringException e) { System.err.println("Not a valid ccn URI: " + args[0] + ": " + e.getMessage()); e.printStackTrace(); } } @Override public void receiveData(String data) { AudioData = data; try { playAudio(AudioData.getBytes(charsetName)); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void receiveMessage(String msg) { MessageArea.insert(msg + "\n", MessageArea.getText().length()); MessageArea.setCaretPosition(MessageArea.getText().length()); } public void setPlayBtnText() { // playBtn.setText("Play"); playBtn.setIcon(playIcon); isPlayed = false; } }
MobileConvergenceLab/icPhone-phoneapp
CCNVoice/src/CCNVoice.java
Java
lgpl-2.1
11,864
#! /usr/bin/python # -*- coding: utf-8 -*- #----------------------------------------------------------------------------- # Name: Generic.py # Purpose: # Author: Fabien Marteau <fabien.marteau@armadeus.com> # Created: 21/05/2008 #----------------------------------------------------------------------------- # Copyright (2008) Armadeus Systems # # 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. # #----------------------------------------------------------------------------- # Revision list : # # Date By Changes # #----------------------------------------------------------------------------- __doc__ = "" __version__ = "1.0.0" __author__ = "Fabien Marteau <fabien.marteau@armadeus.com>" import re from periphondemand.bin.utils.wrapperxml import WrapperXml from periphondemand.bin.utils.error import Error DESTINATION = ["fpga","driver","both"] PUBLIC = ["true","false"] class Generic(WrapperXml): """ Manage generic instance value """ def __init__(self,parent,**keys): """ init Generic, __init__(self,parent,node) __init__(self,parent,nodestring) __init__(self,parent,name) """ self.parent=parent if "node" in keys: self.__initnode(keys["node"]) elif "nodestring" in keys: self.__initnodestring(keys["nodestring"]) elif "name" in keys: self.__initname(keys["name"]) else: raise Error("Keys unknown in Generic init()",0) def __initnode(self,node): WrapperXml.__init__(self,node=node) def __initnodestring(self,nodestring): WrapperXml.__init__(self,nodestring=nodestring) def __initname(self,name): WrapperXml.__init__(self,nodename="generic") self.setName(name) def getOp(self): return self.getAttributeValue("op") def setOp(self,op): self.setAttribute("op",op) def getTarget(self): return self.getAttributeValue("target") def setTarget(self,target): self.setAttribute("target",target) def isPublic(self): if self.getAttributeValue("public")=="true": return "true" else: return "false" def setPublic(self,public): public = public.lower() if not public in PUBLIC: raise Error("Public value "+str(public)+" wrong") self.setAttribute("public",public) def getType(self): the_type = self.getAttributeValue("type") if the_type == None: raise Error("Generic "+self.getName()+\ " description malformed, type must be defined",0) else: return the_type def setType(self,type): self.setAttribute("type",type) def getMatch(self): try: return self.getAttributeValue("match").encode("utf-8") except AttributeError: return None def setMatch(self,match): self.setAttribute("match",match) def getValue(self): """ return the generic value """ component = self.getParent() if self.getOp() == None: return self.getAttributeValue("value") else: target = self.getTarget().split(".") if self.getOp() == "realsizeof": # return the number of connected pin return str(int(component.getInterface(target[0]).getPort(target[1]).getMaxPinNum())+1) else: raise Error("Operator unknown "+self.getOp(),1) def setValue(self,value): if self.getMatch() == None: self.setAttribute("value",value) elif re.compile(self.getMatch()).match(value): self.setAttribute("value",value) else: raise Error("Value doesn't match for attribute "+str(value),0) def getDestination(self): """ return the generic destination (fpga,driver or both) """ return self.getAttributeValue("destination") def setDestination(self,destination): destination = destination.lower() if not destination in DESTINATION: raise Error("Destination value "+str(destination)+\ " unknown") self.setAttribute("destination",destination)
magyarm/periphondemand-code
src/bin/core/generic.py
Python
lgpl-2.1
4,911
/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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. * * Copyright (c) 2001 - 2013 Object Refinery Ltd, Pentaho Corporation and Contributors.. All rights reserved. */ package org.pentaho.reporting.engine.classic.core.style; import org.pentaho.reporting.engine.classic.core.util.ObjectStreamResolveException; import java.io.ObjectStreamException; import java.io.Serializable; /** * Creation-Date: 24.11.2005, 17:08:01 * * @author Thomas Morgner */ public class VerticalTextAlign implements Serializable { public static final VerticalTextAlign USE_SCRIPT = new VerticalTextAlign( "use-script" ); public static final VerticalTextAlign BASELINE = new VerticalTextAlign( "baseline" ); public static final VerticalTextAlign SUB = new VerticalTextAlign( "sub" ); public static final VerticalTextAlign SUPER = new VerticalTextAlign( "super" ); public static final VerticalTextAlign TOP = new VerticalTextAlign( "top" ); public static final VerticalTextAlign TEXT_TOP = new VerticalTextAlign( "text-top" ); public static final VerticalTextAlign CENTRAL = new VerticalTextAlign( "central" ); public static final VerticalTextAlign MIDDLE = new VerticalTextAlign( "middle" ); public static final VerticalTextAlign BOTTOM = new VerticalTextAlign( "bottom" ); public static final VerticalTextAlign TEXT_BOTTOM = new VerticalTextAlign( "text-bottom" ); private String id; private VerticalTextAlign( final String id ) { this.id = id; } /** * Replaces the automatically generated instance with one of the enumeration instances. * * @return the resolved element * @throws java.io.ObjectStreamException * if the element could not be resolved. */ protected Object readResolve() throws ObjectStreamException { if ( this.id.equals( VerticalTextAlign.USE_SCRIPT.id ) ) { return VerticalTextAlign.USE_SCRIPT; } if ( this.id.equals( VerticalTextAlign.BASELINE.id ) ) { return VerticalTextAlign.BASELINE; } if ( this.id.equals( VerticalTextAlign.SUPER.id ) ) { return VerticalTextAlign.SUPER; } if ( this.id.equals( VerticalTextAlign.SUB.id ) ) { return VerticalTextAlign.SUB; } if ( this.id.equals( VerticalTextAlign.TOP.id ) ) { return VerticalTextAlign.TOP; } if ( this.id.equals( VerticalTextAlign.TEXT_TOP.id ) ) { return VerticalTextAlign.TEXT_TOP; } if ( this.id.equals( VerticalTextAlign.BOTTOM.id ) ) { return VerticalTextAlign.BOTTOM; } if ( this.id.equals( VerticalTextAlign.TEXT_BOTTOM.id ) ) { return VerticalTextAlign.TEXT_BOTTOM; } if ( this.id.equals( VerticalTextAlign.CENTRAL.id ) ) { return VerticalTextAlign.CENTRAL; } if ( this.id.equals( VerticalTextAlign.MIDDLE.id ) ) { return VerticalTextAlign.MIDDLE; } // unknown element alignment... throw new ObjectStreamResolveException(); } public static VerticalTextAlign valueOf( String id ) { if ( id == null ) { return null; } if ( id.equals( VerticalTextAlign.USE_SCRIPT.id ) ) { return VerticalTextAlign.USE_SCRIPT; } if ( id.equals( VerticalTextAlign.BASELINE.id ) ) { return VerticalTextAlign.BASELINE; } if ( id.equals( VerticalTextAlign.SUPER.id ) ) { return VerticalTextAlign.SUPER; } if ( id.equals( VerticalTextAlign.SUB.id ) ) { return VerticalTextAlign.SUB; } if ( id.equals( VerticalTextAlign.TOP.id ) ) { return VerticalTextAlign.TOP; } if ( id.equals( VerticalTextAlign.TEXT_TOP.id ) ) { return VerticalTextAlign.TEXT_TOP; } if ( id.equals( VerticalTextAlign.BOTTOM.id ) ) { return VerticalTextAlign.BOTTOM; } if ( id.equals( VerticalTextAlign.TEXT_BOTTOM.id ) ) { return VerticalTextAlign.TEXT_BOTTOM; } if ( id.equals( VerticalTextAlign.CENTRAL.id ) ) { return VerticalTextAlign.CENTRAL; } if ( id.equals( VerticalTextAlign.MIDDLE.id ) ) { return VerticalTextAlign.MIDDLE; } return null; } public boolean equals( final Object o ) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } final VerticalTextAlign that = (VerticalTextAlign) o; if ( !id.equals( that.id ) ) { return false; } return true; } public int hashCode() { return id.hashCode(); } /** * Returns a string representation of the object. In general, the <code>toString</code> method returns a string that * "textually represents" this object. The result should be a concise but informative representation that is easy for * a person to read. It is recommended that all subclasses override this method. * <p/> * The <code>toString</code> method for class <code>Object</code> returns a string consisting of the name of the class * of which the object is an instance, the at-sign character `<code>@</code>', and the unsigned hexadecimal * representation of the hash code of the object. In other words, this method returns a string equal to the value of: * <blockquote> * * <pre> * getClass().getName() + '@' + Integer.toHexString( hashCode() ) * </pre> * * </blockquote> * * @return a string representation of the object. */ public String toString() { return id; } }
EgorZhuk/pentaho-reporting
engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/style/VerticalTextAlign.java
Java
lgpl-2.1
6,057
////////////////////////////////////////////////////////////// // File of helper functions for primitives and world. var helpers = {}; (function() { var format = function(formatStr, args, functionName) { var throwFormatError = function() { functionName = functionName || '#<function>'; var matches = formatStr.match(new RegExp('~[sSaA]', 'g')); var expectedNumberOfArgs = matches == null ? 0 : matches.length; var errorStrBuffer = [functionName + ': format string requires ' + expectedNumberOfArgs + ' arguments, but given ' + args.length + '; arguments were:', types.toWrittenString(formatStr)]; for (var i = 0; i < args.length; i++) { errorStrBuffer.push( types.toWrittenString(args[i]) ); } raise( types.incompleteExn(types.exnFailContract, errorStrBuffer.join(' '), []) ); } var pattern = new RegExp("~[sSaAn%~]", "g"); var buffer = args.slice(0);; function f(s) { if (s == "~~") { return "~"; } else if (s == '~n' || s == '~%') { return "\n"; } else if (s == '~s' || s == "~S") { if (buffer.length == 0) { throwFormatError(); } return types.toWrittenString(buffer.shift()); } else if (s == '~a' || s == "~A") { if (buffer.length == 0) { throwFormatError(); } return types.toDisplayedString(buffer.shift()); } else { throw types.internalError('format: string.replace matched invalid regexp', false); } } var result = formatStr.replace(pattern, f); if (buffer.length > 0) { throwFormatError(); } return result; }; // forEachK: CPS( array CPS(array -> void) (error -> void) -> void ) // Iterates through an array and applies f to each element using CPS // If an error is thrown, it catches the error and calls f_error on it var forEachK = function(a, f, f_error, k) { var forEachHelp = function(i) { if( i >= a.length ) { if (k) { k(); } return; } try { f(a[i], function() { forEachHelp(i+1); }); } catch (e) { f_error(e); } }; forEachHelp(0); }; // reportError: (or exception string) -> void // Reports an error to the user, either at the console // if the console exists, or as alerts otherwise. var reportError = function(e) { var reporter; if (typeof(console) != 'undefined' && typeof(console.log) != 'undefined') { reporter = (function(x) { console.log(x); }); } else { reporter = (function(x) { alert(x); }); } if (typeof e == 'string') { reporter(e); } else if ( types.isSchemeError(e) ) { if ( types.isExn(e.val) ) { reporter( ''+types.exnMessage(e.val) ); } else { reporter(e.val); } } else if (e.message) { reporter(e.message); } else { reporter(e.toString()); } // if (plt.Kernel.lastLoc) { // var loc = plt.Kernel.lastLoc; // if (typeof(loc) === 'string') { // reporter("Error was raised around " + loc); // } else if (typeof(loc) !== 'undefined' && // typeof(loc.line) !== 'undefined') { // reporter("Error was raised around: " // + plt.Kernel.locToString(loc)); // } // } }; var raise = function(v) { throw types.schemeError(v); }; var procArityContains = function(n) { return function(proc) { var singleCase = function(aCase) { if ( aCase instanceof types.ContinuationClosureValue ) { return true; } return (aCase.numParams == n || (aCase.isRest && aCase.numParams <= n)); }; var cases = []; if ( proc instanceof types.ContinuationClosureValue || proc instanceof types.ClosureValue || proc instanceof types.PrimProc ) { return singleCase(proc); } else if (proc instanceof types.CasePrimitive) { cases = proc.cases; } else if (proc instanceof types.CaseLambdaValue) { cases = proc.closures; } for (var i = 0; i < cases.length; i++) { if ( singleCase(cases[i]) ) return true; } return false; } }; var throwUncoloredCheckError = function(aState, details, pos, args){ var errorFormatStr; if (args && args.length > 1) { var errorFormatStrBuffer = ['~a: expects type ~a as ~a arguments, but given: ~s; other arguments were:']; for (var i = 0; i < args.length; i++) { if ( i != pos-1 ) { errorFormatStrBuffer.push( types.toWrittenString(args[i]) ); } } errorFormatStr = errorFormatStrBuffer.join(' '); raise( types.incompleteExn(types.exnFailContract, helpers.format(errorFormatStr, [details.functionName, details.typeName, details.ordinalPosition, details.actualValue]), []) ); } else { errorFormatStr = "~a: expects argument of type ~a, but given: ~s"; raise( types.incompleteExn(types.exnFailContract, helpers.format(errorFormatStr, [details.functionName, details.typeName , details.actualValue]), [])); } }; var throwColoredCheckError = function(aState, details, pos, args){ var positionStack = state.captureCurrentContinuationMarks(aState).ref('moby-application-position-key'); var locationList = positionStack[positionStack.length - 1]; //locations -> array var getArgColoredParts = function(locations) { var coloredParts = []; var locs = locations; var i; //getting the actual arguments from args var actualArgs = []; for(i = 0; i < args.length; i++) { if((! (state.isState(args[i]))) && (!((args[i].name !== undefined) && args[i].name === ""))) { actualArgs.push(args[i]); } } window.wtf = args[2]; for(i = 0; i < actualArgs.length; i++){ if(! (locs.isEmpty())){ if(i != (pos -1)) { //coloredParts.push(new types.ColoredPart(types.toWrittenString(actualArgs[i])+(i < actualArgs.length -1 ? " " : ""), locs.first()));\ coloredParts.push(new types.ColoredPart(types.toWrittenString(actualArgs[i])+" ", locs.first())); } locs = locs.rest(); } } if(coloredParts.length > 0){ //removing the last space var lastEltText = coloredParts[coloredParts.length-1].text; lastEltText = lastEltText.substring(0, lastEltText.length - 1); coloredParts[coloredParts.length - 1] = new types.ColoredPart(lastEltText, coloredParts[coloredParts.length-1].location); } return coloredParts; } // listRef for locationList. var getLocation = function(pos) { var locs = locationList; var i; for(i = 0; i < pos; i++){ locs = locs.rest(); } return locs.first(); } var typeName = details.typeName+''; var fL = typeName.substring(0,1); //first letter of type name if(args) { var argColoredParts = getArgColoredParts(locationList.rest()); if(argColoredParts.length > 0){ raise( types.incompleteExn(types.exnFailContract, new types.Message([ new types.ColoredPart(details.functionName, locationList.first()), ": expects ", ((fL === "a" || fL === "e" || fL === "i" || fL === "o" || fL === "u") ? "an " : "a "), typeName, " as ", details.ordinalPosition, " argument, but given: ", new types.ColoredPart(types.toWrittenString(details.actualValue), getLocation(pos)), "; other arguments were: ", new types.GradientPart(argColoredParts) ]), []) ); } } raise( types.incompleteExn(types.exnFailContract, new types.Message([ new types.ColoredPart(details.functionName, locationList.first()), ": expects ", ((fL === "a" || fL === "e" || fL === "i" || fL === "o" || fL === "u") ? "an " : "a "), typeName, " as ", details.ordinalPosition, " argument, but given: ", new types.ColoredPart(types.toWrittenString(details.actualValue), getLocation(pos)) ]), []) ); }; var throwCheckError = function(aState, details, pos, args) { if(aState instanceof state.State){ //if it's defined and a State, can inspect position stack var positionStack = state.captureCurrentContinuationMarks(aState).ref('moby-application-position-key'); //if the positionStack at the correct position is defined, we can throw a colored error if (positionStack[positionStack.length - 1] !== undefined) { throwColoredCheckError(aState, details, pos, args); } } //otherwise, throw an uncolored error throwUncoloredCheckError(aState, details, pos, args); }; var check = function(aState, x, f, functionName, typeName, position, args) { if ( !f(x) ) { throwCheckError(aState, { functionName: functionName, typeName: typeName, ordinalPosition: helpers.ordinalize(position), actualValue: x }, position, args); } }; var checkVarArity = function(aState, x, f, functionName, typeName, position, args) { //check to ensure last thing is an array if(args.length > 0 && (args[args.length - 1] instanceof Array)) { var flattenedArgs = []; var i; for(i = 0; i < (args.length - 1); i++) { flattenedArgs.push(args[i]); } //the angry variable names are because flattenedArgs = flattenedArgs.concat(args[args.length - 1]) doesn't work var wtf1 = flattenedArgs; var wtf2 = args[args.length -1]; var passOn = wtf1.concat(wtf2); check(aState, x, f, functionName, typeName, position, passOn); } else { check(aState, x, f, functionName, typeName, position, args); } }; var isList = function(x) { var tortoise, hare; tortoise = hare = x; if (hare === types.EMPTY) { return true; } while (true) { if (!(types.isPair(hare))) { return false; } if (types.isPair(tortoise)) { // optimization to get amortized linear time isList. if (tortoise._isList === true) { return true; } tortoise = tortoise.rest(); } hare = hare.rest(); if (types.isPair(hare)) { if (hare._isList) { tortoise._isList = true; return true; } hare = hare.rest(); if (types.isPair(hare) && hare._isList) { tortoise._isList = true; return true; } } if (hare === types.EMPTY) { // optimization to get amortized linear time isList. tortoise._isList = true; return true; } if (tortoise === hare) { return false; } } }; var isListOf = function(x, f) { if (! isList(x)) { return false; } while (types.isPair(x)) { if (! f(x.first())) { return false; } x = x.rest(); } return (x === types.EMPTY); }; var checkListOf = function(aState, lst, f, functionName, typeName, position, args) { if ( !isListOf(lst, f) ) { helpers.throwCheckError(aState, {functionName: functionName, typeName: 'list of ' + typeName, ordinalPosition: helpers.ordinalize(position), actualValue: lst}, position, args); } }; // // remove: array any -> array // // removes the first instance of v in a // // or returns a copy of a if v does not exist // var remove = function(a, v) { // for (var i = 0; i < a.length; i++) { // if (a[i] === v) { // return a.slice(0, i).concat( a.slice(i+1, a.length) ); // } // } // return a.slice(0); // }; // map: array (any -> any) -> array // applies f to each element of a and returns the result // as a new array var map = function(f, a) { var b = new Array(a.length); for (var i = 0; i < a.length; i++) { b[i] = f(a[i]); } return b; }; var schemeListToArray = function(lst) { var result = []; while ( !lst.isEmpty() ) { result.push(lst.first()); lst = lst.rest(); } return result; } // deepListToArray: any -> any // Converts list structure to array structure. var deepListToArray = function(x) { var thing = x; if (thing === types.EMPTY) { return []; } else if (types.isPair(thing)) { var result = []; while (!thing.isEmpty()) { result.push(deepListToArray(thing.first())); thing = thing.rest(); } return result; } else { return x; } } var flattenSchemeListToArray = function(x) { if ( !isList(x) ) { return [x]; } var ret = []; while ( !x.isEmpty() ) { ret = ret.concat( flattenSchemeListToArray(x.first()) ); x = x.rest(); } return ret; }; // assocListToHash: (listof (list X Y)) -> (hashof X Y) var assocListToHash = function(lst) { var result = {}; while ( !lst.isEmpty() ) { var key = lst.first().first(); var val = lst.first().rest().first(); result[key] = val; lst = lst.rest(); } return result; }; var ordinalize = function(n) { // special case for 11th: if ( n % 100 == 11 ) { return n + 'th'; } var res = n; switch( n % 10 ) { case 1: res += 'st'; break; case 2: res += 'nd'; break; case 3: res += 'rd'; break; default: res += 'th'; break; } return res; } var wrapJsObject = function(x) { if (x === undefined) { return types.jsObject('undefined', x); } else if (x === null) { return types.jsObject('null', x); } else if (typeof(x) == 'function') { return types.jsObject('function', x); } else if ( x instanceof Array ) { return types.jsObject('array', x); } else if ( typeof(x) == 'string' ) { return types.jsObject("'" + x.toString() + "'", x); } else { return types.jsObject(x.toString(), x); } }; var getKeyCodeName = function(e) { var code = e.charCode || e.keyCode; var keyname; switch(code) { case 8: keyname = "\b"; break; case 16: keyname = "shift"; break; case 17: keyname = "control"; break; case 19: keyname = "pause"; break; case 27: keyname = "escape"; break; case 33: keyname = "prior"; break; case 34: keyname = "next"; break; case 35: keyname = "end"; break; case 36: keyname = "home"; break; case 37: keyname = "left"; break; case 38: keyname = "up"; break; case 39: keyname = "right"; break; case 40: keyname = "down"; break; case 42: keyname = "print"; break; case 45: keyname = "insert"; break; case 46: keyname = String.fromCharCode(127); break; case 144: keyname = "numlock"; break; case 145: keyname = "scroll"; break; default: if (code >= 112 && code <= 123){ // fn keys keyname = "f" + (code - 111); } else { keyname = ""; } break; } return keyname; }; // maybeCallAfterAttach: dom-node -> void // walk the tree rooted at aNode, and call afterAttach if the element has // such a method. var maybeCallAfterAttach = function(aNode) { var stack = [aNode]; while (stack.length !== 0) { var nextNode = stack.pop(); if (nextNode.afterAttach) { nextNode.afterAttach(nextNode); } if (nextNode.hasChildNodes && nextNode.hasChildNodes()) { var children = nextNode.childNodes; for (var i = 0; i < children.length; i++) { stack.push(children[i]); } } } }; // makeLocationDom: location -> dom // Dom type that has special support in the editor through the print hook. // The print hook is expected to look at the printing of dom values with // this particular structure. In the context of WeScheme, the environment // will rewrite these to be clickable links. var makeLocationDom = function(aLocation) { var locationSpan = document.createElement("span"); var idSpan = document.createElement("span"); var offsetSpan = document.createElement("span"); var lineSpan = document.createElement("span"); var columnSpan = document.createElement("span"); var spanSpan = document.createElement("span"); locationSpan['className'] = 'location-reference'; idSpan['className'] = 'location-id'; offsetSpan['className'] = 'location-offset'; lineSpan['className'] = 'location-line'; columnSpan['className'] = 'location-column'; spanSpan['className'] = 'location-span'; idSpan.appendChild(document.createTextNode(aLocation.id + '')); offsetSpan.appendChild(document.createTextNode(aLocation.offset + '')); lineSpan.appendChild(document.createTextNode(aLocation.line + '')); columnSpan.appendChild(document.createTextNode(aLocation.column + '')); spanSpan.appendChild(document.createTextNode(aLocation.span + '')); locationSpan.appendChild(idSpan); locationSpan.appendChild(offsetSpan); locationSpan.appendChild(lineSpan); locationSpan.appendChild(columnSpan); locationSpan.appendChild(spanSpan); return locationSpan; }; var isLocationDom = function(thing) { return (thing && (thing.nodeType === Node.TEXT_NODE || thing.nodeType === Node.ELEMENT_NODE) && thing['className'] === 'location-reference'); }; //////////////////////////////////////////////// helpers.format = format; helpers.forEachK = forEachK; helpers.reportError = reportError; helpers.raise = raise; helpers.procArityContains = procArityContains; helpers.throwCheckError = throwCheckError; helpers.isList = isList; helpers.isListOf = isListOf; helpers.check = check; helpers.checkVarArity = checkVarArity; helpers.checkListOf = checkListOf; // helpers.remove = remove; helpers.map = map; helpers.schemeListToArray = schemeListToArray; helpers.deepListToArray = deepListToArray; helpers.flattenSchemeListToArray = flattenSchemeListToArray; helpers.assocListToHash = assocListToHash; helpers.ordinalize = ordinalize; helpers.wrapJsObject = wrapJsObject; helpers.getKeyCodeName = getKeyCodeName; helpers.maybeCallAfterAttach = maybeCallAfterAttach; helpers.makeLocationDom = makeLocationDom; helpers.isLocationDom = isLocationDom; })(); /////////////////////////////////////////////////////////////////
bootstrapworld/wescheme-js
src/runtime/helpers.js
JavaScript
lgpl-2.1
17,782
/* -------------------------------------------------------------------------- libmusicbrainz4 - Client library to access MusicBrainz Copyright (C) 2011 Andrew Hawkins This file is part of libmusicbrainz4. This library is free software; you can redistribute it and/or modify it under the terms of v2 of the GNU Lesser General Public License as published by the Free Software Foundation. libmusicbrainz4 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 General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. $Id$ ----------------------------------------------------------------------------*/ #include "musicbrainz4/NameCredit.h" #include "musicbrainz4/Artist.h" class MusicBrainz4::CNameCreditPrivate { public: CNameCreditPrivate() : m_Artist(0) { } std::string m_JoinPhrase; std::string m_Name; CArtist *m_Artist; }; MusicBrainz4::CNameCredit::CNameCredit(const XMLNode& Node) : CEntity(), m_d(new CNameCreditPrivate) { if (!Node.isEmpty()) { //std::cout << "Name credit node: " << std::endl << Node.createXMLString(true) << std::endl; Parse(Node); } } MusicBrainz4::CNameCredit::CNameCredit(const CNameCredit& Other) : CEntity(), m_d(new CNameCreditPrivate) { *this=Other; } MusicBrainz4::CNameCredit& MusicBrainz4::CNameCredit::operator =(const CNameCredit& Other) { if (this!=&Other) { Cleanup(); CEntity::operator =(Other); m_d->m_JoinPhrase=Other.m_d->m_JoinPhrase; m_d->m_Name=Other.m_d->m_Name; if (Other.m_d->m_Artist) m_d->m_Artist=new CArtist(*Other.m_d->m_Artist); } return *this; } MusicBrainz4::CNameCredit::~CNameCredit() { Cleanup(); delete m_d; } void MusicBrainz4::CNameCredit::Cleanup() { delete m_d->m_Artist; m_d->m_Artist=0; } MusicBrainz4::CNameCredit *MusicBrainz4::CNameCredit::Clone() { return new CNameCredit(*this); } bool MusicBrainz4::CNameCredit::ParseAttribute(const std::string& Name, const std::string& Value) { bool RetVal=true; if ("joinphrase"==Name) m_d->m_JoinPhrase=Value; else { std::cerr << "Unrecognised namecredit attribute: '" << Name << "'" << std::endl; RetVal=false; } return RetVal; } bool MusicBrainz4::CNameCredit::ParseElement(const XMLNode& Node) { bool RetVal=true; std::string NodeName=Node.getName(); if ("name"==NodeName) { RetVal=ProcessItem(Node,m_d->m_Name); } else if ("artist"==NodeName) { RetVal=ProcessItem(Node,m_d->m_Artist); } else { std::cerr << "Unrecognised name credit element: '" << NodeName << "'" << std::endl; RetVal=false; } return RetVal; } std::string MusicBrainz4::CNameCredit::GetElementName() { return "name-credit"; } std::string MusicBrainz4::CNameCredit::JoinPhrase() const { return m_d->m_JoinPhrase; } std::string MusicBrainz4::CNameCredit::Name() const { return m_d->m_Name; } MusicBrainz4::CArtist *MusicBrainz4::CNameCredit::Artist() const { return m_d->m_Artist; } std::ostream& MusicBrainz4::CNameCredit::Serialise(std::ostream& os) const { os << "Name credit:" << std::endl; CEntity::Serialise(os); os << "\tJoin phrase: " << JoinPhrase() << std::endl; os << "\tName: " << Name() << std::endl; if (Artist()) os << *Artist() << std::endl; return os; }
ianmcorvidae/libmusicbrainz
src/NameCredit.cc
C++
lgpl-2.1
3,483
// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2013 Mihail Ivchenko <ematirov@gmail.com> // Copyright 2014 Sanjiban Bairagya <sanjiban22393@gmail.com> // Copyright 2014 Illya Kovalevskyy <illya.kovalevskyy@gmail.com> // #include <QToolButton> #include <QLabel> #include <QHBoxLayout> #include <QLineEdit> #include <QFileDialog> #include "SoundCueEditWidget.h" #include "MarbleWidget.h" #include "geodata/data/GeoDataSoundCue.h" #include "GeoDataTypes.h" #include "MarblePlacemarkModel.h" namespace Marble { SoundCueEditWidget::SoundCueEditWidget( const QModelIndex &index, QWidget *parent ) : QWidget( parent ), m_index( index ), m_lineEdit( new QLineEdit ), m_button( new QToolButton ), m_button2( new QToolButton ) { QHBoxLayout *layout = new QHBoxLayout; layout->setSpacing( 5 ); QLabel* iconLabel = new QLabel; iconLabel->setPixmap( QPixmap( ":/marble/playback-play.png" ) ); layout->addWidget( iconLabel ); m_lineEdit->setPlaceholderText( "Audio location" ); m_lineEdit->setText( soundCueElement()->href() ); layout->addWidget( m_lineEdit ); m_button2->setIcon( QIcon( ":/marble/document-open.png" ) ); connect(m_button2, SIGNAL(clicked()), this, SLOT(open())); layout->addWidget( m_button2 ); m_button->setIcon( QIcon( ":/marble/document-save.png" ) ); connect(m_button, SIGNAL(clicked()), this, SLOT(save())); layout->addWidget( m_button ); setLayout( layout ); } bool SoundCueEditWidget::editable() const { return m_button->isEnabled(); } void SoundCueEditWidget::setEditable( bool editable ) { m_button->setEnabled( editable ); } void SoundCueEditWidget::save() { soundCueElement()->setHref( m_lineEdit->text() ); emit editingDone(m_index); } void SoundCueEditWidget::open() { QString fileName = QFileDialog::getOpenFileName(this, tr("Select sound files..."), QDir::homePath(), tr("Supported Sound Files (*.mp3 *.ogg *.wav)")); m_lineEdit->setText(fileName); soundCueElement()->setHref( m_lineEdit->text() ); } GeoDataSoundCue* SoundCueEditWidget::soundCueElement() { GeoDataObject *object = qvariant_cast<GeoDataObject*>(m_index.data( MarblePlacemarkModel::ObjectPointerRole ) ); Q_ASSERT( object ); Q_ASSERT( object->nodeType() == GeoDataTypes::GeoDataSoundCueType ); return static_cast<GeoDataSoundCue*>( object ); } } // namespace Marble #include "moc_SoundCueEditWidget.cpp"
tzapzoor/marble
src/lib/marble/SoundCueEditWidget.cpp
C++
lgpl-2.1
2,613
#include "stdio.h" #include "OSGNode.h" #include "OSGBaseInitFunctions.h" #include "OSGFieldDescFactory.h" #include "OSGBaseSFields.h" #include "OSGBaseMFields.h" int main (int argc, char **argv) { OSG::osgInit(argc, argv); // fprintf(stderr, "%d field types\n"); for(OSG::UInt32 i = 0; i < OSG::FieldDescFactory::the()->getNumFieldTypes(); ++i ) { // fprintf(stderr, "Field } OSG::FieldDescriptionBase *pDesc = OSG::FieldDescFactory::the()->createByNameIdx( NULL, NULL, NULL, NULL); pDesc = OSG::FieldDescFactory::the()->createByNameIdx( "SFUInt32", "myfield", NULL, NULL); fprintf(stderr, "got %p\n", static_cast<void *>(pDesc)); if(pDesc != NULL) { pDesc->getFieldType().dump(); } pDesc = OSG::FieldDescFactory::the()->createByNameIdx( "MFUInt32", "myfield", NULL, NULL); fprintf(stderr, "got %p\n", static_cast<void *>(pDesc)); if(pDesc != NULL) { pDesc->getFieldType().dump(); } pDesc = OSG::FieldDescFactory::the()->createIdx( OSG::SFUInt32::getClassType().getId(), "myfield", NULL, NULL); fprintf(stderr, "got %p\n", static_cast<void *>(pDesc)); if(pDesc != NULL) { pDesc->getFieldType().dump(); } pDesc = OSG::FieldDescFactory::the()->createIdx( OSG::MFUInt32::getClassType().getId(), "myfield", NULL, NULL); fprintf(stderr, "got %p\n", static_cast<void *>(pDesc)); if(pDesc != NULL) { pDesc->getFieldType().dump(); } pDesc = OSG::FieldDescFactory::the()->createIdx( OSG::SFUnrecFieldContainerPtr::getClassType().getId(), "myfield", NULL, NULL); fprintf(stderr, "got %p\n", static_cast<void *>(pDesc)); if(pDesc != NULL) { pDesc->getFieldType().dump(); } pDesc = OSG::FieldDescFactory::the()->createIdx( OSG::MFUnrecFieldContainerPtr::getClassType().getId(), "myfield", NULL, NULL); fprintf(stderr, "got %p\n", static_cast<void *>(pDesc)); if(pDesc != NULL) { pDesc->getFieldType().dump(); } OSG::osgExit(); return 0; }
jondo2010/OpenSG
Source/Base/Field/testFieldDescFactory.cpp
C++
lgpl-2.1
2,414
/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * https://lxqt.org * * Copyright: 2013 Razor team * Authors: * Kuzma Shapran <kuzma.shapran@gmail.com> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "client_proxy.h" #include "org.lxqt.global_key_shortcuts.client.h" ClientProxy::ClientProxy(const QString &service, const QDBusObjectPath &path, const QDBusConnection &connection, QObject *parent) : QObject(parent) { org::lxqt::global_key_shortcuts::client *iface = new org::lxqt::global_key_shortcuts::client(service, path.path(), connection, this); connect(this, SIGNAL(activated()), iface, SLOT(activated())); connect(this, SIGNAL(shortcutChanged(QString, QString)), iface, SLOT(shortcutChanged(QString, QString))); } void ClientProxy::emitActivated() { emit activated(); } void ClientProxy::emitShortcutChanged(const QString &oldShortcut, const QString &newShortcut) { emit shortcutChanged(oldShortcut, newShortcut); }
stefonarch/lxqt-globalkeys
daemon/client_proxy.cpp
C++
lgpl-2.1
1,764
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "variantproperty.h" #include "internalproperty.h" #include "internalvariantproperty.h" #include "invalidmodelnodeexception.h" #include "invalidpropertyexception.h" #include "invalidargumentexception.h" #include "internalnode_p.h" #include "model.h" #include "model_p.h" namespace QmlDesigner { VariantProperty::VariantProperty() {} VariantProperty::VariantProperty(const VariantProperty &property, AbstractView *view) : AbstractProperty(property.name(), property.internalNode(), property.model(), view) { } VariantProperty::VariantProperty(const QString &propertyName, const Internal::InternalNodePointer &internalNode, Model* model, AbstractView *view) : AbstractProperty(propertyName, internalNode, model, view) { } void VariantProperty::setValue(const QVariant &value) { Internal::WriteLocker locker(model()); if (!isValid()) throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__); if (value.isNull()) throw InvalidArgumentException(__LINE__, __FUNCTION__, __FILE__, name()); if (internalNode()->hasProperty(name())) { //check if oldValue != value Internal::InternalProperty::Pointer internalProperty = internalNode()->property(name()); if (internalProperty->isVariantProperty() && internalProperty->toVariantProperty()->value() == value && dynamicTypeName().isEmpty()) return; } if (internalNode()->hasProperty(name()) && !internalNode()->property(name())->isVariantProperty()) model()->d->removeProperty(internalNode()->property(name())); model()->d->setVariantProperty(internalNode(), name(), value); } QVariant VariantProperty::value() const { if (internalNode()->hasProperty(name()) && internalNode()->property(name())->isVariantProperty()) return internalNode()->variantProperty(name())->value(); return QVariant(); } VariantProperty& VariantProperty::operator= (const QVariant &value) { setValue(value); return *this; } void VariantProperty::setDynamicTypeNameAndValue(const QString &type, const QVariant &value) { Internal::WriteLocker locker(model()); if (!isValid()) throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__); if (type.isEmpty()) { throw InvalidArgumentException(__LINE__, __FUNCTION__, __FILE__, name()); } if (internalNode()->hasProperty(name())) { //check if oldValue != value Internal::InternalProperty::Pointer internalProperty = internalNode()->property(name()); if (internalProperty->isVariantProperty() && internalProperty->toVariantProperty()->value() == value && internalProperty->toVariantProperty()->dynamicTypeName() == type) return; } if (internalNode()->hasProperty(name()) && !internalNode()->property(name())->isVariantProperty()) model()->d->removeProperty(internalNode()->property(name())); model()->d->setDynamicVariantProperty(internalNode(), name(), type, value); } VariantProperty& VariantProperty::operator= (const QPair<QString, QVariant> &typeValuePair) { setDynamicTypeNameAndValue(typeValuePair.first, typeValuePair.second); return *this; } QDebug operator<<(QDebug debug, const VariantProperty &VariantProperty) { return debug.nospace() << "VariantProperty(" << VariantProperty.name() << ')'; } QTextStream& operator<<(QTextStream &stream, const VariantProperty &property) { stream << "VariantProperty(" << property.name() << ')'; return stream; } } // namespace QmlDesigner
bakaiadam/collaborative_qt_creator
src/plugins/qmldesigner/designercore/model/variantproperty.cpp
C++
lgpl-2.1
4,854
using System; using Mag.Shared; using Decal.Adapter; namespace MagFilter { class DefaultFirstCharacterManager { readonly LoginCharacterTools loginCharacterTools; readonly System.Windows.Forms.Timer defaultFirstCharTimer = new System.Windows.Forms.Timer(); int state; string zonename; string server; public DefaultFirstCharacterManager(LoginCharacterTools loginCharacterTools) { this.loginCharacterTools = loginCharacterTools; defaultFirstCharTimer.Tick += new EventHandler(defaultFirstCharTimer_Tick); defaultFirstCharTimer.Interval = 1000; } public void FilterCore_ServerDispatch(object sender, NetworkMessageEventArgs e) { // When we login for the first time we get the following for messages in the following order if (e.Message.Type == 0xF658) // Character List (we get this when we log out a character as well) zonename = Convert.ToString(e.Message["zonename"]); if (e.Message.Type == 0xF7E1) // Server Name (we get this when we log out a character as well) server = Convert.ToString(e.Message["server"]); // F7E5 - Unknown? (we only get this the first time we connect), E5 F7 00 00 01 00 00 00 01 00 00 00 01 00 00 00 02 00 00 00 00 00 00 00 01 00 00 00 if (e.Message.Type == 0xF7EA) // Unknown? (we only get this the first time we connect), EA F7 00 0 defaultFirstCharTimer.Start(); } public void FilterCore_CommandLineText(object sender, ChatParserInterceptEventArgs e) { string lower = e.Text.ToLower(); if (lower.StartsWith("/mf dlc set")) { Settings.SettingsManager.CharacterSelectionScreen.SetDefaultFirstCharacter(new DefaultFirstCharacter(server, zonename, CoreManager.Current.CharacterFilter.Name)); Debug.WriteToChat("Default Login Character set to: " + CoreManager.Current.CharacterFilter.Name); e.Eat = true; } else if (lower.StartsWith("/mf dlcbi set ")) { var index = int.Parse(lower.Substring(14, lower.Length - 14)); if (index > 10) { index = -1; Debug.WriteToChat("Default Login Character failed with input too large: " + index); } else if (index < 0) { index = -1; Debug.WriteToChat("Default Login Character failed with input too small: " + index); } else { Settings.SettingsManager.CharacterSelectionScreen.SetDefaultFirstCharacter(new DefaultFirstCharacter(server, zonename, null, index)); Debug.WriteToChat("Default Login Character set to index: " + index); } e.Eat = true; } else if (lower == "/mf dlc clear" || lower == "/mf dlcbi clear") { Settings.SettingsManager.CharacterSelectionScreen.DeleteDefaultFirstCharacter(server, zonename); Debug.WriteToChat("Default Login Character cleared"); e.Eat = true; } else if (lower.StartsWith("/mf sdlcbi set ")) { var index = int.Parse(lower.Substring(15, lower.Length - 15)); if (index > 10) { index = -1; Debug.WriteToChat("Default Login Character failed with input too large: " + index); } else if (index < 0) { index = -1; Debug.WriteToChat("Default Login Character failed with input too small: " + index); } else { Settings.SettingsManager.CharacterSelectionScreen.SetDefaultFirstCharacter(new DefaultFirstCharacter(server, null, null, index)); Debug.WriteToChat("Server Default Login Character set to index: " + index); } e.Eat = true; } else if (lower == "/mf sdlcbi clear") { Settings.SettingsManager.CharacterSelectionScreen.DeleteDefaultFirstCharacters(server); Debug.WriteToChat("Server Default Login Characters cleared"); e.Eat = true; } } void defaultFirstCharTimer_Tick(object sender, EventArgs e) { try { var defaultFirstCharacters = Settings.SettingsManager.CharacterSelectionScreen.DefaultFirstCharacters; foreach (var character in defaultFirstCharacters) { if ((String.IsNullOrEmpty(character.AccountName) || character.AccountName == zonename) && character.Server == server) { // Bypass movies/logos if (state == 1 || state == 2) PostMessageTools.SendMouseClick(350, 100); if (state == 3) { if (!String.IsNullOrEmpty(character.CharacterName)) loginCharacterTools.LoginCharacter(character.CharacterName); else if (character.CharacterIndex != -1) loginCharacterTools.LoginByIndex(character.CharacterIndex); } break; } } if (state >= 3) defaultFirstCharTimer.Stop(); state++; } catch (Exception ex) { Debug.LogException(ex); } } } }
Mag-nus/Mag-Plugins
Mag-Filter/DefaultFirstCharacterManager.cs
C#
lgpl-2.1
4,738
/******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * 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. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.main.cli; import java.io.InputStream; import java.io.PrintStream; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import com.tiemens.secretshare.exceptions.SecretShareException; import com.tiemens.secretshare.math.type.BigIntUtilities; /** * Main command line for the "bigintcs" utilities - converting to/from bigintcs, bigint, and String. * * Takes a mode (bics2bi, bics2s, bi2s, bi2bics, s2bics, s2bi) * and a list of input strings * and writes the conversion strings. * * @author tiemens * */ public final class MainBigIntCs { /** * @param args from command line */ public static void main(String[] args) { main(args, System.in, System.out); } public static void main(String[] args, InputStream in, PrintStream out) { try { BigIntCsInput input = BigIntCsInput.parse(args); BigIntCsOutput output = input.output(); output.print(out); } catch (SecretShareException e) { out.println(e.getMessage()); usage(out); optionallyPrintStackTrace(args, e, out); } } public static void usage(PrintStream out) { out.println("Usage:"); out.println(" bigintcs -h -mode <bics2bi|bics2s|bi2s|bi2bics|s2bics|s2bi> " + " [-v] [-in <bics|bi|s>] [-out <bics|bi|s>] [-sepSpace|-sepNewline] value [value2 ...]"); out.println(" -h print usage"); out.println(" -in <m> set input mode"); out.println(" s String, converted to array of bytes, constructing a Big Integer [default]"); out.println(" bi String, parsed to Big Integer, used as a Big Integer"); out.println(" bics String, parsed and checksummed to Big Integer Checksum, " + "then used as a Big Integer"); out.println(" -out <m> set output mode"); out.println(" s Output Big Integer as array of bytes to construct a String"); out.println(" bi Output Big Integer .toString()"); out.println(" bics Output Big Integer Checksum .toString() [default]"); out.println(" -mode <m> set both input and output operation mode"); out.println(" s2bi -in s -out bi"); out.println(" s2bics -in s -out bics [default]"); out.println(" bi2s -in bi -out s"); out.println(" bics2bi -in bics -out bi"); out.println(" -v print version on 1st line"); out.println(" -sepSpace outputs with spaces between values"); out.println(" -sepNewLine outputs with newlines between values [default]"); out.println(" Example: s2bi 'a' = 97 (ascii 'a')"); out.println(" Example: bi2s '97' = a"); out.println(" Example: s2bi 'ab' = 24930 (ascii 'a' * 256 + ascii 'b')"); out.println(" Example: s2bi '1' = 49 (NOT '1')"); out.println(" Example: s2bi '123' = 3224115 (NOT '123')"); out.println(" Example: s2bics 'Cat' = bigintcs:436174-7BF975"); out.println(" Example: bics2s 'bigintcs:436174-7BF975' = Cat"); out.println(" Example: s2bi 'Cat' = 4415860"); out.println(" Example: bi2bics '4415860' = bigintcs:436174-7BF975"); } public static BigInteger parseBigInteger(String argname, String[] args, int index) { return MainSplit.parseBigInteger(argname, args, index); } public static Integer parseInt(String argname, String[] args, int index) { return MainSplit.parseInt(argname, args, index); } public static void checkIndex(String argname, String[] args, int index) { MainSplit.checkIndex(argname, args, index); } public static void optionallyPrintStackTrace(String[] args, Exception e, PrintStream out) { MainSplit.optionallyPrintStackTrace(args, e, out); } private MainBigIntCs() { // no instances } public static enum Type { bics, bi, s; /** * @param in type to find * @param argName to display if an error happens * @return Type or throw exception * @throws SecretShareException if 'in' is not found */ public static Type findByString(String in, String argName) { Type ret = valueOf(in); if (ret != null) { return ret; } else { throw new SecretShareException("Type value '" + in + "' not found." + ((argName != null) ? " Argname=" + argName : "")); } } } public static enum Type2Type { bics2bics, bics2bi, bics2s, bi2bics, bi2bi, bi2s, s2bics, s2bi, s2s; /** * @param in combination type2type to find * @param argName to display if an error happens * @return Type2Type or throw exception * @throws SecretShareException if 'in' is not found */ public static Type2Type findByString(String in, String argName) { Type2Type ret = valueOf(in); if (ret != null) { return ret; } else { throw new SecretShareException("Type2Type value '" + in + "' not found." + ((argName != null) ? " Argname=" + argName : "")); } } public Type getInputType(String argName) { String name = this.name(); return Type.findByString(name.substring(0, name.indexOf('2')), argName); } public Type getOutputType(String argName) { String name = this.name(); return Type.findByString(name.substring(name.indexOf('2') + 1, name.length()), argName); } } public static class BigIntCsInput { private static final String SYSTEMLINESEPARATOR = System.getProperty("line.separator"); // jdk1.7: System.lineSeparator(); // ================================================== // instance data // ================================================== // required arguments: private final List<String> inputs = new ArrayList<String>(); private Type inputType = Type.s; private Type outputType = Type.bics; // optional private boolean printHeader = false; private String separator = SYSTEMLINESEPARATOR; // ================================================== // constructors // ================================================== public static BigIntCsInput parse(String[] args) { BigIntCsInput ret = new BigIntCsInput(); for (int i = 0, n = args.length; i < n; i++) { if (args[i] == null) { continue; } if ("-in".equals(args[i])) { i++; ret.inputType = parseType("in", args, i); } else if ("-out".equals(args[i])) { i++; ret.outputType = parseType("out", args, i); } else if ("-mode".equals(args[i])) { i++; Type2Type t2t = parseType2Type("mode", args, i); ret.inputType = t2t.getInputType("mode"); ret.outputType = t2t.getOutputType("mode"); } else if ("-sep".equals(args[i])) { i++; checkIndex("sep", args, i); ret.separator = args[i]; } else if ("-sepSpace".equals(args[i])) { ret.separator = " "; } else if ("-sepNewLine".equals(args[i])) { ret.separator = SYSTEMLINESEPARATOR; } else if ("-v".equals(args[i])) { ret.printHeader = true; } else if (args[i].startsWith("-")) { String m = "Argument '" + args[i] + "' not understood"; throw new SecretShareException(m); } else { String v = args[i]; ret.inputs.add(v); } } return ret; } public static Type2Type parseType2Type(String argname, String[] args, int index) { checkIndex(argname, args, index); return parseType2Type(argname, args[index]); } public static Type2Type parseType2Type(String argname, String value) { return Type2Type.findByString(value, argname); } public static Type parseType(String argname, String[] args, int index) { checkIndex(argname, args, index); return parseType(argname, args[index]); } public static Type parseType(String argname, String value) { return Type.findByString(value, argname); } // ================================================== // public methods // ================================================== public BigIntCsOutput output() { BigIntCsOutput ret = new BigIntCsOutput(this); return ret; } // ================================================== // non public methods // ================================================== } public static class BigIntCsOutput { private final BigIntCsInput bigintcsInput; private List<String> output; public BigIntCsOutput(BigIntCsInput inBigIntCsInput) { bigintcsInput = inBigIntCsInput; } public void print(PrintStream out) { output = convert(bigintcsInput.inputs, bigintcsInput.inputType, bigintcsInput.outputType); if (bigintcsInput.printHeader) { printHeaderInfo(out); } String sep = ""; if (output.size() > 0) { for (String s : output) { out.print(sep); sep = bigintcsInput.separator; out.print(s); } out.print(sep); } } // ================================================== // instance data // ================================================== // ================================================== // constructors // ================================================== // ================================================== // public methods // ================================================== // ================================================== // non public methods // ================================================== public static List<String> convert(List<String> inputs, Type inputType, Type outputType) { List<String> ret = new ArrayList<String>(); for (String in : inputs) { String out = convert(in, inputType, outputType); ret.add(out); } return ret; } public static String convert(String in, Type inputType, Type outputType) { if (Type.s.equals(inputType) && Type.s.equals(outputType)) { String asbi = BigIntUtilities.Human.createBigInteger(in).toString(); String noop = BigIntUtilities.Human.createHumanString(new BigInteger(asbi)); if (noop.equals(in)) { // that whole thing was a no-operation; it was just a double-check return in; } else { throw new SecretShareException("Programmer error: in='" + in + "' asbi='" + asbi + "' yet output string was '" + noop + "'"); } } else if (Type.s.equals(inputType) && Type.bi.equals(outputType)) { return BigIntUtilities.Human.createBigInteger(in).toString(); } else if (Type.s.equals(inputType) && Type.bics.equals(outputType)) { BigInteger inbi = BigIntUtilities.Human.createBigInteger(in); return BigIntUtilities.Checksum.createMd5CheckSumString(inbi); } else if (Type.bi.equals(inputType)) { BigInteger inbi = new BigInteger(in); if (Type.s.equals(outputType)) { return BigIntUtilities.Human.createHumanString(inbi); } else if (Type.bi.equals(outputType)) { return inbi.toString(); } else if (Type.bics.equals(outputType)) { return BigIntUtilities.Checksum.createMd5CheckSumString(inbi); } else { error("input type bi, output type unknown: " + outputType); } } else if (Type.bics.equals(inputType)) { BigInteger inbi = BigIntUtilities.Checksum.createBigInteger(in); if (Type.s.equals(outputType)) { return BigIntUtilities.Human.createHumanString(inbi); } else if (Type.bi.equals(outputType)) { return inbi.toString(); } else if (Type.bics.equals(outputType)) { return BigIntUtilities.Checksum.createMd5CheckSumString(inbi); } else { return error("input type bics, output type unknown: " + outputType); } } else { return error("input type unknown: " + inputType); } return error("Programmer Error - fell off if chain"); } private static String error(String msg) { throw new SecretShareException(msg); } private void printHeaderInfo(PrintStream out) { out.print(Main.getVersionLine()); out.print(bigintcsInput.separator); } } // class BigIntCsOutput }
timtiemens/secretshare
src/main/java/com/tiemens/secretshare/main/cli/MainBigIntCs.java
Java
lgpl-2.1
16,433
//============================================================================= /* $Id: ParameterPosition.java,v 1.2 2002/10/25 14:01:41 taq Exp $ */ //============================================================================= package ORG.as220.tinySQL.util; /** * Here you can specify where the <code>PreparedStastement</code> should put a * parametr's value inside a <code.SQL</code> text, this place is marked by the * start of the string until reach the parameter see the example bellow;<br> * <p><code>String stSQL = "select NOME, STREET from PERSON where ID = * ?";</code><br> * The parameter is located in the 43th position, so you must inicialize this * objet as;<br> * <p><code>ParameterPosition pp = new ParameterPosition( 0, 43 );</code><br> * We need do this because <code>tinySQLPreparedStastement</code> use this * information to put the value stored inside <code>StatementParameter</code> * after the end of the position with this, * <code>tinySQLPreparedStatement</code> can cut a mount of <code>SQL</code> * before the <b>?</b> and put value. When the whole process is finished we have * the complete <code>SQL</code> statement ready to the database work. * @author <a href='mailto:GuardianOfSteel@netscape.net'>Edson Alves Pereira</a> - 29/12/2001 * @version $Revision: 1.2 $ */ public class ParameterPosition { private int iStart; private int iEnd; public ParameterPosition() { iStart = 0; iEnd = 0; } public ParameterPosition(int iStart_, int iEnd_) { setStart(iStart_); setEnd(iEnd_); } public void setStart(int iStart_) { if (iStart_ >= 0) iStart = iStart_; } public int getStart() { return iStart; } public void setEnd(int iEnd_) { if (iEnd_ >= 0) iEnd = iEnd_; } public int getEnd() { return iEnd; } }
bharathravi/tinysql
src/ORG/as220/tinySQL/util/ParameterPosition.java
Java
lgpl-2.1
1,864
// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2015 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : platform/glx/io.cpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ // include i/f header #include "platform/glx/io.hpp" // includes, system #include <boost/io/ios_state.hpp> // boost::io::ios_all_save #include <iomanip> // std::hex #include <ostream> // std::ostream // includes, project //#include <> #define UKACHULLDCS_USE_TRACE #undef UKACHULLDCS_USE_TRACE #include <support/trace.hpp> // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) // variables, internal // functions, internal } // namespace { namespace platform { namespace glx { // variables, exported // functions, exported std::ostream& operator<<(std::ostream& os, Display const& a) { std::ostream::sentry const cerberus(os); if (cerberus) { boost::io::ios_all_saver const ias(os); os << '[' << "@" << std::hex << reinterpret_cast<void const*>(&a) << ']'; } return os; } std::ostream& operator<<(std::ostream& os, GLXContext const& a) { std::ostream::sentry const cerberus(os); if (cerberus) { boost::io::ios_all_saver const ias(os); os << '[' << "@" << std::hex << reinterpret_cast<void const*>(a) << ']'; } return os; } std::ostream& operator<<(std::ostream& os, XVisualInfo const& a) { std::ostream::sentry const cerberus(os); if (cerberus) { boost::io::ios_all_saver const ias(os); os << '[' << "@" << std::hex << reinterpret_cast<void const*>(&a) << ']'; } return os; } } // namespace glx { } // namespace platform {
regnirpsj/dcs08961
src/lib/platform/glx/io.cpp
C++
lgpl-2.1
2,851
// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2014 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : support/trace.hpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ #if !defined(UKACHULLDCS_0896X_SUPPORT_TRACE_HPP) #define UKACHULLDCS_0896X_SUPPORT_TRACE_HPP // includes, system #include <boost/noncopyable.hpp> // boost::noncopyable #include <iosfwd> // std::ostream (fwd) #include <iostream> // std::cout #include <string> // std::string // includes, project // #include <> namespace support { // types, exported (class, enum, struct, union, typedef) class trace : private boost::noncopyable { public: explicit trace(std::string const&, std::ostream& = std::cout); ~trace(); static void enter(std::string const&, std::ostream& = std::cout); static void leave(std::string const&, std::ostream& = std::cout); static std::string prefix(); private: std::string msg_; std::ostream& os_; }; // variables, exported (extern) // functions, inlined (inline) // functions, exported (extern) } // namespace support { #include <boost/current_function.hpp> // BOOST_CURRENT_FUNCTION #define TRACE_NEVER(x) #define TRACE_ALWAYS(x) volatile support::trace const _(x) #define TRACE_FUNC_ALWAYS volatile support::trace const _(BOOST_CURRENT_FUNCTION) #define TRACE_ENTER_ALWAYS(x) support::trace::enter(x) #define TRACE_LEAVE_ALWAYS(x) support::trace::leave(x) #endif // #if !defined(UKACHULLDCS_0896X_SUPPORT_TRACE_HPP) // the following is intentionally outside the include guards to allow including this header // multiple times with different settings for UKACHULLDCS_USE_TRACE #if defined(TRACE) # undef TRACE #endif #if defined(TRACE_FUNC) # undef TRACE_FUNC #endif #if defined(TRACE_ENTER) # undef TRACE_ENTER #endif #if defined(TRACE_LEAVE) # undef TRACE_LEAVE #endif #if defined(UKACHULLDCS_ALL_TRACE) # define UKACHULLDCS_USE_TRACE #endif #if defined(UKACHULLDCS_USE_TRACE) # define TRACE(x) TRACE_ALWAYS(x) # define TRACE_FUNC TRACE_FUNC_ALWAYS # define TRACE_ENTER(x) TRACE_ENTER_ALWAYS(x) # define TRACE_LEAVE(x) TRACE_LEAVE_ALWAYS(x) #else # define TRACE(x) # define TRACE_FUNC # define TRACE_ENTER(x) # define TRACE_LEAVE(x) #endif
simviz-dcs-hull/dcs0896x-skeletons
inc/support/trace.hpp
C++
lgpl-2.1
3,302
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2008, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.jca.common.metadata.ds; import org.jboss.jca.common.api.metadata.ds.DataSource; import org.jboss.jca.common.api.metadata.ds.DataSources; import org.jboss.jca.common.api.metadata.ds.Driver; import org.jboss.jca.common.api.metadata.ds.XaDataSource; import org.jboss.jca.common.api.validator.ValidateException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * A DatasourcesImpl. * * @author <a href="stefano.maestri@ironjacamar.org">Stefano Maestri</a> * */ public class DatasourcesImpl implements DataSources { /** The serialVersionUID */ private static final long serialVersionUID = 6933310057105771370L; private final List<DataSource> datasource; private final List<XaDataSource> xaDataSource; private final Map<String, Driver> drivers; /** * Create a new DatasourcesImpl. * * @param datasource datasource * @param xaDataSource xaDataSource * @param drivers drivers * @throws ValidateException ValidateException */ public DatasourcesImpl(List<DataSource> datasource, List<XaDataSource> xaDataSource, Map<String, Driver> drivers) throws ValidateException { super(); if (datasource != null) { this.datasource = new ArrayList<DataSource>(datasource.size()); this.datasource.addAll(datasource); } else { this.datasource = new ArrayList<DataSource>(0); } if (xaDataSource != null) { this.xaDataSource = new ArrayList<XaDataSource>(xaDataSource.size()); this.xaDataSource.addAll(xaDataSource); } else { this.xaDataSource = new ArrayList<XaDataSource>(0); } if (drivers != null) { this.drivers = new HashMap<String, Driver>(drivers.size()); this.drivers.putAll(drivers); } else { this.drivers = new HashMap<String, Driver>(0); } this.validate(); } /** * Get the datasource. * * @return the datasource. */ @Override public final List<DataSource> getDataSource() { return Collections.unmodifiableList(datasource); } /** * Get the xaDataSource. * * @return the xaDataSource. */ @Override public final List<XaDataSource> getXaDataSource() { return Collections.unmodifiableList(xaDataSource); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((datasource == null) ? 0 : datasource.hashCode()); result = prime * result + ((xaDataSource == null) ? 0 : xaDataSource.hashCode()); result = prime * result + ((drivers == null) ? 0 : drivers.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof DatasourcesImpl)) return false; DatasourcesImpl other = (DatasourcesImpl) obj; if (datasource == null) { if (other.datasource != null) return false; } else if (!datasource.equals(other.datasource)) return false; if (xaDataSource == null) { if (other.xaDataSource != null) return false; } else if (!xaDataSource.equals(other.xaDataSource)) return false; if (drivers == null) { if (other.drivers != null) return false; } else if (!drivers.equals(other.drivers)) return false; return true; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); sb.append("<datasources>"); if (datasource != null && datasource.size() > 0) { for (DataSource ds : datasource) { sb.append(ds); } } if (xaDataSource != null && xaDataSource.size() > 0) { for (XaDataSource xads : xaDataSource) { sb.append(xads); } } if (drivers != null && drivers.size() > 0) { sb.append("<").append(DataSources.Tag.DRIVERS).append(">"); for (Driver d : drivers.values()) { sb.append(d); } sb.append("</").append(DataSources.Tag.DRIVERS).append(">"); } sb.append("</datasources>"); return sb.toString(); } @Override public void validate() throws ValidateException { //always validate if all content is validating for (DataSource ds : this.datasource) { ds.validate(); } for (XaDataSource xads : this.xaDataSource) { xads.validate(); } } @Override public Driver getDriver(String name) { return drivers.get(name); } @Override public List<Driver> getDrivers() { return Collections.unmodifiableList(new ArrayList<Driver>(drivers.values())); } }
ironjacamar/ironjacamar
common/impl/src/main/java/org/jboss/jca/common/metadata/ds/DatasourcesImpl.java
Java
lgpl-2.1
6,195
/* * Agent.cpp * * Created on: 20-oct-2009 * Author: hfreire */ #include "Agent.h" namespace opengl{ namespace agents{ log4cxx::LoggerPtr Agent::logger(log4cxx::Logger::getLogger("opengl.agents.Agent")); Agent::Agent(int millisecondsStep){ this->fpsAnimation=25; this->_visible=true; this->clockDivider=this->fpsAnimation/CLOCKS_PER_SEC; this->stepLength=GAME_SQUARE_SIDE * (1000 / millisecondsStep)/this->fpsAnimation; } void Agent::draw(){ if (_visible){ double frame = (clock() - _changePositionTime) * clockDivider; int direction_x; int direction_y; if (_rotationDirection.z == 0){ direction_x = 0; direction_y = -1; }else if (_rotationDirection.z == 90){ direction_x = +1; direction_y = 0; }else if (_rotationDirection.z == 180){ direction_x = 0; direction_y = +1; }else if (_rotationDirection.z == 270){ direction_x = -1; direction_y = 0; } double framePos = stepLength * frame; double x = _lastPosition.x * GAME_SQUARE_SIDE + (framePos * direction_x); double y = _lastPosition.y * GAME_SQUARE_SIDE + (framePos * direction_y); double z = _lastPosition.z; RenderManager::instance()->render( this->wavefrontObj, Vector3D(x, y, z), Vector3D(GAME_SQUARE_SIDE,GAME_SQUARE_SIDE,GAME_SQUARE_SIDE), this->_rotationDirection ); } } void Agent::setPosition(Vector3D position){ _changePositionTime = clock(); _lastPosition = _position; Object3D::setPosition(position); } bool Agent::isVisible(){ return this->_visible; } void Agent::setVisible(bool visible){ this->_visible = visible; } Agent::~Agent() { // TODO Auto-generated destructor stub } } }
TLmaK0/pactan
src/opengl/agents/Agent.cpp
C++
lgpl-2.1
1,761
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "bookmarkmanager.h" #include "bookmark.h" #include "bookmarksplugin.h" #include "bookmarks_global.h" #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/icore.h> #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/uniqueidmanager.h> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/session.h> #include <texteditor/basetexteditor.h> #include <utils/qtcassert.h> #include <QtCore/QDebug> #include <QtCore/QFileInfo> #include <QtGui/QAction> #include <QtGui/QContextMenuEvent> #include <QtGui/QMenu> #include <QtGui/QPainter> Q_DECLARE_METATYPE(Bookmarks::Internal::Bookmark*) using namespace Bookmarks; using namespace Bookmarks::Internal; using namespace ProjectExplorer; using namespace Core; BookmarkDelegate::BookmarkDelegate(QObject *parent) : QStyledItemDelegate(parent), m_normalPixmap(0), m_selectedPixmap(0) { } BookmarkDelegate::~BookmarkDelegate() { delete m_normalPixmap; delete m_selectedPixmap; } QSize BookmarkDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItemV4 opt = option; initStyleOption(&opt, index); QFontMetrics fm(option.font); QSize s; s.setWidth(option.rect.width()); s.setHeight(fm.height() * 2 + 10); return s; } void BookmarkDelegate::generateGradientPixmap(int width, int height, QColor color, bool selected) const { QColor c = color; c.setAlpha(0); QPixmap *pixmap = new QPixmap(width+1, height); pixmap->fill(c); QPainter painter(pixmap); painter.setPen(Qt::NoPen); QLinearGradient lg; lg.setCoordinateMode(QGradient::ObjectBoundingMode); lg.setFinalStop(1,0); lg.setColorAt(0, c); lg.setColorAt(0.4, color); painter.setBrush(lg); painter.drawRect(0, 0, width+1, height); if (selected) m_selectedPixmap = pixmap; else m_normalPixmap = pixmap; } void BookmarkDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItemV4 opt = option; initStyleOption(&opt, index); painter->save(); QFontMetrics fm(opt.font); static int lwidth = fm.width("8888") + 18; QColor backgroundColor; QColor textColor; bool selected = opt.state & QStyle::State_Selected; if (selected) { painter->setBrush(opt.palette.highlight().color()); backgroundColor = opt.palette.highlight().color(); if (!m_selectedPixmap) generateGradientPixmap(lwidth, fm.height()+1, backgroundColor, selected); } else { painter->setBrush(opt.palette.background().color()); backgroundColor = opt.palette.background().color(); if (!m_normalPixmap) generateGradientPixmap(lwidth, fm.height(), backgroundColor, selected); } painter->setPen(Qt::NoPen); painter->drawRect(opt.rect); // Set Text Color if (opt.state & QStyle::State_Selected) textColor = opt.palette.highlightedText().color(); else textColor = opt.palette.text().color(); painter->setPen(textColor); // TopLeft QString topLeft = index.data(BookmarkManager::Filename ).toString(); painter->drawText(6, 2 + opt.rect.top() + fm.ascent(), topLeft); QString topRight = index.data(BookmarkManager::LineNumber).toString(); // Check whether we need to be fancy and paint some background int fwidth = fm.width(topLeft); if (fwidth + lwidth > opt.rect.width()) { int left = opt.rect.right() - lwidth; painter->drawPixmap(left, opt.rect.top(), selected? *m_selectedPixmap : *m_normalPixmap); } // topRight painter->drawText(opt.rect.right() - fm.width(topRight) - 6 , 2 + opt.rect.top() + fm.ascent(), topRight); // Directory QColor mix; mix.setRgbF(0.7 * textColor.redF() + 0.3 * backgroundColor.redF(), 0.7 * textColor.greenF() + 0.3 * backgroundColor.greenF(), 0.7 * textColor.blueF() + 0.3 * backgroundColor.blueF()); painter->setPen(mix); // // QString directory = index.data(BookmarkManager::Directory).toString(); // int availableSpace = opt.rect.width() - 12; // if (fm.width(directory) > availableSpace) { // // We need a shorter directory // availableSpace -= fm.width("..."); // // int pos = directory.size(); // int idx; // forever { // idx = directory.lastIndexOf("/", pos-1); // if (idx == -1) { // // Can't happen, this means the string did fit after all? // break; // } // int width = fm.width(directory.mid(idx, pos-idx)); // if (width > availableSpace) { // directory = "..." + directory.mid(pos); // break; // } else { // pos = idx; // availableSpace -= width; // } // } // } // // painter->drawText(3, opt.rect.top() + fm.ascent() + fm.height() + 6, directory); QString lineText = index.data(BookmarkManager::LineText).toString().trimmed(); painter->drawText(6, opt.rect.top() + fm.ascent() + fm.height() + 6, lineText); // Separator lines painter->setPen(QColor::fromRgb(150,150,150)); painter->drawLine(0, opt.rect.bottom(), opt.rect.right(), opt.rect.bottom()); painter->restore(); } BookmarkView::BookmarkView(QWidget *parent) : QListView(parent), m_bookmarkContext(new BookmarkContext(this)), m_manager(0) { setWindowTitle(tr("Bookmarks")); connect(this, SIGNAL(clicked(const QModelIndex &)), this, SLOT(gotoBookmark(const QModelIndex &))); ICore::instance()->addContextObject(m_bookmarkContext); setItemDelegate(new BookmarkDelegate(this)); setFrameStyle(QFrame::NoFrame); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setFocusPolicy(Qt::NoFocus); } BookmarkView::~BookmarkView() { ICore::instance()->removeContextObject(m_bookmarkContext); } void BookmarkView::contextMenuEvent(QContextMenuEvent *event) { QMenu menu; QAction *moveUp = menu.addAction(tr("Move Up")); QAction *moveDown = menu.addAction(tr("Move Down")); QAction *remove = menu.addAction(tr("&Remove")); QAction *removeAll = menu.addAction(tr("Remove All")); m_contextMenuIndex = indexAt(event->pos()); if (!m_contextMenuIndex.isValid()) { moveUp->setEnabled(false); moveDown->setEnabled(false); remove->setEnabled(false); } if (model()->rowCount() == 0) removeAll->setEnabled(false); connect(moveUp, SIGNAL(triggered()), m_manager, SLOT(moveUp())); connect(moveDown, SIGNAL(triggered()), m_manager, SLOT(moveDown())); connect(remove, SIGNAL(triggered()), this, SLOT(removeFromContextMenu())); connect(removeAll, SIGNAL(triggered()), this, SLOT(removeAll())); menu.exec(mapToGlobal(event->pos())); } void BookmarkView::removeFromContextMenu() { removeBookmark(m_contextMenuIndex); } void BookmarkView::removeBookmark(const QModelIndex& index) { Bookmark *bm = m_manager->bookmarkForIndex(index); m_manager->removeBookmark(bm); } // The perforcemance of this function could be greatly improved. // void BookmarkView::removeAll() { while (m_manager->rowCount()) { QModelIndex index = m_manager->index(0, 0); removeBookmark(index); } } void BookmarkView::setModel(QAbstractItemModel *model) { BookmarkManager *manager = qobject_cast<BookmarkManager *>(model); QTC_ASSERT(manager, return); m_manager = manager; QListView::setModel(model); setSelectionModel(manager->selectionModel()); setSelectionMode(QAbstractItemView::SingleSelection); setSelectionBehavior(QAbstractItemView::SelectRows); } void BookmarkView::gotoBookmark(const QModelIndex &index) { Bookmark *bk = m_manager->bookmarkForIndex(index); if (!m_manager->gotoBookmark(bk)) m_manager->removeBookmark(bk); } //// // BookmarkContext //// BookmarkContext::BookmarkContext(BookmarkView *widget) : Core::IContext(widget), m_bookmarkView(widget) { m_context << UniqueIDManager::instance()->uniqueIdentifier(Constants::BOOKMARKS_CONTEXT); } QList<int> BookmarkContext::context() const { return m_context; } QWidget *BookmarkContext::widget() { return m_bookmarkView; } //// // BookmarkManager //// BookmarkManager::BookmarkManager() : m_bookmarkIcon(QLatin1String(":/bookmarks/images/bookmark.png")), m_selectionModel(new QItemSelectionModel(this, this)) { connect(Core::ICore::instance(), SIGNAL(contextChanged(Core::IContext*)), this, SLOT(updateActionStatus())); connect(ProjectExplorerPlugin::instance()->session(), SIGNAL(sessionLoaded()), this, SLOT(loadBookmarks())); updateActionStatus(); } BookmarkManager::~BookmarkManager() { DirectoryFileBookmarksMap::iterator it, end; end = m_bookmarksMap.end(); for (it = m_bookmarksMap.begin(); it != end; ++it) { FileNameBookmarksMap *bookmarks = it.value(); qDeleteAll(*bookmarks); delete bookmarks; } } QItemSelectionModel *BookmarkManager::selectionModel() const { return m_selectionModel; } QModelIndex BookmarkManager::index(int row, int column, const QModelIndex &parent) const { if (parent.isValid()) return QModelIndex(); else return createIndex(row, column, 0); } QModelIndex BookmarkManager::parent(const QModelIndex &) const { return QModelIndex(); } int BookmarkManager::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; else return m_bookmarksList.count(); } int BookmarkManager::columnCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return 3; } QVariant BookmarkManager::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.column() !=0 || index.row() < 0 || index.row() >= m_bookmarksList.count()) return QVariant(); if (role == BookmarkManager::Filename) return m_bookmarksList.at(index.row())->fileName(); else if (role == BookmarkManager::LineNumber) return m_bookmarksList.at(index.row())->lineNumber(); else if (role == BookmarkManager::Directory) return m_bookmarksList.at(index.row())->path(); else if (role == BookmarkManager::LineText) return m_bookmarksList.at(index.row())->lineText(); else if (role == Qt::ToolTipRole) return m_bookmarksList.at(index.row())->filePath(); return QVariant(); } void BookmarkManager::toggleBookmark() { TextEditor::ITextEditor *editor = currentTextEditor(); if (!editor) return; toggleBookmark(editor->file()->fileName(), editor->currentLine()); } void BookmarkManager::toggleBookmark(const QString &fileName, int lineNumber) { const QFileInfo fi(fileName); const int editorLine = lineNumber; // Remove any existing bookmark on this line if (Bookmark *mark = findBookmark(fi.path(), fi.fileName(), lineNumber)) { // TODO check if the bookmark is really on the same markable Interface removeBookmark(mark); return; } // Add a new bookmark if no bookmark existed on this line Bookmark *bookmark = new Bookmark(fi.filePath(), editorLine, this); addBookmark(bookmark); } void BookmarkManager::updateBookmark(Bookmark *bookmark) { int idx = m_bookmarksList.indexOf(bookmark); emit dataChanged(index(idx, 0, QModelIndex()), index(idx, 2, QModelIndex())); saveBookmarks(); } void BookmarkManager::removeAllBookmarks() { if (m_bookmarksList.isEmpty()) return; beginRemoveRows(QModelIndex(), 0, m_bookmarksList.size() - 1); DirectoryFileBookmarksMap::const_iterator it, end; end = m_bookmarksMap.constEnd(); for (it = m_bookmarksMap.constBegin(); it != end; ++it) { FileNameBookmarksMap *files = it.value(); FileNameBookmarksMap::const_iterator jt, jend; jend = files->constEnd(); for (jt = files->constBegin(); jt != jend; ++jt) { delete jt.value(); } files->clear(); delete files; } m_bookmarksMap.clear(); m_bookmarksList.clear(); endRemoveRows(); } void BookmarkManager::removeBookmark(Bookmark *bookmark) { int idx = m_bookmarksList.indexOf(bookmark); beginRemoveRows(QModelIndex(), idx, idx); const QFileInfo fi(bookmark->filePath() ); FileNameBookmarksMap *files = m_bookmarksMap.value(fi.path()); FileNameBookmarksMap::iterator i = files->begin(); while (i != files->end()) { if (i.value() == bookmark) { files->erase(i); delete bookmark; break; } ++i; } if (files->count() <= 0) { m_bookmarksMap.remove(fi.path()); delete files; } m_bookmarksList.removeAt(idx); endRemoveRows(); if (selectionModel()->currentIndex().isValid()) selectionModel()->setCurrentIndex(selectionModel()->currentIndex(), QItemSelectionModel::Select | QItemSelectionModel::Clear); updateActionStatus(); saveBookmarks(); } Bookmark *BookmarkManager::bookmarkForIndex(QModelIndex index) { if (!index.isValid() || index.row() >= m_bookmarksList.size()) return 0; return m_bookmarksList.at(index.row()); } bool BookmarkManager::gotoBookmark(Bookmark* bookmark) { using namespace TextEditor; if (ITextEditor *editor = BaseTextEditor::openEditorAt(bookmark->filePath(), bookmark->lineNumber())) return (editor->currentLine() == bookmark->lineNumber()); return false; } void BookmarkManager::nextInDocument() { documentPrevNext(true); } void BookmarkManager::prevInDocument() { documentPrevNext(false); } void BookmarkManager::documentPrevNext(bool next) { TextEditor::ITextEditor *editor = currentTextEditor(); int editorLine = editor->currentLine(); QFileInfo fi(editor->file()->fileName()); if (!m_bookmarksMap.contains(fi.path())) return; int firstLine = -1; int lastLine = -1; int prevLine = -1; int nextLine = -1; const QList<Bookmark*> marks = m_bookmarksMap.value(fi.path())->values(fi.fileName()); for (int i = 0; i < marks.count(); ++i) { int markLine = marks.at(i)->lineNumber(); if (firstLine == -1 || firstLine > markLine) firstLine = markLine; if (lastLine < markLine) lastLine = markLine; if (markLine < editorLine && prevLine < markLine) prevLine = markLine; if (markLine > editorLine && (nextLine == -1 || nextLine > markLine)) nextLine = markLine; } Core::EditorManager *em = Core::EditorManager::instance(); em->addCurrentPositionToNavigationHistory(); if (next) { if (nextLine == -1) editor->gotoLine(firstLine); else editor->gotoLine(nextLine); } else { if (prevLine == -1) editor->gotoLine(lastLine); else editor->gotoLine(prevLine); } } void BookmarkManager::next() { QModelIndex current = selectionModel()->currentIndex(); if (!current.isValid()) return; int row = current.row(); ++row; while (true) { if (row == m_bookmarksList.size()) row = 0; Bookmark *bk = m_bookmarksList.at(row); if (gotoBookmark(bk)) { QModelIndex newIndex = current.sibling(row, current.column()); selectionModel()->setCurrentIndex(newIndex, QItemSelectionModel::Select | QItemSelectionModel::Clear); return; } removeBookmark(bk); if (m_bookmarksList.isEmpty()) // No bookmarks anymore ... return; } } void BookmarkManager::prev() { QModelIndex current = selectionModel()->currentIndex(); if (!current.isValid()) return; int row = current.row(); while (true) { if (row == 0) row = m_bookmarksList.size(); --row; Bookmark *bk = m_bookmarksList.at(row); if (gotoBookmark(bk)) { QModelIndex newIndex = current.sibling(row, current.column()); selectionModel()->setCurrentIndex(newIndex, QItemSelectionModel::Select | QItemSelectionModel::Clear); return; } removeBookmark(bk); if (m_bookmarksList.isEmpty()) return; } } TextEditor::ITextEditor *BookmarkManager::currentTextEditor() const { Core::EditorManager *em = Core::EditorManager::instance(); Core::IEditor *currEditor = em->currentEditor(); if (!currEditor) return 0; return qobject_cast<TextEditor::ITextEditor *>(currEditor); } /* Returns the current session. */ SessionManager *BookmarkManager::sessionManager() const { return ProjectExplorerPlugin::instance()->session(); } BookmarkManager::State BookmarkManager::state() const { if (m_bookmarksMap.empty()) return NoBookMarks; TextEditor::ITextEditor *editor = currentTextEditor(); if (!editor) return HasBookMarks; const QFileInfo fi(editor->file()->fileName()); const DirectoryFileBookmarksMap::const_iterator dit = m_bookmarksMap.constFind(fi.path()); if (dit == m_bookmarksMap.constEnd()) return HasBookMarks; return HasBookmarksInDocument; } void BookmarkManager::updateActionStatus() { emit updateActions(state()); } void BookmarkManager::moveUp() { QModelIndex current = selectionModel()->currentIndex(); int row = current.row(); if (row == 0) row = m_bookmarksList.size(); --row; // swap current.row() and row Bookmark *b = m_bookmarksList.at(row); m_bookmarksList[row] = m_bookmarksList.at(current.row()); m_bookmarksList[current.row()] = b; QModelIndex topLeft = current.sibling(row, 0); QModelIndex bottomRight = current.sibling(current.row(), 2); emit dataChanged(topLeft, bottomRight); selectionModel()->setCurrentIndex(current.sibling(row, 0), QItemSelectionModel::Select | QItemSelectionModel::Clear); } void BookmarkManager::moveDown() { QModelIndex current = selectionModel()->currentIndex(); int row = current.row(); ++row; if (row == m_bookmarksList.size()) row = 0; // swap current.row() and row Bookmark *b = m_bookmarksList.at(row); m_bookmarksList[row] = m_bookmarksList.at(current.row()); m_bookmarksList[current.row()] = b; QModelIndex topLeft = current.sibling(current.row(), 0); QModelIndex bottomRight = current.sibling(row, 2); emit dataChanged(topLeft, bottomRight); selectionModel()->setCurrentIndex(current.sibling(row, 0), QItemSelectionModel::Select | QItemSelectionModel::Clear); } /* Returns the bookmark at the given file and line number, or 0 if no such bookmark exists. */ Bookmark* BookmarkManager::findBookmark(const QString &path, const QString &fileName, int lineNumber) { if (m_bookmarksMap.contains(path)) { foreach (Bookmark *bookmark, m_bookmarksMap.value(path)->values(fileName)) { if (bookmark->lineNumber() == lineNumber) return bookmark; } } return 0; } /* Adds a bookmark to the internal data structures. The 'userset' parameter * determines whether action status should be updated and whether the bookmarks * should be saved to the session settings. */ void BookmarkManager::addBookmark(Bookmark *bookmark, bool userset) { beginInsertRows(QModelIndex(), m_bookmarksList.size(), m_bookmarksList.size()); const QFileInfo fi(bookmark->filePath()); const QString &path = fi.path(); if (!m_bookmarksMap.contains(path)) m_bookmarksMap.insert(path, new FileNameBookmarksMap()); m_bookmarksMap.value(path)->insert(fi.fileName(), bookmark); m_bookmarksList.append(bookmark); endInsertRows(); if (userset) { updateActionStatus(); saveBookmarks(); } selectionModel()->setCurrentIndex(index(m_bookmarksList.size()-1 , 0, QModelIndex()), QItemSelectionModel::Select | QItemSelectionModel::Clear); } /* Adds a new bookmark based on information parsed from the string. */ void BookmarkManager::addBookmark(const QString &s) { int index2 = s.lastIndexOf(':'); int index1 = s.indexOf(':'); if (index2 != -1 || index1 != -1) { const QString &filePath = s.mid(index1+1, index2-index1-1); const int lineNumber = s.mid(index2 + 1).toInt(); const QFileInfo fi(filePath); if (!filePath.isEmpty() && !findBookmark(fi.path(), fi.fileName(), lineNumber)) { Bookmark *b = new Bookmark(filePath, lineNumber, this); addBookmark(b, false); } } else { qDebug() << "BookmarkManager::addBookmark() Invalid bookmark string:" << s; } } /* Puts the bookmark in a string for storing it in the settings. */ QString BookmarkManager::bookmarkToString(const Bookmark *b) { const QLatin1Char colon(':'); // Empty string was the name of the bookmark, which now is always "" return QLatin1String("") + colon + b->filePath() + colon + QString::number(b->lineNumber()); } /* Saves the bookmarks to the session settings. */ void BookmarkManager::saveBookmarks() { SessionManager *s = sessionManager(); if (!s) return; QStringList list; foreach (const FileNameBookmarksMap *bookmarksMap, m_bookmarksMap) foreach (const Bookmark *bookmark, *bookmarksMap) list << bookmarkToString(bookmark); s->setValue("Bookmarks", list); } /* Loads the bookmarks from the session settings. */ void BookmarkManager::loadBookmarks() { removeAllBookmarks(); SessionManager *s = sessionManager(); if (!s) return; const QStringList &list = s->value("Bookmarks").toStringList(); foreach (const QString &bookmarkString, list) addBookmark(bookmarkString); updateActionStatus(); } // BookmarkViewFactory BookmarkViewFactory::BookmarkViewFactory(BookmarkManager *bm) : m_manager(bm) { } QString BookmarkViewFactory::displayName() const { return BookmarkView::tr("Bookmarks"); } QString BookmarkViewFactory::id() const { return QLatin1String("Bookmarks"); } QKeySequence BookmarkViewFactory::activationSequence() const { return QKeySequence(Qt::ALT + Qt::Key_M); } Core::NavigationView BookmarkViewFactory::createWidget() { BookmarkView *bookmarkView = new BookmarkView(); bookmarkView->setModel(m_manager); Core::NavigationView view; view.widget = bookmarkView; return view; }
enricoros/k-qt-creator-inspector
src/plugins/bookmarks/bookmarkmanager.cpp
C++
lgpl-2.1
23,863
# Copyright (C) 2013-2017 Chris Lalancette <clalancette@gmail.com> # 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; # version 2.1 of the License. # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """ Linux installation """ import os import re import time import libvirt import oz.Guest import oz.OzException class LinuxCDGuest(oz.Guest.CDGuest): """ Class for Linux installation. """ def __init__(self, tdl, config, auto, output_disk, nicmodel, diskbus, iso_allowed, url_allowed, macaddress, useuefi): oz.Guest.CDGuest.__init__(self, tdl, config, auto, output_disk, nicmodel, None, None, diskbus, iso_allowed, url_allowed, macaddress, useuefi) def _test_ssh_connection(self, guestaddr): """ Internal method to test out the ssh connection before we try to use it. Under systemd, the IP address of a guest can come up and reportip can run before the ssh key is generated and sshd starts up. This check makes sure that we allow an additional 30 seconds (1 second per ssh attempt) for sshd to finish initializing. """ count = 30 success = False while count > 0: try: self.log.debug("Testing ssh connection, try %d", count) start = time.time() self.guest_execute_command(guestaddr, 'ls', timeout=1) self.log.debug("Succeeded") success = True break except oz.ozutil.SubprocessException: # ensure that we spent at least one second before trying again end = time.time() if (end - start) < 1: time.sleep(1 - (end - start)) count -= 1 if not success: self.log.debug("Failed to connect to ssh on running guest") raise oz.OzException.OzException("Failed to connect to ssh on running guest") def get_default_runlevel(self, g_handle): """ Function to determine the default runlevel based on the /etc/inittab. """ runlevel = "3" if g_handle.exists('/etc/inittab'): lines = g_handle.cat('/etc/inittab').split("\n") for line in lines: if re.match('id:', line): runlevel = line.split(':')[1] break return runlevel def guest_execute_command(self, guestaddr, command, timeout=10): """ Method to execute a command on the guest and return the output. """ # ServerAliveInterval protects against NAT firewall timeouts # on long-running commands with no output # # PasswordAuthentication=no prevents us from falling back to # keyboard-interactive password prompting # # -F /dev/null makes sure that we don't use the global or per-user # configuration files return oz.ozutil.subprocess_check_output(["ssh", "-i", self.sshprivkey, "-F", "/dev/null", "-o", "ServerAliveInterval=30", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=" + str(timeout), "-o", "UserKnownHostsFile=/dev/null", "-o", "PasswordAuthentication=no", "-o", "IdentitiesOnly yes", "root@" + guestaddr, command], printfn=self.log.debug) def guest_live_upload(self, guestaddr, file_to_upload, destination, timeout=10): """ Method to copy a file to the live guest. """ self.guest_execute_command(guestaddr, "mkdir -p " + os.path.dirname(destination), timeout) # ServerAliveInterval protects against NAT firewall timeouts # on long-running commands with no output # # PasswordAuthentication=no prevents us from falling back to # keyboard-interactive password prompting # # -F /dev/null makes sure that we don't use the global or per-user # configuration files return oz.ozutil.subprocess_check_output(["scp", "-i", self.sshprivkey, "-F", "/dev/null", "-o", "ServerAliveInterval=30", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=" + str(timeout), "-o", "UserKnownHostsFile=/dev/null", "-o", "PasswordAuthentication=no", "-o", "IdentitiesOnly yes", file_to_upload, "root@" + guestaddr + ":" + destination], printfn=self.log.debug) def _customize_files(self, guestaddr): """ Method to upload the custom files specified in the TDL to the guest. """ self.log.info("Uploading custom files") for name, fp in list(self.tdl.files.items()): # all of the self.tdl.files are named temporary files; we just need # to fetch the name out and have scp upload it self.guest_live_upload(guestaddr, fp.name, name) def _shutdown_guest(self, guestaddr, libvirt_dom): """ Method to shutdown the guest (gracefully at first, then with prejudice). """ if guestaddr is not None: # sometimes the ssh process gets disconnected before it can return # cleanly (particularly when the guest is running systemd). If that # happens, ssh returns 255, guest_execute_command throws an # exception, and the guest is forcibly destroyed. While this # isn't the end of the world, it isn't desirable. To avoid # this, we catch any exception thrown by ssh during the shutdown # command and throw them away. In the (rare) worst case, the # shutdown will not have made it to the guest and we'll have to wait # 90 seconds for wait_for_guest_shutdown to timeout and forcibly # kill the guest. try: self.guest_execute_command(guestaddr, 'shutdown -h now') except Exception: pass try: if not self._wait_for_guest_shutdown(libvirt_dom): self.log.warning("Guest did not shutdown in time, going to kill") else: libvirt_dom = None except Exception: self.log.warning("Failed shutting down guest, forcibly killing") if libvirt_dom is not None: try: libvirt_dom.destroy() except libvirt.libvirtError: # the destroy failed for some reason. This can happen if # _wait_for_guest_shutdown times out, but the domain shuts # down before we get to destroy. Check to make sure that the # domain is gone from the list of running domains; if so, just # continue on; if not, re-raise the error. for domid in self.libvirt_conn.listDomainsID(): if domid == libvirt_dom.ID(): raise def _collect_setup(self, libvirt_xml): # pylint: disable=unused-argument """ Default method to set the guest up for remote access. """ raise oz.OzException.OzException("ICICLE generation and customization is not implemented for guest %s" % (self.tdl.distro)) def _collect_teardown(self, libvirt_xml): # pylint: disable=unused-argument """ Method to reverse the changes done in _collect_setup. """ raise oz.OzException.OzException("ICICLE generation and customization is not implemented for guest %s" % (self.tdl.distro)) def _install_packages(self, guestaddr, packstr): # pylint: disable=unused-argument """ Internal method to install packages; expected to be overriden by child classes. """ raise oz.OzException.OzException("Customization is not implemented for guest %s" % (self.tdl.distro)) def _customize_repos(self, guestaddr): # pylint: disable=unused-argument """ Internal method to customize repositories; expected to be overriden by child classes. """ raise oz.OzException.OzException("Customization is not implemented for guest %s" % (self.tdl.distro)) def _remove_repos(self, guestaddr): # pylint: disable=unused-argument """ Internal method to remove repositories; expected to be overriden by child classes. """ raise oz.OzException.OzException("Repository removal not implemented for guest %s" % (self.tdl.distro)) def do_customize(self, guestaddr): """ Method to customize by installing additional packages and files. """ if not self.tdl.packages and not self.tdl.files and not self.tdl.commands: # no work to do, just return return self._customize_repos(guestaddr) for cmd in self.tdl.precommands: self.guest_execute_command(guestaddr, cmd.read()) self.log.debug("Installing custom packages") packstr = '' for package in self.tdl.packages: packstr += '"' + package.name + '" ' if packstr != '': self._install_packages(guestaddr, packstr) self._customize_files(guestaddr) self.log.debug("Running custom commands") for cmd in self.tdl.commands: self.guest_execute_command(guestaddr, cmd.read()) self.log.debug("Removing non-persisted repos") self._remove_repos(guestaddr) self.log.debug("Syncing") self.guest_execute_command(guestaddr, 'sync') def do_icicle(self, guestaddr): """ Default method to collect the package information and generate the ICICLE XML. """ raise oz.OzException.OzException("ICICLE generation is not implemented for this guest type") def _internal_customize(self, libvirt_xml, action): """ Internal method to customize and optionally generate an ICICLE for the operating system after initial installation. """ # the "action" input is actually a tri-state: # action = "gen_and_mod" means to generate the icicle and to # potentially make modifications # action = "gen_only" means to generate the icicle only, and not # look at any modifications # action = "mod_only" means to not generate the icicle, but still # potentially make modifications self.log.info("Customizing image") if not self.tdl.packages and not self.tdl.files and not self.tdl.commands: if action == "mod_only": self.log.info("No additional packages, files, or commands to install, and icicle generation not requested, skipping customization") return elif action == "gen_and_mod": # It is actually possible to get here with a "gen_and_mod" # action but a TDL that contains no real customizations. # In the "safe ICICLE" code below it is important to know # when we are truly in a "gen_only" state so we modify # the action here if we detect that ICICLE generation is the # only task to be done. self.log.debug("Asked to gen_and_mod but no mods are present - changing action to gen_only") action = "gen_only" # when doing an oz-install with -g, this isn't necessary as it will # just replace the port with the same port. However, it is very # necessary when doing an oz-customize since the serial port might # not match what is specified in the libvirt XML modified_xml = self._modify_libvirt_xml_for_serial(libvirt_xml) if action == "gen_only" and self.safe_icicle_gen: # We are only generating ICICLE and the user has asked us to do # this without modifying the completed image by booting it. # Create a copy on write snapshot to use for ICICLE # generation - discard when finished cow_diskimage = self.diskimage + "-icicle-snap.qcow2" self._internal_generate_diskimage(force=True, backing_filename=self.diskimage, image_filename=cow_diskimage) modified_xml = self._modify_libvirt_xml_diskimage(modified_xml, cow_diskimage, 'qcow2') self._collect_setup(modified_xml) icicle = None try: libvirt_dom = self.libvirt_conn.createXML(modified_xml, 0) try: guestaddr = None guestaddr = self._wait_for_guest_boot(libvirt_dom) self._test_ssh_connection(guestaddr) if action == "gen_and_mod": self.do_customize(guestaddr) icicle = self.do_icicle(guestaddr) elif action == "gen_only": icicle = self.do_icicle(guestaddr) elif action == "mod_only": self.do_customize(guestaddr) else: raise oz.OzException.OzException("Invalid customize action %s; this is a programming error" % (action)) finally: if action == "gen_only" and self.safe_icicle_gen: # if this is a gen_only and safe_icicle_gen, there is no # reason to wait around for the guest to shutdown; we'll # be removing the overlay file anyway. Just destroy it libvirt_dom.destroy() else: self._shutdown_guest(guestaddr, libvirt_dom) finally: if action == "gen_only" and self.safe_icicle_gen: # no need to teardown because we simply discard the file # containing those changes os.unlink(cow_diskimage) else: self._collect_teardown(modified_xml) return icicle def customize(self, libvirt_xml): """ Method to customize the operating system after installation. """ return self._internal_customize(libvirt_xml, "mod_only") def customize_and_generate_icicle(self, libvirt_xml): """ Method to customize and generate the ICICLE for an operating system after installation. This is equivalent to calling customize() and generate_icicle() back-to-back, but is faster. """ return self._internal_customize(libvirt_xml, "gen_and_mod") def generate_icicle(self, libvirt_xml): """ Method to generate the ICICLE from an operating system after installation. The ICICLE contains information about packages and other configuration on the diskimage. """ return self._internal_customize(libvirt_xml, "gen_only")
nullr0ute/oz
oz/Linux.py
Python
lgpl-2.1
16,373
<?php // (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ //this script may only be included - so its better to die if called directly. if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) { header("location: index.php"); exit; } /* * Smarty plugin * ------------------------------------------------------------- * Type: modifier * Name: kbsize * Purpose: returns size in Mb, Kb or bytes. * ------------------------------------------------------------- */ function smarty_modifier_kbsize($string, $bytes = false, $nb_decimals = 2, $unit_separator = '&nbsp;') { if ($string == '') { return ''; } if ($string > 1099511627776) { // 1024 x 1024 x 1024 x 1024 = 1099511627776 $string = number_format($string / 1099511627776, $nb_decimals); $kb_string = 'T'; } elseif ($string > 1073741824) { // 1024 x 1024 x 1024 = 1073741824 $string = number_format($string / 1073741824, $nb_decimals); $kb_string = 'G'; } elseif ($string > 1048576) { // 1024 x 1024 = 1048576 $string = number_format($string / 1048576, $nb_decimals); $kb_string = 'M'; } elseif ($string > 1024) { $string = number_format($string / 1024, $nb_decimals); $kb_string = 'K'; } else { $string = $string; $kb_string = ''; }; $kb_string = $kb_string . (($bytes) ? 'B' : 'b'); return $string . $unit_separator . tra($kb_string); }
tikiorg/tiki
lib/smarty_tiki/modifier.kbsize.php
PHP
lgpl-2.1
1,563
package com.outlookphone.quaritum.flora; public enum EnumDye { Common(0), CommonArcane(1), Arcane(2); private int data; /** * @return the data value */ public int getData() { return data; } EnumDye(int data) { this.data = data; } }
Eladkay/Quaritum-as-is
src/main/java/com/outlookphone/quaritum/flora/EnumDye.java
Java
lgpl-2.1
252
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2015, Open Source Geospatial Foundation (OSGeo) * * 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; * version 2.1 of the License. * * 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. */ package org.geotools.coverage.processing.operation; import it.geosolutions.jaiext.iterators.RandomIterFactory; import it.geosolutions.jaiext.range.NoDataContainer; import javax.media.jai.BorderExtender; import javax.media.jai.PlanarImage; import javax.media.jai.RenderedOp; import javax.media.jai.iterator.RandomIter; import org.geotools.image.ImageWorker; import org.geotools.util.factory.GeoTools; /** * Helper class disposing the border op image along with the iterator when {@link #done()} is called * * @author Andrea Aime - GeoSolutions */ class ExtendedRandomIter implements RandomIter { RandomIter delegate; RenderedOp op; public static RandomIter getRandomIterator( final PlanarImage src, int leftPad, int rightPad, int topPad, int bottomPad, BorderExtender extender) { RandomIter iterSource; if (extender != null) { ImageWorker w = new ImageWorker(src).setRenderingHints(GeoTools.getDefaultHints()); if (w.getNoData() != null) { w.setBackground(new NoDataContainer(w.getNoData()).getAsArray()); } RenderedOp op = w.border(leftPad, rightPad, topPad, bottomPad, extender).getRenderedOperation(); RandomIter it = RandomIterFactory.create(op, op.getBounds(), true, true); return new ExtendedRandomIter(it, op); } else { iterSource = RandomIterFactory.create(src, src.getBounds(), true, true); } return iterSource; } ExtendedRandomIter(RandomIter delegate, RenderedOp op) { super(); this.delegate = delegate; this.op = op; } @Override public int getSample(int x, int y, int b) { return delegate.getSample(x, y, b); } @Override public float getSampleFloat(int x, int y, int b) { return delegate.getSampleFloat(x, y, b); } @Override public double getSampleDouble(int x, int y, int b) { return delegate.getSampleDouble(x, y, b); } @Override public int[] getPixel(int x, int y, int[] iArray) { return delegate.getPixel(x, y, iArray); } @Override public float[] getPixel(int x, int y, float[] fArray) { return delegate.getPixel(x, y, fArray); } @Override public double[] getPixel(int x, int y, double[] dArray) { return delegate.getPixel(x, y, dArray); } @Override public void done() { delegate.done(); op.dispose(); } }
geotools/geotools
modules/library/coverage/src/main/java/org/geotools/coverage/processing/operation/ExtendedRandomIter.java
Java
lgpl-2.1
3,207
<?php /* * Copyright © 2010 - 2012 Modo Labs Inc. All rights reserved. * * The license governing the contents of this file is located in the LICENSE * file located at the root directory of this distribution. If the LICENSE file * is missing, please contact sales@modolabs.com. * */ /** * @package Module * @subpackage Customize */ /** * @package Module * @subpackage Customize */ class CustomizeWebModule extends WebModule { protected $id = 'customize'; protected $canBeHidden = false; protected $defaultAllowRobots = false; // Require sites to intentionally turn this on private function getModuleCustomizeList() { $navModules = $this->getAllModuleNavigationData(self::INCLUDE_DISABLED_MODULES); return $navModules['primary']; } private function handleRequest($args) { if (isset($args['action'])) { $currentModules = $this->getModuleCustomizeList(); switch ($args['action']) { case 'swap': $currentIDs = array_keys($currentModules); if (isset($args['module1'], $args['module2']) && in_array($args['module1'], $currentIDs) && in_array($args['module2'], $currentIDs)) { foreach ($currentIDs as $index => &$id) { if ($id == $args['module1']) { $id = $args['module2']; } else if ($id == $args['module2']) { $id = $args['module1']; } } $this->setNavigationModuleOrder($currentIDs); } break; case 'on': case 'off': if (isset($args['module'])) { $disabledModuleIDs = array(); foreach ($currentModules as $id => &$info) { if ($id == $args['module']) { $info['disabled'] = $args['action'] != 'on'; } if ($info['disabled']) { $disabledModuleIDs[] = $id; } } $this->setNavigationHiddenModules($disabledModuleIDs); } break; default: Kurogo::log(LOG_WARNING,__FUNCTION__."(): Unknown action '{$_REQUEST['action']}'",'module'); break; } } } protected function initializeForPage() { $this->handleRequest($this->args); $modules = $this->getModuleCustomizeList(); $moduleIDs = array(); $disabledModuleIDs = array(); foreach ($modules as $id => $info) { $moduleIDs[] = $id; if ($info['disabled']) { $disabledModuleIDs[] = $id; } } switch($this->pagetype) { case 'compliant': case 'tablet': $this->addInlineJavascript( 'var modules = '.json_encode($moduleIDs).';'. 'var disabledModules = '.json_encode($disabledModuleIDs).';'. 'var MODULE_ORDER_COOKIE = "'.self::MODULE_ORDER_COOKIE.'";'. 'var DISABLED_MODULES_COOKIE = "'.self::DISABLED_MODULES_COOKIE.'";'. 'var MODULE_ORDER_COOKIE_LIFESPAN = '.Kurogo::getSiteVar('MODULE_ORDER_COOKIE_LIFESPAN').';'. 'var COOKIE_PATH = "'.COOKIE_PATH.'";' ); $this->addInlineJavascriptFooter('init();'); break; case 'touch': case 'basic': foreach ($moduleIDs as $index => $id) { $modules[$id]['toggleDisabledURL'] = $this->buildBreadcrumbURL('index', array( 'action' => $modules[$id]['disabled'] ? 'on' : 'off', 'module' => $id, ), false); if ($index > 0) { $modules[$id]['swapUpURL'] = $this->buildBreadcrumbURL('index', array( 'action' => 'swap', 'module1' => $id, 'module2' => $moduleIDs[$index-1], ), false); } if ($index < (count($moduleIDs)-1)) { $modules[$id]['swapDownURL'] = $this->buildBreadcrumbURL('index', array( 'action' => 'swap', 'module1' => $id, 'module2' => $moduleIDs[$index+1], ), false); } } break; default: break; } $this->assignByRef('modules', $modules); } }
CoffeeJack/ElderTracker
app/modules/customize/CustomizeWebModule.php
PHP
lgpl-2.1
4,263
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.tool.schema.extract.internal; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import org.hibernate.JDBCException; import org.hibernate.boot.model.TruthValue; import org.hibernate.boot.model.naming.DatabaseIdentifier; import org.hibernate.boot.model.naming.Identifier; import org.hibernate.boot.model.relational.QualifiedTableName; import org.hibernate.cfg.AvailableSettings; import org.hibernate.engine.config.spi.ConfigurationService; import org.hibernate.engine.config.spi.StandardConverters; import org.hibernate.engine.jdbc.env.spi.IdentifierHelper; import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.collections.ArrayHelper; import org.hibernate.internal.util.compare.EqualsHelper; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.tool.schema.extract.spi.ColumnInformation; import org.hibernate.tool.schema.extract.spi.ExtractionContext; import org.hibernate.tool.schema.extract.spi.ForeignKeyInformation; import org.hibernate.tool.schema.extract.spi.IndexInformation; import org.hibernate.tool.schema.extract.spi.InformationExtractor; import org.hibernate.tool.schema.extract.spi.PrimaryKeyInformation; import org.hibernate.tool.schema.extract.spi.SchemaExtractionException; import org.hibernate.tool.schema.extract.spi.TableInformation; import org.hibernate.tool.schema.spi.SchemaManagementException; /** * Implementation of the SchemaMetaDataExtractor contract which uses the standard JDBC {@link java.sql.DatabaseMetaData} * API for extraction. * * @author Steve Ebersole */ public class InformationExtractorJdbcDatabaseMetaDataImpl implements InformationExtractor { private static final CoreMessageLogger log = CoreLogging.messageLogger( InformationExtractorJdbcDatabaseMetaDataImpl.class ); private final String[] tableTypes; private String[] extraPhysicalTableTypes; private final ExtractionContext extractionContext; public InformationExtractorJdbcDatabaseMetaDataImpl(ExtractionContext extractionContext) { this.extractionContext = extractionContext; ConfigurationService configService = extractionContext.getServiceRegistry() .getService( ConfigurationService.class ); final String extraPhysycalTableTypesConfig = configService.getSetting( AvailableSettings.EXTRA_PHYSICAL_TABLE_TYPES, StandardConverters.STRING, "" ); if ( !"".equals( extraPhysycalTableTypesConfig.trim() ) ) { this.extraPhysicalTableTypes = StringHelper.splitTrimmingTokens( ",;", extraPhysycalTableTypesConfig, false ); } final String[] tempTableTypes; if ( ConfigurationHelper.getBoolean( AvailableSettings.ENABLE_SYNONYMS, configService.getSettings(), false ) ) { tempTableTypes = new String[] {"TABLE", "VIEW", "SYNONYM"}; } else { tempTableTypes = new String[] {"TABLE", "VIEW"}; } if ( this.extraPhysicalTableTypes != null ) { this.tableTypes = ArrayHelper.join( tempTableTypes, this.extraPhysicalTableTypes ); } else { this.tableTypes = tempTableTypes; } } protected IdentifierHelper identifierHelper() { return extractionContext.getJdbcEnvironment().getIdentifierHelper(); } protected JDBCException convertSQLException(SQLException sqlException, String message) { return extractionContext.getJdbcEnvironment().getSqlExceptionHelper().convert( sqlException, message ); } protected String toMetaDataObjectName(Identifier identifier) { return extractionContext.getJdbcEnvironment().getIdentifierHelper().toMetaDataObjectName( identifier ); } @Override public boolean catalogExists(Identifier catalog) { try { final ResultSet resultSet = extractionContext.getJdbcDatabaseMetaData().getCatalogs(); try { while ( resultSet.next() ) { final String existingCatalogName = resultSet.getString( "TABLE_CAT" ); // todo : hmm.. case sensitive or insensitive match... // for now, match any case... if ( catalog.getText().equalsIgnoreCase( existingCatalogName ) ) { return true; } } return false; } finally { try { resultSet.close(); } catch (SQLException ignore) { } } } catch (SQLException sqlException) { throw convertSQLException( sqlException, "Unable to query DatabaseMetaData for existing catalogs" ); } } @Override public boolean schemaExists(Identifier catalog, Identifier schema) { try { final String catalogFilter = determineCatalogFilter( catalog ); final String schemaFilter = determineSchemaFilter( schema ); final ResultSet resultSet = extractionContext.getJdbcDatabaseMetaData().getSchemas( catalogFilter, schemaFilter ); try { if ( !resultSet.next() ) { return false; } if ( resultSet.next() ) { final String catalogName = catalog == null ? "" : catalog.getCanonicalName(); final String schemaName = schema == null ? "" : schema.getCanonicalName(); log.debugf( "Multiple schemas found with that name [%s.%s]", catalogName, schemaName ); } return true; } finally { try { resultSet.close(); } catch (SQLException ignore) { } } } catch (SQLException sqlException) { throw convertSQLException( sqlException, "Unable to query DatabaseMetaData for existing schemas" ); } } private String determineCatalogFilter(Identifier catalog) throws SQLException { Identifier identifierToUse = catalog; if ( identifierToUse == null ) { identifierToUse = extractionContext.getDefaultCatalog(); } return extractionContext.getJdbcEnvironment().getIdentifierHelper().toMetaDataCatalogName( identifierToUse ); } private String determineSchemaFilter(Identifier schema) throws SQLException { Identifier identifierToUse = schema; if ( identifierToUse == null ) { identifierToUse = extractionContext.getDefaultSchema(); } return extractionContext.getJdbcEnvironment().getIdentifierHelper().toMetaDataSchemaName( identifierToUse ); } public TableInformation extractTableInformation( Identifier catalog, Identifier schema, Identifier name, ResultSet resultSet) throws SQLException { if ( catalog == null ) { catalog = identifierHelper().toIdentifier( resultSet.getString( "TABLE_CAT" ) ); } if ( schema == null ) { schema = identifierHelper().toIdentifier( resultSet.getString( "TABLE_SCHEM" ) ); } if ( name == null ) { name = identifierHelper().toIdentifier( resultSet.getString( "TABLE_NAME" ) ); } final QualifiedTableName tableName = new QualifiedTableName( catalog, schema, name ); return new TableInformationImpl( this, tableName, isPhysicalTableType( resultSet.getString( "TABLE_TYPE" ) ), resultSet.getString( "REMARKS" ) ); } @Override public TableInformation getTable(Identifier catalog, Identifier schema, Identifier tableName) { if ( catalog != null || schema != null ) { // The table defined an explicit namespace. In such cases we only ever want to look // in the identified namespace return locateTableInNamespace( catalog, schema, tableName ); } else { // The table did not define an explicit namespace: // 1) look in current namespace // 2) look in default namespace // 3) look in all namespaces - multiple hits is considered an error TableInformation tableInfo = null; // 1) look in current namespace if ( extractionContext.getJdbcEnvironment().getCurrentCatalog() != null || extractionContext.getJdbcEnvironment().getCurrentSchema() != null ) { tableInfo = locateTableInNamespace( extractionContext.getJdbcEnvironment().getCurrentCatalog(), extractionContext.getJdbcEnvironment().getCurrentSchema(), tableName ); if ( tableInfo != null ) { return tableInfo; } } // 2) look in default namespace if ( extractionContext.getDefaultCatalog() != null || extractionContext.getDefaultSchema() != null ) { tableInfo = locateTableInNamespace( extractionContext.getJdbcEnvironment().getCurrentCatalog(), extractionContext.getJdbcEnvironment().getCurrentSchema(), tableName ); if ( tableInfo != null ) { return tableInfo; } } // 3) look in all namespaces try { final String tableNameFilter = toMetaDataObjectName( tableName ); final ResultSet resultSet = extractionContext.getJdbcDatabaseMetaData().getTables( null, null, tableNameFilter, tableTypes ); try { return processGetTableResults( null, null, tableName, resultSet ); } finally { try { resultSet.close(); } catch (SQLException ignore) { } } } catch (SQLException sqlException) { throw convertSQLException( sqlException, "Error accessing table metadata" ); } } } private TableInformation locateTableInNamespace( Identifier catalog, Identifier schema, Identifier tableName) { Identifier catalogToUse = null; Identifier schemaToUse = null; final String catalogFilter; final String schemaFilter; if ( extractionContext.getJdbcEnvironment().getNameQualifierSupport().supportsCatalogs() ) { if ( catalog == null ) { catalogFilter = ""; } else { catalogToUse = catalog; catalogFilter = toMetaDataObjectName( catalog ); } } else { catalogFilter = null; } if ( extractionContext.getJdbcEnvironment().getNameQualifierSupport().supportsSchemas() ) { if ( schema == null ) { schemaFilter = ""; } else { schemaToUse = schema; schemaFilter = toMetaDataObjectName( schema ); } } else { schemaFilter = null; } final String tableNameFilter = toMetaDataObjectName( tableName ); try { ResultSet resultSet = extractionContext.getJdbcDatabaseMetaData().getTables( catalogFilter, schemaFilter, tableNameFilter, tableTypes ); return processGetTableResults( catalogToUse, schemaToUse, tableName, resultSet ); } catch (SQLException sqlException) { throw convertSQLException( sqlException, "Error accessing table metadata" ); } } private TableInformation processGetTableResults( Identifier catalog, Identifier schema, Identifier tableName, ResultSet resultSet) throws SQLException { try { if ( !resultSet.next() ) { log.tableNotFound( tableName.render() ); return null; } final TableInformation tableInformation = extractTableInformation( catalog, schema, tableName, resultSet ); if ( resultSet.next() ) { log.multipleTablesFound( tableName.render() ); final String catalogName = catalog == null ? "" : catalog.render(); final String schemaName = schema == null ? "" : schema.render(); throw new SchemaExtractionException( String.format( Locale.ENGLISH, "More than one table found in namespace (%s, %s) : %s", catalogName, schemaName, tableName.render() ) ); } return tableInformation; } finally { try { resultSet.close(); } catch (SQLException ignore) { } } } protected boolean isPhysicalTableType(String tableType) { if ( extraPhysicalTableTypes == null ) { return "TABLE".equalsIgnoreCase( tableType ); } else { if ( "TABLE".equalsIgnoreCase( tableType ) ) { return true; } for ( int i = 0; i < extraPhysicalTableTypes.length; i++ ) { if ( extraPhysicalTableTypes[i].equalsIgnoreCase( tableType ) ) { return true; } } return false; } } @Override public ColumnInformation getColumn(TableInformation tableInformation, Identifier columnIdentifier) { final Identifier catalog = tableInformation.getName().getCatalogName(); final Identifier schema = tableInformation.getName().getSchemaName(); final String catalogFilter; final String schemaFilter; if ( extractionContext.getJdbcEnvironment().getNameQualifierSupport().supportsCatalogs() ) { if ( catalog == null ) { catalogFilter = ""; } else { catalogFilter = toMetaDataObjectName( catalog ); } } else { catalogFilter = null; } if ( extractionContext.getJdbcEnvironment().getNameQualifierSupport().supportsSchemas() ) { if ( schema == null ) { schemaFilter = ""; } else { schemaFilter = toMetaDataObjectName( schema ); } } else { schemaFilter = null; } final String tableFilter = toMetaDataObjectName( tableInformation.getName().getTableName() ); final String columnFilter = toMetaDataObjectName( columnIdentifier ); try { ResultSet resultSet = extractionContext.getJdbcDatabaseMetaData().getColumns( catalogFilter, schemaFilter, tableFilter, columnFilter ); try { if ( !resultSet.next() ) { return null; } return new ColumnInformationImpl( tableInformation, identifierHelper().toIdentifier( resultSet.getString( "COLUMN_NAME" ) ), resultSet.getInt( "DATA_TYPE" ), new StringTokenizer( resultSet.getString( "TYPE_NAME" ), "() " ).nextToken(), resultSet.getInt( "COLUMN_SIZE" ), resultSet.getInt( "DECIMAL_DIGITS" ), interpretTruthValue( resultSet.getString( "IS_NULLABLE" ) ) ); } finally { resultSet.close(); } } catch (SQLException e) { throw convertSQLException( e, "Error accessing column metadata: " + tableInformation.getName().toString() ); } } private TruthValue interpretTruthValue(String nullable) { if ( "yes".equalsIgnoreCase( nullable ) ) { return TruthValue.TRUE; } else if ( "no".equalsIgnoreCase( nullable ) ) { return TruthValue.FALSE; } return TruthValue.UNKNOWN; } @Override public PrimaryKeyInformation getPrimaryKey(TableInformationImpl tableInformation) { try { ResultSet resultSet = extractionContext.getJdbcDatabaseMetaData().getPrimaryKeys( identifierHelper().toMetaDataCatalogName( tableInformation.getName().getCatalogName() ), identifierHelper().toMetaDataSchemaName( tableInformation.getName().getSchemaName() ), identifierHelper().toMetaDataObjectName( tableInformation.getName().getTableName() ) ); final List<ColumnInformation> pkColumns = new ArrayList<ColumnInformation>(); boolean firstPass = true; Identifier pkIdentifier = null; try { while ( resultSet.next() ) { final String currentPkName = resultSet.getString( "PK_NAME" ); final Identifier currentPkIdentifier = currentPkName == null ? null : identifierHelper().toIdentifier( currentPkName ); if ( firstPass ) { pkIdentifier = currentPkIdentifier; firstPass = false; } else { if ( !EqualsHelper.equals( pkIdentifier, currentPkIdentifier ) ) { throw new SchemaExtractionException( String.format( "Encountered primary keys differing name on table %s", tableInformation.getName().toString() ) ); } } final int columnPosition = resultSet.getInt( "KEY_SEQ" ); final String columnName = resultSet.getString( "COLUMN_NAME" ); final Identifier columnIdentifier = identifierHelper().toIdentifier( columnName ); final ColumnInformation column = tableInformation.getColumn( columnIdentifier ); pkColumns.add( columnPosition-1, column ); } } finally { resultSet.close(); } if ( firstPass ) { // we did not find any results (no pk) return null; } else { // validate column list is properly contiguous for ( int i = 0; i < pkColumns.size(); i++ ) { if ( pkColumns.get( i ) == null ) { throw new SchemaExtractionException( "Primary Key information was missing for KEY_SEQ = " + ( i+1) ); } } // build the return return new PrimaryKeyInformationImpl( pkIdentifier, pkColumns ); } } catch (SQLException e) { throw convertSQLException( e, "Error while reading primary key meta data for " + tableInformation.getName().toString() ); } } @Override public Iterable<IndexInformation> getIndexes(TableInformation tableInformation) { final Map<Identifier, IndexInformationImpl.Builder> builders = new HashMap<Identifier, IndexInformationImpl.Builder>(); try { ResultSet resultSet = extractionContext.getJdbcDatabaseMetaData().getIndexInfo( identifierHelper().toMetaDataCatalogName( tableInformation.getName().getCatalogName() ), identifierHelper().toMetaDataSchemaName( tableInformation.getName().getSchemaName() ), identifierHelper().toMetaDataObjectName( tableInformation.getName().getTableName() ), false, // DO NOT limit to just unique true // DO require up-to-date results ); try { while ( resultSet.next() ) { if ( resultSet.getShort("TYPE") == DatabaseMetaData.tableIndexStatistic ) { continue; } final Identifier indexIdentifier = identifierHelper().toIdentifier( resultSet.getString( "INDEX_NAME" ) ); IndexInformationImpl.Builder builder = builders.get( indexIdentifier ); if ( builder == null ) { builder = IndexInformationImpl.builder( indexIdentifier ); builders.put( indexIdentifier, builder ); } final Identifier columnIdentifier = identifierHelper().toIdentifier( resultSet.getString( "COLUMN_NAME" ) ); final ColumnInformation columnInformation = tableInformation.getColumn( columnIdentifier ); if ( columnInformation == null ) { // See HHH-10191: this may happen when dealing with Oracle/PostgreSQL function indexes log.logCannotLocateIndexColumnInformation( columnIdentifier.getText(), indexIdentifier.getText() ); } builder.addColumn( columnInformation ); } } finally { resultSet.close(); } } catch (SQLException e) { throw convertSQLException( e, "Error accessing index information: " + tableInformation.getName().toString() ); } final List<IndexInformation> indexes = new ArrayList<IndexInformation>(); for ( IndexInformationImpl.Builder builder : builders.values() ) { IndexInformationImpl index = builder.build(); indexes.add( index ); } return indexes; } @Override public Iterable<ForeignKeyInformation> getForeignKeys(TableInformation tableInformation) { final Map<Identifier, ForeignKeyBuilder> fkBuilders = new HashMap<Identifier, ForeignKeyBuilder>(); try { ResultSet resultSet = extractionContext.getJdbcDatabaseMetaData().getImportedKeys( identifierHelper().toMetaDataCatalogName( tableInformation.getName().getCatalogName() ), identifierHelper().toMetaDataSchemaName( tableInformation.getName().getSchemaName() ), identifierHelper().toMetaDataObjectName( tableInformation.getName().getTableName() ) ); // todo : need to account for getCrossReference() as well... try { while ( resultSet.next() ) { // IMPL NOTE : The builder is mainly used to collect the column reference mappings final Identifier fkIdentifier = identifierHelper().toIdentifier( resultSet.getString( "FK_NAME" ) ); ForeignKeyBuilder fkBuilder = fkBuilders.get( fkIdentifier ); if ( fkBuilder == null ) { fkBuilder = generateForeignKeyBuilder( fkIdentifier ); fkBuilders.put( fkIdentifier, fkBuilder ); } final QualifiedTableName incomingPkTableName = extractKeyTableName( resultSet, "PK" ); final TableInformation pkTableInformation = extractionContext.getDatabaseObjectAccess() .locateTableInformation( incomingPkTableName ); if ( pkTableInformation == null ) { // the assumption here is that we have not seen this table already based on fully-qualified name // during previous step of building all table metadata so most likely this is // not a match based solely on schema/catalog and that another row in this result set // should match. continue; } final Identifier fkColumnIdentifier = identifierHelper().toIdentifier( resultSet.getString( "FKCOLUMN_NAME" ) ); final Identifier pkColumnIdentifier = identifierHelper().toIdentifier( resultSet.getString( "PKCOLUMN_NAME" ) ); fkBuilder.addColumnMapping( tableInformation.getColumn( fkColumnIdentifier ), pkTableInformation.getColumn( pkColumnIdentifier ) ); } } finally { resultSet.close(); } } catch (SQLException e) { throw convertSQLException( e, "Error accessing column metadata: " + tableInformation.getName().toString() ); } final List<ForeignKeyInformation> fks = new ArrayList<ForeignKeyInformation>(); for ( ForeignKeyBuilder fkBuilder : fkBuilders.values() ) { ForeignKeyInformation fk = fkBuilder.build(); fks.add( fk ); } return fks; } private ForeignKeyBuilder generateForeignKeyBuilder(Identifier fkIdentifier) { return new ForeignKeyBuilderImpl( fkIdentifier ); } protected interface ForeignKeyBuilder { ForeignKeyBuilder addColumnMapping(ColumnInformation referencing, ColumnInformation referenced); ForeignKeyInformation build(); } protected static class ForeignKeyBuilderImpl implements ForeignKeyBuilder { private final Identifier fkIdentifier; private final List<ForeignKeyInformation.ColumnReferenceMapping> columnMappingList = new ArrayList<ForeignKeyInformation.ColumnReferenceMapping>(); public ForeignKeyBuilderImpl(Identifier fkIdentifier) { this.fkIdentifier = fkIdentifier; } @Override public ForeignKeyBuilder addColumnMapping(ColumnInformation referencing, ColumnInformation referenced) { columnMappingList.add( new ForeignKeyInformationImpl.ColumnReferenceMappingImpl( referencing, referenced ) ); return this; } @Override public ForeignKeyInformationImpl build() { if ( columnMappingList.isEmpty() ) { throw new SchemaManagementException( "Attempt to resolve foreign key metadata from JDBC metadata failed to find " + "column mappings for foreign key named [" + fkIdentifier.getText() + "]" ); } return new ForeignKeyInformationImpl( fkIdentifier, columnMappingList ); } } private QualifiedTableName extractKeyTableName(ResultSet resultSet, String prefix) throws SQLException { final String incomingCatalogName = resultSet.getString( prefix + "TABLE_CAT" ); final String incomingSchemaName = resultSet.getString( prefix + "TABLE_SCHEM" ); final String incomingTableName = resultSet.getString( prefix + "TABLE_NAME" ); final DatabaseIdentifier catalog = DatabaseIdentifier.toIdentifier( incomingCatalogName ); final DatabaseIdentifier schema = DatabaseIdentifier.toIdentifier( incomingSchemaName ); final DatabaseIdentifier table = DatabaseIdentifier.toIdentifier( incomingTableName ); return new QualifiedTableName( catalog, schema, table ); } }
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/InformationExtractorJdbcDatabaseMetaDataImpl.java
Java
lgpl-2.1
23,277
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrice Pominville, Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.Body; import soot.toolkits.exceptions.PedanticThrowAnalysis; /** * <p> * Represents a CFG for a {@link Body} instance where the nodes are {@link soot.Unit} instances, and where control flow * associated with exceptions is taken into account. In a <code>CompleteUnitGraph</code>, every <code>Unit</code> covered by * a {@link soot.Trap} is considered to have the potential to throw an exception caught by the <code>Trap</code>, so there * are edges to the <code>Trap</code>'s handler from every trapped <code>Unit</code> , as well as from all the predecessors * of the trapped <code>Unit</code>s. * * <p> * This implementation of <code>CompleteUnitGraph</code> is included for backwards compatibility (new code should use * {@link ExceptionalUnitGraph}), but the graphs it produces are not necessarily identical to the graphs produced by the * implementation of <code>CompleteUnitGraph</code> provided by versions of Soot up to and including release 2.1.0. The known * differences include: * * <ul> * * <li>If a <code>Body</code> includes <code>Unit</code>s which branch into the middle of the region protected by a * <code>Trap</code> this implementation of <code>CompleteUnitGraph</code> will include edges from those branching * <code>Unit</code>s to the <code>Trap</code>'s handler (since the branches are predecessors of an instruction which may * throw an exception caught by the <code>Trap</code>). The 2.1.0 implementation of <code>CompleteUnitGraph</code> mistakenly * omitted these edges.</li> * * <li>If the initial <code>Unit</code> in the <code>Body</code> might throw an exception caught by a <code>Trap</code> * within the body, this implementation will include the initial handler <code>Unit</code> in the list returned by * <code>getHeads()</code> (since the handler unit might be the first Unit in the method to execute to completion). The 2.1.0 * implementation of <code>CompleteUnitGraph</code> mistakenly omitted the handler from the set of heads.</li> * * </ul> * </p> */ public class CompleteUnitGraph extends ExceptionalUnitGraph { public CompleteUnitGraph(Body b) { super(b, PedanticThrowAnalysis.v(), false); } }
plast-lab/soot
src/main/java/soot/toolkits/graph/CompleteUnitGraph.java
Java
lgpl-2.1
3,038
/* -*-c++-*- IfcPlusPlus - www.ifcplusplus.com - Copyright (C) 2011 Fabian Gerold * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <sstream> #include <limits> #include "ifcpp/model/IfcPPException.h" #include "ifcpp/model/IfcPPAttributeObject.h" #include "ifcpp/model/IfcPPGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IfcPPEntityEnums.h" #include "include/IfcAddressTypeEnum.h" #include "include/IfcLabel.h" #include "include/IfcOrganization.h" #include "include/IfcPerson.h" #include "include/IfcTelecomAddress.h" #include "include/IfcText.h" #include "include/IfcURIReference.h" // ENTITY IfcTelecomAddress IfcTelecomAddress::IfcTelecomAddress() { m_entity_enum = IFCTELECOMADDRESS; } IfcTelecomAddress::IfcTelecomAddress( int id ) { m_id = id; m_entity_enum = IFCTELECOMADDRESS; } IfcTelecomAddress::~IfcTelecomAddress() {} shared_ptr<IfcPPObject> IfcTelecomAddress::getDeepCopy( IfcPPCopyOptions& options ) { shared_ptr<IfcTelecomAddress> copy_self( new IfcTelecomAddress() ); if( m_Purpose ) { copy_self->m_Purpose = dynamic_pointer_cast<IfcAddressTypeEnum>( m_Purpose->getDeepCopy(options) ); } if( m_Description ) { copy_self->m_Description = dynamic_pointer_cast<IfcText>( m_Description->getDeepCopy(options) ); } if( m_UserDefinedPurpose ) { copy_self->m_UserDefinedPurpose = dynamic_pointer_cast<IfcLabel>( m_UserDefinedPurpose->getDeepCopy(options) ); } for( size_t ii=0; ii<m_TelephoneNumbers.size(); ++ii ) { auto item_ii = m_TelephoneNumbers[ii]; if( item_ii ) { copy_self->m_TelephoneNumbers.push_back( dynamic_pointer_cast<IfcLabel>(item_ii->getDeepCopy(options) ) ); } } for( size_t ii=0; ii<m_FacsimileNumbers.size(); ++ii ) { auto item_ii = m_FacsimileNumbers[ii]; if( item_ii ) { copy_self->m_FacsimileNumbers.push_back( dynamic_pointer_cast<IfcLabel>(item_ii->getDeepCopy(options) ) ); } } if( m_PagerNumber ) { copy_self->m_PagerNumber = dynamic_pointer_cast<IfcLabel>( m_PagerNumber->getDeepCopy(options) ); } for( size_t ii=0; ii<m_ElectronicMailAddresses.size(); ++ii ) { auto item_ii = m_ElectronicMailAddresses[ii]; if( item_ii ) { copy_self->m_ElectronicMailAddresses.push_back( dynamic_pointer_cast<IfcLabel>(item_ii->getDeepCopy(options) ) ); } } if( m_WWWHomePageURL ) { copy_self->m_WWWHomePageURL = dynamic_pointer_cast<IfcURIReference>( m_WWWHomePageURL->getDeepCopy(options) ); } for( size_t ii=0; ii<m_MessagingIDs.size(); ++ii ) { auto item_ii = m_MessagingIDs[ii]; if( item_ii ) { copy_self->m_MessagingIDs.push_back( dynamic_pointer_cast<IfcURIReference>(item_ii->getDeepCopy(options) ) ); } } return copy_self; } void IfcTelecomAddress::getStepLine( std::stringstream& stream ) const { stream << "#" << m_id << "= IFCTELECOMADDRESS" << "("; if( m_Purpose ) { m_Purpose->getStepParameter( stream ); } else { stream << "*"; } stream << ","; if( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << "*"; } stream << ","; if( m_UserDefinedPurpose ) { m_UserDefinedPurpose->getStepParameter( stream ); } else { stream << "*"; } stream << ","; writeTypeList( stream, m_TelephoneNumbers ); stream << ","; writeTypeList( stream, m_FacsimileNumbers ); stream << ","; if( m_PagerNumber ) { m_PagerNumber->getStepParameter( stream ); } else { stream << "$"; } stream << ","; writeTypeList( stream, m_ElectronicMailAddresses ); stream << ","; if( m_WWWHomePageURL ) { m_WWWHomePageURL->getStepParameter( stream ); } else { stream << "$"; } stream << ","; writeTypeList( stream, m_MessagingIDs ); stream << ");"; } void IfcTelecomAddress::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_id; } void IfcTelecomAddress::readStepArguments( const std::vector<std::wstring>& args, const boost::unordered_map<int,shared_ptr<IfcPPEntity> >& map ) { const int num_args = (int)args.size(); if( num_args != 9 ){ std::stringstream err; err << "Wrong parameter count for entity IfcTelecomAddress, expecting 9, having " << num_args << ". Entity ID: " << m_id << std::endl; throw IfcPPException( err.str().c_str() ); } m_Purpose = IfcAddressTypeEnum::createObjectFromSTEP( args[0] ); m_Description = IfcText::createObjectFromSTEP( args[1] ); m_UserDefinedPurpose = IfcLabel::createObjectFromSTEP( args[2] ); readSelectList( args[3], m_TelephoneNumbers, map ); readSelectList( args[4], m_FacsimileNumbers, map ); m_PagerNumber = IfcLabel::createObjectFromSTEP( args[5] ); readSelectList( args[6], m_ElectronicMailAddresses, map ); m_WWWHomePageURL = IfcURIReference::createObjectFromSTEP( args[7] ); readSelectList( args[8], m_MessagingIDs, map ); } void IfcTelecomAddress::getAttributes( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes ) { IfcAddress::getAttributes( vec_attributes ); if( m_TelephoneNumbers.size() > 0 ) { shared_ptr<IfcPPAttributeObjectVector> TelephoneNumbers_vec_object( new IfcPPAttributeObjectVector() ); std::copy( m_TelephoneNumbers.begin(), m_TelephoneNumbers.end(), std::back_inserter( TelephoneNumbers_vec_object->m_vec ) ); vec_attributes.push_back( std::make_pair( "TelephoneNumbers", TelephoneNumbers_vec_object ) ); } if( m_FacsimileNumbers.size() > 0 ) { shared_ptr<IfcPPAttributeObjectVector> FacsimileNumbers_vec_object( new IfcPPAttributeObjectVector() ); std::copy( m_FacsimileNumbers.begin(), m_FacsimileNumbers.end(), std::back_inserter( FacsimileNumbers_vec_object->m_vec ) ); vec_attributes.push_back( std::make_pair( "FacsimileNumbers", FacsimileNumbers_vec_object ) ); } vec_attributes.push_back( std::make_pair( "PagerNumber", m_PagerNumber ) ); if( m_ElectronicMailAddresses.size() > 0 ) { shared_ptr<IfcPPAttributeObjectVector> ElectronicMailAddresses_vec_object( new IfcPPAttributeObjectVector() ); std::copy( m_ElectronicMailAddresses.begin(), m_ElectronicMailAddresses.end(), std::back_inserter( ElectronicMailAddresses_vec_object->m_vec ) ); vec_attributes.push_back( std::make_pair( "ElectronicMailAddresses", ElectronicMailAddresses_vec_object ) ); } vec_attributes.push_back( std::make_pair( "WWWHomePageURL", m_WWWHomePageURL ) ); if( m_MessagingIDs.size() > 0 ) { shared_ptr<IfcPPAttributeObjectVector> MessagingIDs_vec_object( new IfcPPAttributeObjectVector() ); std::copy( m_MessagingIDs.begin(), m_MessagingIDs.end(), std::back_inserter( MessagingIDs_vec_object->m_vec ) ); vec_attributes.push_back( std::make_pair( "MessagingIDs", MessagingIDs_vec_object ) ); } } void IfcTelecomAddress::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes_inverse ) { IfcAddress::getAttributesInverse( vec_attributes_inverse ); } void IfcTelecomAddress::setInverseCounterparts( shared_ptr<IfcPPEntity> ptr_self_entity ) { IfcAddress::setInverseCounterparts( ptr_self_entity ); } void IfcTelecomAddress::unlinkFromInverseCounterparts() { IfcAddress::unlinkFromInverseCounterparts(); }
mbinette91/ConstructionLCA-IfcReader
IfcPlusPlus/src/ifcpp/IFC4/IfcTelecomAddress.cpp
C++
lgpl-2.1
7,485
/* XFC: Xfce Foundation Classes (User Interface Library) * Copyright (C) 2004-2005 The XFC Development Team. * * notebookclass.hh - Private interface * * 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 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 */ #ifndef XFC_GTK_NOTEBOOK_CLASS_HH #define XFC_GTK_NOTEBOOK_CLASS_HH #include <xfc/gtk/private/containerclass.hh> namespace Xfc { namespace Gtk { class NotebookClass { public: static void init(GtkNotebookClass *g_class); static GtkNotebookClass* get_parent_class(void *instance); static GType get_type(); static void* create(); static void switch_page_proxy(GtkNotebook *notebook, GtkNotebookPage *page, guint page_num); }; } // namespace Gtk } // namespace Xfc #endif // XFC_GTK_NOTEBOOK_CLASS_HH
interval1066/XFC
ui/xfc/gtk/private/notebookclass.hh
C++
lgpl-2.1
1,422
package com.johnsoft.library.swing.component.gl; import javax.media.opengl.GL; import javax.media.opengl.GL2; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLEventListener; import javax.media.opengl.fixedfunc.GLMatrixFunc; import javax.media.opengl.glu.GLU; public class JohnGLRenderer implements GLEventListener { private GLU glu = new GLU(); private JohnGLPane pane; public final void setGLPane(JohnGLPane pane) { this.pane = pane; } protected JohnGLPane getGLPane() { return pane; } protected GLU getGLU() { return glu; } protected void defaultReshape(GLAutoDrawable drawable, int w, int h, float fovy, float zNear, float zFar) { GL2 gl = drawable.getGL().getGL2(); gl.glViewport(0, 0, w, h); gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION); gl.glLoadIdentity(); glu.gluPerspective(fovy, (float)w/h, zNear, zFar); } protected GL2 optionalDisposeMethodInitialize(GLAutoDrawable drawable) { GL2 gl = drawable.getGL().getGL2(); gl.glClear(GL.GL_COLOR_BUFFER_BIT); gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); gl.glLoadIdentity(); return gl; } @Override public void display(GLAutoDrawable drawable) { } @Override public void dispose(GLAutoDrawable drawable) { } @Override public void init(GLAutoDrawable drawable) { } @Override public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) { } }
johnlee175/john4j
src/com/johnsoft/library/swing/component/gl/JohnGLRenderer.java
Java
lgpl-2.1
1,405
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.common.beans.property; import java.util.Comparator; import java.util.concurrent.atomic.AtomicInteger; /** * @author baranowb * */ public class AtomicIntegerEditorTestCase extends PropertyEditorTester<AtomicInteger> { @Override public String[] getInputData() { return new String[] { "-1", "0", "1" }; } @Override public Object[] getOutputData() { return new Object[] { new AtomicInteger(-1), new AtomicInteger(0), new AtomicInteger(1) }; } @Override public String[] getConvertedToText() { return getInputData(); } @Override public Comparator<AtomicInteger> getComparator() { return new NumberComparator(); } @Override public Class getType() { return AtomicInteger.class; } class NumberComparator implements Comparator<AtomicInteger> { public int compare(AtomicInteger o1, AtomicInteger o2) { return o1.intValue() - o2.intValue(); } } }
wolfc/jboss-common-beans
src/test/java/org/jboss/common/beans/property/AtomicIntegerEditorTestCase.java
Java
lgpl-2.1
2,026
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #define SOFA_COMPONENT_MAPPING_SquareDistanceMapping_CPP #include "SquareDistanceMapping.inl" #include <sofa/core/ObjectFactory.h> namespace sofa { namespace component { namespace mapping { SOFA_DECL_CLASS(SquareDistanceMapping) using namespace defaulttype; // Register in the Factory int SquareDistanceMappingClass = core::RegisterObject("Compute square edge extensions") #ifndef SOFA_FLOAT .add< SquareDistanceMapping< Vec3dTypes, Vec1dTypes > >() .add< SquareDistanceMapping< Rigid3dTypes, Vec1dTypes > >() #endif #ifndef SOFA_DOUBLE .add< SquareDistanceMapping< Vec3fTypes, Vec1fTypes > >() .add< SquareDistanceMapping< Rigid3fTypes, Vec1fTypes > >() #endif ; #ifndef SOFA_FLOAT template class SOFA_MISC_MAPPING_API SquareDistanceMapping< Vec3dTypes, Vec1dTypes >; template class SOFA_MISC_MAPPING_API SquareDistanceMapping< Rigid3dTypes, Vec1dTypes >; #endif #ifndef SOFA_DOUBLE template class SOFA_MISC_MAPPING_API SquareDistanceMapping< Vec3fTypes, Vec1fTypes >; template class SOFA_MISC_MAPPING_API SquareDistanceMapping< Rigid3fTypes, Vec1fTypes >; #endif ////////////////// int SquareDistanceMultiMappingClass = core::RegisterObject("Compute square edge extensions") #ifndef SOFA_FLOAT .add< SquareDistanceMultiMapping< Vec3dTypes, Vec1dTypes > >() .add< SquareDistanceMultiMapping< Rigid3dTypes, Vec1dTypes > >() #endif #ifndef SOFA_DOUBLE .add< SquareDistanceMultiMapping< Vec3fTypes, Vec1fTypes > >() .add< SquareDistanceMultiMapping< Rigid3fTypes, Vec1fTypes > >() #endif ; #ifndef SOFA_FLOAT template class SOFA_MISC_MAPPING_API SquareDistanceMultiMapping< Vec3dTypes, Vec1dTypes >; template class SOFA_MISC_MAPPING_API SquareDistanceMultiMapping< Rigid3dTypes, Vec1dTypes >; #endif #ifndef SOFA_DOUBLE template class SOFA_MISC_MAPPING_API SquareDistanceMultiMapping< Vec3fTypes, Vec1fTypes >; template class SOFA_MISC_MAPPING_API SquareDistanceMultiMapping< Rigid3fTypes, Vec1fTypes >; #endif } // namespace mapping } // namespace component } // namespace sofa
Anatoscope/sofa
modules/SofaMiscMapping/SquareDistanceMapping.cpp
C++
lgpl-2.1
3,759
/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ package com.kurento.kmf.test.media; import java.awt.Color; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.junit.Assert; import org.junit.Test; import com.kurento.kmf.media.HttpGetEndpoint; import com.kurento.kmf.media.MediaPipeline; import com.kurento.kmf.media.WebRtcEndpoint; import com.kurento.kmf.test.base.BrowserMediaApiTest; import com.kurento.kmf.test.client.Browser; import com.kurento.kmf.test.client.BrowserClient; import com.kurento.kmf.test.client.Client; import com.kurento.kmf.test.client.WebRtcChannel; /** * <strong>Description</strong>: WebRTC in loopback, and connected to this * stream also connected N HttpEndpoint.<br/> * <strong>Pipeline</strong>: * <ul> * <li>WebRtcEndpoint -> WebRtcEndpoint</li> * <li>WebRtcEndpoint -> HttpEndpoint</li> * </ul> * <strong>Pass criteria</strong>: * <ul> * <li>Browsers starts before default timeout</li> * <li>HttpPlayer play time does not differ in a 10% of the transmitting time by * WebRTC</li> * <li>Color received by HttpPlayer should be green (RGB #008700, video test of * Chrome)</li> * </ul> * * @author Boni Garcia (bgarcia@gsyc.es) * @since 4.2.3 */ public class MediaApiWebRtc2HttpTest extends BrowserMediaApiTest { private static int PLAYTIME = 5; // seconds to play in HTTP player private static int NPLAYERS = 2; // number of HttpEndpoint connected to // WebRTC source @Test public void testWebRtc2Http() throws Exception { // Media Pipeline final MediaPipeline mp = pipelineFactory.create(); final WebRtcEndpoint webRtcEndpoint = mp.newWebRtcEndpoint().build(); webRtcEndpoint.connect(webRtcEndpoint); // Test execution try (BrowserClient browser = new BrowserClient.Builder() .browser(Browser.CHROME).client(Client.WEBRTC).build()) { browser.subscribeEvents("playing"); browser.connectToWebRtcEndpoint(webRtcEndpoint, WebRtcChannel.AUDIO_AND_VIDEO); // Wait until event playing in the WebRTC remote stream Assert.assertTrue("Timeout waiting playing event", browser.waitForEvent("playing")); // HTTP Players ExecutorService exec = Executors.newFixedThreadPool(NPLAYERS); List<Future<?>> results = new ArrayList<>(); for (int i = 0; i < NPLAYERS; i++) { results.add(exec.submit(new Runnable() { @Override public void run() { HttpGetEndpoint httpEP = mp.newHttpGetEndpoint() .build(); webRtcEndpoint.connect(httpEP); try { createPlayer(httpEP.getUrl()); } catch (InterruptedException e) { Assert.fail("Exception creating http players: " + e.getClass().getName()); } } })); } for (Future<?> r : results) { r.get(); } } } private void createPlayer(String url) throws InterruptedException { try (BrowserClient browser = new BrowserClient.Builder() .browser(Browser.CHROME).client(Client.PLAYER).build()) { browser.setURL(url); browser.subscribeEvents("playing"); browser.start(); Assert.assertTrue("Timeout waiting playing event", browser.waitForEvent("playing")); // Guard time to see the video Thread.sleep(PLAYTIME * 1000); // Assertions double currentTime = browser.getCurrentTime(); Assert.assertTrue("Error in play time of HTTP player (expected: " + PLAYTIME + " sec, real: " + currentTime + " sec)", compare(PLAYTIME, currentTime)); Assert.assertTrue( "The color of the video should be green (RGB #008700)", browser.colorSimilarTo(new Color(0, 135, 0))); browser.stop(); } } }
KurentoLegacy/kurento-media-framework
kmf-integration-tests/kmf-system-test/src/test/java/com/kurento/kmf/test/media/MediaApiWebRtc2HttpTest.java
Java
lgpl-2.1
4,245
<?php // (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ require_once('lib/wizard/wizard.php'); $userprefslib = TikiLib::lib('userprefs'); /** * Set up the Basic User Information */ class UserWizardPreferencesInfo extends Wizard { function pageTitle() { return tra('User Preferences:') . ' ' . tra('Personal Information'); } function isEditable() { return true; } function isVisible() { global $prefs; //return $prefs['feature_userPreferences'] === 'y'; return true; // hardcoded to true since at least the first page is shown to tell the user that the user // preferences feature is disabled site-wide & he/she might want to ask the site admin to enable it } function onSetupPage($homepageUrl) { global $user, $prefs, $user_preferences; $userlib = TikiLib::lib('user'); $tikilib = TikiLib::lib('tiki'); $smarty = TikiLib::lib('smarty'); // Run the parent first parent::onSetupPage($homepageUrl); // Show page always since in case user prefs are not enabled, // a message will be shown to the user reporting that and // suggesting to request the admin to enable it. $showPage = true; //// Show if option is selected //if ($prefs['feature_userPreferences'] === 'y') { //$showPage = true; //} $userwatch = $user; $userinfo = $userlib->get_user_info($userwatch); $smarty->assign_by_ref('userinfo', $userinfo); $smarty->assign('userwatch', $userwatch); $realName = $tikilib->get_user_preference($userwatch, 'realName', ''); $smarty->assign('realName', $realName); if ($prefs['feature_community_gender'] == 'y') { $gender = $tikilib->get_user_preference($userwatch, 'gender', 'Hidden'); $smarty->assign('gender', $gender); } $flags = $tikilib->get_flags('', '', '', true); $smarty->assign_by_ref('flags', $flags); $country = $tikilib->get_user_preference($userwatch, 'country', 'Other'); $smarty->assign('country', $country); $homePage = $tikilib->get_user_preference($userwatch, 'homePage', ''); $smarty->assign('homePage', $homePage); $avatar = $tikilib->get_user_avatar($userwatch); $smarty->assign_by_ref('avatar', $avatar); $smarty->assign_by_ref('user_prefs', $user_preferences[$userwatch]); $user_information = $tikilib->get_user_preference($userwatch, 'user_information', 'public'); $smarty->assign_by_ref('user_information', $user_information); $usertrackerId = false; $useritemId = false; if ($prefs['userTracker'] == 'y') { $re = $userlib->get_usertracker($userinfo["userId"]); if (isset($re['usersTrackerId']) and $re['usersTrackerId']) { $trklib = TikiLib::lib('trk'); $info = $trklib->get_item_id($re['usersTrackerId'], $trklib->get_field_id($re['usersTrackerId'], 'Login'), $userwatch); $usertrackerId = $re['usersTrackerId']; $useritemId = $info; } } $smarty->assign('usertrackerId', $usertrackerId); $smarty->assign('useritemId', $useritemId); return $showPage; } function getTemplate() { $wizardTemplate = 'wizard/user_preferences_info.tpl'; return $wizardTemplate; } function onContinue($homepageUrl) { global $user, $prefs; $tikilib = TikiLib::lib('tiki'); $userwatch = $user; // Run the parent first parent::onContinue($homepageUrl); if (isset($_REQUEST["realName"]) && ($prefs['auth_ldap_nameattr'] == '' || $prefs['auth_method'] != 'ldap')) { $tikilib->set_user_preference($userwatch, 'realName', $_REQUEST["realName"]); if ($prefs['user_show_realnames'] == 'y') { $cachelib = TikiLib::lib('cache'); $cachelib->invalidate('userlink.' . $user . '0'); } } if ($prefs['feature_community_gender'] == 'y') { if (isset($_REQUEST["gender"])) { $tikilib->set_user_preference($userwatch, 'gender', $_REQUEST["gender"]); } } $tikilib->set_user_preference($userwatch, 'country', $_REQUEST["country"]); if (isset($_REQUEST["homePage"])) { $tikilib->set_user_preference($userwatch, 'homePage', $_REQUEST["homePage"]); } $tikilib->set_user_preference($userwatch, 'user_information', $_REQUEST['user_information']); } }
tikiorg/tiki
lib/wizard/pages/user_preferences_info.php
PHP
lgpl-2.1
4,258
/***************************************************************** SPINE - Signal Processing In-Node Environment is a framework that allows dynamic configuration of feature extraction capabilities of WSN nodes via an OtA protocol Copyright (C) 2007 Telecom Italia S.p.A.   GNU Lesser General Public License   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, version 2.1 of the License.   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 logic; import java.util.Arrays; import java.util.Vector; import spine.SPINEFunctionConstants; /** * SensorDataManager: calculate feature on sensor data. * * @author Alessia Salmeri : alessia.salmeri@telecomitalia.it * @author Raffaele Gravina * * @version 1.0 */ public class SensorDataManager { int sensorCodeKey; byte featureCode; short windowSize; short shiftSize; Vector[] sensorRawValue; Vector ch1RawValue; Vector ch2RawValue; Vector ch3RawValue; Vector ch4RawValue; /** * Constructor of an SensorDataManager. * * @param sensorCodeKey is a sensor code. * @param sensorRawValue is the set of sensor raw data. * @param windowSize is the windows feature setup info. * @param shiftSize is the shift feature setup info. * */ public SensorDataManager(int sensorCodeKey, Vector[] sensorRawValue, short windowSize, short shiftSize) { this.sensorCodeKey = sensorCodeKey; this.sensorRawValue = sensorRawValue; this.ch1RawValue = sensorRawValue[0]; this.ch2RawValue = sensorRawValue[1]; this.ch3RawValue = sensorRawValue[2]; this.ch4RawValue = sensorRawValue[3]; this.windowSize = windowSize; this.shiftSize = shiftSize; }; /** * Calculate feature (RAW_DATA, MAX, MIN, RANGE, MEAN, AMPLITUDE, RMS, * ST_DEV, TOTAL_ENERGY, VARIANCE, MODE, MEDIAN). * * @param featureCode is a feature code (SPINEFunctionConstants). * */ public Vector[] calculateFeature(byte featureCode) { this.featureCode = featureCode; Vector[] sensorFeatureValue = new Vector[4]; Vector ch1FeatureValue = new Vector(); Vector ch2FeatureValue = new Vector(); Vector ch3FeatureValue = new Vector(); Vector ch4FeatureValue = new Vector(); int[] rawData; if (windowSize <= 0 || shiftSize <= 0 || shiftSize > windowSize) { System.out.println("WINDOW and/or SHIFT INVALID."); } // ch1FeatureValue rawData = new int[ch1RawValue.size()]; for (int i = 0; i < ch1RawValue.size(); i++) { rawData[i] = (Integer) ch1RawValue.get(i); } if (rawData.length < windowSize) { System.out.println("WINDOW > rawData.lenght"); } else { ch1FeatureValue = calculate(rawData, featureCode); } // ch2FeatureValue rawData = new int[ch2RawValue.size()]; for (int i = 0; i < ch2RawValue.size(); i++) { rawData[i] = (Integer) ch2RawValue.get(i); } // ch2FeatureValue = calculate(rawData, featureCode); if (rawData.length < windowSize) { System.out.println("WINDOW > rawData.lenght"); } else { ch2FeatureValue = calculate(rawData, featureCode); } // ch3FeatureValue rawData = new int[ch3RawValue.size()]; for (int i = 0; i < ch3RawValue.size(); i++) { rawData[i] = (Integer) ch3RawValue.get(i); } // ch3FeatureValue = calculate(rawData, featureCode); if (rawData.length < windowSize) { System.out.println("WINDOW > rawData.lenght"); } else { ch3FeatureValue = calculate(rawData, featureCode); } // ch4FeatureValue rawData = new int[ch4RawValue.size()]; for (int i = 0; i < ch4RawValue.size(); i++) { rawData[i] = (Integer) ch4RawValue.get(i); } // ch4FeatureValue = calculate(rawData, featureCode); if (rawData.length < windowSize) { System.out.println("WINDOW > rawData.lenght"); } else { ch4FeatureValue = calculate(rawData, featureCode); } sensorFeatureValue[0] = ch1FeatureValue; sensorFeatureValue[1] = ch2FeatureValue; sensorFeatureValue[2] = ch3FeatureValue; sensorFeatureValue[3] = ch4FeatureValue; return sensorFeatureValue; } private Vector calculate(int[] rawData, byte featureCode) { int[] dataWindow = new int[windowSize]; Vector currInstance = new Vector(); int startIndex = 0; int j = 0; try { while (true) { System.arraycopy(rawData, startIndex, dataWindow, 0, windowSize); currInstance.add((int) calculate(featureCode, dataWindow)); startIndex = shiftSize * ++j; } } catch (Exception e) { System.err.println("No more data from rawData to dataWindow"); } return currInstance; } private static int calculate(byte featurecode, int[] data) { switch (featurecode) { case SPINEFunctionConstants.RAW_DATA: return raw(data); case SPINEFunctionConstants.MAX: return max(data); case SPINEFunctionConstants.MIN: return min(data); case SPINEFunctionConstants.RANGE: return range(data); case SPINEFunctionConstants.MEAN: return mean(data); case SPINEFunctionConstants.AMPLITUDE: return amplitude(data); case SPINEFunctionConstants.RMS: return rms(data); case SPINEFunctionConstants.ST_DEV: return stDev(data); case SPINEFunctionConstants.TOTAL_ENERGY: return totEnergy(data); case SPINEFunctionConstants.VARIANCE: return variance(data); case SPINEFunctionConstants.MODE: return mode(data); case SPINEFunctionConstants.MEDIAN: return median(data); default: return 0; } } // RAW_DATA calculate: the last raw_data in a window private static int raw(int[] data) { int indexLastValue = data.length - 1; int raw = data[indexLastValue]; return raw; } private static int max(int[] data) { int max = data[0]; for (int i = 1; i < data.length; i++) if (data[i] > max) max = data[i]; return max; } private static int min(int[] data) { int min = data[0]; for (int i = 1; i < data.length; i++) if (data[i] < min) min = data[i]; return min; } private static int range(int[] data) { int min = data[0]; int max = min; // we don't use the methods 'max' and 'min'; // instead, to boost the alg, we can compute both using one single for // loop ( O(n) vs O(2n) ) for (int i = 1; i < data.length; i++) { if (data[i] < min) min = data[i]; if (data[i] > max) max = data[i]; } return (max - min); } private static int mean(int[] data) { double mean = 0; for (int i = 0; i < data.length; i++) mean += data[i]; return (int) (Math.round(mean / data.length)); } private static int amplitude(int[] data) { return (max(data) - mean(data)); } private static int rms(int[] data) { double rms = 0; for (int i = 0; i < data.length; i++) rms += (data[i] * data[i]); rms /= data.length; return (int) Math.round(Math.sqrt(rms)); } private static int variance(int[] data) { double var = 0, mu = 0; int val = 0; for (int i = 0; i < data.length; i++) { val = data[i]; mu += val; var += (val * val); } mu /= data.length; var /= data.length; var -= (mu * mu); return (int) Math.round(var); } private static int stDev(int[] data) { return (int) (Math.round(Math.sqrt(variance(data)))); } private static int mode(int[] data) { int iMax = 0; int[] orderedData = new int[data.length]; System.arraycopy(data, 0, orderedData, 0, data.length); int[] tmp = new int[data.length]; // to boost the algorithm, we first sort the array (mergeSort takes // O(nlogn)) Arrays.sort(orderedData); int i = 0; // now we look for the max number of occurences per each value while (i < data.length - 1) { for (int j = i + 1; j < data.length; j++) if (orderedData[i] == orderedData[j]) { tmp[i] = j - i + 1; if (j == (data.length - 1)) i = data.length - 1; // exit condition } else { i = j; break; } } // we choose the overall max for (i = 1; i < data.length; i++) if (tmp[i] > tmp[iMax]) iMax = i; return orderedData[iMax]; } private static int median(int[] data) { int[] sortedData = new int[data.length]; System.arraycopy(data, 0, sortedData, 0, data.length); Arrays.sort(sortedData); return (data.length % 2 == 0) ? (sortedData[data.length / 2] + sortedData[(data.length / 2) - 1]) / 2 : sortedData[(data.length - 1) / 2]; } private static int totEnergy(int[] data) { double totEn = 0; for (int i = 0; i < data.length; i++) totEn += (data[i] * data[i]); return (int) (totEn / data.length); } }
raffy1982/spine-project
Spine_apps/nodeEmulator/src/logic/SensorDataManager.java
Java
lgpl-2.1
9,284
/* Lasso range library Name: Lasso Description: Lightweight, crossbrowser javascript library for creating and modifying ranges. Used by the GhostEdit editor. Licence: Dual licensed under MIT and LGPL licenses. Browser Support: Internet Explorer 6+, Mozilla Firefox 3.5+, Google Chrome, Apple Safari 3+, Opera 10.50+, Any other browser that supports DOMranges or TextRanges Author: Nico Burns <nico@nicoburns.com> Website: http://ghosted.it/lasso Version: 1.5.0 Release Date: --- Changelog: Changes to the node selection functions. Change to deleteContents() for TextRange browsers (ie) Added clearSelection(); Available methods: Native range: setFromNative(nativerange) getNative() Selection: setToSelection() select() clearSelection() Modify range: reset() setStartToRangeStart(lasso object | range) setStartToRangeEnd(lasso object | range) setEndToRangeStart(lasso object | range) setStartToRangeEnd(lasso object | range) Modify content: deleteContents() pasteText(string) Get content: getText() extractText() getHTML() extractHTML() Node/element: selectNode(node) selectNodeContents(node) [only works on block elements in ie8] setCaretToStart(elem | elemid) setCaretToEnd(elem | elemid) Range information: isCollapsed() compareEndPoints() getStartNode() getEndNode() getParentNode() getStartElement() getEndElement() Save & restore: saveToDOM() restoreFromDOM() isSavedRange() removeDOMmarkers() bookmarkify() [ie <= 8 only] unbookmarkify() [ie <= 8 only] other: clone() inspect() Example usage: 1. Set the caret to the end of an element with ID 'testelem': lasso().setCaretToEnd('testelem').select(); 2. Get the currently selected text lasso().setToSelection().getText(); */ window.lasso = function() { //define local range object to be returned at end var r = { saved: null, endpoint: null, startpoint: null, bookmark: null, textrange: false, domrange: false, isLassoObject: true }, lasso = window.lasso, console = window.console || {}; console.log = console.log || function () {}; r.init = r.reset = r.create = function () { if(document.createRange) { r.textrange = false; r.saved = document.createRange(); } else if (document.selection) { r.textrange = true; r.saved = document.body.createTextRange(); } r.bookmark = false; r.domrange = !r.textrange; return r; }; r.setToEmpty = function () { if (r.domrange) { r.saved = document.createRange(); } else if (r.textrange) { r.saved = document.body.createTextRange(); } return r; }; /* Native Range Functions */ r.setFromNative = function (nativerange) { r.saved = nativerange; return r; }; r.getNative = function () { return r.saved; }; /* Selection Functions */ r.setToSelection = function () { var s; if(r.domrange) { s = window.getSelection(); if(s.rangeCount > 0) { r.saved = s.getRangeAt(0).cloneRange(); } } else if (r.textrange) { r.saved = document.selection.createRange(); } return r; }; r.select = function () { if (r.domrange) { var s = window.getSelection(); if (s.rangeCount > 0) s.removeAllRanges(); s.addRange(r.saved); } else if (r.textrange) { r.saved.select(); } return r; }; r.clearSelection = function () { if (r.domrange) { var s = window.getSelection(); if (s.rangeCount > 0) s.removeAllRanges(); } else if (r.textrange) { document.selection.empty(); } return r; }; /* Modify Range Functions */ r.collapseToStart = function () { r.saved.collapse(true); return r; }; r.collapseToEnd = function () { r.saved.collapse(false); return r; }; r.setStartToRangeStart = function (range) { if (range && range.saved) range = range.getNative(); if (r.domrange) { r.saved.setStart(range.startContainer, range.startOffset); } else if (r.textrange) { r.saved.setEndPoint("StartToStart", range); } return r; }; r.setStartToRangeEnd = function (range) { if (range && range.saved) range = range.getNative(); if (r.domrange) { r.saved.setStart(range.endContainer, range.endOffset); } else if (r.textrange) { r.saved.setEndPoint("StartToEnd", range); } return r; }; r.setEndToRangeStart = function (range) { if (range && range.saved) range = range.getNative(); if (r.domrange) { r.saved.setStart(range.endContainer, range.endOffset); } else if (r.textrange) { r.saved.setEndPoint("EndToStart", range); } return r; }; r.setEndToRangeEnd = function (range) { if (range && range.saved) range = range.getNative(); if (r.domrange) { r.saved.setEnd(range.endContainer, range.endOffset); } else if (r.textrange) { r.saved.setEndPoint("EndToEnd", range); } return r; }; /* Modify Content Functions */ r.deleteContents = function () { if (r.domrange) { r.saved.deleteContents(); } else if (r.textrange) { /* TextRange deleting seems quite buggy - these *should* work, but text = "" has been most successful so far try { r.saved.pasteHTML(""); } catch (e) { r.saved.execCommand("delete"); }*/ r.saved.text = ""; } return r; }; r.pasteText = function (text, collapse) { if(typeof collapse === "undefined") collapse = true; r.deleteContents(); if (r.domrange) { var txt = document.createTextNode(text); r.saved.insertNode(txt); r.reset().selectNodeContents(txt); } else if (r.textrange) { r.saved.pasteHTML(text); } if (collapse) r.collapseToEnd(); r.select(); return r; }; r.insertNode = function (node, collapse) { var div; if(typeof collapse === "undefined") collapse = true; r.deleteContents(); if (r.domrange) { r.saved.insertNode(node); r.setToEmpty().selectNodeContents(node); } else if (r.textrange) { div = document.createNode("div"); div.appendChild(node); r.saved.pasteHTML(div.innerHTML); } if (collapse) r.collapseToEnd(); //r.select(); return r; }; /* Get Content Functions */ r.getText = function () { if (r.domrange) { return r.saved.toString(); } else if (r.textrange) { return r.saved.text; } }; r.extractText = function () { var text = r.getText(); r.deleteContents(); return text; }; r.getHTML = function () { var tempelem, docfrag; if (r.domrange) { docfrag = r.saved.cloneContents(); tempelem = document.createElement("div"); tempelem.appendChild(docfrag); return tempelem.innerHTML; } else if (r.textrange) { return r.saved.htmlText; } }; r.extractHTML = function () { var html = r.getHTML(); r.deleteContents(); return html; }; /* Node/Element Functions */ r.actualSelectNode = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) { r.saved.selectNode(elem); } else if (r.textrange) { r.saved.moveToElementText(elem); } return r; }; r.selectNode = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) { r.saved.selectNodeContents(elem); } else if (r.textrange) { r.saved.moveToElementText(elem); } return r; }; //Only works on block elements in ie8 r.selectNodeContents = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); var r1, r2; if (r.domrange) { r.saved.selectNodeContents(elem); } else if (r.textrange) { r.saved.moveToElementText(elem); r1 = lasso().setCaretToStart(elem).getNative(); r2 = lasso().setCaretToEnd(elem).getNative(); r.saved.setEndPoint("StartToStart", r1); r.saved.setEndPoint("EndToStart", r2); } return r; }; r.setCaretToStart = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) { r.saved.selectNodeContents(elem); r.saved.collapse(true); } else if (r.textrange) { /*elem.innerHTML = "<span id=\"range_marker\">&#x200b;</span>" + elem.innerHTML; r.selectNode('range_marker');//.deleteContents(); // For some reason .deleteContents() sometimes deletes too much document.getElementById('range_marker').parentNode.removeChild(document.getElementById('range_marker'));*/ r.saved.moveToElementText(elem); r.saved.collapse(true); } return r; }; r.setCaretToBlockStart = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) { r.saved.selectNodeContents(elem); r.saved.collapse(true); } else if (r.textrange) { r.saved.moveToElementText(elem); r.saved.collapse(false); r.saved.move("character", -(elem.innerText.length + 1)); } return r; }; r.selectInlineStart = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) { r.saved.selectNodeContents(elem); r.saved.collapse(true).select(); } else if (r.textrange) { elem.innerHTML = "a" + elem.innerHTML; // The 'a' is arbitrary, any single character will work r.saved.moveToElementText(elem); r.saved.collapse(false); r.saved.move("character", -(elem.innerText.length + 1)); r.saved.moveEnd("character", 1); r.saved.select(); r.saved.text = ""; } return r; }; r.setCaretToEnd = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) { r.saved.selectNodeContents(elem); r.saved.collapse(false); } else if (r.textrange) { /*elem.innerHTML = elem.innerHTML + "<span id=\"range_marker\">&#x200b;</span>"; r.selectNode('range_marker');//.deleteContents(); document.getElementById('range_marker').parentNode.removeChild(document.getElementById('range_marker'));*/ r.saved.moveToElementText(elem); r.saved.collapse(false); } return r; }; /* Range Information Functions */ r.isCollapsed = function () { if (r.domrange) { return r.saved.collapsed; } else if (r.textrange) { //return r.saved.compareEndPoints("StartToEnd", r.saved) === 0 ? true : false; return r.saved.isEqual(r.clone().collapseToStart().saved); } }; r.compareEndPoints = function (how, range) { var R; if (range && range.saved) range = range.getNative(); if (r.domrange) { // Note that EndToStart and StartToEnd are reversed (to make compatible with ie order) R = window.Range; var howlookup = {"StartToStart": R.START_TO_START, "StartToEnd": R.END_TO_START, "EndToStart": R.START_TO_END, "EndToEnd": R.END_TO_END}; how = howlookup[how]; return r.saved.compareBoundaryPoints(how, range); } else if (r.textrange) { return r.saved.compareEndPoints(how, range); } }; r.isEqualTo = function (range) { if (range && range.saved) range = range.getNative(); if (r.compareEndPoints("StartToStart", range) !== 0) return false; if (r.compareEndPoints("EndToEnd", range) !== 0) return false; return true; }; r.getStartNode = function () { if (r.domrange) { return r.saved.startContainer; } else if (r.textrange) { var range = r.saved.duplicate(); range.collapse(true); return range.parentElement(); } }; r.getEndNode = function () { if (r.domrange) { return r.saved.endContainer; } else if (r.textrange) { var range = r.saved.duplicate(); range.collapse(false); return range.parentElement(); } }; r.getParentNode = function () { if (r.domrange) { return r.saved.commonAncestorContainer; } else if (r.textrange) { return r.saved.parentElement(); } }; r.getStartElement = function () { return r.util.getParentElement( r.getStartNode() ); }; r.getEndElement = function () { return r.util.getParentElement( r.getEndNode() ); }; r.getParentElement = function () { if (r.domrange) { return r.util.getParentElement( r.saved.commonAncestorContainer); } else if (r.textrange) { return r.saved.parentElement(); } }; /* Clone Function */ r.clone = function () { var r2 = lasso(); if(r.domrange) { r2.saved = r.saved.cloneRange(); } else if (r.textrange) { r2.saved = r.saved.duplicate(); } r2.bookmark = r.cloneBookmark(); return r2; }; /* Save and Restore Functions (save to DOM) */ r.saveToDOM = function (id) { var start, end, smark, emark, collapsed; if (!id) id = "lasso"; r.removeDOMmarkers(id); collapsed = r.isCollapsed(); start = r.clone().collapseToStart().getNative(); if (!collapsed) end = r.clone().collapseToEnd().getNative(); if (r.domrange) { smark = document.createElement("span"); smark.innerHTML = "&#x200b"; smark.id = id + "_range_start"; start.insertNode(smark); if (!collapsed) { emark = document.createElement("span"); emark.innerHTML = "&#x200b"; emark.id = id + "_range_end"; end.insertNode(emark); } } else if (r.textrange) { start.pasteHTML("<span id=\"" + id + "_range_start\">&#x200b;</span>"); if (!collapsed) { end.pasteHTML("<span id=\"" + id + "_range_end\">&#x200b;</span>"); } } // Restore in case selection is lost by changing DOM above r = r.restoreFromDOM(id, false) || r.reset(); return r; }; r.restoreFromDOM = function (id, removemarkers) { var start, end, smark, emark; if (!id || id === "" || id === true || id === false) id = "lasso"; if (id === true) removemarkers = true; smark = document.getElementById(id + "_range_start"); emark = document.getElementById(id + "_range_end"); if (!smark) return false; start = lasso().actualSelectNode(smark).collapseToEnd(); if (removemarkers !== false) smark.parentNode.removeChild(smark); if (emark) { end= lasso().actualSelectNode(emark).collapseToStart(); if (removemarkers !== false) emark.parentNode.removeChild(emark); } else { end = start; } r = lasso().setStartToRangeStart(start).setEndToRangeEnd(end); return r; }; r.isSavedRange = function (id) { if (!id) id = "lasso"; return (document.getElementById(id + "_range_start")) ? true : false; }; r.removeDOMmarkers = function (id) { var smark, emark; if (!id) id = "lasso"; smark = document.getElementById(id + "_range_start"); emark = document.getElementById(id + "_range_end"); if (smark) smark.parentNode.removeChild(smark); if (emark) emark.parentNode.removeChild(emark); }; /* More save and restore functions (save reference from root node) */ r.bookmarkify = function (rootnode) { if (r.domrange) { var node, startnodeoffsets, endnodeoffsets, b = {}; if (!rootnode || !rootnode.nodeType) return r; // Save start and end offset to bookmark b.startoffset = r.saved.startOffset; b.endoffset = r.saved.endOffset; // Get start node offset path relative to rootnode startnodeoffsets = []; node = r.saved.startContainer; while (node !== rootnode) { startnodeoffsets.unshift(r.util.getNodeOffset(node)); node = node.parentNode; if (node === null) return r; } // Get end node offset path relative to rootnode endnodeoffsets = []; node = r.saved.endContainer; while (node !== rootnode) { endnodeoffsets.unshift(r.util.getNodeOffset(node)); node = node.parentNode; if (node === null) return r; } // Save paths to bookmark b.startnodeoffsets = startnodeoffsets.join("-"); b.endnodeoffsets = endnodeoffsets.join("-"); // Save rootnode to bookmark (used to show that bookmark exists) b.rootnode = rootnode; r.bookmark = b; } else if (r.textrange) { r.bookmark = r.saved.getBookmark(); } return r; }; r.unbookmarkify = function (rootnode) { var bookmark = r.bookmark; if (r.domrange) { var node, offset, startnodeoffsets, endnodeoffsets, startcontainer, endcontainer; if (!bookmark.rootnode || !rootnode) return r.setToEmpty(); node = rootnode; startnodeoffsets = bookmark.startnodeoffsets.split("-"); while (startnodeoffsets.length > 0) { offset = startnodeoffsets.shift(); if (!node.childNodes || !node.childNodes[offset]) return r.setToEmpty(); node = node.childNodes[offset]; } startcontainer = node; node = rootnode; endnodeoffsets = bookmark.endnodeoffsets.split("-"); while (endnodeoffsets.length > 0) { offset = endnodeoffsets.shift(); if (!node.childNodes || !node.childNodes[offset]) return r.setToEmpty(); node = node.childNodes[offset]; } endcontainer = node; r.setToEmpty(); r.saved.setStart(startcontainer, bookmark.startoffset); r.saved.setEnd(endcontainer, bookmark.endoffset); } else if (r.textrange) { if (r.bookmark) { r.reset().saved.moveToBookmark(bookmark); r.bookmarkify(); } } return r; }; r.clearBookmark = function () { r.bookmark = false; return r; }; r.cloneBookmark = function (bookmark) { if (!bookmark) bookmark = r.bookmark; if (r.domrange) { return !bookmark ? false : { "rootnode": bookmark.rootnode, "startnodeoffsets": bookmark.startnodeoffsets, "endnodeoffsets": bookmark.endnodeoffsets, "startoffset": bookmark.startoffset, "endoffset": bookmark.endoffset }; } else if (r.textrange) { if (!bookmark) return false; var r2 = lasso().getNative(); return r2.moveToBookmark(bookmark) ? r2.getBookmark() : false; } }; /* Inspection and debugging functions */ r.inspect = function (logid) { console.log({ logid: logid ? logid : "", startelement: r.getStartElement(), startnode: r.getStartNode(), endelement: r.getEndElement(), endnode: r.getEndNode(), text: r.getText(), html: r.getHTML(), parent: r.getParentNode() }); }; /* Utility, 'non-public' functions, used by other functions */ r.util = { //Used only for next two functions (getStartElement and getEndElement) getParentElement: function (node) { if (node.nodeType !== 1) { while (node.nodeType !== 1) { node = node.parentNode; if (node === null) return null; } } return node; }, getNodeOffset: function (node) { if (!node || !node.parentNode) return; var offset = 0; while (node.parentNode.childNodes[offset] !== node) { offset += 1; } return offset; } }; r.init(); return r; }; (function(window, undefined) { // Create ghostedit object and global variables var _ghostedit = { version: "1.0pre", enabledplugins: [], ready: false, active: false, isEditing: true, blockElemId: 0, editorchrome: null, debug: false }; // Empty object for references to any elements which need to be globally accesable to be stored on _ghostedit.el = {}; // Empty api object for plugins and init functions to add to _ghostedit.api = {}; // Empty object for plugins to be stored in _ghostedit.plugins = {}; // Add the ghostedit object to the global namespace window.ghostedit = _ghostedit; })(window); (function(window, undefined) { window.ghostedit.init = function (source, options) { if (typeof source === "string") source = document.getElementById(source); var i, handler, ghostedit = window.ghostedit, rootnode, uilayer, htmlelem; // Set up user options ghostedit.options = {}; ghostedit.options = options || {}; // Check for debug option (but only enable if log module exists) if (ghostedit.options.debug) { ghostedit.debug = true; } // Detect whether we need to add extra br's to work around firefox's bugs (also used for webkit and opera) ghostedit.browserEngine = ghostedit.util.detectEngines(); ghostedit.useMozBr = (ghostedit.browserEngine.gecko !== 0 || ghostedit.browserEngine.webkit !== 0 || ghostedit.browserEngine.opera !== 0); //Hide div containing original content source.style.display = 'none'; ghostedit.el.source = source; // Create contextual ui layer uilayer = document.createElement("div"); uilayer.id = "ghostedit_uilayer"; uilayer.className = "ghostedit_uilayer"; uilayer.innerHTML = "<span style='position: absolute; display: none;left: 0; top: 0;line-height: 0'>ie bug fix</span>"; source.parentNode.insertBefore(uilayer, source); ghostedit.el.uilayer = uilayer; // Run init events for core modules ghostedit.history.init(); ghostedit.inout.init(); ghostedit.clipboard.init(); // Enable plugins ghostedit.options.plugins = ghostedit.options.plugins || []; ghostedit.options.plugins.unshift("container", "textblock"); if (ghostedit.options.plugins) { for (i = 0; i < ghostedit.options.plugins.length; i++) { ghostedit.api.plugin.enable(ghostedit.options.plugins[i]); } } // Send init event to plugins (and core modules) ghostedit.event.trigger("init"); // Import initial content rootnode = ghostedit.inout.importHTML(source); source.parentNode.insertBefore(rootnode, source); ghostedit.el.rootnode = rootnode; // Focus the editor handler = rootnode.getAttribute("data-ghostedit-handler"); ghostedit.plugins[handler].focus(rootnode); // Make sure that FF uses tags not CSS, and doesn't show resize handles on images try{document.execCommand("styleWithCSS", false, false);} catch(err){}//makes FF use tags for contenteditable try{document.execCommand("enableObjectResizing", false, false);} catch(err){}//stops resize handles being resizeable in FF // Save selection & setup undo ghostedit.selection.save(); ghostedit.history.reset(); ghostedit.history.saveUndoState(); // Attach event handlers to html element htmlelem = document.getElementsByTagName("html")[0]; ghostedit.util.addEvent(htmlelem, "dragenter", ghostedit.util.cancelEvent); ghostedit.util.addEvent(htmlelem, "dragleave", ghostedit.util.cancelEvent); ghostedit.util.addEvent(htmlelem, "dragover", ghostedit.util.cancelEvent); ghostedit.util.addEvent(htmlelem, "drop", ghostedit.util.cancelEvent); // Attach handlers to rootnode ghostedit.util.addEvent(rootnode, "click", ghostedit.selection.save); ghostedit.util.addEvent(rootnode, "mouseup", ghostedit.selection.save); ghostedit.util.addEvent(rootnode, "keyup", ghostedit.selection.save); ghostedit.util.addEvent(rootnode, "keydown", function (event) {ghostedit.event.keydown(this, event); }); ghostedit.util.addEvent(rootnode, "keypress", function (event) {ghostedit.event.keypress(this, event); }); ghostedit.util.addEvent(rootnode, "dragenter", ghostedit.util.cancelEvent); ghostedit.util.addEvent(rootnode, "dragleave", ghostedit.util.cancelEvent); ghostedit.util.addEvent(rootnode, "dragover", ghostedit.util.cancelEvent); ghostedit.util.addEvent(rootnode, "drop", ghostedit.util.cancelEvent); // Focus rootnode rootnode.focus(); ghostedit.plugins.container.focus(rootnode); ghostedit.ready = true; ghostedit.event.trigger("init:after"); }; })(window); (function (window, undefined) { var _plugins = {}, ghostedit = window.ghostedit; _plugins.register = function(name, object) { if (ghostedit.plugins[name]) return false; ghostedit.plugins[name] = object; return true; }; _plugins.enable = function (name) { if (!ghostedit.plugins[name]) return false; if (ghostedit.enabledplugins[name]) _plugins.disable(name); var plugin = ghostedit.plugins[name]; if (typeof(plugin.enable) === "function") { plugin.enable(); } ghostedit.enabledplugins[name] = true; }; _plugins.disable = function (name) { if (!ghostedit.enabledplugins[name] || !ghostedit.plugins[name]) return false; var plugin = ghostedit.plugins[name]; if (typeof(plugin.disable) === "function") { plugin.disable(); } ghostedit.enabledplugins[name] = false; }; window.ghostedit.api.plugin = _plugins; })(window); (function (window, undefined) { var _util = {}; _util.trim = function (string) { return string.replace(/^\s+/, "").replace(/\s+$/, ""); }; // This will call a function using a reference with predefined arguments. //SECOND ARGUMENT = CONTEXT (this) - should usually be false _util.preparefunction = function (func, context /*, 0..n args */) { var args = Array.prototype.slice.call(arguments, 2); return function() { var allArguments = args.concat(Array.prototype.slice.call(arguments)); return func.apply(context ? context : this, allArguments); }; }; _util.isFunction = function (variable) { if (!variable) return false; if (typeof variable !== "function") return false; return true; }; _util.cloneObject = function (obj) { var copy, len, i, attr; // Handle the 3 simple types, and null or undefined if (null === obj || "object" !== typeof obj) return obj; // Handle Date if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { copy = []; for (i = 0, len = obj.length; i < len; ++i) { copy[i] = _util.cloneObject(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { copy = {}; for (attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = _util.cloneObject(obj[attr]); } return copy; } }; _util.addClass = function (elem, c) { elem.className = _util.trim(elem.className) + " " + c; }; _util.removeClass = function (elem, c) { var r = new RegExp(c,"g"); elem.className = _util.trim(elem.className.replace(r, "")); }; _util.cancelEvent = function (e) { if (e && e.preventDefault) { e.stopPropagation(); // DOM style (return false doesn't always work in FF) e.preventDefault(); } else if (e) { e.returnValue = false; } return false; // false = IE style }; _util.cancelAllEvents = function (e) { if (e && e.preventDefault) { e.stopPropagation(); // DOM style (return false doesn't always work in FF) e.preventDefault(); } else if (window.event) { window.event.cancelBubble = true; //IE cancel bubble; } return false; // false = IE style }; _util.preventDefault = function (e) { // Standards based browsers if (e && e.preventDefault) { e.preventDefault(); } // ie <= 8 return false; }; _util.preventBubble = function (e) { // Standards based browsers if (e && e.stopPropagation) { e.stopPropagation(); } // ie <= 8 if (window.event) window.event.cancelBubble = true; }; _util.addEvent = function (elem, eventType, handle) { if (elem.addEventListener !== undefined) { elem.addEventListener(eventType, handle, false); } else { elem.attachEvent("on" + eventType, handle); } }; _util.removeEvent = function (elem, eventType, handle) { if (elem.removeEventListener !== undefined) { elem.removeEventListener(eventType, handle, false); } else { elem.detachEvent("on" + eventType, handle); } }; _util.ajax = function (URL, method, params, sHandle, dataType) { var time, connector, xhr; if (!URL || !method) return false; // Get XHR object xhr = false; if(window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject)) { xhr = new window.XMLHttpRequest(); } else { try { xhr = new window.ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { xhr = new window.ActiveXObject("MSXML2.XMLHTTP"); } catch (e2) {} } } if (!xhr) return false; // Prepare variables method = method.toUpperCase(); time = new Date().getTime(); URL = URL.replace(/(\?)+$/, ""); connector = (URL.indexOf('?') === -1) ? "?" : "&"; //connector = (URL.indexOf('?') === URL.length - 1) ? "" : "&"; // Open ajax Request if (method === "GET") { xhr.open(method, URL + connector + time + "&" + params, true); } else { xhr.open(method, URL + connector + time, true); } // Define function to handle response xhr.onreadystatechange = function () { var responseData; if(xhr.readyState === 4) { if(xhr.status === 200) { responseData = (dataType === "xml") ? xhr.responseXML : xhr.responseText; if (sHandle !== null){ sHandle(true, responseData); } return true; } else{ if (sHandle !== null){ sHandle(false, responseData); } return false; } } }; // Set HTTP headers xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //xhr.setRequestHeader("Content-length", params.length); //xhr.setRequestHeader("Connection", "close"); // Send ajax request if (method === "POST" && params !== null) { xhr.send(params); } else { xhr.send(); } }; _util.detectEngines = function() { //rendering engines var engine = {ie: 0, gecko: 0, webkit: 0, khtml: 0, opera: 0, ver: null}; // Detect rendering engines/browsers var ua = navigator.userAgent; if (window.opera){ engine.ver = window.opera.version(); engine.opera = parseFloat(engine.ver); } else if (/AppleWebKit\/(\S+)/.test(ua)){ engine.ver = RegExp.$1; engine.webkit = parseFloat(engine.ver); } else if (/KHTML\/(\S+)/.test(ua) || /Konqueror\/([^;]+)/.test(ua)){ engine.ver = RegExp.$1; engine.khtml = parseFloat(engine.ver); } else if (/rv:([^\)]+)\) Gecko\/\d{8}/.test(ua)){ engine.ver = RegExp.$1; engine.gecko = parseFloat(engine.ver); } else if (/MSIE ([^;]+)/.test(ua)){ engine.ver = RegExp.$1; engine.ie = parseFloat(engine.ver); } //return it return engine; }; window.ghostedit.util = _util; })(window); (function(window, undefined) { var _event = { listeners: [], listenerid: 0, eventtypes: [], cancelKeypress: false //allows onkeypress event to be cancelled from onkeydown event. }, ghostedit = window.ghostedit; // Used to capture non-repeating keyboard event (also, non-printing keys don't fire onkeypress in most browsers) _event.keydown = function (elem, e) { var keycode, ghostblock, handler, handled; ghostedit.selection.save(false); e = !(e && e.istest) && window.event ? window.event : e; keycode = e.keyCode !== null ? e.keyCode : e.charCode; _event.trigger("input:keydown", {"event": e, "keycode": keycode}); // Global shortcuts switch(keycode) { case 8: //backspace case 46: // delete key _event.cancelKeypress = false; if(ghostedit.selection.savedRange.isCollapsed() === false) { ghostedit.history.saveUndoState(); ghostedit.selection.deleteContents( (keycode === 8) ? "collapsetostart" : "collapsetoend" ); ghostedit.history.saveUndoState(); _event.cancelKeypress = true;//otherwise opera fires default backspace event onkeyPRESS (not onkeyDOWN) return ghostedit.util.cancelEvent ( e ); } break; case 83: //ctrl-s if (e.ctrlKey){ ghostedit.api.save(); return ghostedit.util.cancelEvent ( e ); } break; case 66: //ctrl-b if (e.ctrlKey) { ghostedit.plugins.textblock.format.bold (); return ghostedit.util.cancelEvent ( e ); } break; case 73: //ctrl-i if (e.ctrlKey && !e.shiftKey) { ghostedit.plugins.textblock.format.italic (); return ghostedit.util.cancelEvent ( e ); } break; case 85: //ctrl-u if (e.ctrlKey) { ghostedit.plugins.textblock.format.underline (); return ghostedit.util.cancelEvent ( e ); } break; case 90: //ctrl-z if (e.ctrlKey) { ghostedit.history.undo (); return ghostedit.util.cancelEvent ( e ); } break; case 89: //ctrl-y if (e.ctrlKey) { ghostedit.history.redo (); return ghostedit.util.cancelEvent ( e ); } break; } // If not handled by one of above, pass to plugin keydown handlers ghostblock = ghostedit.selection.getContainingGhostBlock(); while (true) { // If plugin for the GhostBlock containing the selection has an 'event.keydown' function, call it handler = ghostblock.getAttribute("data-ghostedit-handler"); if (ghostedit.plugins[handler] && ghostedit.plugins[handler].event && ghostedit.plugins[handler].event.keydown) { handled = ghostedit.plugins[handler].event.keydown(ghostblock, keycode, e); if (handled === true) break; } // If above GhostBlock doesn't handle the keypress, send event to it's parent ghostblock = ghostedit.dom.getParentGhostBlock(ghostblock); if (!ghostblock) break; } ghostedit.selection.save(); return true; }; _event.keypress = function (elem, e) { var keycode, ghostblock, handler, handled, currentDocLen, savedDocLen; ghostedit.selection.save(); currentDocLen = ghostedit.el.rootnode.innerHTML.length; savedDocLen = ghostedit.history.undoData[ghostedit.history.undoPoint] !== undefined ? ghostedit.history.undoData[ghostedit.history.undoPoint].content.string.length : 0; //if (currentDocLen - savedDocLen >= 20 || savedDocLen - currentDocLen >= 20) ghostedit.history.saveUndoState(); e = !(e && e.istest) && window.event ? window.event : e; keycode = e.keyCode !== null ? e.keyCode : e.charCode; _event.trigger("input:keydown", {"event": e, "keycode": keycode}); if (ghostedit.selection.saved.type !== "none" && !ghostedit.selection.savedRange.isCollapsed() && !e.ctrlKey) { ghostedit.selection.deleteContents("collapsetostart"); } // Global keyevents switch(keycode) { case 8: //cancel backspace event in opera if cancelKeypress = true if (_event.cancelKeypress === true) { _event.cancelKeypress = false; return ghostedit.util.cancelEvent ( e ); } break; case 13: // Enter (don't allow default action for enter to happen) ghostedit.util.cancelEvent ( e ); break; } // If not handled by one of above, pass to plugin keypress handlers ghostblock = ghostedit.selection.getContainingGhostBlock(); while (true) { // If plugin for the GhostBlock containing the selection has an 'event.keypress' function, call it handler = ghostblock.getAttribute("data-ghostedit-handler"); if (ghostedit.plugins[handler] && ghostedit.plugins[handler].event && ghostedit.plugins[handler].event.keypress) { handled = ghostedit.plugins[handler].event.keypress(ghostblock, keycode, e); if (handled === true) break; } // If above GhostBlock doesn't handle the keypress, send event to it's parent ghostblock = ghostedit.dom.getParentGhostBlock(ghostblock); if (!ghostblock) break; } ghostedit.selection.save(); return true; }; _event.addListener = function (event, callback, revokekey) { var listeners, eventtypes, isnewevent, i; if (typeof(callback) !== "function") return false; // Check if array for that event needs to be created listeners = _event.listeners; if (!listeners[event] || typeof(listeners[event]) !== "object" || !(listeners[event] instanceof Array)) { listeners[event] = []; } // Add event to list of events eventtypes = _event.eventtypes; isnewevent = true; for (i = 0; i < eventtypes.length; i++) { if (eventtypes[i] === event) { isnewevent = false; break; } } if (isnewevent) eventtypes.push(event); _event.listenerid++; listeners[event].push({"id": _event.listenerid, "callback": callback, "revokekey": revokekey}); return _event.listenerid; }; _event.removeListener = function (event, listenerid) { var listeners = _event.listeners, i, newlist = []; if(!listeners[event]) return; for (i = 0; i < listeners[event].length; i++) { if (listeners[event].id !== listenerid) { newlist.push(listeners[event][i]); } } listeners[event] = newlist; }; _event.removeAllListeners = function (revokekey) { var listeners, eventtypes, event, i, j, newlist = []; if(!revokekey) return; listeners = _event.listeners; eventtypes = _event.eventtypes; for (i = 0; i < eventtypes.length; i++) { event = eventtypes[i]; for (j = 0; j < listeners[event].length; j++) { if(!listeners[event][j].revokekey || listeners[event][j].revokekey !== revokekey) { newlist.push(listeners[event][j]); } } listeners[event] = ghostedit.util.cloneObject(newlist); newlist = []; } }; _event.trigger = function (event, params) { var listeners = _event.listeners, i; if (params === undefined) params = {}; if (!listeners[event] || typeof(listeners[event]) !== "object" || !(listeners[event] instanceof Array)) return; if (ghostedit.debug) { window.console.log(event); window.console.log(params); } for (i = 0; i < listeners[event].length; i++) { listeners[event][i].callback.call(this, params); } }; _event.sendBackwards = function (eventtype, source, params) { var target = false, tracker, result, direction; if (!params) params = {}; if (!ghostedit.dom.isGhostBlock(source)) return false; tracker = source; //tracks currently tried targets while(true) { if ((target = ghostedit.dom.getPreviousSiblingGhostBlock(tracker))) { direction = "ahead"; } else if ((target = ghostedit.dom.getParentGhostBlock(tracker))) { direction = "top"; } result = _event.send (eventtype, target, direction, params); if (!result) return false; else if (result.handled === true) return true; tracker = target; } }; _event.sendForwards = function (eventtype, source, params) { var target = false, tracker, result, direction; if (!params) params = {}; if (!ghostedit.dom.isGhostBlock(source)) return false; tracker = source; //tracks currently tried targets while(true) { if ((target = ghostedit.dom.getNextSiblingGhostBlock(tracker))) { direction = "behind"; } else if ((target = ghostedit.dom.getParentGhostBlock(tracker))) { direction = "bottom"; } result = _event.send (eventtype, target, direction, params); if (!result) return false; else if (result.handled === true) return true; tracker = target; } }; _event.send = function (eventtype, target, fromdirection, params) { var handler, handled; if (!target) return false; // = no previous/next GhostBlock handler = target.getAttribute("data-ghostedit-handler"); if (!ghostedit.plugins[handler] || !ghostedit.plugins[handler].dom || !ghostedit.plugins[handler].dom.deleteevent) { return {"handled": false}; // = no handler for this elemtype } handled = ghostedit.plugins[handler].dom.deleteevent (target, fromdirection, params); return {"handled": handled}; }; window.ghostedit.event = _event; })(window); (function(window, undefined) { var _dom = {}; _dom.getNodeOffset = function (node) { var offset, nodelist; if (!node || !node.parentNode) return; offset = 0; nodelist = node.parentNode.childNodes; while (nodelist[offset] !== node) { offset += 1; } return offset; }; _dom.extractContent = function (node) { var frag = document.createDocumentFragment(), child; while ( (child = node.firstChild) ) { frag.appendChild(child); } return frag; }; _dom.cloneContent = function (node) { var child, i, frag = document.createDocumentFragment(); for (i = 0; i < node.childNodes.length; i++) { child = node.childNodes[i]; frag.appendChild(child.cloneNode(true)); } return frag; }; _dom.parse = function (node, rules) { var parsednode = false, nodes, parsedchild, i, j, value, text, tagname, tagrules, attribute, style; if (!node || !rules || !node.nodeType) return false; rules.textnode = rules.textnode || {}; rules.tags = rules.tags || {}; // Handle textnodes if (node.nodeType === 3) { text = (rules.textnode.clean) ? node.nodeValue.replace(/[\n\r\t]/g,"") : node.nodeValue; return (text.length > 0) ? document.createTextNode(text) : false; } // Handle not-element case (textnodes already handled) if (node.nodeType !== 1) return false; // Get rules for tag, if none default to content only tagname = node.tagName.toLowerCase(); tagrules = {"contentsonly": true}; if (rules.tags[tagname]) { tagrules = rules.tags[tagname]; if (typeof tagrules.template === "string") tagrules = tagrules.template; if (typeof tagrules === "string" && rules.templates[tagrules]) tagrules = rules.templates[tagrules]; if (typeof tagrules === "string") return false; } // If "contentsonly" flag set, create document fragment, else create element of same type as node parsednode = tagrules.contentsonly ? document.createDocumentFragment() : document.createElement(node.tagName.toLowerCase()); // Unless "ignorechildren" flag set, recurse on children if (!tagrules.ignorechildren) { nodes = node.childNodes; for (i = 0; i < nodes.length; i++) { parsedchild = _dom.parse(nodes[i], rules); if (parsedchild) { parsednode.appendChild(parsedchild); } } } // Return here if contents only (no need to copy attributes if no node to copy to) if (tagrules.contentsonly) return (parsednode.childNodes.length > 0) ? parsednode : false; // If attributes specified, copy specified attributes if (tagrules.attributes) { for (i = 0; i < tagrules.attributes.length; i++) { attribute = tagrules.attributes[i]; // Handle simple (no rules) case if (typeof attribute === "string") attribute = {"name": attribute}; // Get value of attribute on source node if (typeof attribute.name !== "string") break; value = attribute.value || (attribute.name === "class") ? node.className : node.getAttribute(attribute.name); if (value === undefined) break; attribute.copy = true; // If allowedvalues are specified, check if value is correct if (attribute.allowedvalues) { attribute.copy = false; for (j = 0; j < attribute.allowedvalues.length; j++) { if (attribute.allowedvalues[i] === value){ attribute.copy = true; break; } } } // If all checks passed, set attribute on new node if (attribute.copy) { if (attribute.name === "class") { parsednode.className = value; } else { parsednode.setAttribute(attribute.name, value); } } } } // If styles specified, copy specified attributes if (tagrules.styles) { for (i = 0; i < tagrules.styles.length; i++) { style = tagrules.styles[i]; // Handle simple (no rules) case if (typeof style === "string") style = {"name": style}; // Get value of style on source node if (typeof style.name !== "string") break; if (style.name === "float") style.name = (node.style.cssFloat) ? "cssFloat" : "styleFloat"; value = style.value || node.style[style.name]; if (value === undefined) break; style.copy = true; // If allowedvalues are specified, check if value is correct if (style.allowedvalues) { style.copy = false; for (j = 0; j < style.allowedvalues.length; j++) { if (style.allowedvalues[j] === value) { style.copy = true; break; } } } // If all checks passed, set style on new node if (style.copy) parsednode.style[style.name] = value; } } return parsednode; }; _dom./*compareNodes = function (node1, node2) { var node; // If node1 is a documentFragment, wrap in an element if (n1.nodeType === 11) { node = document.createElement("div"); node.appendChild(nodeOrFrag); node1 = node; } // If node2 is a documentFragment, wrap in an element if (n2.nodeType === 11) { node = document.createElement("div"); node.appendChild(nodeOrFrag); node2 = node; } function getNextNode (nodelist, current) { } nodes1 = node1.getElementsByTagName(*); },*/ isGhostBlock = function (node) { if (!node || !node.nodeType || node.nodeType !== 1) return false; var ghosttype = node.getAttribute("data-ghostedit-elemtype"); return (ghosttype !== undefined && ghosttype !== false && ghosttype !== null) ? true : false; }; _dom.isChildGhostBlock = function (elem, parent) { var i; if (!elem || !parent || !parent.childNodes) return false; if (elem.nodeType !== 1) return false; if (elem.getAttribute("data-ghostedit-elemtype") === undefined) return false; if (elem.getAttribute("data-ghostedit-elemtype") === false) return false; if (elem.getAttribute("data-ghostedit-elemtype") === null) return false; var childblocks = parent.childNodes; for(i = 0; i < childblocks.length; i += 1) { if (elem === childblocks[i]) { return true; } } return false; }; _dom.isGhostToplevel = function (node) { return (node && node.getAttribute("data-ghostedit-isrootnode") === true) ? true : false; }; _dom.getParentGhostBlock = function (node) { if (!node) return false; do { node = node.parentNode; if (node === null) return false; } while (!_dom.isGhostBlock(node)); return node; }; _dom.getFirstChildGhostBlock = function (node) { var children, i; if (!node || !node.childNodes) return false; // Otherwise, recurse forwards through DOM until first GhostBlock is found. children = node.childNodes; for (i = 0; i < children.length; i += 1) { if (_dom.isGhostBlock(children[i])) { return children[i]; } } return false; }; _dom.getLastChildGhostBlock = function (node) { var children, i; if (!node || !node.childNodes) return false; // Otherwise, recurse backwards through DOM until previous GhostBlock is found. children = node.childNodes; for (i = children.length -1; i >= 0; i -= 1) { if (_dom.isGhostBlock(children[i])) { return children[i]; } } return false; }; _dom.getPreviousSiblingGhostBlock = function (node) { var parent, offset, siblings; if (!node || !node.parentNode) return false; // Otherwise, recurse backwards through DOM until previous GhostBlock is found. parent = node.parentNode; offset = _dom.getNodeOffset (node) - 1; siblings = parent.childNodes; do { if (_dom.isGhostBlock(siblings[offset]) === true) { return siblings[offset]; } offset -= 1; } while (offset >= 0); return false; }; _dom.getNextSiblingGhostBlock = function (node) { var parent, offset, siblings; if (!node || !node.parentNode) return false; // Otherwise, recurse forwards through DOM until next GhostBlock is found. parent = node.parentNode; offset = _dom.getNodeOffset (node) + 1; siblings = parent.childNodes; do { if (_dom.isGhostBlock(siblings[offset]) === true) { return siblings[offset]; } offset += 1; } while (offset < siblings.length); return false; }; _dom.getParentElement = function (node) { if (node.nodeType !== 1) { while (node.nodeType !== 1) { node = node.parentNode; if (node === null) return null; } } return node; }; _dom.isDescendant = function (parent, child) { var node = child.parentNode; while (node !== null) { if (node === parent) { return true; } node = node.parentNode; } return false; }; _dom.getFirstChildElement = function (node) { var children, i; if (!node || !node.childNodes) return false; // Otherwise, recurse forwards through DOM until next element is found. children = node.childNodes; for (i = 0; i < children.length; i += 1) { if (children[i].nodeType === 1) { return children[i]; } } return false; }; _dom.getCertainParent = function (condition, elem) { var args = [].slice.call(arguments); args.shift(); if (!condition.apply(this, args)) { while (!condition.apply(this, args)) { elem = elem.parentNode; args[0] = elem; if (elem === null) return false; } } return elem; }; window.ghostedit.dom = _dom; })(window); (function(window, undefined) { var _selection = { savedRange: null, nodepath: [], saved: {type: "none", data: null}, archived: {type: "none", data: null} }, ghostedit = window.ghostedit, lasso = window.lasso; _selection.save = function (updateui) { var sel; if (updateui !== false) updateui = true; sel = lasso().setToSelection(); if (!_selection.isInEditdiv(sel.getStartNode())) { _selection.saved.type = "none"; return false; } else { //Save current selection to range _selection.saved.type = "textblock"; _selection.saved.data = sel;//.bookmarkify(ghostedit.el.rootnode); // Save to legacy variable _selection.savedRange = _selection.saved.data; ghostedit.event.trigger("selection:change"); _selection.updatePathInfo(); if (updateui) ghostedit.event.trigger("ui:update"); return true; } }; _selection.set = function (type, data, updateui) { if (updateui !== false) updateui = true; if (typeof type !== "string") return; // Update selection variables _selection.saved.type = type; _selection.saved.data = data; // Save to legacy variable _selection.savedRange = _selection.saved.data; // Update path information _selection.updatePathInfo(); // Send events ghostedit.event.trigger("selection:change"); if (updateui) ghostedit.event.trigger("ui:update"); return true; }; _selection.restore = function (type, data, mustbevalid) { if (!type || typeof type !== "string") type = _selection.saved.type; if (!data) data = _selection.saved.data; // if type is none, but cant be, get archived selection if (type === "none" && mustbevalid) { type = _selection.archived.type; data = _selection.archived.data; } // If type is none, clear selection if (type === "none") { _selection.clear(); return true; } // Else, call restore function from appropriate plugin if (ghostedit.plugins[type] && ghostedit.plugins[type].selection.restore) { if (ghostedit.plugins[type].selection.restore(data)) { return true; } else { _selection.clear(); return false; } } }; _selection.restoreValid = function (type, data) { return _selection.restore(type, data, true); }; _selection.deleteContents = function (collapse) { if (collapse !== "collapsetostart" && collapse !== "collapsetoend") collapse = false; var handler, handled, ghostblock; ghostblock = _selection.getContainingGhostBlock(); while (true) { handler = ghostblock.getAttribute("data-ghostedit-handler"); handled = ghostedit.plugins[handler].selection.deleteContents(ghostblock, collapse); if (handled === true) break; ghostblock = ghostedit.dom.getParentGhostBlock(ghostblock); if (!ghostblock) break; } switch (collapse) { case "collapsetostart": lasso().setToSelection().collapseToStart().select(); break; case "collapsetoend": lasso().setToSelection().collapseToEnd().select(); break; } _selection.save(); }; _selection.isSameAs = function (sel) { if (!sel || !sel.type) return false; if (sel.type !== _selection.saved.type) return false; if (sel.type === "none") return true; // Else, call compare function from appropriate plugin if (ghostedit.plugins[sel.type] && ghostedit.plugins[sel.type].selection.compare) { return ghostedit.plugins[sel.type].selection.compare (sel.data, _selection.saved.data); } return false; }; _selection.clear = function () { lasso().clearSelection(); _selection.saved = {"type": "none", "data": null}; }; _selection.isInEditdiv = function (elem) { if (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-isrootnode") !== "true") { while (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-isrootnode") !== "true") { if (elem === null) return false; elem = elem.parentNode; if (elem === null) return false; } } return true; }; _selection.updatePathInfo = function (elem) { if (!elem) elem = _selection.saved.data; if (!elem.nodeType) elem = elem.getParentNode(); // If nodepath is same as before, don't bother calculating it again // below code DOES NOT equal above statement. (dom node can have moved) //if (elem === _selection.nodepath[0]) return true; _selection.nodepath = []; if (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-isrootnode") !== "true") { while (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-isrootnode") !== "true") { if (elem === null) return null; if (elem.nodeType === 1) _selection.nodepath.push(elem); elem = elem.parentNode; if (elem === null) return false; } } // Make sure rootnode is also included in path if (elem && elem.getAttribute("data-ghostedit-isrootnode") === "true") { _selection.nodepath.push(elem); } }; _selection.getContainingGhostBlock = function () { var node = _selection.saved.data; if (!node.nodeType) node = node.getParentNode(); if (!node) return false; while (!ghostedit.dom.isGhostBlock(node)) { node = node.parentNode; if (node === null) return false; } return node; }; window.ghostedit.selection = _selection; })(window); (function(window, undefined) { var _inout = {}, ghostedit = window.ghostedit; _inout.init = function () { // Set initial variables _inout.reset(); // Add listener to check whether the selection has changed since the last undo save ghostedit.event.addListener("selection:change", function () { ghostedit.history.selectionchanged = true; }); // Export undo and redo function to the api ghostedit.api.importHTML = function (source) { return _inout.importHTML(source); }; ghostedit.api.exportHTML = function () { return _inout.exportHTML(); }; }; _inout.reset = function () { _inout.importhandlers = []; }; _inout.importHTML = function (sourcenode) { var /*tagname, handler, result*/ rootnode; if (!sourcenode || sourcenode.childNodes.length < 1) return false; /*var tagname = sourcenode.tagName.toLowerCase(); if (handler = _inout.importhandlers[tagname]) { result = ghostedit.plugins[handler].inout.importHTML(insertedelem, elem) if (result) insertedelem = result; }*/ // Call container import, and set resulting domnode's contenteditable to true rootnode = ghostedit.plugins.container.inout.importHTML(sourcenode); rootnode.className = "ghostedit_rootnode"; rootnode.setAttribute("data-ghostedit-isrootnode", "true"); rootnode.contentEditable = 'true'; // Trigger 'import:after' event ghostedit.event.trigger("import:after", {"rootnode": rootnode}); // Return rootnode container return rootnode; }; _inout.exportHTML = function () { var finalexport, editwrap = ghostedit.el.rootnode; ghostedit.event.trigger("export:before"); //Preparation - contenteditable = false editwrap.contentEditable = false; finalexport = ghostedit.plugins.container.inout.exportHTML(editwrap, false); //Tidy up - contenteditable = true editwrap.contentEditable = true; ghostedit.event.trigger("export:after"); return finalexport; //{snippet: snippet, full: finalCode}; }; _inout.openPreview = function () { window.open(ghostedit.options.previewurl); }; _inout.registerimporthandler = function (importhandler/*, tagnames of elements that can be handled*/) { var i, args, tag; if (typeof importhandler !== "function") return false; if (arguments.length < 2) return false; args = Array.prototype.slice.call(arguments); args.shift(); // Loop through arguments for (i = 0; i < args.length; i++) { tag = args[i]; _inout.importhandlers[tag] = importhandler; } }; window.ghostedit.inout = _inout; })(window); (function(window, undefined) { var _history = {}, ghostedit = window.ghostedit; _history.init = function () { // Set initial variables _history.reset(); // Add listener to check whether the selection has changed since the last undo save ghostedit.event.addListener("selection:change", function () { _history.selectionchanged = true; }); // Export undo and redo function to the api ghostedit.api.undo = function () { return _history.undo(); }; ghostedit.api.redo = function () { return _history.redo(); }; }; _history.reset = function () { _history.undoData = [];//new Array(_history.undolevels); /*_history.undolevels = 4000,*/ _history.undoPoint = 0; _history.selectionchanged = true; }; _history.saveUndoState = function (force) { var undoPoint, undoData, contentchanged, selectionchanged, currentstate, undostate, editwrap = ghostedit.el.rootnode; if (force !== true) force = false; ghostedit.event.trigger("history:save:before"); // Localise undo variables undoPoint = _history.undoPoint; undoData = _history.undoData; // Get latest undopoint into a variable undostate = undoData[undoPoint]; if (!undostate) force = true; // Start capturing current editor state currentstate = { id: "", selection: { "type": ghostedit.selection.saved.type, //"data": ghostedit.selection.saved.type === "textblock" ? ghostedit.selection.saved.data.clone() : ghostedit.selection.saved.data "data": ghostedit.selection.saved.data }, content: { "string": editwrap.innerHTML } }; // Calcuate whether the selection or content have changed if (!force) { contentchanged = (undostate.content.string !== currentstate.content.string) ? true : false; selectionchanged = !(ghostedit.selection.isSameAs(undostate.selection)); } if (force || selectionchanged || contentchanged) { // Clone editor content as documentFragment currentstate.content.dom = ghostedit.dom.extractContent(editwrap.cloneNode(true)); if (force || contentchanged) { // Remove existing redo data if (undoPoint > 0) _history.undoData.splice(0, undoPoint); // Save new data and set undoPoint to point at it _history.undoData.unshift(currentstate); _history.undoPoint = 0; } else { _history.undoData[undoPoint] = currentstate; } } ghostedit.event.trigger("history:save:after"); }; _history.restoreUndoPoint = function (undopoint) { var undoData = _history.undoData, undostate = undoData[undopoint]; if (!undostate || undostate.content.string.length < 1) return false; ghostedit.event.trigger("history:restore:before"); ghostedit.el.rootnode.innerHTML = ""; ghostedit.el.rootnode.appendChild(ghostedit.dom.cloneContent(undostate.content.dom)); ghostedit.selection.restore (undostate.selection.type, undostate.selection.data); //ghostedit.selection.save(); ghostedit.event.trigger("history:restore:after"); }; _history.undo = function () { var undoPoint = _history.undoPoint, undoData = _history.undoData, editwrap = ghostedit.el.rootnode; if (undoData[undoPoint+1] === undefined || undoData[undoPoint+1].content.string.length <= 0) return; // if (undoPoint < _history.undolevels - 1) return; //unlimited undo levels ghostedit.event.trigger("history:undo:before"); // If there are unsaved changes, save current content and revert to last saved undopoint (was 0, but now 1 because current state saved in 0) if (undoData[undoPoint].content.string !== editwrap.innerHTML) { _history.saveUndoState(); undoPoint = 1; } // Else, current state already saved, revert to previous saved one (undoPoint + 1) else { if (undoPoint === 0) { _history.saveUndoState(); } undoPoint = _history.undoPoint; undoPoint += 1; } _history.restoreUndoPoint(undoPoint); _history.undoPoint = undoPoint; _history.undoData = undoData; ghostedit.event.trigger("history:undo:after"); }; _history.redo = function () { var undoPoint = _history.undoPoint, undoData = _history.undoData, editwrap = ghostedit.el.rootnode; if (undoPoint > 0 && undoData[undoPoint-1] !== undefined && undoData[undoPoint-1].content.string.length > 0) { ghostedit.event.trigger("history:redo:before"); // The user has made changes since the last undo/redo, throw away redo data and save undo state if (undoData[undoPoint].content.string !== editwrap.innerHTML) { _history.saveUndoState(true); } // Last action was an undo/redo, move one point forwards if possible else { undoPoint-=1; _history.restoreUndoPoint(undoPoint); _history.undoPoint = undoPoint; _history.undoData = undoData; } ghostedit.event.trigger("history:redo:after"); } }; window.ghostedit.history = _history; })(window); (function (window, undefined) { var _clipboard = {}, _paste, _cut, lasso = window.lasso, ghostedit = window.ghostedit, console = window.console || {}; console.log = console.log || function () {}; _clipboard.init = function () { _clipboard.paste.init(); _clipboard.cut.init(); }; _paste = { savedcontent: null, savedundodata: null, savedundopoint: null, beforerangedata: "", afterrangedata: "", waitlength: 0, postpastetidylist: [] }; _paste.init = function () { ghostedit.event.addListener("init:after", function () { ghostedit.util.addEvent(ghostedit.el.rootnode, "paste", function(event) { _paste.handle(event); }); }, "clipboard"); }; _paste.handle = function (e) {//elem no longer used? // Save editor state, and save undo data in case paste functions mess up undo stack ghostedit.history.saveUndoState(); _paste.savedundodata = ghostedit.history.undoData; _paste.savedundopoint = ghostedit.history.undoPoint; _paste.triedpasteimage = false; // If webkit - get data from clipboard, put into rootnode, cleanup, then cancel event if (e.clipboardData && e.clipboardData.getData) { if (/image/.test(e.clipboardData.types)) { _paste.triedpasteimage = true; } if (/text\/html/.test(e.clipboardData.types)) { ghostedit.el.rootnode.innerHTML = e.clipboardData.getData('text/html'); } else if (/text\/plain/.test(e.clipboardData.types) || ghostedit.browserEngine.opera) { ghostedit.el.rootnode.innerHTML = e.clipboardData.getData('text/plain').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); } else { ghostedit.el.rootnode.innerHTML = ""; } _paste.waitfordata(); return ghostedit.util.cancelEvent(e); } //Else - empty rootnode and allow browser to paste content into it, then cleanup else { ghostedit.el.rootnode.innerHTML = ""; _paste.waitfordata(); return true; } }; _paste.waitfordata = function () { var elem = ghostedit.el.rootnode; if (elem.childNodes && elem.childNodes.length > 0) { _paste.process(); } else { setTimeout(_paste.waitfordata, 20); } }; _paste.process = function () { var pastenode, collapsed, hasmerged, handler, target, result, source, position; // Extract pasted content into a new element pastenode = document.createElement("div"); pastenode = ghostedit.plugins.container.inout.importHTML(ghostedit.el.rootnode); console.log ("processed content"); console.log (pastenode.cloneNode(true)); // Restore undo data, and restore editor content ghostedit.history.undoData = _paste.savedundodata; ghostedit.history.undoPoint = _paste.savedundopoint; ghostedit.history.restoreUndoPoint(ghostedit.history.undoPoint); ghostedit.selection.save(); // Delete selection contents if selection is non-collapsed ghostedit.selection.deleteContents(); ghostedit.selection.save(); // If no content was pasted, return source = ghostedit.dom.getFirstChildGhostBlock(pastenode); if (!source) return; // Save selection to DOM if(ghostedit.selection.saved.data.isCollapsed()){ ghostedit.selection.saved.data.saveToDOM("ghostedit_paste_start"); } else { ghostedit.selection.saved.data.clone().collapseToStart().saveToDOM("ghostedit_paste_start"); ghostedit.selection.saved.data.clone().collapseToEnd().saveToDOM("ghostedit_paste_end"); } // Call handler on first pasted node target = function () { return ghostedit.selection.saved.data.getStartNode(); }; position = {"isfirst": true, "islast": (ghostedit.dom.getLastChildGhostBlock(pastenode) === source) ? true : false}; target = _paste.callHandler (target, source, position); /*ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", false); if (lasso().isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.setEndToRangeEnd(lasso().restoreFromDOM("ghostedit_paste_end", false)); } ghostedit.selection.saved.data.select().inspect(); return;/* */ // Call handler on last pasted node source = ghostedit.dom.getLastChildGhostBlock(pastenode); if (source) { target = function () { return ghostedit.selection.saved.data.getEndNode(); }; position = {"isfirst": false, "islast": true}; _paste.callHandler (target, source, position); } /*ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", false); if (lasso().isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.setEndToRangeEnd(lasso().restoreFromDOM("ghostedit_paste_end", false)); } ghostedit.selection.saved.data.select().inspect(); return;/* */ // Loop through and call handler on remaining nodes target = function () { return ghostedit.selection.saved.data.getParentNode(); }; position = {"isfirst": false, "islast": false}; while ((source = ghostedit.dom.getFirstChildGhostBlock(pastenode))) { _paste.callHandler (target, source, position); } // Restore the selection (collapsed to the end) ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", true).select(); if (ghostedit.selection.saved.data.isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_end", true).select(); } ghostedit.selection.save(); // Save undo state ghostedit.history.undoData = _paste.savedundodata; ghostedit.history.undoPoint = _paste.savedundopoint; ghostedit.history.saveUndoState(); if (_paste.triedpasteimage) { ghostedit.event.trigger("ui:message", {message: "You cannot paste images into the editor, please use the add image button instead", time: 2, color: "warn"}); } ghostedit.event.trigger("clipboard:paste:after"); }; _paste.callHandler = function (targetF, source, position) { var target, handler, result; // Restore the selection from DOM markers ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", false); if (lasso().isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.setEndToRangeEnd(lasso().restoreFromDOM("ghostedit_paste_end", false)); } // Get the target target = targetF(); if (!ghostedit.dom.isGhostBlock(target)) target = ghostedit.dom.getParentGhostBlock(target); // Recursively call handler of target and it's parents while (true) { if (!target) break; // Get handler plugin for specified target handler = target.getAttribute("data-ghostedit-handler"); if (!ghostedit.plugins[handler] || !ghostedit.plugins[handler].paste) break; console.log("Call handler: (" + (position.isfirst?"first":position.islast?"last":"normal") + ")" + handler); console.log(target.cloneNode(true)); console.log(source.cloneNode(true)); // Call handler function for target result = ghostedit.plugins[handler].paste.handle (target, source, position); console.log("result: " + result); // If handler function returns true, then source is handled: remove it and return false to indicate not to continue if (result) { source.parentNode.removeChild(source); break; } // Else, restore the selection from DOM markers ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", false); if (lasso().isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.setEndToRangeEnd(lasso().restoreFromDOM("ghostedit_paste_end", false)); } // Get the the parent GhostBlock as the next target to try target = ghostedit.dom.getParentGhostBlock(target); } }; _cut = { savedcontent: null, savedundodata: null, savedundopoint: null }; _cut.init = function () { ghostedit.event.addListener("init:after", function () { ghostedit.util.addEvent(ghostedit.el.rootnode, "cut", function(event) { _cut.handle(event); }); }, "clipboard"); }; _cut.handle = function () { // Save editor state, and save undo data in case paste functions mess up undo stack ghostedit.history.saveUndoState(); _cut.savedundodata = ghostedit.history.undoData; _cut.savedundopoint = ghostedit.history.undoPoint; //Else - empty rootnode and allow browser to paste content into it, then cleanup setTimeout(_cut.cleanup, 20); return true; }; _cut.cleanup = function () { // Restore undo data, and restore editor content ghostedit.history.undoData = _cut.savedundodata; ghostedit.history.undoPoint = _cut.savedundopoint; ghostedit.history.restoreUndoPoint(ghostedit.history.undoPoint); ghostedit.selection.save(); // Delete selection contents if selection is non-collapsed ghostedit.selection.deleteContents(); ghostedit.selection.save(); ghostedit.history.saveUndoState(); }; _clipboard.paste = _paste; _clipboard.cut = _cut; window.ghostedit.clipboard = _clipboard; })(window); (function (window, undefined) { var _textblock = {}, lasso = window.lasso, ghostedit = window.ghostedit, console = window.console || {}; console.log = console.log || function () {}; _textblock.enable = function () { _textblock.format.init(); ghostedit.inout.registerimporthandler (_textblock.inout.importHTML, "p", "h1", "h2", "h3", "h4", "h5", "h6"); ghostedit.inout.registerimporthandler (_textblock.inout.importHTML, "#textnode", "b", "strong", "i", "em", "u", "strike", "span"); // Bookmarkify (serialize) the selection, and save the bookmark to the lasso object ghostedit.event.addListener("history:save:after", function () { if (ghostedit.selection.saved.type === "textblock") { ghostedit.selection.saved.data.bookmarkify(ghostedit.el.rootnode); } }); // Clone range object after undo save to avoid accidentally modifying the saved range objects ghostedit.event.addListener("history:save:after", function () { if (ghostedit.selection.saved.type === "textblock") { ghostedit.selection.saved.data = ghostedit.selection.saved.data.clone(); } }); ghostedit.api.insert = ghostedit.api.insert || {}; ghostedit.api.insert.character = function (character) { return _textblock.insert.character(character); }; ghostedit.api.insert.br = function () {return _textblock.insert.br; }; return true; }; _textblock.event = { keydown: function (target, keycode, event) { switch (keycode) { case 8: // backspace return _textblock.event.backspace(target, event); case 46: //delete return _textblock.event.deletekey (target, event); } }, keypress: function (target, keycode, event) { // Enter key if (keycode === 13) return _textblock.event.enterkey (target, event); }, backspace: function (block, e) { if (_textblock.selection.isAtStartOfTextBlock() !== true) { //Caret not at start of textblock: return true to indicate handled return true; } else { //var block = ghostedit.selection.getContainingGhostBlock(); var params = { "merge": { "contenttype": "inlinehtml", "sourcecontent": block.innerHTML, callback: ghostedit.util.preparefunction(function (node) { var parent = node.parentNode; var handler = parent.getAttribute("data-ghostedit-handler"); ghostedit.plugins[handler].dom.removechild(parent, node);}, false, block) } }; ghostedit.event.sendBackwards("delete", block, params ); ghostedit.event.cancelKeypress = true; ghostedit.util.cancelEvent ( e ); return true; } }, deletekey: function (block, e) { //var block = ghostedit.selection.getContainingGhostBlock(); if (_textblock.selection.isAtEndOfTextBlock() !== true) { //Caret not at end of textblock: return true to indicate handled return true; } else { ghostedit.event.sendForwards("delete", block); //_textblock.remove(_textblock.selection.getStartTextBlockNode()); ghostedit.event.cancelKeypress = true; ghostedit.util.cancelEvent ( e ); return true; } }, enterkey: function (elem, e) { ghostedit.history.saveUndoState(); if (e.shiftKey) { _textblock.insert.br(); _textblock.mozBrs.tidy (elem); } else { _textblock.split(elem); } ghostedit.history.saveUndoState(); ghostedit.util.cancelEvent ( e ); return true; } }; _textblock.dom = { deleteevent: function (target, sourcedirection, params){ var parent, handler, block; switch (sourcedirection) { case "ahead": ghostedit.history.saveUndoState(); if (!_textblock.isEmpty(target)) { target.innerHTML += "<span id='ghostedit_selection_marker'>&#x200b;</span>"; if (params.merge && params.merge.sourcecontent && (params.merge.contenttype === "inlinehtml" || params.merge.contenttype === "text")) { target.innerHTML += params.merge.sourcecontent; } _textblock.mozBrs.tidy(target); params.merge.callback(); //params.sourceblock.parentNode.removeChild(params.sourceblock); lasso().selectNode("ghostedit_selection_marker").select();//.deleteContents(); document.getElementById("ghostedit_selection_marker").parentNode.removeChild(document.getElementById("ghostedit_selection_marker")); ghostedit.selection.save(); } else { parent = ghostedit.dom.getParentGhostBlock(target); handler = parent.getAttribute("data-ghostedit-handler"); //alert(target.id); ghostedit.plugins[handler].dom.removechild(parent, target); } ghostedit.history.saveUndoState(); return true; case "behind": block = ghostedit.selection.getContainingGhostBlock(); params = { "merge": { "contenttype": "inlinehtml", "sourcecontent": target.innerHTML, "callback": ghostedit.util.preparefunction(function (node) { var parent = node.parentNode, handler = parent.getAttribute("data-ghostedit-handler"); ghostedit.plugins[handler].dom.removechild(parent, node); }, false, target) } }; ghostedit.event.sendBackwards("delete", target, params); //---------------------------------- //_textblock.remove(_textblock.selection.getStartTextBlockNode()); //ghostedit.event.cancelKeypress = true; //return ghostedit.util.cancelEvent ( e ); return true; } } }; _textblock.selection = { compare: function (r1, r2) { if (!r1 || !r1.isEqualTo) return false; return r1.isEqualTo(r2); }, restore: function (savedrange) { if (!savedrange || !savedrange.unbookmarkify) return false; savedrange.unbookmarkify(ghostedit.el.rootnode); savedrange.select(); return true; }, deleteContents: function (textblockelem) { var startofblock, endofblock, selrange; // Temporary selection range to avoid changing actual saved range selrange = ghostedit.selection.savedRange.clone(); // Ranges representing the start and end of the block startofblock = lasso().setCaretToStart(textblockelem); endofblock = lasso().setCaretToEnd(textblockelem); // If selrange starts before block, move start of selrange to start of block if (selrange.compareEndPoints("StartToStart", startofblock) === -1) { selrange.setStartToRangeStart(startofblock); } // If selrange end after block, move end of selrange to end of block if (selrange.compareEndPoints("EndToEnd", endofblock) === 1) { //alert(textblockelem.id); selrange.setEndToRangeEnd(endofblock); } selrange.deleteContents(); return true; }, getTextBlockNode: function (elem) { if (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-elemtype") !== "textblock") { while (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-elemtype") !== "textblock") { elem = elem.parentNode; if (elem === null) return false; } } return elem; }, getStartTextBlockNode: function () { return _textblock.selection.getTextBlockNode( ghostedit.selection.savedRange.getStartNode() ); }, getEndTextBlockNode: function () { return _textblock.selection.getTextBlockNode( ghostedit.selection.savedRange.getEndNode() ); }, //Assumes selection saved manually isAtStartOfTextBlock: function (point) { var caretIsAtStart = false, range, selrange, i, isequal, firstnode, textblocknode, wholenode, tempnode, useselection; // Check if 'point' parameter was passed and is a lasso object, otherwise get selection useselection = false; if (!point || !point.isLassoObject) { if (ghostedit.selection.saved.type !== "textblock") return false; point = ghostedit.selection.saved.data; useselection = true; } if(document.createRange) { range = point; if(range.isCollapsed() && range.getNative().startOffset === 0) { caretIsAtStart = true; tempnode = ghostedit.selection.savedRange.getStartNode(); } if (!tempnode) return caretIsAtStart; // If tempnode not right at start while (tempnode.nodeType !== 1 || tempnode.getAttribute("data-ghostedit-elemtype") !== "textblock") { if (tempnode !== tempnode.parentNode.childNodes[0]) { isequal = false; if((tempnode.parentNode.childNodes[0].nodeType === 3 && tempnode.parentNode.childNodes[0].length === 0) || (tempnode.parentNode.childNodes[0].nodeType === 1 && tempnode.parentNode.childNodes[0].className === "moz_dirty")) { //Deals with empty text nodes at start of textblock elem for(i = 1; i < tempnode.parentNode.childNodes.length; i += 1) { firstnode = tempnode.parentNode.childNodes[0]; if (tempnode === tempnode.parentNode.childNodes[i]) { isequal = true; break; } else if(!(firstnode.nodeType === 3 && firstnode.length === 0) && !(firstnode.nodeType === 1 && firstnode.className === "moz_dirty")) { break; } } } if(isequal !== true) { caretIsAtStart = false; break; } } tempnode = tempnode.parentNode; } } else if (document.selection) { // Bookmarkify range, so DOM modification doesn't break it selrange = point.clone().bookmarkify(); textblocknode = _textblock.selection.getStartTextBlockNode(); // Get range representing the whole TextBlock contents wholenode = lasso().selectNodeContents( textblocknode ); // Unbookmarkify the range, so it can be used in comparisons again selrange.unbookmarkify(); // Compare html of wholenode with html of node starting from selected point, if eqaul then selection is at the start of the textblock if (wholenode.getHTML() === wholenode.setStartToRangeStart(selrange).getHTML()) { caretIsAtStart = true; } if (useselection) { ghostedit.selection.savedRange = selrange.select(); } } return caretIsAtStart; }, //Assumes selection saved manually isAtEndOfTextBlock: function () { var caretIsAtEnd = false, selrange, range, rangefrag, elemfrag, textblocknode, endpoint; if (!ghostedit.selection.savedRange.isCollapsed()) return false; textblocknode = _textblock.selection.getEndTextBlockNode(); if(document.createRange) { rangefrag = document.createElement("div"); rangefrag.appendChild( ghostedit.selection.savedRange.getNative().cloneContents() ); range = ghostedit.selection.savedRange.getNative(); range.setEnd(textblocknode, textblocknode.childNodes.length); elemfrag = document.createElement("div"); rangefrag.appendChild( range.cloneContents() ); _textblock.mozBrs.clear(rangefrag); _textblock.mozBrs.clear(elemfrag); if(rangefrag.innerHTML === elemfrag.innerHTML) { caretIsAtEnd = true; } } else if (document.selection) { // Bookmarkify range, so DOM modification doesn't break it selrange = ghostedit.selection.savedRange.clone().bookmarkify(); // Get range representing the end of the TextBlock textblocknode.innerHTML += "<span id=\"range_marker\">&#x200b;</span>"; endpoint = lasso().selectNode('range_marker');//.deleteContents(); document.getElementById('range_marker').parentNode.removeChild(document.getElementById('range_marker')); // Unbookmarkify the range, so it can be used in comparisons again selrange.unbookmarkify(); // Compare endpoint to selected point, if equal then selection is at the end of the textblock if (selrange.compareEndPoints("EndToEnd", endpoint) === 0) { caretIsAtEnd = true; } ghostedit.selection.savedRange = selrange.select(); } return caretIsAtEnd; }, extendtoword: function (range, onlyfrommiddle) { var wordstart, wordend; range = range.clone().getNative(); if (document.createRange) { wordstart = _textblock.selection.findwordstart (range.startContainer, range.startOffset); wordend = _textblock.selection.findwordend (range.endContainer, range.endOffset); //If only one end has moved (or neither), then it's not from the middle if (onlyfrommiddle) { if (range.startContainer === wordstart.node && range.startOffset === wordstart.offset) return lasso().setFromNative(range); if (range.endContainer === wordend.node && range.endOffset === wordend.offset) return lasso().setFromNative(range); } range.setStart(wordstart.node, wordstart.offset); range.setEnd(wordend.node, wordend.offset); } else { range.expand("word"); if (range.htmlText.split().reverse()[0] === " ") { range.moveEnd("character", -1); } } return lasso().setFromNative(range); }, findwordstart: function (node, offset) { var leftnodecontent, stroffset, totalstroffset, prevnode, wordendregex = /\s|[\!\?\.\,\:\;\"]/; if (!node || !node.nodeType) return false; // Handle text node if (node.nodeType === 3) { leftnodecontent = node.nodeValue.substring(0, offset); stroffset = leftnodecontent.search(wordendregex); //If there is a space or punctuation mark left of position in current textNode if(stroffset !== -1) { totalstroffset = stroffset + 1; while ((stroffset = leftnodecontent.substring(totalstroffset).search(wordendregex)) !== -1) { totalstroffset += stroffset + 1; } return { node: node, offset: totalstroffset }; } } // Handle Element else if (node.nodeType === 1) { if (offset > 0) { return _textblock.selection.findwordstart(node.childNodes[offset - 1], node.childNodes[offset - 1].length); } } // If no wordend match found in current node and node is a ghostedit_textblock: return current position if (_textblock.isTextBlock(node)){ return {"node": node, "offset": offset}; } // If node is a NOT ghostedit_textblock: check previous node prevnode = node.previousSibling; if (prevnode) { if (prevnode.nodeType === 3) { return _textblock.selection.findwordstart(prevnode, prevnode.nodeValue.length); } else if (prevnode.nodeType === 1) { return _textblock.selection.findwordstart(prevnode, prevnode.childNodes.length); } } // If node is a NOT ghostedit_textblock and no previousSibling: move up tree else { return _textblock.selection.findwordstart(node.parentNode, ghostedit.dom.getNodeOffset(node)); } }, findwordend: function (node, offset) { var rightnodecontent, stroffset, totalstroffset, nextnode, wordendregex = /\s|[\!\?\.\,\:\;\"]/; if (!node || !node.nodeType) return false; // Handle text node if (node.nodeType === 3) { rightnodecontent = node.nodeValue.substring(offset); stroffset = rightnodecontent.search(wordendregex); //If there is a space or punctuation mark left of position in current textNode if (stroffset !== -1) { totalstroffset = offset + stroffset; return { node: node, offset: totalstroffset }; } } // Handle Element else if (node.nodeType === 1) { if (offset < node.childNodes.length) { return _textblock.selection.findwordend(node.childNodes[offset], 0); } } // If no wordend match found in current node and node is a ghostedit_textblock: return current position if (_textblock.isTextBlock(node)){ return {"node": node, "offset": offset}; } // If node is a NOT ghostedit_textblock: check next node nextnode = node.nextSibling; if (nextnode) { return _textblock.selection.findwordend(nextnode, 0); } // If node is a NOT ghostedit_textblock and no nextSibling: move up tree else { return _textblock.selection.findwordend(node.parentNode, ghostedit.dom.getNodeOffset(node) + 1); } } }; _textblock.inout = { handledtags: { "h1": "block", "h2": "block", "h3": "block", "h4": "block", "h5": "block", "h6": "block", "p": "block", "b": "child", "i": "child", "u": "child", "strong": "child", "em": "child", "strike": "child", "br": "child", "a": "contents", "span": "contents" }, parserules: { "textnode": { "clean": true }, "tags": { "h1": "textblock", "h2": "textblock", "h3": "textblock", "h4": "textblock", "h5": "textblock", "h6": "textblock", "p": "textblock", "b": {}, "i": {}, "u": {}, "strong": {}, "em": {}, "strike": {}, "br": { "attributes": [ {"name": "class", "allowedvalues": [ "moz_dirty" ]} ] } }, "templates": { "textblock": { "attributes": [ "class" ], "styles": [ {"name": "textAlign", "allowedvalues": ["left", "right", "center", "justified"] }, {"name": "clear", "allowedvalues": ["left", "right"] } ] } } }, importHTML: function (source) { var newTextBlock, tagname, node, childcount, prevnode, nodetype, parsednode; nodetype = _textblock.inout.isHandleableNode(source); switch (nodetype) { case "block": // Create TextBlock tagname = source.tagName.toLowerCase(); newTextBlock = ghostedit.dom.parse(source, _textblock.inout.parserules); ghostedit.blockElemId += 1; newTextBlock.id = 'ghostedit_textblock_' + ghostedit.blockElemId; // Set GhostEdit handler attributes newTextBlock.setAttribute("data-ghostedit-iselem", "true"); newTextBlock.setAttribute("data-ghostedit-elemtype", "textblock"); newTextBlock.setAttribute("data-ghostedit-handler", "textblock"); // Add event handlers newTextBlock.ondragenter = function(){return false;}; newTextBlock.ondragleave = function(){return false;}; newTextBlock.ondragover = function(){return false;}; newTextBlock.ondrop = function(e){ var elem, elemid; // This function does basic image paragraph changing dnd elemid = e.dataTransfer.getData("Text") || e.srcElement.id; //alert(elemid); TODO drag drop elem = document.getElementById(elemid); elem.parentNode.insertBefore(elem,this); ghostedit.image.focus(elem); }; newTextBlock.onresizestart = function(e) {return ghostedit.util.cancelEvent(e);}; _textblock.mozBrs.tidy (newTextBlock); return newTextBlock; case "child": case "contents": case "text": newTextBlock = _textblock.create("p"); newTextBlock.setAttribute("data-ghostedit-importinfo", "wasinline"); childcount = 0; node = source; do { parsednode = ghostedit.dom.parse(node, _textblock.inout.parserules); if (parsednode) { childcount += 1; newTextBlock.appendChild(parsednode); prevnode = node; node = node.nextSibling; if (childcount > 1) prevnode.parentNode.removeChild(prevnode); } } while (_textblock.inout.isHandleableNode(node) && _textblock.inout.isHandleableNode(node) !== "block"); _textblock.mozBrs.tidy (newTextBlock); return (childcount > 0) ? newTextBlock : false; } return false; }, exportHTML: function (target) { if (!target || !ghostedit.dom.isGhostBlock(target) || target.getAttribute("data-ghostedit-elemtype") !== "textblock") return false; var finalCode = "", stylecode = "", elem; elem = target; _textblock.mozBrs.clear(elem); //if(elem.tagName.toLowerCase() == "p") paracount++; finalCode += "<" + elem.tagName.toLowerCase(); // Extract styles if (elem.style.textAlign !== "") { stylecode += "text-align:" + elem.style.textAlign + ";"; } if (elem.style.clear !== "") stylecode += "clear:" + elem.style.clear + ";"; if (stylecode.length > 0) finalCode += " style='" + stylecode + "'"; // Extract class if (elem.className.length > 0 && !/ghostedit/.test(elem.className)) finalCode += " class='" + elem.className + "'"; finalCode += ">"; // Copy content and end tag finalCode += elem.innerHTML; finalCode += "</" + elem.tagName.toLowerCase() + ">"; _textblock.mozBrs.tidy(elem); return {content: finalCode}; }, isHandleableNode: function (node) { var nodetag; if (!node || !node.nodeType) return false; // Handle textnode case if (node.nodeType === 3) return (node.nodeValue.replace(/[\n\r\t]/g,"").length > 0) ? "text" : false; // Handle not-element case (textnodes already handled) if (node.nodeType !== 1) return false; // Handle textblock case if(node.getAttribute("data-ghostedit-elemtype") === "textblock") return "block"; // Handle other GhostBlock case (don't process other plugins' stuff) if (ghostedit.dom.isGhostBlock(node)) return false; // Else get tagname, and check handleable tag list nodetag = node.tagName.toLowerCase(); if (_textblock.inout.handledtags[nodetag]) { return _textblock.inout.handledtags[nodetag]; } // Else return false return false; } }; _textblock.paste = { handle: function (target, source, position) { if (!ghostedit.dom.isGhostBlock(target) || !ghostedit.dom.isGhostBlock(source)) return; console.log(position); // If source is first pasted element, and was inline content, or is of same type as target, then merge contents into target node if (position.isfirst) { return _textblock.paste.handleFirst(target, source, position); } if (position.islast) { return _textblock.paste.handleLast(target, source, position); } _textblock.paste.split(target); return false; /*if (!position.islast || !(source.tagName.toLowerCase() === "p" || source.tagName === target.tagName) && _textblock.isEmpty(blocks.block2)) { parent = ghostedit.dom.getParentGhostBlock(blocks.block2); handler = parent.getAttribute("data-ghostedit-handler"); marker = document.createElement("span"); marker.id = "ghostedit_paste_end_range_start"; marker.innerHTML = "&#x200b;"; lasso().removeDOMmarkers("ghostedit_paste_end"); ghostedit.plugins[handler].dom.addchild(parent, "after", blocks.block2, marker); ghostedit.plugins[handler].dom.removechild(parent, blocks.block2); return false; }*/ /*PART OF SPLIT FUNCTION lasso().removeDOMmarkers("ghostedit_paste_end"); blocks.block2.innerHTML = "<span id='ghostedit_paste_end_range_start'>&#x200b;</span>" + blocks.block2.innerHTML; _textblock.mozBrs.tidy(blocks.block2);*/ // If source is last pasted element, and was inline content, or is of same type as target, then prepend contents to second node /*if (position.islast && (source.tagName.toLowerCase() === "p" || source.tagName === target.tagName)) { //DEV console.log("paste (last):"); //DEV console.log(blocks.block2); blocks.block2.innerHTML = source.innerHTML + blocks.block2.innerHTML; blocks.block2 = _textblock.format.setTagType({"textblock": blocks.block2, "tagname": source.tagName.toLowerCase()}); return true; }*/ //DEV console.log(blocks.block1.parentNode.cloneNode(true)); }, handleFirst: function (target, source, position) { // No longer needed because is subset of 'p' check: source.getAttribute("data-ghostedit-importinfo") === "wasinline" if (source.tagName.toLowerCase() === "p" || source.tagName === target.tagName) { console.log("paste (first):"); _textblock.mozBrs.clear(source); lasso().removeDOMmarkers("ghostedit_paste_start"); source.innerHTML += "<span id='ghostedit_paste_start_range_start' class='t1'>&#x200b;</span>"; if (document.createRange) { ghostedit.selection.saved.data.collapseToStart().getNative().insertNode( ghostedit.dom.extractContent(source) ); } else { ghostedit.selection.saved.data.collapseToStart().getNative().pasteHTML(source.innerHTML); } return true; } else { return false; } }, handleLast: function (target, source, position) { if (source.tagName.toLowerCase() === "p" || source.tagName === target.tagName) { console.log("paste (last):"); // If selection is collapsed, then create a new paragraph before merging contents if (ghostedit.selection.saved.data.isCollapsed()) { _textblock.paste.split(target); ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", false); if (lasso().isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.setEndToRangeEnd(lasso().restoreFromDOM("ghostedit_paste_end", false)); } } _textblock.mozBrs.clear(source); lasso().removeDOMmarkers("ghostedit_paste_end"); source.innerHTML += "<span id='ghostedit_paste_end_range_start'>&#x200b;</span>"; if (document.createRange) { ghostedit.selection.saved.data.collapseToEnd().getNative().insertNode( ghostedit.dom.extractContent(source) ); } else { ghostedit.selection.saved.data.collapseToEnd().getNative().pasteHTML(source.innerHTML); } return true; } else { return false; } }, split: function (target, range) { var blocks, handlestartmarker = false; range = range || ghostedit.selection.saved.data; range = range.clone().collapseToStart(); // Check whether target contains a start marker if (ghostedit.dom.isDescendant(target, document.getElementById("ghostedit_paste_start_range_start"))) { handlestartmarker = true; } if (handlestartmarker) { lasso().removeDOMmarkers("ghostedit_paste_start");//Must be before split or marker is duplicated } blocks = _textblock.split(target, range); if (handlestartmarker) { blocks.block1.innerHTML += "<span id='ghostedit_paste_start_range_start' class='t2'>&#x200b;</span>"; _textblock.mozBrs.tidy(blocks.block1); } // Tidy up end marker lasso().removeDOMmarkers("ghostedit_paste_end"); blocks.block2.innerHTML = "<span id='ghostedit_paste_end_range_start'>&#x200b;</span>" + blocks.block2.innerHTML; _textblock.mozBrs.tidy(blocks.block2); return blocks; } }; _textblock.isTextBlock = function (textblock) { if (!ghostedit.dom.isGhostBlock(textblock)) return false; if (textblock.getAttribute("data-ghostedit-elemtype") !== "textblock") return false; return true; }; _textblock.isEmpty = function (textblock) { var textcontent, imgs, brs, i; // If the node contains textual content then it's not empty //if (ghostedit.util.strip_tags(textblockelem.innerHTML).length > 1) return false; textcontent = textblock.innerText || textblock.textContent; if (textcontent && textcontent.length > 1) return false; // If the node contains no textual content and no <br> or <img> tags then it is empty brs = textblock.getElementsByTagName("br"); imgs = textblock.getElementsByTagName("img"); if (brs.length === 0 && imgs.length === 0) return true; // Otherwise check for non MozDirty <br>'s for(i = 0; i < brs.length; i += 1) { if(brs[i].MozDirty === undefined && !/moz_dirty/.test(brs[i].className)) return false; } // If none are found then it's empty return true; }; _textblock.isFirst = function (textblockelem) { var rootnode, i; rootnode = ghostedit.el.rootnode; for(i = 0; i < rootnode.getElementsByTagName("*").length; i += 1) { if(rootnode.getElementsByTagName("*")[i].getAttribute("data-ghostedit-elemtype") === "textblock") { if(rootnode.getElementsByTagName("*")[i] === textblockelem) { return true; } else { return false; } } } }; _textblock.isLast = function (textblockelem) { var rootnode, i; rootnode = ghostedit.el.rootnode; for(i = rootnode.getElementsByTagName("*").length - 1; i > 0; i -= 1) { if(rootnode.getElementsByTagName("*")[i].getAttribute("data-ghostedit-elemtype") === "textblock") { if(rootnode.getElementsByTagName("*")[i] === textblockelem) { return true; } else { return false; } } } }; _textblock.count = function () { var rootnode, childCount, i; rootnode = ghostedit.el.rootnode; childCount = 0; for(i = 0; i < rootnode.getElementsByTagName("*").length; i += 1) { if(rootnode.getElementsByTagName("*")[i].getAttribute("data-ghostedit-elemtype") === "textblock") { childCount += 1; } } return childCount; }; _textblock.create = function (elemtype, content, id) { var newElem; // If explicit id not passed, get next blockElemId if (!id) { ghostedit.blockElemId += 1; id = 'ghostedit_textblock_' + ghostedit.blockElemId; } // If no content sent, set to default content of "" ---"Edit Here!" content = (content && ((content.length && content.length > 0) || content.nodeType)) ? content : "";//"Edit Here!"; // Create element, and assign id and content newElem = document.createElement(elemtype); newElem.id = id; if (content.nodeType) { content = ghostedit.dom.parse(content, {"textnode": { "clean": true }, "tags": { "b": {}, "i": {}, "u": {}, "strong": {}, "em": {}, "strike": {}, "br": {} } }); if (content) newElem.appendChild(content); } else { newElem.innerHTML = content; } // Set GhostEdit handler attributes newElem.setAttribute("data-ghostedit-iselem", "true"); newElem.setAttribute("data-ghostedit-elemtype", "textblock"); newElem.setAttribute("data-ghostedit-handler", "textblock"); // Add event handlers newElem.ondragenter = function(){return false;}; newElem.ondragleave = function(){return false;}; newElem.ondragover = function(){return false;}; newElem.ondrop = function(e){ var elem, elemid; // This function does basic image paragraph changing dnd elemid = e.dataTransfer.getData("Text") || e.srcElement.id; //alert(elemid); TODO drag drop elem = document.getElementById(elemid); elem.parentNode.insertBefore(elem,this); ghostedit.image.focus(elem); }; newElem.onresizestart = function(e) {return ghostedit.util.cancelEvent(e);}; // Tidy MozBr's in new element _textblock.mozBrs.tidy(newElem); return newElem; }; _textblock.remove = function (textblockelem) { var savedElemContent, rootnode, focuselem, i, thisone, textblockelems; ghostedit.selection.save(); ghostedit.history.saveUndoState(); // If textblock elem still contains content, save to variable for appending to previous textblock elem savedElemContent = ""; savedElemContent = textblockelem.innerHTML; // Cycle through textblock elements backwards to select the one before the current one to focus rootnode = ghostedit.el.rootnode; textblockelems = rootnode.getElementsByTagName("*"); thisone = false; for(i = textblockelems.length - 1; i >= 0; i -= 1) { if (thisone === true && textblockelems[i].getAttribute("data-ghostedit-elemtype") === "textblock") { focuselem = textblockelems[i]; break; } else if (textblockelems[i] === textblockelem) { thisone = true; } } // If focuselem is empty, delete it instead (intuitive behaviour) if (_textblock.isEmpty(focuselem)) { rootnode.removeChild(focuselem); lasso().setCaretToStart(textblockelem).select(); ghostedit.selection.save(); ghostedit.history.saveUndoState(); return; } // Remove textblock elem rootnode.removeChild(textblockelem); // Set caret to end of focuselem lasso().setCaretToEnd(focuselem).select(); ghostedit.selection.save(); // Add saved content focuselem.innerHTML += "<span id='ghostedit_marker'>&#x200b;</span>" + savedElemContent; // Sort out MozBr's (one at very end of elements, that's it) _textblock.mozBrs.tidy(focuselem); // Place caret in correct place lasso().selectNode('ghostedit_marker').deleteContents().select(); if (document.getElementById('ghostedit_marker')) { document.getElementById('ghostedit_marker').parentNode.removeChild(document.getElementById('ghostedit_marker')); } ghostedit.selection.save(); ghostedit.history.saveUndoState(); }; _textblock.focus = function (target) { if (!target || target.nodeType !== 1 || target.getAttribute("data-ghostedit-elemtype") !== "textblock") return false; lasso().setCaretToEnd(target).select(); ghostedit.selection.save(); return true; }; _textblock.merge = function (block1, block2, collapse) { var block1type, block2type, parent, handler; // If collapse === false don't merge if (collapse === false) return block1; // If blocks are same node, return that node if (block1 === block2) return block1; block1type = block1.getAttribute("data-ghostedit-elemtype"); block2type = block2.getAttribute("data-ghostedit-elemtype"); // If one of the blocks isn't a textblock, return false if (block1type !== "textblock" || block2type !== "textblock") return false; // Otherwise, append block2content to block1 and delete block2 block1.innerHTML += "<span id='ghostedit_marker'>&#x200b;</span>" + block2.innerHTML; parent = block2.parentNode; handler = parent.getAttribute("data-ghostedit-handler"); ghostedit.plugins[handler].dom.removechild(parent, block2); _textblock.mozBrs.tidy(block1); lasso().selectNode("ghostedit_marker").select();//.deleteContents(); document.getElementById("ghostedit_marker").parentNode.removeChild(document.getElementById("ghostedit_marker")); return block1; }; _textblock.split = function (elem, splitpoint) { var wheretoinsert, atstart, atend, elemtype, savedElemContent, range, result, newTextBlock, parent, handler, useselection; useselection = false; if (!splitpoint || !splitpoint.isLassoObject) { ghostedit.selection.save(); if (ghostedit.selection.saved.type !== "textblock") return false; splitpoint = ghostedit.selection.saved.data; useselection = true; } splitpoint = splitpoint.clone().collapseToStart(); atstart = (_textblock.selection.isAtStartOfTextBlock() === true) ? true : false; atend = (_textblock.selection.isAtEndOfTextBlock() === true) ? true : false; wheretoinsert = (atstart && !atend) ? "before" : "after"; elemtype = (wheretoinsert === "before" || atend) ? "p" : _textblock.selection.getStartTextBlockNode().tagName; //console.log("atstart - " + atstart+ "\natend - " + atend + "\nwhere - " + wheretoinsert); // Tidy MozBr's in original element _textblock.mozBrs.tidy(elem); // Save and the delete the content after the caret from the original element if(!atstart && !atend) {//wheretoinsert === "after") { if (document.createRange) { range = lasso().selectNodeContents( elem ).setStartToRangeStart(splitpoint); // Odd bug (at least in chrome) where savedRange is already to the end. savedElemContent = range.getHTML(); range.deleteContents(); } else if (document.selection) { // Bookmark lines allow innerHTML to be modified as long as it is put back to how it was /*savedrange = ghostedit.selection.savedRange.getNative().getBookmark(); range = lasso().selectNodeContents( elem ); ghostedit.selection.savedRange.getNative().moveToBookmark(savedrange); range.getNative().setEndPoint("StartToEnd", ghostedit.selection.savedRange.getNative());*/ range = lasso().selectNode(elem); range.setStartToRangeEnd(splitpoint); savedElemContent = range.getHTML(); range.getNative().text = ""; } } else { savedElemContent = ""; } /*result = _textblock.insert(elem, elemtype, false, wheretoinsert, savedElemContent); */ // Create new element for inserting newTextBlock = _textblock.create(elemtype, savedElemContent); if (!newTextBlock) return false; // Ask (ghost) parent to insert new element into page parent = ghostedit.dom.getParentGhostBlock(elem); handler = parent.getAttribute("data-ghostedit-handler"); result = ghostedit.plugins[handler].dom.addchild (parent, wheretoinsert, elem, newTextBlock, {"contentlength": savedElemContent.length}); if (!result) return false; /* IF !result, replace saved and deleted content after cursor */ // Workaround for ie (6?) bug which doesn't allow an empty element to be selected newTextBlock.innerHTML = "dummy"; lasso().selectNode(newTextBlock).select(); newTextBlock.innerHTML = savedElemContent; // Tidy MozBrs (previous code section often) removes all MozBrs) _textblock.mozBrs.tidy(newTextBlock); // Set caret to start of new element if(wheretoinsert === "before") { range = lasso().setCaretToBlockStart(elem); } else { range = lasso().setCaretToBlockStart(newTextBlock); } // If using selection, set caret to range position if (useselection) { range.select(); ghostedit.selection.save(); } // block1 = first in dom; block2 = second in dom return { "block1": wheretoinsert === "before" ? newTextBlock : elem, "block2": wheretoinsert === "before" ? elem :newTextBlock, "caretposition": range }; }; _textblock.mozBrs = { checkifcontains: function (node) { var elements, i; elements = node.getElementsByTagName("br"); for(i = 0; i < elements.length; i += 1) { if(elements[i].MozDirty !== undefined) return true; } return false; }, insert: function (elem) { var brNode; brNode = document.createElement("br"); brNode.setAttribute("_moz_dirty", ""); brNode.className = "moz_dirty"; elem.appendChild(brNode); }, clear: function (node) { var elements, i; elements = node.getElementsByTagName("br"); for(i = 0; i < elements.length; i += 1) { if(elements[i].MozDirty !== undefined || /moz_dirty/.test(elements[i].className)) { elements[i].parentNode.removeChild(elements[i]); i--; //One less element in live list, so decrease iterator } } }, tidy: function (elem) { _textblock.mozBrs.clear(elem); if(ghostedit.useMozBr) { _textblock.mozBrs.insert(elem); } } }; _textblock.insert = { character: function (character) { if(ghostedit.selection.saved.type === "textblock") { ghostedit.selection.restore(); ghostedit.selection.savedRange.pasteText(character); } }, br: function () { //var isEmpty = false; var s, newBr, r; if (window.getSelection) { s = window.getSelection(); s.getRangeAt(0).collapse(false); newBr = document.createElement("br"); newBr.id = "newBr"; s.getRangeAt(0).insertNode(newBr); s.getRangeAt(0).selectNode(newBr.parentNode); //alert(newBr.nextSibling); r = document.createRange(); r.setStartAfter(newBr); r.setEndAfter(newBr); s.removeAllRanges(); s.addRange(r); document.getElementById("newBr").removeAttribute("id"); } else if (document.selection) { r = document.selection.createRange(); r.collapse(false); r.pasteHTML("<br id='newBr' />"); r.moveToElementText(document.getElementById("newBr")); r.collapse(false); r.select(); document.getElementById("newBr").removeAttribute("id"); } } }; _textblock.format = { init: function () { ghostedit.api.format = ghostedit.api.format || {}; ghostedit.api.format.setStyle = function (tagname, newclass) { _textblock.format.formatSelected(_textblock.format.setTagType, {"tagname": tagname,"newclass": newclass}); }; ghostedit.api.format.alignText = function (alignDirection) { if (!/left|right|center|justify/.test(alignDirection)) return false; _textblock.format.formatSelected(_textblock.format.alignText, {"alignDirection": alignDirection}); }; ghostedit.api.format.bold = function () { _textblock.format.formatSelected(_textblock.format.bold); }; ghostedit.api.format.italic = function () { _textblock.format.formatSelected(_textblock.format.italic); }; ghostedit.api.format.underline = function () { _textblock.format.formatSelected(_textblock.format.underline); }; ghostedit.api.format.strikethrough = function () { _textblock.format.formatSelected(_textblock.format.strikethrough); }; ghostedit.api.format.textColor = function (color) { _textblock.format.formatSelected(_textblock.format.textColor, {"color": color}); }; }, useCommand: function (commandType, param) { //var i, nodes, node, selrange, startofblock, endofblock; //if (typeof param == "undefined") { param = null; } //if (ghostedit.selection.saved.type !== "text") return false; //ghostedit.history.saveUndoState(); document.execCommand(commandType, false, param); //ghostedit.selection.save(); //ghostedit.history.saveUndoState(); }, getNextNode: function (node) { if (node.firstChild) return node.firstChild; while (node) { if (node.nextSibling) return node.nextSibling; node = node.parentNode; } }, getNodesInRange: function (range) { var start = range.getStartNode(), end = range.getEndNode(), commonAncestor = range.getParentNode(), nodes = [], node; // walk parent nodes from start to common ancestor for (node = start.parentNode; node; node = node.parentNode) { nodes.push(node); if (node === commonAncestor) break; } nodes.reverse(); // walk children and siblings from start until end is found for (node = start; node; node = _textblock.format.getNextNode(node)) { nodes.push(node); if (node === end) break; } return nodes; }, useCommandOnWord: function (command) { var range, marker; if (ghostedit.selection.savedRange.isCollapsed() && _textblock.selection.getStartTextBlockNode()) { range = ghostedit.selection.savedRange.clone(); if (document.createRange) { marker = document.createElement("span"); marker.id = "ghostedit_marker"; range.getNative().insertNode(marker); } if (!document.createRange && document.selection) { range.getNative().pasteHTML("<span id='ghostedit_marker'>z</span>"); } range.selectNode("ghostedit_marker"); range = _textblock.selection.extendtoword(range, true); range.select(); } /* Placing cursor inside empty <b> doesn't work in ie <=8 (might work in 6/7) if (range.isCollapsed() && document.selection) { if (document.selection) { range.getNative().pasteHTML("<b><span id='ghostedit_marker'>&#x200b;</span></b>"); alert(lasso().selectNodeContents("ghostedit_marker").getHTML());//.select().deleteContents(); //document.getElementById("ghostedit_newnode").innerHTML = ""; //document.getElementById("ghostedit_newnode").id = ""; } } else {*/ _textblock.format.useCommand(command); if (document.getElementById("ghostedit_marker")) { lasso().selectNode("ghostedit_marker").select(); document.getElementById("ghostedit_marker").parentNode.removeChild(document.getElementById("ghostedit_marker")); } ghostedit.selection.save(); }, bold: function () { _textblock.format.useCommand("bold"); }, italic: function () { _textblock.format.useCommand("italic"); }, underline: function () { _textblock.format.useCommand("underline"); }, strikethrough: function () { _textblock.format.useCommand("strikethrough"); }, textColor: function (color) { _textblock.format.useCommand("foreColor",color); }, formatSelected: function (formatFunc, params) { var elem, startpara, endpara, oldelem, doend, i, descendantblocks; ghostedit.selection.save(); ghostedit.history.saveUndoState(); startpara = _textblock.selection.getStartTextBlockNode(); endpara = _textblock.selection.getEndTextBlockNode(); if (startpara && endpara) { elem = startpara; doend = false; do { if (elem === ghostedit.el.rootnode || elem === null) break; if (_textblock.isTextBlock(elem)) { if (elem === endpara) doend = true; elem = _textblock.format.formatTextBlock(elem, ghostedit.selection.saved.data.clone(), formatFunc, params); if (doend) break; elem = elem.nextSibling ? elem.nextSibling : elem.parentNode; continue; } else if (ghostedit.dom.isDescendant(elem, endpara)) { elem = ghostedit.dom.getFirstChildElement(elem); continue; } else { oldelem = elem; //necessary because setTagType kills list item (and if no list item, then no nextSibling) elem = elem.nextSibling ? elem.nextSibling : elem.parentNode; descendantblocks = oldelem.getElementsByTagName("*"); for(i = 0; i < descendantblocks.length; i += 1) { if (_textblock.isTextBlock(descendantblocks[i])) { _textblock.format.formatTextBlock(descendantblocks[i], ghostedit.selection.saved.data.clone(), formatFunc, params); } } } } while (true); ghostedit.selection.save(); ghostedit.history.saveUndoState(); } ghostedit.history.saveUndoState(); }, formatTextBlock: function (textblock, range, formatFunc, params) { var startofblock, endofblock, newelem; if (!params) params = {}; params.textblock = textblock; // Clone range to avoid reference errors range = range.clone(); // Ranges representing the start and end of the block startofblock = lasso().setCaretToStart(textblock); endofblock = lasso().setCaretToEnd(textblock); // If range doesn't intersect textblock return false //console.log(range.compareEndPoints("EndToStart", startofblock)); //console.log(range.compareEndPoints("StartToEnd", endofblock)); if (range.compareEndPoints("EndToStart", startofblock) === -1 || range.compareEndPoints("StartToEnd", endofblock) === 1) return false; // If range starts before block, move start of selrange to start of block if (range.compareEndPoints("StartToStart", startofblock) === -1) range.setStartToRangeStart(startofblock); // If range end after block, move end of selrange to end of block if (range.compareEndPoints("EndToEnd", endofblock) === 1) range.setEndToRangeEnd(endofblock); ghostedit.selection.saved.data.clone().saveToDOM("ghostedit_format"); //if(textblock.id === "ghostedit_textblock_4") return; range.select(); newelem = formatFunc(params); lasso().restoreFromDOM("ghostedit_format").select(); ghostedit.selection.save(); return newelem && newelem.nodeType !== undefined ? newelem : textblock; }, alignText: function(params) { var elem = lasso().setToSelection().getParentElement(); while (!ghostedit.dom.isGhostBlock(elem)) { elem = elem.parentNode; if (elem === null) return false; } if (!_textblock.isTextBlock(elem)) return false; elem.style.textAlign = params.alignDirection; }, // .tagName is readonly -> need to remove element and add new one setTagType: function (params) { var target, tagtype, newclass, parent, targetid, newTextBlock; target = params.textblock; tagtype = params.tagname; newclass = params.newclass; // Retrieve target node //target = target || ghostedit.selection.nodepath[0]; if (!_textblock.isTextBlock(target)) return false; // Save id of target targetid = 'ghostedit_textblock_' + target.id.replace("ghostedit_textblock_",""); // Create replacement element, and copy over attributes/html newTextBlock = _textblock.create(tagtype); newTextBlock.appendChild(ghostedit.dom.extractContent(target)); _textblock.mozBrs.tidy(newTextBlock); newTextBlock.setAttribute("style", target.getAttribute("style")); if (newclass !== undefined) newTextBlock.className = newclass; // Use naive DOM manipulation because just doing an in place swap parent = target.parentNode; target.id = ""; parent.insertBefore(newTextBlock, target); parent.removeChild(target); // Set id of new TextBlock newTextBlock.id = targetid; return newTextBlock; } }; ghostedit.api.plugin.register("textblock", _textblock); })(window); (function (window, undefined) { var _container = {}, lasso = window.lasso, ghostedit = window.ghostedit; _container.enable = function () { return true; }; _container.dom = { addchild: function (target, wheretoinsert, anchorelem, newElem) { if (wheretoinsert === "before") { target.insertBefore(newElem, anchorelem); } else { if (anchorelem.nextSibling !== null) { target.insertBefore(newElem, anchorelem.nextSibling); } else { target.appendChild(newElem); } } return true; }, removechild: function (target, child) { if (!target || !child) return false; target.removeChild(child); return true; } // Not currently needed, but comments left for easier future implementation /*deleteevent: function (target, sourcedirection, params) { switch (sourcedirection) { case "ahead": // Backspace was pressed at the start of the element after the container break; case "behind": // Delete was pressed at the end of the element before the container break; case "top": // Backspace was pressed at the start of the first child GhostBlock of the container break; case "bottom": // Delete was pressed at the end of the last child GhostBlock the container break; } return false; }*/ }; _container.selection = { deleteContents: function (container, collapse) { var i, firstchildblock, lastchildblock, startofblock, endofblock, atverystart = false, atveryend = false, startblock, endblock, cblock, startcblock, endcblock, childblocks, dodelete, selrange, handler; // Temporary selection range to avoid changing actual saved range if(ghostedit.selection.saved.type !== "textblock") return false; selrange = ghostedit.selection.saved.data; // Get first and last child ghostblock childblocks = container.childNodes; firstchildblock = ghostedit.dom.getFirstChildGhostBlock(container); lastchildblock = ghostedit.dom.getLastChildGhostBlock(container); // Ranges representing the start and end of the block startofblock = lasso().setCaretToStart(firstchildblock); endofblock = lasso().setCaretToEnd(lastchildblock); // If selrange starts before or at block, set startblock to the first child ghostblock if (selrange.compareEndPoints("StartToStart", startofblock) !== 1) { atverystart = true; startblock = firstchildblock; } // Otherwise, set child ghostblock containing the start of the selection else { startblock = selrange.getStartNode(); if (!ghostedit.dom.isGhostBlock(startblock)) startblock = ghostedit.dom.getParentGhostBlock(startblock); } // If selrange ends after or at block, set endblock to the last child ghostblock if (selrange.compareEndPoints("EndToEnd", endofblock) !== -1) { atveryend = true; endblock = lastchildblock; } // Otherwise, set child ghostblock containing the end of the selection else { endblock = selrange.getEndNode(); if (!ghostedit.dom.isGhostBlock(endblock)) endblock = ghostedit.dom.getParentGhostBlock(endblock); } startcblock = startblock; while(!ghostedit.dom.isChildGhostBlock(startcblock, container)) startcblock = ghostedit.dom.getParentGhostBlock(startcblock); endcblock = endblock; while(!ghostedit.dom.isChildGhostBlock(endcblock, container)) endcblock = ghostedit.dom.getParentGhostBlock(endcblock); //alert(startblock.id + endblock.id); /*//Handle selectall case if (isatverystart && isatveryend) { dodelete = false; firsttextblocktype = textblockelems[i].tagName.toLowerCase(); for(i = 0; i < childblocks.length; i += 1) { if (childblocks[i].getAttribute("data-ghostedit-elemtype") !== undefined && childblocks[i].getAttribute("data-ghostedit-elemtype") !== false) { firstchildblock = childblocks[i]; break; } } lasso().setCaretToStart(firstchildblock).select(); return true; }*/ //ghostedit.textblock.selection.deleteContents(lastchildblock); //alert("start - " + startblock.id + "\nend - " + endblock.id); // Cycle through SELECTED child ghostblocks and call delete method dodelete = false; for(i = 0; i < childblocks.length; i += 1) { cblock = childblocks[i]; if ( !ghostedit.dom.isGhostBlock(cblock) ) continue; handler = cblock.getAttribute("data-ghostedit-handler"); if (cblock.id === startcblock.id) { ghostedit.plugins[handler].selection.deleteContents( cblock ); dodelete = true; continue; } else if (cblock.id === endcblock.id) { ghostedit.plugins[handler].selection.deleteContents( cblock ); dodelete = false; break; } if (dodelete) { container.removeChild(childblocks[i]); i--; } } // If the first and last elements in the selection are the same type, then merge if(startcblock.getAttribute("data-ghostedit-elemtype") === endcblock.getAttribute("data-ghostedit-elemtype")) { lasso().setToSelection().saveToDOM("ghostedit_container_deleteselection"); ghostedit.plugins[startcblock.getAttribute("data-ghostedit-elemtype")].merge(startcblock, endcblock, collapse); lasso().restoreFromDOM("ghostedit_container_deleteselection").select(); //if (!ghostedit.dom.getParentGhostBlock(endcblock)) lasso().setToSelection().collapseToStart().select(); //^^tests whether endcblock is still in the document, i.e. whether a merge took place } // If container has no children left, create empty <p> element if (!ghostedit.dom.getFirstChildGhostBlock(container)) { container.appendChild(ghostedit.plugins.textblock.create("p")); } // Place caret where the selection was //lasso().setCaretToStart(endelem).select(); return true; } }; _container.inout = { importHTML: function (sourcenode) { var container, result, i, elemcount, elem, tagname; if (!sourcenode || sourcenode.childNodes.length < 1) return false; container = _container.create(); // For each source child node, check if appropriate import handler exists, if so then call it on the node for (i = 0; i < sourcenode.childNodes.length; i += 1) { elem = sourcenode.childNodes[i]; if (elem.nodeType !== 1 && elem.nodeType !== 3) continue; tagname = (elem.nodeType === 3) ? "#textnode" : elem.tagName.toLowerCase(); /*if (handler = ghostedit.inout.importhandlers[tagname]) { result = ghostedit.plugins[handler].inout.importHTML(elem) if (result && ghostedit.dom.isGhostBlock(result)) { container.appendChild(result); } }*/ if (ghostedit.inout.importhandlers[tagname]) { result = ghostedit.inout.importhandlers[tagname].call(this, elem); if (result && ghostedit.dom.isGhostBlock(result)) { container.appendChild(result); } } else if (elem.childNodes.length > 0) { elemcount = elem.childNodes.length; elem.parentNode.insertBefore(ghostedit.dom.extractContent(elem), elem); elem.parentNode.removeChild(elem); i -= 1; } } // Check any GhostBlock children have been added, else add empty paragraph if (!ghostedit.dom.getFirstChildGhostBlock(container)) { container.appendChild(ghostedit.plugins.textblock.create("p")); } return container; }, exportHTML: function (target/*, includeself*/) { // Shouldn't be used without first using export prepare functions if (!target || !ghostedit.dom.isGhostBlock(target) || target.getAttribute("data-ghostedit-elemtype") !== "container") return false; var i = 0, elem, blockreturn, finalCode = "", blockcount = 0, snippet, handler; //if (target.getAttribute("data-ghostedit-isrootnode") === true) isrootnode = true; // Allows for inclusion of enclosing <div> if wanted in future, may also want to retreieve properties //if (includeself === true) finalCode =+ "<div>"; for (i = 0; i < target.childNodes.length; i += 1) { elem = ghostedit.dom.isGhostBlock( target.childNodes[i] ) ? target.childNodes[i] : false; if (!elem) continue; handler = elem.getAttribute("data-ghostedit-handler"); if (!handler || !ghostedit.plugins[handler]) continue; blockreturn = ghostedit.plugins[handler].inout.exportHTML(elem); if (blockreturn) { finalCode += blockreturn.content; blockcount++; } //Create snippet from first 3 paragraphs if (blockcount <= 3){ snippet = finalCode; } } return {content: finalCode, snippet: snippet}; } }; _container.paste = { handle: function (target, source, position) { var sel, anchor, newnode, dummy; if (!ghostedit.dom.isGhostBlock(target) || !ghostedit.dom.isGhostBlock(source)) return false; //if (position.isfirst || position.islast) return false; sel = ghostedit.selection.saved.data; anchor = sel.clone().collapseToStart().getParentElement(); sel.saveToDOM("ghostedit_paste_start"); if (anchor === target) { /* Just use range marker as dummy elem dummy = document.createElement("span"); dummy.innerHTML = "&#x200b"; dummy.id = "ghostedit_paste_dummy"; sel.clone().collapseToStart().insertNode(dummy);*/ dummy = document.getElementById("ghostedit_paste_start_range_start"); anchor = ghostedit.dom.getPreviousSiblingGhostBlock(dummy) || dummy; } while (anchor.parentNode !== target) { anchor = anchor.parentNode; if (anchor === null || !anchor.parentNode) return true; } newnode = source.cloneNode(true); /*if (position.islast) { sel.removeDOMmarkers("ghostedit_paste"); newnode.innerHTML = "<span id='ghostedit_paste_range_end'>&#x200b;</span>" + newnode.innerHTML; } else { document.getElementById("ghostedit_paste_range_start").parentNode.removeChild(document.getElementById("ghostedit_paste_range_start")); }*/ lasso().removeDOMmarkers("ghostedit_paste_start"); newnode.innerHTML += "<span id='ghostedit_paste_start_range_start' class='t3'>&#x200b;</span>"; _container.dom.addchild(target, "after", anchor, newnode); if (dummy && dummy.parentNode) dummy.parentNode.removeChild(dummy); return true; } }; // TODO remove this function is favour of dom.isChildGhostBlock _container.isChildGhostBlock = function (elem, childblocks) { var i; if (!elem) return false; if (elem.nodeType !== 1) return false; if (elem.getAttribute("data-ghostedit-elemtype") === undefined) return false; if (elem.getAttribute("data-ghostedit-elemtype") === false) return false; if (elem.getAttribute("data-ghostedit-elemtype") === null) return false; for(i = 0; i < childblocks.length; i += 1) { if (elem === childblocks[i]) { return true; } } return false; }; _container.create = function () { var newElem; // Create element, and assign id and content newElem = document.createElement("div"); ghostedit.blockElemId += 1; newElem.id = "ghostedit_container_" + ghostedit.blockElemId; // Set GhostEdit handler attributes newElem.setAttribute("data-ghostedit-iselem", "true"); newElem.setAttribute("data-ghostedit-elemtype", "container"); newElem.setAttribute("data-ghostedit-handler", "container"); return newElem; }; _container.focus = function (target) { var firstchild, handler; if (!target || target.nodeType !== 1 || target.getAttribute("data-ghostedit-elemtype") !== "container") return false; // Get first child of container firstchild = ghostedit.dom.getFirstChildGhostBlock (target); if (!firstchild) return false; handler = firstchild.getAttribute("data-ghostedit-handler"); ghostedit.plugins[handler].focus(firstchild); return true; }; ghostedit.api.plugin.register("container", _container); })(window);
nicoburns/ghostedit
dist/ghostedit-core-1.0.0-pre.js
JavaScript
lgpl-2.1
128,789
package org.ddd.toolbox.dao; /** * Callback interface for building queries. * * <br> * Patterns: Callback * * <br> * Revisions: jnorris: Oct 2, 2007: Initial revision. * * @param <T_QUERY> * The type of the query being constructed. * * @author jnorris */ public interface QueryFactoryCallback<T_QUERY> { /** * Build the query. * * @return The resulting query. */ public T_QUERY build(); }
jeremynorris/ddd-toolbox
dao/src/main/java/org/ddd/toolbox/dao/QueryFactoryCallback.java
Java
lgpl-2.1
468
// This code is derived from jcifs smb client library <jcifs at samba dot org> // Ported by J. Arturo <webmaster at komodosoft dot net> // // 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 using WinrtCifs.Util; namespace WinrtCifs.Smb { internal class NetServerEnum2Response : SmbComTransactionResponse { internal class ServerInfo1 : IFileEntry { internal string Name; internal int VersionMajor; internal int VersionMinor; internal int Type; internal string CommentOrMasterBrowser; public virtual string GetName() { return Name; } public virtual int GetFilesystemType() { return (Type & unchecked((int)(0x80000000))) != 0 ? SmbFile.TypeWorkgroup : SmbFile.TypeServer; } public virtual int GetAttributes() { return SmbFile.AttrReadonly | SmbFile.AttrDirectory; } public virtual long CreateTime() { return 0L; } public virtual long LastModified() { return 0L; } public virtual long Length() { return 0L; } public override string ToString() { return "ServerInfo1[" + "name=" + Name + ",versionMajor=" + VersionMajor + ",versionMinor=" + VersionMinor + ",type=0x" + Hexdump.ToHexString (Type, 8) + ",commentOrMasterBrowser=" + CommentOrMasterBrowser + "]"; } internal ServerInfo1(NetServerEnum2Response enclosing) { this._enclosing = enclosing; } private readonly NetServerEnum2Response _enclosing; } private int _converter; private int _totalAvailableEntries; internal string LastName; internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) { return 0; } internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) { return 0; } internal override int WriteDataWireFormat(byte[] dst, int dstIndex) { return 0; } internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len ) { return 0; } internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len) { int start = bufferIndex; Status = ReadInt2(buffer, bufferIndex); bufferIndex += 2; _converter = ReadInt2(buffer, bufferIndex); bufferIndex += 2; NumEntries = ReadInt2(buffer, bufferIndex); bufferIndex += 2; _totalAvailableEntries = ReadInt2(buffer, bufferIndex); bufferIndex += 2; return bufferIndex - start; } internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) { int start = bufferIndex; ServerInfo1 e = null; Results = new ServerInfo1[NumEntries]; for (int i = 0; i < NumEntries; i++) { Results[i] = e = new ServerInfo1(this); e.Name = ReadString(buffer, bufferIndex, 16, false); bufferIndex += 16; e.VersionMajor = buffer[bufferIndex++] & unchecked(0xFF); e.VersionMinor = buffer[bufferIndex++] & unchecked(0xFF); e.Type = ReadInt4(buffer, bufferIndex); bufferIndex += 4; int off = ReadInt4(buffer, bufferIndex); bufferIndex += 4; off = (off & unchecked(0xFFFF)) - _converter; off = start + off; e.CommentOrMasterBrowser = ReadString(buffer, off, 48, false); if (Log.Level >= 4) { Log.WriteLine(e); } } LastName = NumEntries == 0 ? null : e.Name; return bufferIndex - start; } public override string ToString() { return "NetServerEnum2Response[" + base.ToString() + ",status=" + Status + ",converter=" + _converter + ",entriesReturned=" + NumEntries + ",totalAvailableEntries=" + _totalAvailableEntries + ",lastName=" + LastName + "]"; } } }
saki-saki/WinRTCifs
WinRTCifs/Smb/NetServerEnum2Response.cs
C#
lgpl-2.1
4,259
using System.Runtime.Versioning; using Mapsui.UI.Maui; using Microsoft.Maui.Controls.Hosting; using Microsoft.Maui.Hosting; using SkiaSharp.Views.Maui.Controls.Hosting; namespace Mapsui.Samples.Maui { public static class MauiProgram { [SupportedOSPlatform("windows10.0.18362")] public static MauiApp CreateMauiApp() { // GPU does not work currently on MAUI MapControl.UseGPU = false; var builder = MauiApp.CreateBuilder(); builder .UseSkiaSharp(true) .UseMauiApp<App>() .ConfigureFonts(fonts => { fonts.AddFont("OpenSansRegular.ttf", "OpenSansRegular"); }); return builder.Build(); } } }
pauldendulk/Mapsui
Samples/Mapsui.Samples.Maui/MauiProgram.cs
C#
lgpl-2.1
781
<?php /* * 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/>. * */ /** * This class represents a clipboard * * @author wassim Chegham & hugo Marchadour * @package Command * @version 0.1 */ class Clipboard { /** * @var String $_text the current text content * @access private */ private $_text; /** * The constructor of the Clipboard * @param String $str The value of the new string to be set * @return void */ public function __construct($str="") { $this->_text = $str; } /** * Set the current text * @return void * @param String $str the new text content */ public function setText($str) { $this->_text = $str; } /** * Get the current text content * @return String the current text */ public function getText() { return $this->_text; } } ?>
manekinekko/acoprojet
bin/patterns/Clipboard.php
PHP
lgpl-2.1
1,461
<?php // // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997-2002 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 2.02 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available at through the world-wide-web at | // | http://www.php.net/license/2_02.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Authors: Richard Heyes <richard@phpguru.org> | // +----------------------------------------------------------------------+ /** * * Raw mime encoding class * * What is it? * This class enables you to manipulate and build * a mime email from the ground up. * * Why use this instead of mime.php? * mime.php is a userfriendly api to this class for * people who aren't interested in the internals of * mime mail. This class however allows full control * over the email. * * Eg. * * // Since multipart/mixed has no real body, (the body is * // the subpart), we set the body argument to blank. * * $params['content_type'] = 'multipart/mixed'; * $email = new Mail_mimePart('', $params); * * // Here we add a text part to the multipart we have * // already. Assume $body contains plain text. * * $params['content_type'] = 'text/plain'; * $params['encoding'] = '7bit'; * $text = $email->addSubPart($body, $params); * * // Now add an attachment. Assume $attach is * the contents of the attachment * * $params['content_type'] = 'application/zip'; * $params['encoding'] = 'base64'; * $params['disposition'] = 'attachment'; * $params['dfilename'] = 'example.zip'; * $attach =& $email->addSubPart($body, $params); * * // Now build the email. Note that the encode * // function returns an associative array containing two * // elements, body and headers. You will need to add extra * // headers, (eg. Mime-Version) before sending. * * $email = $message->encode(); * $email['headers'][] = 'Mime-Version: 1.0'; * * * Further examples are available at http://www.phpguru.org * * TODO: * - Set encode() to return the $obj->encoded if encode() * has already been run. Unless a flag is passed to specifically * re-build the message. * * @author Richard Heyes <richard@phpguru.org> * @version $Revision: 1.1 $ * @package Mail */ class Mail_mimePart { /** * The encoding type of this part * @var string */ public $_encoding; /** * An array of subparts * @var array */ public $_subparts; /** * The output of this part after being built * @var string */ public $_encoded; /** * Headers for this part * @var array */ public $_headers; /** * The body of this part (not encoded) * @var string */ public $_body; /** * Constructor. * * Sets up the object. * * @param $body - The body of the mime part if any. * @param $params - An associative array of parameters: * content_type - The content type for this part eg multipart/mixed * encoding - The encoding to use, 7bit, 8bit, base64, or quoted-printable * cid - Content ID to apply * disposition - Content disposition, inline or attachment * dfilename - Optional filename parameter for content disposition * description - Content description * charset - Character set to use * @access public */ public function Mail_mimePart($body = '', $params = array()) { if (!defined('MAIL_MIMEPART_CRLF')) { define('MAIL_MIMEPART_CRLF', defined('MAIL_MIME_CRLF') ? MAIL_MIME_CRLF : "\r\n", TRUE); } foreach ($params as $key => $value) { switch ($key) { case 'content_type': $headers['Content-Type'] = $value . (isset($charset) ? '; charset="' . $charset . '"' : ''); break; case 'encoding': $this->_encoding = $value; $headers['Content-Transfer-Encoding'] = $value; break; case 'cid': $headers['Content-ID'] = '<' . $value . '>'; break; case 'disposition': $headers['Content-Disposition'] = $value . (isset($dfilename) ? '; filename="' . $dfilename . '"' : ''); break; case 'dfilename': if (isset($headers['Content-Disposition'])) { $headers['Content-Disposition'] .= '; filename="' . $value . '"'; } else { $dfilename = $value; } break; case 'description': $headers['Content-Description'] = $value; break; case 'charset': if (isset($headers['Content-Type'])) { $headers['Content-Type'] .= '; charset="' . $value . '"'; } else { $charset = $value; } break; } } // Default content-type if (!isset($headers['Content-Type'])) { $headers['Content-Type'] = 'text/plain'; } //Default encoding if (!isset($this->_encoding)) { $this->_encoding = '7bit'; } // Assign stuff to member variables $this->_encoded = array(); $this->_headers = $headers; $this->_body = $body; } /** * encode() * * Encodes and returns the email. Also stores * it in the encoded member variable * * @return An associative array containing two elements, * body and headers. The headers element is itself * an indexed array. * @access public */ public function encode() { $encoded =& $this->_encoded; if (!empty($this->_subparts)) { srand((double)microtime()*1000000); $boundary = '=_' . md5(uniqid(rand()) . microtime()); $this->_headers['Content-Type'] .= ';' . MAIL_MIMEPART_CRLF . "\t" . 'boundary="' . $boundary . '"'; // Add body parts to $subparts for ($i = 0; $i < count($this->_subparts); $i++) { $headers = array(); $tmp = $this->_subparts[$i]->encode(); foreach ($tmp['headers'] as $key => $value) { $headers[] = $key . ': ' . $value; } $subparts[] = implode(MAIL_MIMEPART_CRLF, $headers) . MAIL_MIMEPART_CRLF . MAIL_MIMEPART_CRLF . $tmp['body']; } $encoded['body'] = '--' . $boundary . MAIL_MIMEPART_CRLF . implode('--' . $boundary . MAIL_MIMEPART_CRLF, $subparts) . '--' . $boundary.'--' . MAIL_MIMEPART_CRLF; } else { $encoded['body'] = $this->_getEncodedData($this->_body, $this->_encoding) . MAIL_MIMEPART_CRLF; } // Add headers to $encoded $encoded['headers'] =& $this->_headers; return $encoded; } /** * &addSubPart() * * Adds a subpart to current mime part and returns * a reference to it * * @param $body The body of the subpart, if any. * @param $params The parameters for the subpart, same * as the $params argument for constructor. * @return A reference to the part you just added. It is * crucial if using multipart/* in your subparts that * you use =& in your script when calling this function, * otherwise you will not be able to add further subparts. * @access public */ function &addSubPart($body, $params) { $this->_subparts[] = new Mail_mimePart($body, $params); return $this->_subparts[count($this->_subparts) - 1]; } /** * _getEncodedData() * * Returns encoded data based upon encoding passed to it * * @param $data The data to encode. * @param $encoding The encoding type to use, 7bit, base64, * or quoted-printable. * @access private */ public function _getEncodedData($data, $encoding) { switch ($encoding) { case '8bit': case '7bit': return $data; break; case 'quoted-printable': return $this->_quotedPrintableEncode($data); break; case 'base64': return rtrim(chunk_split(base64_encode($data), 76, MAIL_MIMEPART_CRLF)); break; default: return $data; } } /** * quoteadPrintableEncode() * * Encodes data to quoted-printable standard. * * @param $input The data to encode * @param $line_max Optional max line length. Should * not be more than 76 chars * * @access private */ public function _quotedPrintableEncode($input , $line_max = 76) { $lines = preg_split("/\r?\n/", $input); $eol = MAIL_MIMEPART_CRLF; $escape = '='; $output = ''; while(list(, $line) = each($lines)){ $linlen = strlen($line); $newline = ''; for ($i = 0; $i < $linlen; $i++) { $char = substr($line, $i, 1); $dec = ord($char); if (($dec == 32) AND ($i == ($linlen - 1))){ // convert space at eol only $char = '=20'; } elseif($dec == 9) { ; // Do nothing if a tab. } elseif(($dec == 61) OR ($dec < 32 ) OR ($dec > 126)) { $char = $escape . strtoupper(sprintf('%02s', dechex($dec))); } if ((strlen($newline) + strlen($char)) >= $line_max) { // MAIL_MIMEPART_CRLF is not counted $output .= $newline . $escape . $eol; // soft line break; " =\r\n" is okay $newline = ''; } $newline .= $char; } // end of for $output .= $newline . $eol; } $output = substr($output, 0, -1 * strlen($eol)); // Don't want last crlf return $output; } } // End of class
lilobase/ICONTO-EcoleNumerique
utils/htmlMimeMail/mimePart.php
PHP
lgpl-2.1
11,112
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "renderarea.h" #include "window.h" #include <QtWidgets> //! [0] const int IdRole = Qt::UserRole; //! [0] //! [1] Window::Window() { renderArea = new RenderArea; shapeComboBox = new QComboBox; shapeComboBox->addItem(tr("Polygon"), RenderArea::Polygon); shapeComboBox->addItem(tr("Rectangle"), RenderArea::Rect); shapeComboBox->addItem(tr("Rounded Rectangle"), RenderArea::RoundedRect); shapeComboBox->addItem(tr("Ellipse"), RenderArea::Ellipse); shapeComboBox->addItem(tr("Pie"), RenderArea::Pie); shapeComboBox->addItem(tr("Chord"), RenderArea::Chord); shapeComboBox->addItem(tr("Path"), RenderArea::Path); shapeComboBox->addItem(tr("Line"), RenderArea::Line); shapeComboBox->addItem(tr("Polyline"), RenderArea::Polyline); shapeComboBox->addItem(tr("Arc"), RenderArea::Arc); shapeComboBox->addItem(tr("Points"), RenderArea::Points); shapeComboBox->addItem(tr("Text"), RenderArea::Text); shapeComboBox->addItem(tr("Pixmap"), RenderArea::Pixmap); shapeLabel = new QLabel(tr("&Shape:")); shapeLabel->setBuddy(shapeComboBox); //! [1] //! [2] penWidthSpinBox = new QSpinBox; penWidthSpinBox->setRange(0, 20); penWidthSpinBox->setSpecialValueText(tr("0 (cosmetic pen)")); penWidthLabel = new QLabel(tr("Pen &Width:")); penWidthLabel->setBuddy(penWidthSpinBox); //! [2] //! [3] penStyleComboBox = new QComboBox; penStyleComboBox->addItem(tr("Solid"), static_cast<int>(Qt::SolidLine)); penStyleComboBox->addItem(tr("Dash"), static_cast<int>(Qt::DashLine)); penStyleComboBox->addItem(tr("Dot"), static_cast<int>(Qt::DotLine)); penStyleComboBox->addItem(tr("Dash Dot"), static_cast<int>(Qt::DashDotLine)); penStyleComboBox->addItem(tr("Dash Dot Dot"), static_cast<int>(Qt::DashDotDotLine)); penStyleComboBox->addItem(tr("None"), static_cast<int>(Qt::NoPen)); penStyleLabel = new QLabel(tr("&Pen Style:")); penStyleLabel->setBuddy(penStyleComboBox); penCapComboBox = new QComboBox; penCapComboBox->addItem(tr("Flat"), Qt::FlatCap); penCapComboBox->addItem(tr("Square"), Qt::SquareCap); penCapComboBox->addItem(tr("Round"), Qt::RoundCap); penCapLabel = new QLabel(tr("Pen &Cap:")); penCapLabel->setBuddy(penCapComboBox); penJoinComboBox = new QComboBox; penJoinComboBox->addItem(tr("Miter"), Qt::MiterJoin); penJoinComboBox->addItem(tr("Bevel"), Qt::BevelJoin); penJoinComboBox->addItem(tr("Round"), Qt::RoundJoin); penJoinLabel = new QLabel(tr("Pen &Join:")); penJoinLabel->setBuddy(penJoinComboBox); //! [3] //! [4] brushStyleComboBox = new QComboBox; brushStyleComboBox->addItem(tr("Linear Gradient"), static_cast<int>(Qt::LinearGradientPattern)); brushStyleComboBox->addItem(tr("Radial Gradient"), static_cast<int>(Qt::RadialGradientPattern)); brushStyleComboBox->addItem(tr("Conical Gradient"), static_cast<int>(Qt::ConicalGradientPattern)); brushStyleComboBox->addItem(tr("Texture"), static_cast<int>(Qt::TexturePattern)); brushStyleComboBox->addItem(tr("Solid"), static_cast<int>(Qt::SolidPattern)); brushStyleComboBox->addItem(tr("Horizontal"), static_cast<int>(Qt::HorPattern)); brushStyleComboBox->addItem(tr("Vertical"), static_cast<int>(Qt::VerPattern)); brushStyleComboBox->addItem(tr("Cross"), static_cast<int>(Qt::CrossPattern)); brushStyleComboBox->addItem(tr("Backward Diagonal"), static_cast<int>(Qt::BDiagPattern)); brushStyleComboBox->addItem(tr("Forward Diagonal"), static_cast<int>(Qt::FDiagPattern)); brushStyleComboBox->addItem(tr("Diagonal Cross"), static_cast<int>(Qt::DiagCrossPattern)); brushStyleComboBox->addItem(tr("Dense 1"), static_cast<int>(Qt::Dense1Pattern)); brushStyleComboBox->addItem(tr("Dense 2"), static_cast<int>(Qt::Dense2Pattern)); brushStyleComboBox->addItem(tr("Dense 3"), static_cast<int>(Qt::Dense3Pattern)); brushStyleComboBox->addItem(tr("Dense 4"), static_cast<int>(Qt::Dense4Pattern)); brushStyleComboBox->addItem(tr("Dense 5"), static_cast<int>(Qt::Dense5Pattern)); brushStyleComboBox->addItem(tr("Dense 6"), static_cast<int>(Qt::Dense6Pattern)); brushStyleComboBox->addItem(tr("Dense 7"), static_cast<int>(Qt::Dense7Pattern)); brushStyleComboBox->addItem(tr("None"), static_cast<int>(Qt::NoBrush)); brushStyleLabel = new QLabel(tr("&Brush:")); brushStyleLabel->setBuddy(brushStyleComboBox); //! [4] //! [5] otherOptionsLabel = new QLabel(tr("Options:")); //! [5] //! [6] antialiasingCheckBox = new QCheckBox(tr("&Antialiasing")); //! [6] //! [7] transformationsCheckBox = new QCheckBox(tr("&Transformations")); //! [7] //! [8] connect(shapeComboBox, SIGNAL(activated(int)), this, SLOT(shapeChanged())); connect(penWidthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(penChanged())); connect(penStyleComboBox, SIGNAL(activated(int)), this, SLOT(penChanged())); connect(penCapComboBox, SIGNAL(activated(int)), this, SLOT(penChanged())); connect(penJoinComboBox, SIGNAL(activated(int)), this, SLOT(penChanged())); connect(brushStyleComboBox, SIGNAL(activated(int)), this, SLOT(brushChanged())); connect(antialiasingCheckBox, SIGNAL(toggled(bool)), renderArea, SLOT(setAntialiased(bool))); connect(transformationsCheckBox, SIGNAL(toggled(bool)), renderArea, SLOT(setTransformed(bool))); //! [8] //! [9] QGridLayout *mainLayout = new QGridLayout; //! [9] //! [10] mainLayout->setColumnStretch(0, 1); mainLayout->setColumnStretch(3, 1); mainLayout->addWidget(renderArea, 0, 0, 1, 4); mainLayout->addWidget(shapeLabel, 2, 0, Qt::AlignRight); mainLayout->addWidget(shapeComboBox, 2, 1); mainLayout->addWidget(penWidthLabel, 3, 0, Qt::AlignRight); mainLayout->addWidget(penWidthSpinBox, 3, 1); mainLayout->addWidget(penStyleLabel, 4, 0, Qt::AlignRight); mainLayout->addWidget(penStyleComboBox, 4, 1); mainLayout->addWidget(penCapLabel, 3, 2, Qt::AlignRight); mainLayout->addWidget(penCapComboBox, 3, 3); mainLayout->addWidget(penJoinLabel, 2, 2, Qt::AlignRight); mainLayout->addWidget(penJoinComboBox, 2, 3); mainLayout->addWidget(brushStyleLabel, 4, 2, Qt::AlignRight); mainLayout->addWidget(brushStyleComboBox, 4, 3); mainLayout->addWidget(otherOptionsLabel, 5, 0, Qt::AlignRight); mainLayout->addWidget(antialiasingCheckBox, 5, 1, 1, 1, Qt::AlignRight); mainLayout->addWidget(transformationsCheckBox, 5, 2, 1, 2, Qt::AlignRight); setLayout(mainLayout); shapeChanged(); penChanged(); brushChanged(); antialiasingCheckBox->setChecked(true); setWindowTitle(tr("Basic Drawing")); } //! [10] //! [11] void Window::shapeChanged() { RenderArea::Shape shape = RenderArea::Shape(shapeComboBox->itemData( shapeComboBox->currentIndex(), IdRole).toInt()); renderArea->setShape(shape); } //! [11] //! [12] void Window::penChanged() { int width = penWidthSpinBox->value(); Qt::PenStyle style = Qt::PenStyle(penStyleComboBox->itemData( penStyleComboBox->currentIndex(), IdRole).toInt()); Qt::PenCapStyle cap = Qt::PenCapStyle(penCapComboBox->itemData( penCapComboBox->currentIndex(), IdRole).toInt()); Qt::PenJoinStyle join = Qt::PenJoinStyle(penJoinComboBox->itemData( penJoinComboBox->currentIndex(), IdRole).toInt()); renderArea->setPen(QPen(Qt::blue, width, style, cap, join)); } //! [12] //! [13] void Window::brushChanged() { Qt::BrushStyle style = Qt::BrushStyle(brushStyleComboBox->itemData( //! [13] brushStyleComboBox->currentIndex(), IdRole).toInt()); //! [14] if (style == Qt::LinearGradientPattern) { QLinearGradient linearGradient(0, 0, 100, 100); linearGradient.setColorAt(0.0, Qt::white); linearGradient.setColorAt(0.2, Qt::green); linearGradient.setColorAt(1.0, Qt::black); renderArea->setBrush(linearGradient); //! [14] //! [15] } else if (style == Qt::RadialGradientPattern) { QRadialGradient radialGradient(50, 50, 50, 70, 70); radialGradient.setColorAt(0.0, Qt::white); radialGradient.setColorAt(0.2, Qt::green); radialGradient.setColorAt(1.0, Qt::black); renderArea->setBrush(radialGradient); } else if (style == Qt::ConicalGradientPattern) { QConicalGradient conicalGradient(50, 50, 150); conicalGradient.setColorAt(0.0, Qt::white); conicalGradient.setColorAt(0.2, Qt::green); conicalGradient.setColorAt(1.0, Qt::black); renderArea->setBrush(conicalGradient); //! [15] //! [16] } else if (style == Qt::TexturePattern) { renderArea->setBrush(QBrush(QPixmap(":/images/brick.png"))); //! [16] //! [17] } else { renderArea->setBrush(QBrush(Qt::green, style)); } } //! [17]
CodeDJ/qt5-hidpi
qt/qtbase/examples/widgets/painting/basicdrawing/window.cpp
C++
lgpl-2.1
10,930